diff --git a/algorithm.html b/algorithm.html new file mode 100644 index 0000000000000..53852e1af0127 --- /dev/null +++ b/algorithm.html @@ -0,0 +1,978 @@ + + + + + + + +std/algorithm + + + + + + + + + + + + + + + + +
+
+

std/algorithm

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements some common generic algorithms on openArrays. +

Basic usage

+

Example:

+
import std/algorithm
+type People = tuple
+  year: int
+  name: string
+
+var a: seq[People]
+
+a.add((2000, "John"))
+a.add((2005, "Marie"))
+a.add((2010, "Jane"))
+
+# Sorting with default system.cmp
+a.sort()
+assert a == @[(year: 2000, name: "John"), (year: 2005, name: "Marie"),
+              (year: 2010, name: "Jane")]
+
+proc myCmp(x, y: People): int =
+  cmp(x.name, y.name)
+
+# Sorting with custom proc
+a.sort(myCmp)
+assert a == @[(year: 2010, name: "Jane"), (year: 2000, name: "John"),
+              (year: 2005, name: "Marie")]
+

See also

+

+ +
+

Types

+
+
+
SortOrder = enum
+  Descending, Ascending
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `*`(x: int; order: SortOrder): int {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Flips the sign of x if order == Descending. If order == Ascending then x is returned.

+

x is supposed to be the result of a comparator, i.e.

< 0 for less than,
== 0 for equal,
> 0 for greater than.

+ +

Example:

+
assert -123 * Descending == 123
+assert 123 * Descending == -123
+assert -123 * Ascending == -123
+assert 123 * Ascending == 123
+ Source   +Edit   + +
+
+ +
+
+
+
proc binarySearch[T, K](a: openArray[T]; key: K;
+                        cmp: proc (x: T; y: K): int {.closure.}): int {.
+    effectsOf: cmp.}
+
+ +

Binary search for key in a. Return the index of key or -1 if not found. Assumes that a is sorted according to cmp.

+

cmp is the comparator function to use, the expected return values are the same as those of system.cmp.

+ +

Example:

+
assert binarySearch(["a", "b", "c", "d"], "d", system.cmp[string]) == 3
+assert binarySearch(["a", "b", "c", "d"], "c", system.cmp[string]) == 2
+ Source   +Edit   + +
+
+
+
proc binarySearch[T](a: openArray[T]; key: T): int
+
+ + Binary search for key in a. Return the index of key or -1 if not found. Assumes that a is sorted. +

Example:

+
assert binarySearch([0, 1, 2, 3, 4], 4) == 4
+assert binarySearch([0, 1, 2, 3, 4], 2) == 2
+ Source   +Edit   + +
+
+ +
+
+
+
proc fill[T](a: var openArray[T]; first, last: Natural; value: T)
+
+ +

Assigns value to all elements of the slice a[first..last].

+

If an invalid range is passed, it raises IndexDefect.

+ +

Example:

+
var a: array[6, int]
+a.fill(1, 3, 9)
+assert a == [0, 9, 9, 9, 0, 0]
+a.fill(3, 5, 7)
+assert a == [0, 9, 9, 7, 7, 7]
+doAssertRaises(IndexDefect, a.fill(1, 7, 9))
+ Source   +Edit   + +
+
+
+
proc fill[T](a: var openArray[T]; value: T)
+
+ + Assigns value to all elements of the container a. +

Example:

+
var a: array[6, int]
+a.fill(9)
+assert a == [9, 9, 9, 9, 9, 9]
+a.fill(4)
+assert a == [4, 4, 4, 4, 4, 4]
+ Source   +Edit   + +
+
+ +
+
+
+
func isSorted[T](a: openArray[T]; cmp: proc (x, y: T): int {.closure.};
+                 order = SortOrder.Ascending): bool {.effectsOf: cmp.}
+
+ +

Checks to see whether a is already sorted in order using cmp for the comparison. The parameters are identical to sort. Requires O(n) time.

+

See also:

+ + +

Example:

+
let
+  a = [2, 3, 1, 5, 4]
+  b = [1, 2, 3, 4, 5]
+  c = [5, 4, 3, 2, 1]
+  d = ["adam", "brian", "cat", "dande"]
+  e = ["adam", "dande", "brian", "cat"]
+assert isSorted(a) == false
+assert isSorted(b) == true
+assert isSorted(c) == false
+assert isSorted(c, Descending) == true
+assert isSorted(d) == true
+assert isSorted(e) == false
+ Source   +Edit   + +
+
+
+
proc isSorted[T](a: openArray[T]; order = SortOrder.Ascending): bool
+
+ +

Shortcut version of isSorted that uses system.cmp[T] as the comparison function.

+

See also:

+ + +

Example:

+
let
+  a = [2, 3, 1, 5, 4]
+  b = [1, 2, 3, 4, 5]
+  c = [5, 4, 3, 2, 1]
+  d = ["adam", "brian", "cat", "dande"]
+  e = ["adam", "dande", "brian", "cat"]
+assert isSorted(a) == false
+assert isSorted(b) == true
+assert isSorted(c) == false
+assert isSorted(c, Descending) == true
+assert isSorted(d) == true
+assert isSorted(e) == false
+ Source   +Edit   + +
+
+ +
+
+
+
proc lowerBound[T, K](a: openArray[T]; key: K;
+                      cmp: proc (x: T; k: K): int {.closure.}): int {.
+    effectsOf: cmp.}
+
+ +

Returns the index of the first element in a that is not less than (i.e. greater or equal to) key, or last if no such element is found. In other words if you have a sorted sequence and you call insert(thing, elm, lowerBound(thing, elm)) the sequence will still be sorted. Assumes that a is sorted according to cmp.

+

If an invalid range is passed, it raises IndexDefect.

+

This version uses cmp to compare the elements. The expected return values are the same as those of system.cmp.

+

See also:

+ + +

Example:

+
var arr = @[1, 2, 3, 5, 6, 7, 8, 9]
+assert arr.lowerBound(3, system.cmp[int]) == 2
+assert arr.lowerBound(4, system.cmp[int]) == 3
+assert arr.lowerBound(5, system.cmp[int]) == 3
+arr.insert(4, arr.lowerBound(4, system.cmp[int]))
+assert arr == [1, 2, 3, 4, 5, 6, 7, 8, 9]
+ Source   +Edit   + +
+
+
+
proc lowerBound[T](a: openArray[T]; key: T): int
+
+ +

Returns the index of the first element in a that is not less than (i.e. greater or equal to) key, or last if no such element is found. In other words if you have a sorted sequence and you call insert(thing, elm, lowerBound(thing, elm)) the sequence will still be sorted. Assumes that a is sorted.

+

This version uses the default comparison function cmp.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc merge[T](result: var seq[T]; x, y: openArray[T]) {.inline.}
+
+ +

Shortcut version of merge that uses system.cmp[T] as the comparison function.

+

See also:

+ + +

Example:

+
let x = [5, 10, 15, 20, 25]
+let y = [50, 40, 30, 20, 10].sorted
+
+var merged: seq[int]
+merged.merge(x, y)
+assert merged.isSorted
+assert merged == @[5, 10, 10, 15, 20, 20, 25, 30, 40, 50]
+ Source   +Edit   + +
+
+
+
proc merge[T](result: var seq[T]; x, y: openArray[T];
+              cmp: proc (x, y: T): int {.closure.}) {.effectsOf: cmp.}
+
+ + Merges two sorted openArray. x and y are assumed to be sorted. If you do not wish to provide your own cmp, you may use system.cmp or instead call the overloaded version of merge, which uses system.cmp.
Note: +The original data of result is not cleared, new data is appended to result.
+

See also:

+ + +

Example:

+
let x = @[1, 3, 6]
+let y = @[2, 3, 4]
+
+block:
+  var merged = @[7] # new data is appended to merged sequence
+  merged.merge(x, y, system.cmp[int])
+  assert merged == @[7, 1, 2, 3, 3, 4, 6]
+
+block:
+  var merged = @[7] # if you only want new data, clear merged sequence first
+  merged.setLen(0)
+  merged.merge(x, y, system.cmp[int])
+  assert merged.isSorted
+  assert merged == @[1, 2, 3, 3, 4, 6]
+
+import std/sugar
+
+var res: seq[(int, int)]
+res.merge([(1, 1)], [(1, 2)], (a, b) => a[0] - b[0])
+assert res == @[(1, 1), (1, 2)]
+
+assert seq[int].default.dup(merge([1, 3], [2, 4])) == @[1, 2, 3, 4]
+ Source   +Edit   + +
+
+ +
+
+
+
proc nextPermutation[T](x: var openArray[T]): bool {.discardable.}
+
+ +

Calculates the next lexicographic permutation, directly modifying x. The result is whether a permutation happened, otherwise we have reached the last-ordered permutation.

+

If you start with an unsorted array/seq, the repeated permutations will not give you all permutations but stop with the last.

+

See also:

+ + +

Example:

+
var v = @[0, 1, 2, 3]
+assert v.nextPermutation() == true
+assert v == @[0, 1, 3, 2]
+assert v.nextPermutation() == true
+assert v == @[0, 2, 1, 3]
+assert v.prevPermutation() == true
+assert v == @[0, 1, 3, 2]
+v = @[3, 2, 1, 0]
+assert v.nextPermutation() == false
+assert v == @[3, 2, 1, 0]
+ Source   +Edit   + +
+
+ +
+
+
+
proc prevPermutation[T](x: var openArray[T]): bool {.discardable.}
+
+ +

Calculates the previous lexicographic permutation, directly modifying x. The result is whether a permutation happened, otherwise we have reached the first-ordered permutation.

+

See also:

+ + +

Example:

+
var v = @[0, 1, 2, 3]
+assert v.prevPermutation() == false
+assert v == @[0, 1, 2, 3]
+assert v.nextPermutation() == true
+assert v == @[0, 1, 3, 2]
+assert v.prevPermutation() == true
+assert v == @[0, 1, 2, 3]
+ Source   +Edit   + +
+
+ +
+
+
+
proc product[T](x: openArray[seq[T]]): seq[seq[T]]
+
+ + Produces the Cartesian product of the array. Every element of the result is a combination of one element from each seq in x, with the ith element coming from x[i].
Warning: +complexity may explode.
+ +

Example:

+
assert product(@[@[1], @[2]]) == @[@[1, 2]]
+assert product(@[@["A", "K"], @["Q"]]) == @[@["K", "Q"], @["A", "Q"]]
+ Source   +Edit   + +
+
+ +
+
+
+
proc reverse[T](a: var openArray[T])
+
+ +

Reverses the contents of the container a.

+

See also:

+ + +

Example:

+
var a = [1, 2, 3, 4, 5, 6]
+a.reverse()
+assert a == [6, 5, 4, 3, 2, 1]
+a.reverse()
+assert a == [1, 2, 3, 4, 5, 6]
+ Source   +Edit   + +
+
+
+
proc reverse[T](a: var openArray[T]; first, last: Natural)
+
+ +

Reverses the slice a[first..last].

+

If an invalid range is passed, it raises IndexDefect.

+

See also:

+ + +

Example:

+
var a = [1, 2, 3, 4, 5, 6]
+a.reverse(1, 3)
+assert a == [1, 4, 3, 2, 5, 6]
+a.reverse(1, 3)
+assert a == [1, 2, 3, 4, 5, 6]
+doAssertRaises(IndexDefect, a.reverse(1, 7))
+ Source   +Edit   + +
+
+ +
+
+
+
proc reversed[T](a: openArray[T]): seq[T] {.inline.}
+
+ +

Returns the elements of a in reverse order.

+

See also:

+ + +

Example:

+
assert [10, 11, 12].reversed == @[12, 11, 10]
+assert seq[string].default.reversed == @[]
+ Source   +Edit   + +
+
+
+
proc reversed[T](a: openArray[T]; first: Natural; last: int): seq[T] {.inline,
+    ...deprecated: "use: `reversed(toOpenArray(a, first, last))`".}
+
+
+ Deprecated: use: `reversed(toOpenArray(a, first, last))` +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rotatedLeft[T](arg: openArray[T]; dist: int): seq[T]
+
+ +

Same as rotateLeft, just with the difference that it does not modify the argument. It creates a new seq instead.

+

See also:

+ + +

Example:

+
var a = @[1, 2, 3, 4, 5]
+a = rotatedLeft(a, 2)
+assert a == @[3, 4, 5, 1, 2]
+a = rotatedLeft(a, 4)
+assert a == @[2, 3, 4, 5, 1]
+a = rotatedLeft(a, -6)
+assert a == @[1, 2, 3, 4, 5]
+ Source   +Edit   + +
+
+
+
proc rotatedLeft[T](arg: openArray[T]; slice: HSlice[int, int]; dist: int): seq[
+    T]
+
+ +

Same as rotateLeft, just with the difference that it does not modify the argument. It creates a new seq instead.

+

Elements outside of slice will be left unchanged. If an invalid range (HSlice) is passed, it raises IndexDefect.

+
slice
+
The indices of the element range that should be rotated.
+
dist
+
The distance in amount of elements that the data should be rotated. Can be negative, can be any number.
+
+

See also:

+ + +

Example:

+
var a = @[1, 2, 3, 4, 5]
+a = rotatedLeft(a, 1 .. 4, 3)
+assert a == @[1, 5, 2, 3, 4]
+a = rotatedLeft(a, 1 .. 3, 2)
+assert a == @[1, 3, 5, 2, 4]
+a = rotatedLeft(a, 1 .. 3, -2)
+assert a == @[1, 5, 2, 3, 4]
+ Source   +Edit   + +
+
+ +
+
+
+
proc rotateLeft[T](arg: var openArray[T]; dist: int): int {.discardable.}
+
+ +

Same as rotateLeft, but with default arguments for slice, so that this procedure operates on the entire arg, and not just on a part of it.

+

See also:

+ + +

Example:

+
var a = [1, 2, 3, 4, 5]
+a.rotateLeft(2)
+assert a == [3, 4, 5, 1, 2]
+a.rotateLeft(4)
+assert a == [2, 3, 4, 5, 1]
+a.rotateLeft(-6)
+assert a == [1, 2, 3, 4, 5]
+ Source   +Edit   + +
+
+
+
proc rotateLeft[T](arg: var openArray[T]; slice: HSlice[int, int]; dist: int): int {.
+    discardable.}
+
+ + Performs a left rotation on a range of elements. If you want to rotate right, use a negative dist. Specifically, rotateLeft rotates the elements at slice by dist positions.

The element at index slice.a + dist will be at index slice.a.
The element at index slice.b will be at slice.a + dist - 1.
The element at index slice.a will be at slice.b + 1 - dist.
The element at index slice.a + dist - 1 will be at slice.b.

Elements outside of slice will be left unchanged. The time complexity is linear to slice.b - slice.a + 1. If an invalid range (HSlice) is passed, it raises IndexDefect.

+
slice
+
The indices of the element range that should be rotated.
+
dist
+
The distance in amount of elements that the data should be rotated. Can be negative, can be any number.
+
+

See also:

+ + +

Example:

+
var a = [0, 1, 2, 3, 4, 5]
+a.rotateLeft(1 .. 4, 3)
+assert a == [0, 4, 1, 2, 3, 5]
+a.rotateLeft(1 .. 4, 3)
+assert a == [0, 3, 4, 1, 2, 5]
+a.rotateLeft(1 .. 4, -3)
+assert a == [0, 4, 1, 2, 3, 5]
+doAssertRaises(IndexDefect, a.rotateLeft(1 .. 7, 2))
+ Source   +Edit   + +
+
+ +
+
+
+
func sort[T](a: var openArray[T]; cmp: proc (x, y: T): int {.closure.};
+             order = SortOrder.Ascending) {.effectsOf: cmp.}
+
+ +

Default Nim sort (an implementation of merge sort). The sorting is guaranteed to be stable (that is, equal elements stay in the same order) and the worst case is guaranteed to be O(n log n). Sorts by cmp in the specified order.

+

The current implementation uses an iterative mergesort to achieve this. It uses a temporary sequence of length a.len div 2. If you do not wish to provide your own cmp, you may use system.cmp or instead call the overloaded version of sort, which uses system.cmp.

+

sort(myIntArray, system.cmp[int])
+# do not use cmp[string] here as we want to use the specialized
+# overload:
+sort(myStrArray, system.cmp)

+

You can inline adhoc comparison procs with the do notation. Example:

+

people.sort do (x, y: Person) -> int:
+  result = cmp(x.surname, y.surname)
+  if result == 0:
+    result = cmp(x.name, y.name)

+

See also:

+ + +

Example:

+
var d = ["boo", "fo", "barr", "qux"]
+proc myCmp(x, y: string): int =
+  if x.len() > y.len() or x.len() == y.len(): 1
+  else: -1
+sort(d, myCmp)
+assert d == ["fo", "qux", "boo", "barr"]
+ Source   +Edit   + +
+
+
+
proc sort[T](a: var openArray[T]; order = SortOrder.Ascending)
+
+ +

Shortcut version of sort that uses system.cmp[T] as the comparison function.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sorted[T](a: openArray[T]; cmp: proc (x, y: T): int {.closure.};
+               order = SortOrder.Ascending): seq[T] {.effectsOf: cmp.}
+
+ +

Returns a sorted by cmp in the specified order.

+

See also:

+ + +

Example:

+
let
+  a = [2, 3, 1, 5, 4]
+  b = sorted(a, system.cmp[int])
+  c = sorted(a, system.cmp[int], Descending)
+  d = sorted(["adam", "dande", "brian", "cat"], system.cmp[string])
+assert b == @[1, 2, 3, 4, 5]
+assert c == @[5, 4, 3, 2, 1]
+assert d == @["adam", "brian", "cat", "dande"]
+ Source   +Edit   + +
+
+
+
proc sorted[T](a: openArray[T]; order = SortOrder.Ascending): seq[T]
+
+ +

Shortcut version of sorted that uses system.cmp[T] as the comparison function.

+

See also:

+ + +

Example:

+
let
+  a = [2, 3, 1, 5, 4]
+  b = sorted(a)
+  c = sorted(a, Descending)
+  d = sorted(["adam", "dande", "brian", "cat"])
+assert b == @[1, 2, 3, 4, 5]
+assert c == @[5, 4, 3, 2, 1]
+assert d == @["adam", "brian", "cat", "dande"]
+ Source   +Edit   + +
+
+ +
+
+
+
proc upperBound[T, K](a: openArray[T]; key: K;
+                      cmp: proc (x: T; k: K): int {.closure.}): int {.
+    effectsOf: cmp.}
+
+ +

Returns the index of the first element in a that is greater than key, or last if no such element is found. In other words if you have a sorted sequence and you call insert(thing, elm, upperBound(thing, elm)) the sequence will still be sorted. Assumes that a is sorted according to cmp.

+

If an invalid range is passed, it raises IndexDefect.

+

This version uses cmp to compare the elements. The expected return values are the same as those of system.cmp.

+

See also:

+ + +

Example:

+
var arr = @[1, 2, 3, 5, 6, 7, 8, 9]
+assert arr.upperBound(2, system.cmp[int]) == 2
+assert arr.upperBound(3, system.cmp[int]) == 3
+assert arr.upperBound(4, system.cmp[int]) == 3
+arr.insert(4, arr.upperBound(3, system.cmp[int]))
+assert arr == [1, 2, 3, 4, 5, 6, 7, 8, 9]
+ Source   +Edit   + +
+
+
+
proc upperBound[T](a: openArray[T]; key: T): int
+
+ +

Returns the index of the first element in a that is greater than key, or last if no such element is found. In other words if you have a sorted sequence and you call insert(thing, elm, upperBound(thing, elm)) the sequence will still be sorted. Assumes that a is sorted.

+

This version uses the default comparison function cmp.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template sortedByIt(seq1, op: untyped): untyped
+
+ +

Convenience template around the sorted proc to reduce typing.

+

The template injects the it variable which you can use directly in an expression.

+

Because the underlying cmp() is defined for tuples you can also do a nested sort.

+

See also:

+ + +

Example:

+
type Person = tuple[name: string, age: int]
+var
+  p1: Person = (name: "p1", age: 60)
+  p2: Person = (name: "p2", age: 20)
+  p3: Person = (name: "p3", age: 30)
+  p4: Person = (name: "p4", age: 30)
+  people = @[p1, p2, p4, p3]
+
+assert people.sortedByIt(it.name) == @[(name: "p1", age: 60), (name: "p2",
+    age: 20), (name: "p3", age: 30), (name: "p4", age: 30)]
+# Nested sort
+assert people.sortedByIt((it.age, it.name)) == @[(name: "p2", age: 20),
+   (name: "p3", age: 30), (name: "p4", age: 30), (name: "p1", age: 60)]
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/algorithm.idx b/algorithm.idx new file mode 100644 index 0000000000000..b98a0c90ff880 --- /dev/null +++ b/algorithm.idx @@ -0,0 +1,47 @@ +nimTitle algorithm algorithm.html module std/algorithm 0 +nim Descending algorithm.html#Descending SortOrder.Descending 52 +nim Ascending algorithm.html#Ascending SortOrder.Ascending 52 +nim SortOrder algorithm.html#SortOrder enum SortOrder 52 +nim `*` algorithm.html#*,int,SortOrder proc `*`(x: int; order: SortOrder): int 55 +nim fill algorithm.html#fill,openArray[T],Natural,Natural,T proc fill[T](a: var openArray[T]; first, last: Natural; value: T) 77 +nim fill algorithm.html#fill,openArray[T],T proc fill[T](a: var openArray[T]; value: T) 90 +nim reverse algorithm.html#reverse,openArray[T],Natural,Natural proc reverse[T](a: var openArray[T]; first, last: Natural) 101 +nim reverse algorithm.html#reverse,openArray[T] proc reverse[T](a: var openArray[T]) 123 +nim reversed algorithm.html#reversed,openArray[T] proc reversed[T](a: openArray[T]): seq[T] 138 +nim reversed algorithm.html#reversed,openArray[T],Natural,int proc reversed[T](a: openArray[T]; first: Natural; last: int): seq[T] 151 +nim binarySearch algorithm.html#binarySearch,openArray[T],K,proc(T,K) proc binarySearch[T, K](a: openArray[T]; key: K;\n cmp: proc (x: T; y: K): int {.closure.}): int 160 +nim binarySearch algorithm.html#binarySearch,openArray[T],T proc binarySearch[T](a: openArray[T]; key: T): int 211 +nim lowerBound algorithm.html#lowerBound,openArray[T],K,proc(T,K) proc lowerBound[T, K](a: openArray[T]; key: K; cmp: proc (x: T; k: K): int {.closure.}): int 222 +nim lowerBound algorithm.html#lowerBound,openArray[T],T proc lowerBound[T](a: openArray[T]; key: T): int 258 +nim upperBound algorithm.html#upperBound,openArray[T],K,proc(T,K) proc upperBound[T, K](a: openArray[T]; key: K; cmp: proc (x: T; k: K): int {.closure.}): int 272 +nim upperBound algorithm.html#upperBound,openArray[T],T proc upperBound[T](a: openArray[T]; key: T): int 308 +nim sort algorithm.html#sort,openArray[T],proc(T,T) proc sort[T](a: var openArray[T]; cmp: proc (x, y: T): int {.closure.};\n order = SortOrder.Ascending) 369 +nim sort algorithm.html#sort,openArray[T] proc sort[T](a: var openArray[T]; order = SortOrder.Ascending) 422 +nim sorted algorithm.html#sorted,openArray[T],proc(T,T) proc sorted[T](a: openArray[T]; cmp: proc (x, y: T): int {.closure.};\n order = SortOrder.Ascending): seq[T] 432 +nim sorted algorithm.html#sorted,openArray[T] proc sorted[T](a: openArray[T]; order = SortOrder.Ascending): seq[T] 454 +nim sortedByIt algorithm.html#sortedByIt.t,untyped,untyped template sortedByIt(seq1, op: untyped): untyped 472 +nim isSorted algorithm.html#isSorted,openArray[T],proc(T,T) proc isSorted[T](a: openArray[T]; cmp: proc (x, y: T): int {.closure.};\n order = SortOrder.Ascending): bool 508 +nim isSorted algorithm.html#isSorted,openArray[T] proc isSorted[T](a: openArray[T]; order = SortOrder.Ascending): bool 535 +nim merge algorithm.html#merge,seq[T],openArray[T],openArray[T],proc(T,T) proc merge[T](result: var seq[T]; x, y: openArray[T];\n cmp: proc (x, y: T): int {.closure.}) 555 +nim merge algorithm.html#merge,seq[T],openArray[T],openArray[T] proc merge[T](result: var seq[T]; x, y: openArray[T]) 632 +nim product algorithm.html#product,openArray[seq[T]] proc product[T](x: openArray[seq[T]]): seq[seq[T]] 647 +nim nextPermutation algorithm.html#nextPermutation,openArray[T] proc nextPermutation[T](x: var openArray[T]): bool 684 +nim prevPermutation algorithm.html#prevPermutation,openArray[T] proc prevPermutation[T](x: var openArray[T]): bool 724 +nim rotateLeft algorithm.html#rotateLeft,openArray[T],HSlice[int,int],int proc rotateLeft[T](arg: var openArray[T]; slice: HSlice[int, int]; dist: int): int 813 +nim rotateLeft algorithm.html#rotateLeft,openArray[T],int proc rotateLeft[T](arg: var openArray[T]; dist: int): int 851 +nim rotatedLeft algorithm.html#rotatedLeft,openArray[T],HSlice[int,int],int proc rotatedLeft[T](arg: openArray[T]; slice: HSlice[int, int]; dist: int): seq[T] 871 +nim rotatedLeft algorithm.html#rotatedLeft,openArray[T],int proc rotatedLeft[T](arg: openArray[T]; dist: int): seq[T] 901 +heading Basic usage algorithm.html#basic-usage Basic usage 0 +heading See also algorithm.html#see-also See also 0 +nimgrp rotateleft algorithm.html#rotateLeft-procs-all proc 813 +nimgrp sort algorithm.html#sort-procs-all proc 369 +nimgrp issorted algorithm.html#isSorted-procs-all proc 508 +nimgrp lowerbound algorithm.html#lowerBound-procs-all proc 222 +nimgrp reverse algorithm.html#reverse-procs-all proc 101 +nimgrp sorted algorithm.html#sorted-procs-all proc 432 +nimgrp reversed algorithm.html#reversed-procs-all proc 138 +nimgrp binarysearch algorithm.html#binarySearch-procs-all proc 160 +nimgrp merge algorithm.html#merge-procs-all proc 555 +nimgrp rotatedleft algorithm.html#rotatedLeft-procs-all proc 871 +nimgrp fill algorithm.html#fill-procs-all proc 77 +nimgrp upperbound algorithm.html#upperBound-procs-all proc 272 diff --git a/apis.html b/apis.html new file mode 100644 index 0000000000000..3d88aadfb5915 --- /dev/null +++ b/apis.html @@ -0,0 +1,92 @@ + + + + + + + +API naming design + + + + + + + + + + + + + + + + +
+
+

API naming design

+

The API is designed to be easy to use and consistent. Ease of use is measured by the number of calls to achieve a concrete high-level action.

+ +

Naming scheme

The library uses a simple naming scheme that makes use of common abbreviations to keep the names short but meaningful. Since version 0.8.2 many symbols have been renamed to fit this scheme. The ultimate goal is that the programmer can guess a name.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
English wordTo useNotes
initializeinitT init is used to create a value type T
newnewP new is used to create a reference type P
findfindshould return the position where something was found; for a bool result use contains
containscontainsoften short for find() >= 0
appendadduse add instead of append
comparecmpshould return an int with the < 0 == 0 or > 0 semantics; for a bool result use sameXYZ
putput, []=consider overloading []= for put
getget, []consider overloading [] for get; consider to not use get as a prefix: len instead of getLen
lengthlenalso used for number of elements
sizesize, lensize should refer to a byte size
capacitycap
memorymemimplies a low-level operation
itemsitemsdefault iterator over a collection
pairspairsiterator over (key, value) pairs
deletedelete, deldel is supposed to be faster than delete, because it does not keep the order; delete keeps the order
removedelete, delinconsistent right now
remove-and-returnpopTable/TableRef alias to take
includeincl
excludeexcl
commandcmd
executeexec
environmentenv
variablevar
valuevalue, val val is preferred, inconsistent right now
executableexe
directorydir
pathpathpath is the string "/usr/bin" (for example), dir is the content of "/usr/bin"; inconsistent right now
extensionext
separatorsep
columncol, column col is preferred, inconsistent right now
applicationapp
configurationcfg
messagemsg
argumentarg
objectobj
parameterparam
operatoropr
procedureproc
functionfunc
coordinatecoord
rectanglerect
pointpoint
symbolsym
literallit
stringstr
identifierident
indentationindent
+ + + +
+
+ + + + diff --git a/apis.idx b/apis.idx new file mode 100644 index 0000000000000..eb91544f932ab --- /dev/null +++ b/apis.idx @@ -0,0 +1,2 @@ +markupTitle API naming design apis.html API naming design 0 +heading Naming scheme apis.html#naming-scheme Naming scheme 0 diff --git a/appdirs.html b/appdirs.html new file mode 100644 index 0000000000000..131b2c56f92c0 --- /dev/null +++ b/appdirs.html @@ -0,0 +1,250 @@ + + + + + + + +std/appdirs + + + + + + + + + + + + + + + + +
+
+

std/appdirs

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements helpers for determining special directories used by apps.

+ +
+

Procs

+
+
+
+
proc getCacheDir(): Path {.inline, ...raises: [], tags: [ReadEnvEffect],
+                           forbids: [].}
+
+ +

Returns the cache directory of the current user for applications.

+

This makes use of the following environment variables:

+
  • On Windows: getEnv("LOCALAPPDATA")
  • +
  • On macOS: getEnv("XDG_CACHE_HOME", getEnv("HOME") / "Library/Caches")
  • +
  • On other platforms: getEnv("XDG_CACHE_HOME", getEnv("HOME") / ".cache")
  • +
+

See also:

+ + + Source   +Edit   + +
+
+
+
proc getCacheDir(app: Path): Path {.inline, ...raises: [], tags: [ReadEnvEffect],
+                                    forbids: [].}
+
+ + Returns the cache directory for an application app.
  • On Windows, this uses: getCacheDir() / app / "cache"
  • +
  • On other platforms, this uses: getCacheDir() / app
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
proc getConfigDir(): Path {.inline, ...tags: [ReadEnvEffect, ReadIOEffect],
+                            raises: [], forbids: [].}
+
+ +

Returns the config directory of the current user for applications.

+

On non-Windows OSs, this proc conforms to the XDG Base Directory spec. Thus, this proc returns the value of the XDG_CONFIG_HOME environment variable if it is set, otherwise it returns the default configuration directory ("~/.config/").

+

An OS-dependent trailing slash is always present at the end of the returned string: \\ on Windows and / on all other OSs.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getDataDir(): Path {.inline, ...tags: [ReadEnvEffect, ReadIOEffect],
+                          raises: [], forbids: [].}
+
+ +

Returns the data directory of the current user for applications.

+

On non-Windows OSs, this proc conforms to the XDG Base Directory spec. Thus, this proc returns the value of the XDG_DATA_HOME environment variable if it is set, otherwise it returns the default configuration directory ("~/.local/share" or "~/Library/Application Support" on macOS).

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getHomeDir(): Path {.inline, ...tags: [ReadEnvEffect, ReadIOEffect],
+                          raises: [], forbids: [].}
+
+ +

Returns the home directory of the current user.

+

This proc is wrapped by the paths: expandTilde proc for the convenience of processing paths coming from user configuration files.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getTempDir(): Path {.inline, ...tags: [ReadEnvEffect, ReadIOEffect],
+                          raises: [], forbids: [].}
+
+ +

Returns the temporary directory of the current user for applications to save temporary files in.

+

On Windows, it calls GetTempPath. On Posix based platforms, it will check TMPDIR, TEMP, TMP and TEMPDIR environment variables in order. On all platforms, /tmp will be returned if the procs fails.

+

You can override this implementation by adding -d:tempDir=mytempname to your compiler invocation.

+
Note: +This proc does not check whether the returned path exists.
+

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/appdirs.idx b/appdirs.idx new file mode 100644 index 0000000000000..67cba093a89d3 --- /dev/null +++ b/appdirs.idx @@ -0,0 +1,8 @@ +nimTitle appdirs appdirs.html module std/appdirs 0 +nim getHomeDir appdirs.html#getHomeDir proc getHomeDir(): Path 9 +nim getDataDir appdirs.html#getDataDir proc getDataDir(): Path 20 +nim getConfigDir appdirs.html#getConfigDir proc getConfigDir(): Path 37 +nim getCacheDir appdirs.html#getCacheDir proc getCacheDir(): Path 53 +nim getCacheDir appdirs.html#getCacheDir,Path proc getCacheDir(app: Path): Path 71 +nim getTempDir appdirs.html#getTempDir proc getTempDir(): Path 78 +nimgrp getcachedir appdirs.html#getCacheDir-procs-all proc 53 diff --git a/asciitables.html b/asciitables.html new file mode 100644 index 0000000000000..cc42f6c75abbb --- /dev/null +++ b/asciitables.html @@ -0,0 +1,172 @@ + + + + + + + +std/private/asciitables + + + + + + + + + + + + + + + + +
+
+

std/private/asciitables

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
+

Types

+
+
+
Cell = object
+  text*: string
+  width*, row*, col*, ncols*, nrows*: int
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc alignTable(s: string; delim = '\t'; fill = ' '; sep = " "): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Formats a delim-delimited s representing a table; each cell is aligned to a width that's computed for each column; consecutive columns are delimited by sep, and alignment space is filled using fill. More customized formatting can be done by calling parseTableCells directly. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator parseTableCells(s: string; delim = '\t'): Cell {....raises: [], tags: [],
+    forbids: [].}
+
+ + Iterates over all cells in a delim-delimited s, after a 1st pass that computes number of rows, columns, and width of each column. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/asciitables.idx b/asciitables.idx new file mode 100644 index 0000000000000..eb682bcc84736 --- /dev/null +++ b/asciitables.idx @@ -0,0 +1,4 @@ +nimTitle asciitables asciitables.html module std/private/asciitables 0 +nim Cell asciitables.html#Cell object Cell 6 +nim parseTableCells asciitables.html#parseTableCells.i,string,char iterator parseTableCells(s: string; delim = '\t'): Cell 10 +nim alignTable asciitables.html#alignTable,string,char,char,string proc alignTable(s: string; delim = '\t'; fill = ' '; sep = " "): string 71 diff --git a/assertions.html b/assertions.html new file mode 100644 index 0000000000000..3ed281f28991d --- /dev/null +++ b/assertions.html @@ -0,0 +1,241 @@ + + + + + + + +std/assertions + + + + + + + + + + + + + + + + +
+
+

std/assertions

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements assertion handling.

+
+

Imports

+
+ miscdollars +
+
+
+

Procs

+
+
+
+
proc failedAssertImpl(msg: string) {....raises: [], tags: [], forbids: [].}
+
+ + Raises an AssertionDefect with msg, but this is hidden from the effect system. Called when an assertion failed. + Source   +Edit   + +
+
+ +
+
+
+
proc raiseAssert(msg: string) {.noinline, noreturn, nosinks, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + Raises an AssertionDefect with msg. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template assert(cond: untyped; msg = "")
+
+ +

Raises AssertionDefect with msg if cond is false. Note that AssertionDefect is hidden from the effect system, so it doesn't produce {.raises: [AssertionDefect].}. This exception is only supposed to be caught by unit testing frameworks.

+

No code will be generated for assert when passing -d:danger (implied by --assertions:off). See command line switches.

+ +

Example:

+
assert 1 == 1
+

Example: cmd: --assertions:off

+
assert 1 == 2 # no code generated, no failure here
+

Example: cmd: -d:danger

+
assert 1 == 2 # ditto
+ Source   +Edit   + +
+
+ +
+
+
+
template doAssert(cond: untyped; msg = "")
+
+ + Similar to assert but is always turned on regardless of --assertions. +

Example:

+
doAssert 1 == 1 # generates code even when built with `-d:danger` or `--assertions:off`
+ Source   +Edit   + +
+
+ +
+
+
+
template doAssertRaises(exception: typedesc; code: untyped)
+
+ + Raises AssertionDefect if specified code does not raise exception. +

Example:

+
doAssertRaises(ValueError): raise newException(ValueError, "Hello World")
+doAssertRaises(CatchableError): raise newException(ValueError, "Hello World")
+doAssertRaises(AssertionDefect): doAssert false
+ Source   +Edit   + +
+
+ +
+
+
+
template onFailedAssert(msg, code: untyped): untyped {.dirty.}
+
+ + Sets an assertion failure handler that will intercept any assert statements following onFailedAssert in the current scope. +

Example:

+
type MyError = object of CatchableError
+  lineinfo: tuple[filename: string, line: int, column: int]
+# block-wide policy to change the failed assert exception type in order to
+# include a lineinfo
+onFailedAssert(msg):
+  raise (ref MyError)(msg: msg, lineinfo: instantiationInfo(-2))
+doAssertRaises(MyError): doAssert false
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/assertions.idx b/assertions.idx new file mode 100644 index 0000000000000..f6d0da2fc3fe3 --- /dev/null +++ b/assertions.idx @@ -0,0 +1,7 @@ +nimTitle assertions assertions.html module std/assertions 0 +nim raiseAssert assertions.html#raiseAssert,string proc raiseAssert(msg: string) 31 +nim failedAssertImpl assertions.html#failedAssertImpl,string proc failedAssertImpl(msg: string) 38 +nim assert assertions.html#assert.t,untyped,string template assert(cond: untyped; msg = "") 54 +nim doAssert assertions.html#doAssert.t,untyped,string template doAssert(cond: untyped; msg = "") 68 +nim onFailedAssert assertions.html#onFailedAssert.t,untyped,untyped template onFailedAssert(msg, code: untyped): untyped 74 +nim doAssertRaises assertions.html#doAssertRaises.t,typedesc,untyped template doAssertRaises(exception: typedesc; code: untyped) 91 diff --git a/async.html b/async.html new file mode 100644 index 0000000000000..0f9416b637146 --- /dev/null +++ b/async.html @@ -0,0 +1,88 @@ + + + + + + + +std/async + + + + + + + + + + + + + + + + +
+
+

std/async

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Exports asyncmacro and asyncfutures for native backends, and asyncjs on the JS backend.

+ + +
+
+ + +
+
+ + + + diff --git a/async.idx b/async.idx new file mode 100644 index 0000000000000..30a67d8174095 --- /dev/null +++ b/async.idx @@ -0,0 +1 @@ +nimTitle async async.html module std/async 0 diff --git a/asyncdispatch.html b/asyncdispatch.html new file mode 100644 index 0000000000000..01a4712c54a15 --- /dev/null +++ b/asyncdispatch.html @@ -0,0 +1,1087 @@ + + + + + + + +std/asyncdispatch + + + + + + + + + + + + + + + + +
+
+

std/asyncdispatch

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements asynchronous IO. This includes a dispatcher, a Future type implementation, and an async macro which allows asynchronous code to be written in a synchronous style with the await keyword.

+

The dispatcher acts as a kind of event loop. You must call poll on it (or a function which does so for you such as waitFor or runForever) in order to poll for any outstanding events. The underlying implementation is based on epoll on Linux, IO Completion Ports on Windows and select on other operating systems.

+

The poll function will not, on its own, return any events. Instead an appropriate Future object will be completed. A Future is a type which holds a value which is not yet available, but which may be available in the future. You can check whether a future is finished by using the finished function. When a future is finished it means that either the value that it holds is now available or it holds an error instead. The latter situation occurs when the operation to complete a future fails with an exception. You can distinguish between the two situations with the failed function.

+

Future objects can also store a callback procedure which will be called automatically once the future completes.

+

Futures therefore can be thought of as an implementation of the proactor pattern. In this pattern you make a request for an action, and once that action is fulfilled a future is completed with the result of that action. Requests can be made by calling the appropriate functions. For example: calling the recv function will create a request for some data to be read from a socket. The future which the recv function returns will then complete once the requested amount of data is read or an exception occurs.

+

Code to read some data from a socket may look something like this:

+

var future = socket.recv(100)
+future.addCallback(
+  proc () =
+    echo(future.read)
+)

+

All asynchronous functions returning a Future will not block. They will not however return immediately. An asynchronous function will have code which will be executed before an asynchronous request is made, in most cases this code sets up the request.

+

In the above example, the recv function will return a brand new Future instance once the request for data to be read from the socket is made. This Future instance will complete once the requested amount of data is read, in this case it is 100 bytes. The second line sets a callback on this future which will be called once the future completes. All the callback does is write the data stored in the future to stdout. The read function is used for this and it checks whether the future completes with an error for you (if it did, it will simply raise the error), if there is no error, however, it returns the value of the future.

+ +

Asynchronous procedures

Asynchronous procedures remove the pain of working with callbacks. They do this by allowing you to write asynchronous code the same way as you would write synchronous code.

+

An asynchronous procedure is marked using the {.async.} pragma. When marking a procedure with the {.async.} pragma it must have a Future[T] return type or no return type at all. If you do not specify a return type then Future[void] is assumed.

+

Inside asynchronous procedures await can be used to call any procedures which return a Future; this includes asynchronous procedures. When a procedure is "awaited", the asynchronous procedure it is awaited in will suspend its execution until the awaited procedure's Future completes. At which point the asynchronous procedure will resume its execution. During the period when an asynchronous procedure is suspended other asynchronous procedures will be run by the dispatcher.

+

The await call may be used in many contexts. It can be used on the right hand side of a variable declaration: var data = await socket.recv(100), in which case the variable will be set to the value of the future automatically. It can be used to await a Future object, and it can be used to await a procedure returning a Future[void]: await socket.send("foobar").

+

If an awaited future completes with an error, then await will re-raise this error. To avoid this, you can use the yield keyword instead of await. The following section shows different ways that you can handle exceptions in async procs.

+
Caution: +Procedures marked {.async.} do not support mutable parameters such as var int. References such as ref int should be used instead.
+ +

Handling Exceptions

You can handle exceptions in the same way as in ordinary Nim code; by using the try statement:

+

try:
+  let data = await sock.recv(100)
+  echo("Received ", data)
+except:
+  # Handle exception

+

An alternative approach to handling exceptions is to use yield on a future then check the future's failed property. For example:

+

var future = sock.recv(100)
+yield future
+if future.failed:
+  # Handle exception

+ +

Discarding futures

Futures should never be discarded directly because they may contain errors. If you do not care for the result of a Future then you should use the asyncCheck procedure instead of the discard keyword. Note that this does not wait for completion, and you should use waitFor or await for that purpose.

+
Note: +await also checks if the future fails, so you can safely discard its result.
+ +

Handling futures

There are many different operations that apply to a future. The three primary high-level operations are asyncCheck, waitFor, and await.

+
  • asyncCheck: Raises an exception if the future fails. It neither waits for the future to finish nor returns the result of the future.
  • +
  • waitFor: Polls the event loop and blocks the current thread until the future finishes. This is often used to call an async procedure from a synchronous context and should never be used in an async proc.
  • +
  • await: Pauses execution in the current async procedure until the future finishes. While the current procedure is paused, other async procedures will continue running. Should be used instead of waitFor in an async procedure.
  • +
+

Here is a handy quick reference chart showing their high-level differences:

+ + + + +
ProcedureContextBlocking
asyncChecknon-async and asyncnon-blocking
waitFornon-asyncblocks current thread
awaitasyncsuspends current proc
+

Examples

For examples take a look at the documentation for the modules implementing asynchronous IO. A good place to start is the asyncnet module.

+ +

Investigating pending futures

It's possible to get into a situation where an async proc, or more accurately a Future[T] gets stuck and never completes. This can happen for various reasons and can cause serious memory leaks. When this occurs it's hard to identify the procedure that is stuck.

+

Thankfully there is a mechanism which tracks the count of each pending future. All you need to do to enable it is compile with -d:futureLogging and use the getFuturesInProgress procedure to get the list of pending futures together with the stack traces to the moment of their creation.

+

You may also find it useful to use this prometheus package which will log the pending futures into prometheus, allowing you to analyse them via a nice graph.

+ +

Limitations/Bugs

  • The effect system (raises: []) does not work with async procedures.
  • +
  • Mutable parameters are not supported by async procedures.
  • +
+ +

Multiple async backend support

Thanks to its powerful macro support, Nim allows async/await to be implemented in libraries with only minimal support from the language - as such, multiple async libraries exist, including asyncdispatch and chronos, and more may come to be developed in the future.

+

Libraries built on top of async/await may wish to support multiple async backends - the best way to do so is to create separate modules for each backend that may be imported side-by-side.

+

An alternative way is to select backend using a global compile flag - this method makes it difficult to compose applications that use both backends as may happen with transitive dependencies, but may be appropriate in some cases - libraries choosing this path should call the flag asyncBackend, allowing applications to choose the backend with -d:asyncBackend=<backend_name>.

+

Known async backends include:

+ +

none can be used when a library supports both a synchronous and asynchronous API, to disable the latter.

+

+ +
+

Types

+
+
+
AsyncEvent = ptr AsyncEventImpl
+
+ + + Source   +Edit   + +
+
+
+
AsyncFD = distinct int
+
+ + + Source   +Edit   + +
+
+
+
Callback = proc (fd: AsyncFD): bool {.closure, ...gcsafe.}
+
+ + + Source   +Edit   + +
+
+
+
CompletionData = object
+  fd*: AsyncFD
+  cb*: owned(proc (fd: AsyncFD; bytesTransferred: DWORD; errcode: OSErrorCode) {.
+      closure, ...gcsafe.})
+  cell*: ForeignCell
+
+ + + Source   +Edit   + +
+
+
+
CustomRef = ref CustomObj
+
+ + + Source   +Edit   + +
+
+
+
PDispatcher = ref object of PDispatcherBase
+  handles*: HashSet[AsyncFD]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `==`(x: AsyncFD; y: AsyncFD): bool {.borrow, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc accept(socket: AsyncFD; flags = {SafeDisconn};
+            inheritable = defined(nimInheritHandles)): owned(Future[AsyncFD]) {.
+    ...raises: [ValueError, OSError, Exception], tags: [RootEffect], forbids: [].}
+
+ +

Accepts a new connection. Returns a future containing the client socket corresponding to that connection.

+

If inheritable is false (the default), the resulting client socket will not be inheritable by child processes.

+

The future will complete when the connection is successfully accepted.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc acceptAddr(socket: AsyncFD; flags = {SafeDisconn};
+                inheritable = defined(nimInheritHandles)): owned(
+    Future[tuple[address: string, client: AsyncFD]]) {....gcsafe,
+    raises: [ValueError, OSError, Exception, ValueError, Exception],
+    tags: [RootEffect], forbids: [].}
+
+ +

Accepts a new connection. Returns a future containing the client socket corresponding to that connection and the remote address of the client. The future will complete when the connection is successfully accepted.

+

The resulting client socket is automatically registered to the dispatcher.

+

If inheritable is false (the default), the resulting client socket will not be inheritable by child processes.

+

The accept call may result in an error if the connecting socket disconnects during the duration of the accept. If the SafeDisconn flag is specified then this error will not be raised and instead accept will be called again.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc activeDescriptors(): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Returns the current number of active file descriptors for the current event loop. This is a cheap operation that does not involve a system call. + Source   +Edit   + +
+
+ +
+
+
+
proc addEvent(ev: AsyncEvent; cb: Callback) {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ + Registers callback cb to be called when ev will be signaled + Source   +Edit   + +
+
+ +
+
+
+
proc addProcess(pid: int; cb: Callback) {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ + Registers callback cb to be called when process with process ID pid exited. + Source   +Edit   + +
+
+ +
+
+
+
proc addRead(fd: AsyncFD; cb: Callback) {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ +

Start watching the file descriptor for read availability and then call the callback cb.

+

This is not pure mechanism for Windows Completion Ports (IOCP), so if you can avoid it, please do it. Use addRead only if really need it (main usecase is adaptation of unix-like libraries to be asynchronous on Windows).

+

If you use this function, you don't need to use asyncdispatch.recv() or asyncdispatch.accept(), because they are using IOCP, please use nativesockets.recv() and nativesockets.accept() instead.

+

Be sure your callback cb returns true, if you want to remove watch of read notifications, and false, if you want to continue receiving notifications.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc addTimer(timeout: int; oneshot: bool; cb: Callback) {....raises: [OSError],
+    tags: [], forbids: [].}
+
+ +

Registers callback cb to be called when timer expired.

+

Parameters:

+
  • timeout - timeout value in milliseconds.
  • +
  • oneshot
    • true - generate only one timeout event
    • +
    • false - generate timeout events periodically
    • +
    +
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
proc addWrite(fd: AsyncFD; cb: Callback) {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ +

Start watching the file descriptor for write availability and then call the callback cb.

+

This is not pure mechanism for Windows Completion Ports (IOCP), so if you can avoid it, please do it. Use addWrite only if really need it (main usecase is adaptation of unix-like libraries to be asynchronous on Windows).

+

If you use this function, you don't need to use asyncdispatch.send() or asyncdispatch.connect(), because they are using IOCP, please use nativesockets.send() and nativesockets.connect() instead.

+

Be sure your callback cb returns true, if you want to remove watch of write notifications, and false, if you want to continue receiving notifications.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc callSoon(cbproc: proc () {....gcsafe.}) {....gcsafe, raises: [], tags: [],
+    forbids: [].}
+
+ + Schedule cbproc to be called as soon as possible. The callback is called when control returns to the event loop. + Source   +Edit   + +
+
+ +
+
+
+
proc close(ev: AsyncEvent) {....raises: [OSError], tags: [], forbids: [].}
+
+ + Closes event ev. + Source   +Edit   + +
+
+ +
+
+
+
proc closeSocket(socket: AsyncFD) {....raises: [], tags: [], forbids: [].}
+
+ + Closes a socket and ensures that it is unregistered. + Source   +Edit   + +
+
+ +
+
+
+
proc connect(socket: AsyncFD; address: string; port: Port;
+             domain = Domain.AF_INET): owned(Future[void]) {.
+    ...raises: [OSError, IOError, ValueError, Exception], tags: [RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc contains(disp: PDispatcher; fd: AsyncFD): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createAsyncNativeSocket(domain: cint; sockType: cint; protocol: cint;
+                             inheritable = defined(nimInheritHandles)): AsyncFD {.
+    ...raises: [OSError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc createAsyncNativeSocket(domain: Domain = Domain.AF_INET;
+                             sockType: SockType = SOCK_STREAM;
+                             protocol: Protocol = IPPROTO_TCP;
+                             inheritable = defined(nimInheritHandles)): AsyncFD {.
+    ...raises: [OSError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc dial(address: string; port: Port; protocol: Protocol = IPPROTO_TCP): owned(
+    Future[AsyncFD]) {....raises: [OSError, ValueError, Exception],
+                       tags: [RootEffect], forbids: [].}
+
+ + Establishes connection to the specified address:port pair via the specified protocol. The procedure iterates through possible resolutions of the address until it succeeds, meaning that it seamlessly works with both IPv4 and IPv6. Returns the async file descriptor, registered in the dispatcher of the current thread, ready to send or receive data. + Source   +Edit   + +
+
+ +
+
+
+
proc drain(timeout = 500) {....raises: [ValueError, Exception, OSError],
+                            tags: [TimeEffect, RootEffect], forbids: [].}
+
+ + Waits for completion of all events and processes them. Raises ValueError if there are no pending operations. In contrast to poll this processes as many events as are available until the timeout has elapsed. + Source   +Edit   + +
+
+ +
+
+
+
proc getGlobalDispatcher(): PDispatcher {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getIoHandler(disp: PDispatcher): Handle {....raises: [], tags: [], forbids: [].}
+
+ + Returns the underlying IO Completion Port handle (Windows) or selector (Unix) for the specified dispatcher. + Source   +Edit   + +
+
+ +
+
+
+
proc hasPendingOperations(): bool {....raises: [], tags: [], forbids: [].}
+
+ + Returns true if the global dispatcher has pending operations. + Source   +Edit   + +
+
+ +
+
+
+
proc maxDescriptors(): int {....raises: OSError, tags: [], forbids: [].}
+
+ + Returns the maximum number of active file descriptors for the current process. This involves a system call. For now maxDescriptors is supported on the following OSes: Windows, Linux, OSX, BSD, Solaris. + Source   +Edit   + +
+
+ +
+
+
+
proc newAsyncEvent(): AsyncEvent {....raises: [OSError], tags: [], forbids: [].}
+
+ +

Creates a new thread-safe AsyncEvent object.

+

New AsyncEvent object is not automatically registered with dispatcher like AsyncSocket.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newCustom(): CustomRef {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newDispatcher(): owned PDispatcher {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new Dispatcher instance. + Source   +Edit   + +
+
+ +
+
+
+
proc poll(timeout = 500) {....raises: [ValueError, Exception, OSError],
+                           tags: [TimeEffect, RootEffect], forbids: [].}
+
+ + Waits for completion events and processes them. Raises ValueError if there are no pending operations. This runs the underlying OS epoll or kqueue primitive only once. + Source   +Edit   + +
+
+ +
+
+
+
proc readAll(future: FutureStream[string]): owned(Future[string]) {.
+    ...stackTrace: false, raises: [Exception, ValueError], tags: [RootEffect],
+    forbids: [].}
+
+ + Returns a future that will complete when all the string data from the specified future stream is retrieved. + Source   +Edit   + +
+
+ +
+
+
+
proc recv(socket: AsyncFD; size: int; flags = {SafeDisconn}): owned(
+    Future[string]) {....raises: [ValueError, Exception], tags: [RootEffect],
+                      forbids: [].}
+
+ + Reads up to size bytes from socket. Returned future will complete once all the data requested is read, a part of the data has been read, or the socket has disconnected in which case the future will complete with a value of "".
Warning: +The Peek socket flag is not supported on Windows.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc recvFromInto(socket: AsyncFD; data: pointer; size: int;
+                  saddr: ptr SockAddr; saddrLen: ptr SockLen;
+                  flags = {SafeDisconn}): owned(Future[int]) {.
+    ...raises: [ValueError, Exception], tags: [RootEffect], forbids: [].}
+
+ + Receives a datagram data from socket into buf, which must be at least of size size, address of datagram's sender will be stored into saddr and saddrLen. Returned future will complete once one datagram has been received, and will return size of packet received. + Source   +Edit   + +
+
+ +
+
+
+
proc recvInto(socket: AsyncFD; buf: pointer; size: int; flags = {SafeDisconn}): owned(
+    Future[int]) {....raises: [ValueError, Exception], tags: [RootEffect],
+                   forbids: [].}
+
+ + Reads up to size bytes from socket into buf, which must at least be of that size. Returned future will complete once all the data requested is read, a part of the data has been read, or the socket has disconnected in which case the future will complete with a value of 0.
Warning: +The Peek socket flag is not supported on Windows.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc register(fd: AsyncFD) {....raises: [OSError], tags: [], forbids: [].}
+
+ + Registers fd with the dispatcher. + Source   +Edit   + +
+
+ +
+
+
+
proc runForever() {....raises: [ValueError, Exception, OSError],
+                    tags: [TimeEffect, RootEffect], forbids: [].}
+
+ + Begins a never ending global dispatcher poll loop. + Source   +Edit   + +
+
+ +
+
+
+
proc send(socket: AsyncFD; buf: pointer; size: int; flags = {SafeDisconn}): owned(
+    Future[void]) {....raises: [ValueError, Exception], tags: [RootEffect],
+                    forbids: [].}
+
+ + Sends size bytes from buf to socket. The returned future will complete once all data has been sent.
Warning: +Use it with caution. If buf refers to GC'ed object, you must use GC_ref/GC_unref calls to avoid early freeing of the buffer.
+ + Source   +Edit   + +
+
+
+
proc send(socket: AsyncFD; data: string; flags = {SafeDisconn}): owned(
+    Future[void]) {....raises: [ValueError, Exception], tags: [RootEffect],
+                    forbids: [].}
+
+ + Sends data to socket. The returned future will complete once all data has been sent. + Source   +Edit   + +
+
+ +
+
+
+
proc sendTo(socket: AsyncFD; data: pointer; size: int; saddr: ptr SockAddr;
+            saddrLen: SockLen; flags = {SafeDisconn}): owned(Future[void]) {.
+    ...raises: [ValueError, Exception], tags: [RootEffect], forbids: [].}
+
+ + Sends data to specified destination saddr, using socket socket. The returned future will complete once all data has been sent. + Source   +Edit   + +
+
+ +
+
+
+
proc setGlobalDispatcher(disp: sink PDispatcher) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setInheritable(fd: AsyncFD; inheritable: bool): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Control whether a file handle can be inherited by child processes. Returns true on success.

+

This procedure is not guaranteed to be available for all platforms. Test for availability with declared().

+ + Source   +Edit   + +
+
+ +
+
+
+
proc sleepAsync(ms: int | float): owned(Future[void])
+
+ + Suspends the execution of the current async procedure for the next ms milliseconds. + Source   +Edit   + +
+
+ +
+
+
+
proc trigger(ev: AsyncEvent) {....raises: [OSError], tags: [], forbids: [].}
+
+ + Set event ev to signaled state. + Source   +Edit   + +
+
+ +
+
+
+
proc unregister(ev: AsyncEvent) {....raises: [OSError], tags: [], forbids: [].}
+
+ + Unregisters event ev. + Source   +Edit   + +
+
+
+
proc unregister(fd: AsyncFD) {....raises: [], tags: [], forbids: [].}
+
+ + Unregisters fd. + Source   +Edit   + +
+
+ +
+
+
+
proc waitFor[T](fut: Future[T]): T
+
+ + Blocks the current thread until the specified future completes. + Source   +Edit   + +
+
+ +
+
+
+
proc withTimeout[T](fut: Future[T]; timeout: int): owned(Future[bool])
+
+ +

Returns a future which will complete once fut completes or after timeout milliseconds has elapsed.

+

If fut completes first the returned future will hold true, otherwise, if timeout milliseconds has elapsed first, the returned future will hold false.

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/asyncdispatch.idx b/asyncdispatch.idx new file mode 100644 index 0000000000000..e72f190264633 --- /dev/null +++ b/asyncdispatch.idx @@ -0,0 +1,63 @@ +nimTitle asyncdispatch asyncdispatch.html module std/asyncdispatch 0 +nim callSoon asyncdispatch.html#callSoon,proc) proc callSoon(cbproc: proc () {.gcsafe.}) 286 +nim CompletionData asyncdispatch.html#CompletionData object CompletionData 309 +nim PDispatcher asyncdispatch.html#PDispatcher type PDispatcher 317 +nim CustomRef asyncdispatch.html#CustomRef type CustomRef 324 +nim AsyncFD asyncdispatch.html#AsyncFD type AsyncFD 326 +nim AsyncEvent asyncdispatch.html#AsyncEvent type AsyncEvent 339 +nim Callback asyncdispatch.html#Callback type Callback 341 +nim `==` asyncdispatch.html#==,AsyncFD,AsyncFD proc `==`(x: AsyncFD; y: AsyncFD): bool 344 +nim newDispatcher asyncdispatch.html#newDispatcher proc newDispatcher(): owned PDispatcher 346 +nim setGlobalDispatcher asyncdispatch.html#setGlobalDispatcher,sinkPDispatcher proc setGlobalDispatcher(disp: sink PDispatcher) 356 +nim getGlobalDispatcher asyncdispatch.html#getGlobalDispatcher proc getGlobalDispatcher(): PDispatcher 362 +nim getIoHandler asyncdispatch.html#getIoHandler,PDispatcher proc getIoHandler(disp: PDispatcher): Handle 367 +nim register asyncdispatch.html#register,AsyncFD proc register(fd: AsyncFD) 372 +nim hasPendingOperations asyncdispatch.html#hasPendingOperations proc hasPendingOperations(): bool 390 +nim newCustom asyncdispatch.html#newCustom proc newCustom(): CustomRef 487 +nim recv asyncdispatch.html#recv,AsyncFD,int proc recv(socket: AsyncFD; size: int; flags = {SafeDisconn}): owned(Future[string]) 494 +nim recvInto asyncdispatch.html#recvInto,AsyncFD,pointer,int proc recvInto(socket: AsyncFD; buf: pointer; size: int; flags = {SafeDisconn}): owned(\n Future[int]) 567 +nim send asyncdispatch.html#send,AsyncFD,pointer,int proc send(socket: AsyncFD; buf: pointer; size: int; flags = {SafeDisconn}): owned(\n Future[void]) 633 +nim sendTo asyncdispatch.html#sendTo,AsyncFD,pointer,int,ptr.SockAddr,SockLen proc sendTo(socket: AsyncFD; data: pointer; size: int; saddr: ptr SockAddr;\n saddrLen: SockLen; flags = {SafeDisconn}): owned(Future[void]) 678 +nim recvFromInto asyncdispatch.html#recvFromInto,AsyncFD,pointer,int,ptr.SockAddr,ptr.SockLen proc recvFromInto(socket: AsyncFD; data: pointer; size: int; saddr: ptr SockAddr;\n saddrLen: ptr SockLen; flags = {SafeDisconn}): owned(Future[int]) 723 +nim acceptAddr asyncdispatch.html#acceptAddr,AsyncFD proc acceptAddr(socket: AsyncFD; flags = {SafeDisconn};\n inheritable = defined(nimInheritHandles)): owned(\n Future[tuple[address: string, client: AsyncFD]]) 771 +nim setInheritable asyncdispatch.html#setInheritable,AsyncFD,bool proc setInheritable(fd: AsyncFD; inheritable: bool): bool 868 +nim closeSocket asyncdispatch.html#closeSocket,AsyncFD proc closeSocket(socket: AsyncFD) 870 +nim unregister asyncdispatch.html#unregister,AsyncFD proc unregister(fd: AsyncFD) 875 +nim contains asyncdispatch.html#contains,PDispatcher,AsyncFD proc contains(disp: PDispatcher; fd: AsyncFD): bool 879 +nim addRead asyncdispatch.html#addRead,AsyncFD,Callback proc addRead(fd: AsyncFD; cb: Callback) 974 +nim addWrite asyncdispatch.html#addWrite,AsyncFD,Callback proc addWrite(fd: AsyncFD; cb: Callback) 992 +nim addTimer asyncdispatch.html#addTimer,int,bool,Callback proc addTimer(timeout: int; oneshot: bool; cb: Callback) 1045 +nim addProcess asyncdispatch.html#addProcess,int,Callback proc addProcess(pid: int; cb: Callback) 1079 +nim newAsyncEvent asyncdispatch.html#newAsyncEvent proc newAsyncEvent(): AsyncEvent 1098 +nim trigger asyncdispatch.html#trigger,AsyncEvent proc trigger(ev: AsyncEvent) 1113 +nim unregister asyncdispatch.html#unregister,AsyncEvent proc unregister(ev: AsyncEvent) 1118 +nim close asyncdispatch.html#close,AsyncEvent proc close(ev: AsyncEvent) 1129 +nim addEvent asyncdispatch.html#addEvent,AsyncEvent,Callback proc addEvent(ev: AsyncEvent; cb: Callback) 1136 +nim drain asyncdispatch.html#drain,int proc drain(timeout = 500) 1695 +nim poll asyncdispatch.html#poll,int proc poll(timeout = 500) 1707 +nim createAsyncNativeSocket asyncdispatch.html#createAsyncNativeSocket,cint,cint,cint proc createAsyncNativeSocket(domain: cint; sockType: cint; protocol: cint;\n inheritable = defined(nimInheritHandles)): AsyncFD 1724 +nim createAsyncNativeSocket asyncdispatch.html#createAsyncNativeSocket,Domain,SockType,Protocol proc createAsyncNativeSocket(domain: Domain = Domain.AF_INET;\n sockType: SockType = SOCK_STREAM;\n protocol: Protocol = IPPROTO_TCP;\n inheritable = defined(nimInheritHandles)): AsyncFD 1729 +nim dial asyncdispatch.html#dial,string,Port,Protocol proc dial(address: string; port: Port; protocol: Protocol = IPPROTO_TCP): owned(\n Future[AsyncFD]) 1889 +nim connect asyncdispatch.html#connect,AsyncFD,string,Port proc connect(socket: AsyncFD; address: string; port: Port; domain = Domain.AF_INET): owned(\n Future[void]) 1904 +nim sleepAsync asyncdispatch.html#sleepAsync proc sleepAsync(ms: int | float): owned(Future[void]) 1919 +nim withTimeout asyncdispatch.html#withTimeout,Future[T],int proc withTimeout[T](fut: Future[T]; timeout: int): owned(Future[bool]) 1931 +nim accept asyncdispatch.html#accept,AsyncFD proc accept(socket: AsyncFD; flags = {SafeDisconn};\n inheritable = defined(nimInheritHandles)): owned(Future[AsyncFD]) 1953 +nim send asyncdispatch.html#send,AsyncFD,string proc send(socket: AsyncFD; data: string; flags = {SafeDisconn}): owned(Future[void]) 1977 +nim readAll asyncdispatch.html#readAll,FutureStream[string] proc readAll(future: FutureStream[string]): owned(Future[string]) 2000 +nim runForever asyncdispatch.html#runForever proc runForever() 2014 +nim waitFor asyncdispatch.html#waitFor,Future[T] proc waitFor[T](fut: Future[T]): T 2019 +nim activeDescriptors asyncdispatch.html#activeDescriptors proc activeDescriptors(): int 2026 +nim maxDescriptors asyncdispatch.html#maxDescriptors proc maxDescriptors(): int 2039 +heading Asynchronous procedures asyncdispatch.html#asynchronous-procedures Asynchronous procedures 0 +heading Handling Exceptions asyncdispatch.html#asynchronous-procedures-handling-exceptions Handling Exceptions 0 +heading Discarding futures asyncdispatch.html#discarding-futures Discarding futures 0 +heading Handling futures asyncdispatch.html#handling-futures Handling futures 0 +heading Examples asyncdispatch.html#examples Examples 0 +heading Investigating pending futures asyncdispatch.html#investigating-pending-futures Investigating pending futures 0 +heading Limitations/Bugs asyncdispatch.html#limitationsslashbugs Limitations/Bugs 0 +heading Multiple async backend support asyncdispatch.html#multiple-async-backend-support Multiple async backend support 0 +idx epoll asyncdispatch.html#epoll_1 Multiple async backend support 0 +idx kqueue asyncdispatch.html#kqueue_1 Multiple async backend support 0 +nimgrp createasyncnativesocket asyncdispatch.html#createAsyncNativeSocket-procs-all proc 1724 +nimgrp send asyncdispatch.html#send-procs-all proc 633 +nimgrp unregister asyncdispatch.html#unregister-procs-all proc 875 diff --git a/asyncfile.html b/asyncfile.html new file mode 100644 index 0000000000000..c4b2bfff8500a --- /dev/null +++ b/asyncfile.html @@ -0,0 +1,417 @@ + + + + + + + +std/asyncfile + + + + + + + + + + + + + + + + +
+
+

std/asyncfile

+
+ +
+ Source   +Edit   + +
+ +

This module implements asynchronous file reading and writing.

+

import std/[asyncfile, asyncdispatch, os]
+
+proc main() {.async.} =
+  var file = openAsync(getTempDir() / "foobar.txt", fmReadWrite)
+  await file.write("test")
+  file.setFilePos(0)
+  let data = await file.readAll()
+  doAssert data == "test"
+  file.close()
+
+waitFor main()

+

+ +
+

Types

+
+
+
AsyncFile = ref object
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc close(f: AsyncFile) {....raises: [OSError], tags: [], forbids: [].}
+
+ + Closes the file specified. + Source   +Edit   + +
+
+ +
+
+
+
proc getFilePos(f: AsyncFile): int64 {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the current position of the file pointer that is used to read from the specified file. The file's first byte has the index zero. + Source   +Edit   + +
+
+ +
+
+
+
proc getFileSize(f: AsyncFile): int64 {....raises: [OSError], tags: [], forbids: [].}
+
+ + Retrieves the specified file's size. + Source   +Edit   + +
+
+ +
+
+
+
proc newAsyncFile(fd: AsyncFD): AsyncFile {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ + Creates AsyncFile with a previously opened file descriptor fd. + Source   +Edit   + +
+
+ +
+
+
+
proc openAsync(filename: string; mode = fmRead): AsyncFile {....raises: [OSError],
+    tags: [], forbids: [].}
+
+ + Opens a file specified by the path in filename using the specified FileMode mode asynchronously. + Source   +Edit   + +
+
+ +
+
+
+
proc read(f: AsyncFile; size: int): Future[string] {.
+    ...raises: [ValueError, Exception], tags: [RootEffect], forbids: [].}
+
+ +

Read size bytes from the specified file asynchronously starting at the current position of the file pointer. size should be greater than zero.

+

If the file pointer is past the end of the file then an empty string is returned.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc readAll(f: AsyncFile): Future[string] {....stackTrace: false,
+    raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}
+
+ + Reads all data from the specified file. + Source   +Edit   + +
+
+ +
+
+
+
proc readBuffer(f: AsyncFile; buf: pointer; size: int): Future[int] {.
+    ...raises: [ValueError, Exception], tags: [RootEffect], forbids: [].}
+
+ +

Read size bytes from the specified file asynchronously starting at the current position of the file pointer.

+

If the file pointer is past the end of the file then zero is returned and no bytes are read into buf

+ + Source   +Edit   + +
+
+ +
+
+
+
proc readLine(f: AsyncFile): Future[string] {....stackTrace: false,
+    raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}
+
+ + Reads a single line from the specified file asynchronously. + Source   +Edit   + +
+
+ +
+
+
+
proc readToStream(f: AsyncFile; fs: FutureStream[string]): owned(
+    Future[void]) {....stackTrace: false, raises: [Exception], tags: [RootEffect],
+                    forbids: [].}
+
+ + Writes data to the specified future stream as the file is read. + Source   +Edit   + +
+
+ +
+
+
+
proc setFilePos(f: AsyncFile; pos: int64) {....raises: [], tags: [], forbids: [].}
+
+ + Sets the position of the file pointer that is used for read/write operations. The file's first byte has the index zero. + Source   +Edit   + +
+
+ +
+
+
+
proc setFileSize(f: AsyncFile; length: int64) {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ + Set a file length. + Source   +Edit   + +
+
+ +
+
+
+
proc write(f: AsyncFile; data: string): Future[void] {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ +

Writes data to the file specified asynchronously.

+

The returned Future will complete once all data has been written to the specified file.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc writeBuffer(f: AsyncFile; buf: pointer; size: int): Future[void] {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ +

Writes size bytes from buf to the file specified asynchronously.

+

The returned Future will complete once all data has been written to the specified file.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc writeFromStream(f: AsyncFile; fs: FutureStream[string]): owned(
+    Future[void]) {....stackTrace: false, raises: [Exception], tags: [RootEffect],
+                    forbids: [].}
+
+ +

Reads data from the specified future stream until it is completed. The data which is read is written to the file immediately and freed from memory.

+

This procedure is perfect for saving streamed data to a file without wasting memory.

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/asyncfile.idx b/asyncfile.idx new file mode 100644 index 0000000000000..a52ac8f30acbc --- /dev/null +++ b/asyncfile.idx @@ -0,0 +1,17 @@ +nimTitle asyncfile asyncfile.html module std/asyncfile 0 +nim AsyncFile asyncfile.html#AsyncFile type AsyncFile 41 +nim getFileSize asyncfile.html#getFileSize,AsyncFile proc getFileSize(f: AsyncFile): int64 78 +nim newAsyncFile asyncfile.html#newAsyncFile,AsyncFD proc newAsyncFile(fd: AsyncFD): AsyncFile 92 +nim openAsync asyncfile.html#openAsync,string proc openAsync(filename: string; mode = fmRead): AsyncFile 98 +nim readBuffer asyncfile.html#readBuffer,AsyncFile,pointer,int proc readBuffer(f: AsyncFile; buf: pointer; size: int): Future[int] 127 +nim read asyncfile.html#read,AsyncFile,int proc read(f: AsyncFile; size: int): Future[string] 204 +nim readLine asyncfile.html#readLine,AsyncFile proc readLine(f: AsyncFile): Future[string] 299 +nim getFilePos asyncfile.html#getFilePos,AsyncFile proc getFilePos(f: AsyncFile): int64 314 +nim setFilePos asyncfile.html#setFilePos,AsyncFile,int64 proc setFilePos(f: AsyncFile; pos: int64) 320 +nim readAll asyncfile.html#readAll,AsyncFile proc readAll(f: AsyncFile): Future[string] 329 +nim writeBuffer asyncfile.html#writeBuffer,AsyncFile,pointer,int proc writeBuffer(f: AsyncFile; buf: pointer; size: int): Future[void] 338 +nim write asyncfile.html#write,AsyncFile,string proc write(f: AsyncFile; data: string): Future[void] 407 +nim setFileSize asyncfile.html#setFileSize,AsyncFile,int64 proc setFileSize(f: AsyncFile; length: int64) 488 +nim close asyncfile.html#close,AsyncFile proc close(f: AsyncFile) 505 +nim writeFromStream asyncfile.html#writeFromStream,AsyncFile,FutureStream[string] proc writeFromStream(f: AsyncFile; fs: FutureStream[string]): owned(Future[void]) 515 +nim readToStream asyncfile.html#readToStream,AsyncFile,FutureStream[string] proc readToStream(f: AsyncFile; fs: FutureStream[string]): owned(Future[void]) 529 diff --git a/asyncftpclient.html b/asyncftpclient.html new file mode 100644 index 0000000000000..9ff35a7be2f15 --- /dev/null +++ b/asyncftpclient.html @@ -0,0 +1,578 @@ + + + + + + + +src/asyncftpclient + + + + + + + + + + + + + + + + +
+
+

src/asyncftpclient

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

Note: +In order to use this module, run nimble install asyncftpclient.
+

This module implements an asynchronous FTP client. It allows you to connect to an FTP server and perform operations on it such as for example:

+
  • The upload of new files.
  • +
  • The removal of existing files.
  • +
  • Download of files.
  • +
  • Changing of files' permissions.
  • +
  • Navigation through the FTP server's directories.
  • +
+ +

Connecting to an FTP server

In order to begin any sort of transfer of files you must first connect to an FTP server. You can do so with the connect procedure.

+

import std/asyncdispatch
+import pkg/asyncftpclient
+proc main() {.async.} =
+  var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test")
+  await ftp.connect()
+  echo("Connected")
+waitFor(main())

+

A new main async procedure must be declared to allow the use of the await keyword. The connection will complete asynchronously and the client will be connected after the await ftp.connect() call.

+ +

Uploading a new file

After a connection is made you can use the store procedure to upload a new file to the FTP server. Make sure to check you are in the correct working directory before you do so with the pwd procedure, you can also instead specify an absolute path.

+

import std/asyncdispatch
+import pkg/asyncftpclient
+proc main() {.async.} =
+  var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test")
+  await ftp.connect()
+  let currentDir = await ftp.pwd()
+  assert currentDir == "/home/user/"
+  await ftp.store("file.txt", "file.txt")
+  echo("File finished uploading")
+waitFor(main())

+ +

Checking the progress of a file transfer

The progress of either a file upload or a file download can be checked by specifying a onProgressChanged procedure to the store or retrFile procedures.

+

Procs that take an onProgressChanged callback will call this every progressInterval milliseconds.

+

import std/asyncdispatch
+import pkg/asyncftpclient
+
+proc onProgressChanged(total, progress: BiggestInt,
+                        speed: float) {.async.} =
+  echo("Uploaded ", progress, " of ", total, " bytes")
+  echo("Current speed: ", speed, " kb/s")
+
+proc main() {.async.} =
+  var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test", progressInterval = 500)
+  await ftp.connect()
+  await ftp.store("file.txt", "/home/user/file.txt", onProgressChanged)
+  echo("File finished uploading")
+waitFor(main())

+

+
+

Types

+
+
+
AsyncFtpClient = ref object
+  csock*: AsyncSocket
+  dsock*: AsyncSocket
+  user*, pass*: string
+  address*: string
+  port*: Port
+  jobInProgress*: bool
+  job*: FtpJob
+  dsockConnected*: bool
+  when defined(ssl):
+
+ + + +
+
+
+
FtpEvent = object
+  filename*: string
+  case typ*: FtpEventType
+  of EvLines:
+    lines*: string           ## Lines that have been transferred.
+  of EvRetr, EvStore:       ## Retr/Store operation finished.
+    nil
+  of EvTransferProgress:
+    bytesTotal*: BiggestInt  ## Bytes total.
+    bytesFinished*: BiggestInt ## Bytes transferred.
+    speed*: BiggestInt       ## Speed in bytes/s
+    currentJob*: FtpJobType  ## The current job being performed.
+
+ + Event + +
+
+
+
FtpEventType = enum
+  EvTransferProgress, EvLines, EvRetr, EvStore
+
+ + + +
+
+
+
FtpJobType = enum
+  JRetrText, JRetr, JStore
+
+ + + +
+
+
+
ProgressChangedProc = proc (total, progress: BiggestInt; speed: float): Future[
+    void] {.closure, ...gcsafe.}
+
+ + + +
+
+
+
ReplyError = object of IOError
+
+ + + +
+
+ +
+
+
+

Procs

+
+
+
+
proc cd(ftp: AsyncFtpClient; dir: string): owned(Future[void]) {.
+    ...stackTrace: false, raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + Changes the current directory on the remote FTP server to dir. + +
+
+ +
+
+
+
proc cdup(ftp: AsyncFtpClient): owned(Future[void]) {....stackTrace: false,
+    raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + Changes the current directory to the parent of the current directory. + +
+
+ +
+
+
+
proc chmod(ftp: AsyncFtpClient; path: string; permissions: set[FilePermission]): owned(
+    Future[void]) {....stackTrace: false, raises: [Exception], tags: [RootEffect],
+                    forbids: [].}
+
+ + Changes permission of path to permissions. + +
+
+ +
+
+
+
proc connect(ftp: AsyncFtpClient): owned(Future[void]) {....stackTrace: false,
+    raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + Connect to the FTP server specified by ftp. + +
+
+ +
+
+
+
proc createDir(ftp: AsyncFtpClient; dir: string; recursive = false): owned(
+    Future[void]) {....stackTrace: false, raises: [Exception], tags: [RootEffect],
+                    forbids: [].}
+
+ + Creates a directory dir. If recursive is true, the topmost subdirectory of dir will be created first, following the secondmost... etc. this allows you to give a full path as the dir without worrying about subdirectories not existing. + +
+
+ +
+
+
+
proc defaultOnProgressChanged(total, progress: BiggestInt; speed: float): Future[
+    void] {.nimcall, ...gcsafe, raises: [Exception], tags: [RootEffect],
+            forbids: [].}
+
+ + Default FTP onProgressChanged handler. Does nothing. + +
+
+ +
+
+
+
proc fileExists(ftp: AsyncFtpClient; file: string): Future[bool] {.
+    ...stackTrace: false, raises: [Exception, ValueError], tags: [RootEffect],
+    forbids: [].}
+
+ + Determines whether file exists. + +
+
+ +
+
+
+
proc list(ftp: AsyncFtpClient; dir = ""): Future[string] {....stackTrace: false,
+    raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}
+
+ + Lists all files in dir. If dir is "", uses the current working directory. + +
+
+ +
+
+
+
proc listDirs(ftp: AsyncFtpClient; dir = ""): Future[seq[string]] {.
+    ...stackTrace: false, raises: [Exception, ValueError], tags: [RootEffect],
+    forbids: [].}
+
+ + Returns a list of filenames in the given directory. If dir is "", the current directory is used. If async is true, this function will return immediately and it will be your job to use asyncdispatch's poll to progress this operation. + +
+
+ +
+
+
+
proc newAsyncFtpClient(address: string; port = Port(21); user, pass = "";
+                       progressInterval: int = 1000; useTls = false;
+                       sslContext: SslContext = nil): AsyncFtpClient {.
+    ...raises: [OSError], tags: [], forbids: [].}
+
+ + Creates a new AsyncFtpClient object. + +
+
+ +
+
+
+
proc pwd(ftp: AsyncFtpClient): Future[string] {....stackTrace: false,
+    raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}
+
+ + Returns the current working directory. + +
+
+ +
+
+
+
proc removeDir(ftp: AsyncFtpClient; dir: string): owned(Future[void]) {.
+    ...stackTrace: false, raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + Delete a directory dir on the remote FTP server + +
+
+ +
+
+
+
proc removeFile(ftp: AsyncFtpClient; filename: string): owned(Future[void]) {.
+    ...stackTrace: false, raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + Delete a file filename on the remote FTP server + +
+
+ +
+
+
+
proc rename(ftp: AsyncFtpClient; nameFrom: string; nameTo: string): owned(
+    Future[void]) {....stackTrace: false, raises: [Exception], tags: [RootEffect],
+                    forbids: [].}
+
+ + Rename a file or directory on the remote FTP Server from current name name_from to new name name_to + +
+
+ +
+
+
+
proc retrFile(ftp: AsyncFtpClient; file, dest: string;
+              onProgressChanged: ProgressChangedProc = defaultOnProgressChanged): owned(
+    Future[void]) {....stackTrace: false, raises: [Exception],
+                    tags: [RootEffect, TimeEffect, WriteIOEffect], forbids: [].}
+
+ + Downloads file and saves it to dest. The EvRetr event is passed to the specified handleEvent function when the download is finished. The event's filename field will be equal to file. + +
+
+ +
+
+
+
proc retrText(ftp: AsyncFtpClient; file: string): Future[string] {.
+    ...stackTrace: false, raises: [Exception, ValueError], tags: [RootEffect],
+    forbids: [].}
+
+ + Retrieves file. File must be ASCII text. + +
+
+ +
+
+
+
proc send(ftp: AsyncFtpClient; m: string): Future[string] {....stackTrace: false,
+    raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}
+
+ +

Send a message to the server, and wait for a primary reply. \c\L is added for you.

+

You need to make sure that the message m doesn't contain any newline characters. Failing to do so will raise AssertionDefect.

+

Note: The server may return multiple lines of coded replies.

+ + +
+
+ +
+
+
+
proc store(ftp: AsyncFtpClient; file, dest: string;
+           onProgressChanged: ProgressChangedProc = defaultOnProgressChanged): owned(
+    Future[void]) {....stackTrace: false, raises: [Exception],
+                    tags: [RootEffect, ReadIOEffect, TimeEffect], forbids: [].}
+
+ + Uploads file to dest on the remote FTP server. Usage of this function asynchronously is recommended to view the progress of the download. The EvStore event is passed to the specified handleEvent function when the upload is finished, and the filename field will be equal to file. + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/asyncftpclient.idx b/asyncftpclient.idx new file mode 100644 index 0000000000000..8499466d3aeb1 --- /dev/null +++ b/asyncftpclient.idx @@ -0,0 +1,35 @@ +nimTitle asyncftpclient asyncftpclient.html module src/asyncftpclient 0 +nim AsyncFtpClient asyncftpclient.html#AsyncFtpClient type AsyncFtpClient 110 +nim JRetrText asyncftpclient.html#JRetrText FtpJobType.JRetrText 124 +nim JRetr asyncftpclient.html#JRetr FtpJobType.JRetr 124 +nim JStore asyncftpclient.html#JStore FtpJobType.JStore 124 +nim FtpJobType asyncftpclient.html#FtpJobType enum FtpJobType 124 +nim EvTransferProgress asyncftpclient.html#EvTransferProgress FtpEventType.EvTransferProgress 141 +nim EvLines asyncftpclient.html#EvLines FtpEventType.EvLines 141 +nim EvRetr asyncftpclient.html#EvRetr FtpEventType.EvRetr 141 +nim EvStore asyncftpclient.html#EvStore FtpEventType.EvStore 141 +nim FtpEventType asyncftpclient.html#FtpEventType enum FtpEventType 141 +nim FtpEvent asyncftpclient.html#FtpEvent object FtpEvent 144 +nim ReplyError asyncftpclient.html#ReplyError object ReplyError 157 +nim ProgressChangedProc asyncftpclient.html#ProgressChangedProc type ProgressChangedProc 159 +nim send asyncftpclient.html#send,AsyncFtpClient,string proc send(ftp: AsyncFtpClient; m: string): Future[string] 177 +nim connect asyncftpclient.html#connect,AsyncFtpClient proc connect(ftp: AsyncFtpClient): owned(Future[void]) 224 +nim pwd asyncftpclient.html#pwd,AsyncFtpClient proc pwd(ftp: AsyncFtpClient): Future[string] 259 +nim cd asyncftpclient.html#cd,AsyncFtpClient,string proc cd(ftp: AsyncFtpClient; dir: string): owned(Future[void]) 265 +nim cdup asyncftpclient.html#cdup,AsyncFtpClient proc cdup(ftp: AsyncFtpClient): owned(Future[void]) 269 +nim listDirs asyncftpclient.html#listDirs,AsyncFtpClient,string proc listDirs(ftp: AsyncFtpClient; dir = ""): Future[seq[string]] 286 +nim fileExists asyncftpclient.html#fileExists,AsyncFtpClient,string proc fileExists(ftp: AsyncFtpClient; file: string): Future[bool] 297 +nim createDir asyncftpclient.html#createDir,AsyncFtpClient,string proc createDir(ftp: AsyncFtpClient; dir: string; recursive = false): owned(\n Future[void]) 303 +nim chmod asyncftpclient.html#chmod,AsyncFtpClient,string,set[FilePermission] proc chmod(ftp: AsyncFtpClient; path: string; permissions: set[FilePermission]): owned(\n Future[void]) 321 +nim list asyncftpclient.html#list,AsyncFtpClient,string proc list(ftp: AsyncFtpClient; dir = ""): Future[string] 342 +nim retrText asyncftpclient.html#retrText,AsyncFtpClient,string proc retrText(ftp: AsyncFtpClient; file: string): Future[string] 352 +nim defaultOnProgressChanged asyncftpclient.html#defaultOnProgressChanged,BiggestInt,BiggestInt,float proc defaultOnProgressChanged(total, progress: BiggestInt; speed: float): Future[void] 388 +nim retrFile asyncftpclient.html#retrFile,AsyncFtpClient,string,string,ProgressChangedProc proc retrFile(ftp: AsyncFtpClient; file, dest: string;\n onProgressChanged: ProgressChangedProc = defaultOnProgressChanged): owned(\n Future[void]) 396 +nim store asyncftpclient.html#store,AsyncFtpClient,string,string,ProgressChangedProc proc store(ftp: AsyncFtpClient; file, dest: string;\n onProgressChanged: ProgressChangedProc = defaultOnProgressChanged): owned(\n Future[void]) 448 +nim rename asyncftpclient.html#rename,AsyncFtpClient,string,string proc rename(ftp: AsyncFtpClient; nameFrom: string; nameTo: string): owned(\n Future[void]) 463 +nim removeFile asyncftpclient.html#removeFile,AsyncFtpClient,string proc removeFile(ftp: AsyncFtpClient; filename: string): owned(Future[void]) 469 +nim removeDir asyncftpclient.html#removeDir,AsyncFtpClient,string proc removeDir(ftp: AsyncFtpClient; dir: string): owned(Future[void]) 473 +nim newAsyncFtpClient asyncftpclient.html#newAsyncFtpClient,string,string,string,int,SslContext proc newAsyncFtpClient(address: string; port = Port(21); user, pass = "";\n progressInterval: int = 1000; useTls = false;\n sslContext: SslContext = nil): AsyncFtpClient 477 +heading Connecting to an FTP server asyncftpclient.html#connecting-to-an-ftp-server Connecting to an FTP server 0 +heading Uploading a new file asyncftpclient.html#uploading-a-new-file Uploading a new file 0 +heading Checking the progress of a file transfer asyncftpclient.html#checking-the-progress-of-a-file-transfer Checking the progress of a file transfer 0 diff --git a/asyncfutures.html b/asyncfutures.html new file mode 100644 index 0000000000000..6a810a4778596 --- /dev/null +++ b/asyncfutures.html @@ -0,0 +1,673 @@ + + + + + + + +std/asyncfutures + + + + + + + + + + + + + + + + +
+
+

std/asyncfutures

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
Future[T] = ref object of FutureBase
+  ## Stored value
+
+ + Typed future. + Source   +Edit   + +
+
+
+
FutureBase = ref object of RootObj
+  error*: ref Exception      ## Stored exception
+  errorStackTrace*: string
+  when not defined(release) or defined(futureLogging):
+    ## For debugging purposes only.
+
+ + Untyped future. + Source   +Edit   + +
+
+
+
FutureError = object of Defect
+  cause*: FutureBase
+
+ + + Source   +Edit   + +
+
+
+
FutureVar[T] = distinct Future[T]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
isFutureLoggingEnabled = false
+
+ + + Source   +Edit   + +
+
+
+
NimAsyncContinueSuffix = "NimAsyncContinue"
+
+ + For internal usage. Do not use. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(stackTraceEntries: seq[StackTraceEntry]): string {.
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addCallback(future: FutureBase; cb: proc () {.closure, ...gcsafe.}) {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ +

Adds the callbacks proc to be called when the future completes.

+

If future has already completed then cb will be called immediately.

+ + Source   +Edit   + +
+
+
+
proc addCallback[T](future: Future[T];
+                    cb: proc (future: Future[T]) {.closure, ...gcsafe.})
+
+ +

Adds the callbacks proc to be called when the future completes.

+

If future has already completed then cb will be called immediately.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc all[T](futs: varargs[Future[T]]): auto
+
+ +

Returns a future which will complete once all futures in futs complete. If the argument is empty, the returned future completes immediately.

+

If the awaited futures are not Future[void], the returned future will hold the values of all awaited futures in a sequence.

+

If the awaited futures are Future[void], this proc returns Future[void].

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `and`[T, Y](fut1: Future[T]; fut2: Future[Y]): Future[void]
+
+ + Returns a future which will complete once both fut1 and fut2 complete. + Source   +Edit   + +
+
+ +
+
+
+
proc asyncCheck[T](future: Future[T])
+
+ +

Sets a callback on future which raises an exception if the future finished with an error.

+

This should be used instead of discard to discard void futures, or use waitFor if you need to wait for the future's completion.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc callback=(future: FutureBase; cb: proc () {.closure, ...gcsafe.}) {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ +

Clears the list of callbacks and sets the callback proc to be called when the future completes.

+

If future has already completed then cb will be called immediately.

+

It's recommended to use addCallback or then instead.

+ + Source   +Edit   + +
+
+
+
proc callback=[T](future: Future[T];
+                  cb: proc (future: Future[T]) {.closure, ...gcsafe.})
+
+ +

Sets the callback proc to be called when the future completes.

+

If future has already completed then cb will be called immediately.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc callSoon(cbproc: proc () {....gcsafe.}) {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ +

Call cbproc "soon".

+

If async dispatcher is running, cbproc will be executed during next dispatcher tick.

+

If async dispatcher is not running, cbproc will be executed immediately.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc clean[T](future: FutureVar[T])
+
+ + Resets the finished status of future. + Source   +Edit   + +
+
+ +
+
+
+
proc clearCallbacks(future: FutureBase) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc complete(future: Future[void]; val = Future[void].default) {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc complete[T](future: Future[T]; val: sink T)
+
+ + Completes future with value val. + Source   +Edit   + +
+
+
+
proc complete[T](future: FutureVar[T])
+
+ + Completes a FutureVar. + Source   +Edit   + +
+
+
+
proc complete[T](future: FutureVar[T]; val: sink T)
+
+ +

Completes a FutureVar with value val.

+

Any previously stored value will be overwritten.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc fail[T](future: Future[T]; error: ref Exception)
+
+ + Completes future with error. + Source   +Edit   + +
+
+ +
+
+
+
proc failed(future: FutureBase): bool {....raises: [], tags: [], forbids: [].}
+
+ + Determines whether future completed with an error. + Source   +Edit   + +
+
+ +
+
+
+
proc finished(future: FutureBase | FutureVar): bool
+
+ +

Determines whether future has completed.

+

True may indicate an error or a value. Use failed to distinguish.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getCallSoonProc(): (proc (cbproc: proc ()) {....gcsafe.}) {....raises: [],
+    tags: [], forbids: [].}
+
+ + Get current implementation of callSoon. + Source   +Edit   + +
+
+ +
+
+
+
proc mget[T](future: FutureVar[T]): var T
+
+ +

Returns a mutable value stored in future.

+

Unlike read, this function will not raise an exception if the Future has not been finished.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newFuture[T](fromProc: string = "unspecified"): owned(Future[T])
+
+ +

Creates a new future.

+

Specifying fromProc, which is a string specifying the name of the proc that this future belongs to, is a good habit as it helps with debugging.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newFutureVar[T](fromProc = "unspecified"): owned(FutureVar[T])
+
+ +

Create a new FutureVar. This Future type is ideally suited for situations where you want to avoid unnecessary allocations of Futures.

+

Specifying fromProc, which is a string specifying the name of the proc that this future belongs to, is a good habit as it helps with debugging.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `or`[T, Y](fut1: Future[T]; fut2: Future[Y]): Future[void]
+
+ + Returns a future which will complete once either fut1 or fut2 complete. + Source   +Edit   + +
+
+ +
+
+
+
proc read(future: Future[void] | FutureVar[void])
+
+ + + Source   +Edit   + +
+
+
+
proc read[T](future: Future[T] | FutureVar[T]): lent T
+
+ +

Retrieves the value of future. Future must be finished otherwise this function will fail with a ValueError exception.

+

If the result of the future is an error then that error will be raised.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc readError[T](future: Future[T]): ref Exception
+
+ +

Retrieves the exception stored in future.

+

An ValueError exception will be thrown if no exception exists in the specified Future.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc setCallSoonProc(p: (proc (cbproc: proc ()) {....gcsafe.})) {....raises: [],
+    tags: [], forbids: [].}
+
+ + Change current implementation of callSoon. This is normally called when dispatcher from asyncdispatcher is initialized. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/asyncfutures.idx b/asyncfutures.idx new file mode 100644 index 0000000000000..c67a237b07c81 --- /dev/null +++ b/asyncfutures.idx @@ -0,0 +1,38 @@ +nimTitle asyncfutures asyncfutures.html module std/asyncfutures 0 +nim FutureBase asyncfutures.html#FutureBase type FutureBase 26 +nim Future asyncfutures.html#Future type Future 37 +nim FutureVar asyncfutures.html#FutureVar type FutureVar 40 +nim FutureError asyncfutures.html#FutureError object FutureError 42 +nim isFutureLoggingEnabled asyncfutures.html#isFutureLoggingEnabled const isFutureLoggingEnabled 48 +nim NimAsyncContinueSuffix asyncfutures.html#NimAsyncContinueSuffix const NimAsyncContinueSuffix 51 +nim getCallSoonProc asyncfutures.html#getCallSoonProc proc getCallSoonProc(): (proc (cbproc: proc ()) {.gcsafe.}) 92 +nim setCallSoonProc asyncfutures.html#setCallSoonProc proc setCallSoonProc(p: (proc (cbproc: proc ()) {.gcsafe.})) 96 +nim callSoon asyncfutures.html#callSoon,proc) proc callSoon(cbproc: proc () {.gcsafe.}) 100 +nim newFuture asyncfutures.html#newFuture,string proc newFuture[T](fromProc: string = "unspecified"): owned(Future[T]) 121 +nim newFutureVar asyncfutures.html#newFutureVar,string proc newFutureVar[T](fromProc = "unspecified"): owned(FutureVar[T]) 129 +nim clean asyncfutures.html#clean,FutureVar[T] proc clean[T](future: FutureVar[T]) 139 +nim complete asyncfutures.html#complete,Future[T],sinkT proc complete[T](future: Future[T]; val: sink T) 206 +nim complete asyncfutures.html#complete,Future[void] proc complete(future: Future[void]; val = Future[void].default) 210 +nim complete asyncfutures.html#complete,FutureVar[T] proc complete[T](future: FutureVar[T]) 213 +nim complete asyncfutures.html#complete,FutureVar[T],sinkT proc complete[T](future: FutureVar[T]; val: sink T) 222 +nim fail asyncfutures.html#fail,Future[T],ref.Exception proc fail[T](future: Future[T]; error: ref Exception) 234 +nim clearCallbacks asyncfutures.html#clearCallbacks,FutureBase proc clearCallbacks(future: FutureBase) 245 +nim addCallback asyncfutures.html#addCallback,FutureBase,proc) proc addCallback(future: FutureBase; cb: proc () {.closure, gcsafe.}) 249 +nim addCallback asyncfutures.html#addCallback,Future[T],proc(Future[T]) proc addCallback[T](future: Future[T];\n cb: proc (future: Future[T]) {.closure, gcsafe.}) 259 +nim callback= asyncfutures.html#callback=,FutureBase,proc) proc callback=(future: FutureBase; cb: proc () {.closure, gcsafe.}) 269 +nim callback= asyncfutures.html#callback=,Future[T],proc(Future[T]) proc callback=[T](future: Future[T]; cb: proc (future: Future[T]) {.closure, gcsafe.}) 278 +nim `$` asyncfutures.html#$,seq[StackTraceEntry] proc `$`(stackTraceEntries: seq[StackTraceEntry]): string 314 +nim read asyncfutures.html#read proc read[T](future: Future[T] | FutureVar[T]): lent T 388 +nim read asyncfutures.html#read_2 proc read(future: Future[void] | FutureVar[void]) 395 +nim readError asyncfutures.html#readError,Future[T] proc readError[T](future: Future[T]): ref Exception 398 +nim mget asyncfutures.html#mget,FutureVar[T] proc mget[T](future: FutureVar[T]): var T 407 +nim finished asyncfutures.html#finished proc finished(future: FutureBase | FutureVar): bool 414 +nim failed asyncfutures.html#failed,FutureBase proc failed(future: FutureBase): bool 423 +nim asyncCheck asyncfutures.html#asyncCheck,Future[T] proc asyncCheck[T](future: Future[T]) 427 +nim `and` asyncfutures.html#and,Future[T],Future[Y] proc `and`[T, Y](fut1: Future[T]; fut2: Future[Y]): Future[void] 442 +nim `or` asyncfutures.html#or,Future[T],Future[Y] proc `or`[T, Y](fut1: Future[T]; fut2: Future[Y]): Future[void] 458 +nim all asyncfutures.html#all,varargs[Future[T]] proc all[T](futs: varargs[Future[T]]): auto 470 +nimgrp complete asyncfutures.html#complete-procs-all proc 206 +nimgrp read asyncfutures.html#read-procs-all proc 388 +nimgrp callback= asyncfutures.html#callback=-procs-all proc 269 +nimgrp addcallback asyncfutures.html#addCallback-procs-all proc 249 diff --git a/asynchttpserver.html b/asynchttpserver.html new file mode 100644 index 0000000000000..7601b84c70442 --- /dev/null +++ b/asynchttpserver.html @@ -0,0 +1,409 @@ + + + + + + + +std/asynchttpserver + + + + + + + + + + + + + + + + +
+
+

std/asynchttpserver

+
+ +
+ Source   +Edit   + +
+ +

This module implements a high performance asynchronous HTTP server.

+

This HTTP server has not been designed to be used in production, but for testing applications locally. Because of this, when deploying your application in production you should use a reverse proxy (for example nginx) instead of allowing users to connect directly to this server.

+ +

Example: cmd: -r:off

+
import std/asynchttpserver
+# This example will create an HTTP server on an automatically chosen port.
+# It will respond to all requests with a `200 OK` response code and "Hello World"
+# as the response body.
+import std/asyncdispatch
+proc main {.async.} =
+  var server = newAsyncHttpServer()
+  proc cb(req: Request) {.async.} =
+    echo (req.reqMethod, req.url, req.headers)
+    let headers = {"Content-type": "text/plain; charset=utf-8"}
+    await req.respond(Http200, "Hello World", headers.newHttpHeaders())
+
+  server.listen(Port(0)) # or Port(8080) to hardcode the standard HTTP port.
+  let port = server.getPort
+  echo "test this with: curl localhost:" & $port.uint16 & "/"
+  while true:
+    if server.shouldAcceptRequest():
+      await server.acceptRequest(cb)
+    else:
+      # too many concurrent connections, `maxFDs` exceeded
+      # wait 500ms for FDs to be closed
+      await sleepAsync(500)
+
+waitFor main()

+ +
+

Types

+
+
+
AsyncHttpServer = ref object
+  ## The maximum content-length that will be read for the body.
+
+ + + Source   +Edit   + +
+
+
+
Request = object
+  client*: AsyncSocket
+  reqMethod*: HttpMethod
+  headers*: HttpHeaders
+  protocol*: tuple[orig: string, major, minor: int]
+  url*: Uri
+  hostname*: string          ## The hostname of the client that made the request.
+  body*: string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
nimMaxDescriptorsFallback {.intdefine.} = 16000
+
+ + fallback value for +when maxDescriptors is not available. This can be set on the command line during compilation via -d:nimMaxDescriptorsFallback=N + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc acceptRequest(server: AsyncHttpServer; callback: proc (request: Request): Future[
+    void] {.closure, ...gcsafe.}): owned(Future[void]) {....stackTrace: false,
+    raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + Accepts a single request. Write an explicit loop around this proc so that errors can be handled properly. + Source   +Edit   + +
+
+ +
+
+
+
proc close(server: AsyncHttpServer) {....raises: [LibraryError, Exception, SslError],
+                                      tags: [RootEffect], forbids: [].}
+
+ + Terminates the async http server instance. + Source   +Edit   + +
+
+ +
+
+
+
proc getPort(self: AsyncHttpServer): Port {....raises: [OSError, Exception],
+    tags: [], forbids: [].}
+
+ +

Returns the port self was bound to.

+

Useful for identifying what port self is bound to, if it was chosen automatically, for example via listen(Port(0)).

+ +

Example:

+
from std/nativesockets import Port
+let server = newAsyncHttpServer()
+server.listen(Port(0))
+assert server.getPort.uint16 > 0
+server.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc listen(server: AsyncHttpServer; port: Port; address = ""; domain = AF_INET) {.
+    ...raises: [OSError, ValueError], tags: [WriteIOEffect, ReadIOEffect],
+    forbids: [].}
+
+ + Listen to the given port and address. + Source   +Edit   + +
+
+ +
+
+
+
proc newAsyncHttpServer(reuseAddr = true; reusePort = false; maxBody = 8388608): AsyncHttpServer {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Creates a new AsyncHttpServer instance. + Source   +Edit   + +
+
+ +
+
+
+
proc respond(req: Request; code: HttpCode; content: string;
+             headers: HttpHeaders = nil): Future[void] {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ +

Responds to the request with the specified HttpCode, headers and content.

+

This procedure will not close the client socket.

+

Example:

+

import std/json
+proc handler(req: Request) {.async.} =
+  if req.url.path == "/hello-world":
+    let msg = %* {"message": "Hello World"}
+    let headers = newHttpHeaders([("Content-Type","application/json")])
+    await req.respond(Http200, $msg, headers)
+  else:
+    await req.respond(Http404, "Not Found")

+ + Source   +Edit   + +
+
+ +
+
+
+
proc sendHeaders(req: Request; headers: HttpHeaders): Future[void] {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + Sends the specified headers to the requesting client. + Source   +Edit   + +
+
+ +
+
+
+
proc serve(server: AsyncHttpServer; port: Port;
+           callback: proc (request: Request): Future[void] {.closure, ...gcsafe.};
+           address = ""; assumedDescriptorsPerRequest = -1; domain = AF_INET): owned(
+    Future[void]) {....stackTrace: false, raises: [Exception], tags: [
+    WriteIOEffect, ReadIOEffect, RootEffect, TimeEffect], forbids: [].}
+
+ +

Starts the process of listening for incoming HTTP connections on the specified address and port.

+

When a request is made by a client the specified callback will be called.

+

If assumedDescriptorsPerRequest is 0 or greater the server cares about the process's maximum file descriptor limit. It then ensures that the process still has the resources for assumedDescriptorsPerRequest file descriptors before accepting a connection.

+

You should prefer to call acceptRequest instead with a custom server loop so that you're in control over the error handling and logging.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc shouldAcceptRequest(server: AsyncHttpServer;
+                         assumedDescriptorsPerRequest = 5): bool {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Returns true if the process's current number of opened file descriptors is still within the maximum limit and so it's reasonable to accept yet another request. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/asynchttpserver.idx b/asynchttpserver.idx new file mode 100644 index 0000000000000..ee544fb6c38e0 --- /dev/null +++ b/asynchttpserver.idx @@ -0,0 +1,13 @@ +nimTitle asynchttpserver asynchttpserver.html module std/asynchttpserver 0 +nim Request asynchttpserver.html#Request object Request 61 +nim AsyncHttpServer asynchttpserver.html#AsyncHttpServer type AsyncHttpServer 70 +nim getPort asynchttpserver.html#getPort,AsyncHttpServer proc getPort(self: AsyncHttpServer): Port 77 +nim newAsyncHttpServer asynchttpserver.html#newAsyncHttpServer,int proc newAsyncHttpServer(reuseAddr = true; reusePort = false; maxBody = 8388608): AsyncHttpServer 90 +nim sendHeaders asynchttpserver.html#sendHeaders,Request,HttpHeaders proc sendHeaders(req: Request; headers: HttpHeaders): Future[void] 99 +nim respond asynchttpserver.html#respond,Request,HttpCode,string,HttpHeaders proc respond(req: Request; code: HttpCode; content: string;\n headers: HttpHeaders = nil): Future[void] 105 +nim nimMaxDescriptorsFallback asynchttpserver.html#nimMaxDescriptorsFallback const nimMaxDescriptorsFallback 376 +nim listen asynchttpserver.html#listen,AsyncHttpServer,Port,string proc listen(server: AsyncHttpServer; port: Port; address = ""; domain = AF_INET) 381 +nim shouldAcceptRequest asynchttpserver.html#shouldAcceptRequest,AsyncHttpServer,int proc shouldAcceptRequest(server: AsyncHttpServer; assumedDescriptorsPerRequest = 5): bool 396 +nim acceptRequest asynchttpserver.html#acceptRequest,AsyncHttpServer,proc(Request) proc acceptRequest(server: AsyncHttpServer; callback: proc (request: Request): Future[\n void] {.closure, gcsafe.}): owned(Future[void]) 405 +nim serve asynchttpserver.html#serve,AsyncHttpServer,Port,proc(Request),string,int proc serve(server: AsyncHttpServer; port: Port;\n callback: proc (request: Request): Future[void] {.closure, gcsafe.};\n address = ""; assumedDescriptorsPerRequest = -1; domain = AF_INET): owned(\n Future[void]) 415 +nim close asynchttpserver.html#close,AsyncHttpServer proc close(server: AsyncHttpServer) 438 diff --git a/asyncjs.html b/asyncjs.html new file mode 100644 index 0000000000000..b14835c3ce6b4 --- /dev/null +++ b/asyncjs.html @@ -0,0 +1,328 @@ + + + + + + + +std/asyncjs + + + + + + + + + + + + + + + + +
+
+

std/asyncjs

+
+ +
+ Source   +Edit   + +
+ +

This module implements types and macros for writing asynchronous code for the JS backend. It provides tools for interaction with JavaScript async API-s and libraries, writing async procedures in Nim and converting callback-based code to promises.

+

A Nim procedure is asynchronous when it includes the {.async.} pragma. It should always have a Future[T] return type or not have a return type at all. A Future[void] return type is assumed by default.

+

This is roughly equivalent to the async keyword in JavaScript code.

+

proc loadGame(name: string): Future[Game] {.async.} =
+  # code

+

should be equivalent to

+

async function loadGame(name) {
+  // code
+}

+

A call to an asynchronous procedure usually needs await to wait for the completion of the Future.

+

var game = await loadGame(name)

+

Often, you might work with callback-based API-s. You can wrap them with asynchronous procedures using promises and newPromise:

+

proc loadGame(name: string): Future[Game] =
+  var promise = newPromise() do (resolve: proc(response: Game)):
+    cbBasedLoadGame(name) do (game: Game):
+      resolve(game)
+  return promise

+

Forward definitions work properly, you just need to always add the {.async.} pragma:

+

proc loadGame(name: string): Future[Game] {.async.}

+ +

JavaScript compatibility

Nim currently generates async/await JavaScript code which is supported in modern EcmaScript and most modern versions of browsers, Node.js and Electron. If you need to use this module with older versions of JavaScript, you can use a tool that backports the resulting JavaScript code, as babel.

+

+
+

Imports

+
+ jsffi, macros, since +
+
+
+

Types

+
+
+
Error {.importjs: "Error".} = ref object of JsRoot
+  message*: cstring
+  name*: cstring
+
+ + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error + Source   +Edit   + +
+
+
+
Future[T] = ref object
+  future*: T
+
+ + + Source   +Edit   + +
+
+
+
OnReject = proc (reason: Error)
+
+ + + Source   +Edit   + +
+
+
+
PromiseJs {.importjs: "Promise".} = ref object
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc catch[T](future: Future[T]; onReject: OnReject): Future[void]
+
+ + See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch +

Example: cmd: -r:off

+
from std/sugar import `=>`
+from std/strutils import contains
+
+proc fn(n: int): Future[int] {.async.} =
+  if n >= 7: raise newException(ValueError, "foobar: " & $n)
+  else: result = n * 2
+
+proc main() {.async.} =
+  var reason: Error
+  await fn(6).catch((r: Error) => (reason = r)) # note: `()` are needed, `=> reason = r` would not work
+  assert reason == nil
+  await fn(7).catch((r: Error) => (reason = r))
+  assert reason != nil
+  assert  "foobar: 7" in $reason.message
+
+discard main()
+ Source   +Edit   + +
+
+ +
+
+
+
proc newPromise(handler: proc (resolve: proc ())): Future[void] {.
+    importjs: "(new Promise(#))", ...raises: [], tags: [], forbids: [].}
+
+ + A helper for wrapping callback-based functions into promises and async procedures. + Source   +Edit   + +
+
+
+
proc newPromise[T](handler: proc (resolve: proc (response: T))): Future[T] {.
+    importjs: "(new Promise(#))", ...raises: [], tags: [], forbids: [].}
+
+ + A helper for wrapping callback-based functions into promises and async procedures. + Source   +Edit   + +
+
+ +
+
+
+
proc then[T](future: Future[T]; onSuccess: proc; onReject: OnReject = nil): auto
+
+ + See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then Returns a Future from the return type of onSuccess(T.default). +

Example: cmd: -r:off

+
from std/sugar import `=>`
+
+proc fn(n: int): Future[int] {.async.} =
+  if n >= 7: raise newException(ValueError, "foobar: " & $n)
+  else: result = n * 2
+
+proc asyncFact(n: int): Future[int] {.async.} =
+  if n > 0: result = n * await asyncFact(n-1)
+  else: result = 1
+
+proc main() {.async.} =
+  block: # then
+    assert asyncFact(3).await == 3*2
+    assert asyncFact(3).then(asyncFact).await == 6*5*4*3*2
+    let x1 = await fn(3)
+    assert x1 == 3 * 2
+    let x2 = await fn(4)
+      .then((a: int) => a.float)
+      .then((a: float) => $a)
+    assert x2 == "8.0"
+
+  block: # then with `onReject` callback
+    var witness = 1
+    await fn(6).then((a: int) => (witness = 2), (r: Error) => (witness = 3))
+    assert witness == 2
+    await fn(7).then((a: int) => (witness = 2), (r: Error) => (witness = 3))
+    assert witness == 3
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro async(arg: untyped): untyped
+
+ + Macro which converts normal procedures into javascript-compatible async procedures. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/asyncjs.idx b/asyncjs.idx new file mode 100644 index 0000000000000..6c905686b84bd --- /dev/null +++ b/asyncjs.idx @@ -0,0 +1,12 @@ +nimTitle asyncjs asyncjs.html module std/asyncjs 0 +nim Future asyncjs.html#Future type Future 75 +nim PromiseJs asyncjs.html#PromiseJs type PromiseJs 79 +nim async asyncjs.html#async.m,untyped macro async(arg: untyped): untyped 159 +nim newPromise asyncjs.html#newPromise,proc(proc(T)) proc newPromise[T](handler: proc (resolve: proc (response: T))): Future[T] 169 +nim newPromise asyncjs.html#newPromise,proc(proc)) proc newPromise(handler: proc (resolve: proc ())): Future[void] 173 +nim Error asyncjs.html#Error type Error 195 +nim OnReject asyncjs.html#OnReject type OnReject 200 +nim then asyncjs.html#then,Future[T],proc,OnReject proc then[T](future: Future[T]; onSuccess: proc; onReject: OnReject = nil): auto 202 +nim catch asyncjs.html#catch,Future[T],OnReject proc catch[T](future: Future[T]; onReject: OnReject): Future[void] 249 +heading JavaScript compatibility asyncjs.html#javascript-compatibility JavaScript compatibility 0 +nimgrp newpromise asyncjs.html#newPromise-procs-all proc 169 diff --git a/asyncmacro.html b/asyncmacro.html new file mode 100644 index 0000000000000..6d6698f240976 --- /dev/null +++ b/asyncmacro.html @@ -0,0 +1,180 @@ + + + + + + + +std/asyncmacro + + + + + + + + + + + + + + + + +
+
+

std/asyncmacro

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Implements the async and multisync macros for asyncdispatch.

+ +
+

Macros

+
+
+
+
macro async(prc: untyped): untyped
+
+ + Macro which processes async procedures into the appropriate iterators and yield statements. + Source   +Edit   + +
+
+ +
+
+
+
macro multisync(prc: untyped): untyped
+
+ +

Macro which processes async procedures into both asynchronous and synchronous procedures.

+

The generated async procedures use the async macro, whereas the generated synchronous procedures simply strip off the await calls.

+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template await(f: typed): untyped {.used.}
+
+ + + Source   +Edit   + +
+
+
+
template await[T](f: Future[T]): auto {.used.}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/asyncmacro.idx b/asyncmacro.idx new file mode 100644 index 0000000000000..41b61da4085a2 --- /dev/null +++ b/asyncmacro.idx @@ -0,0 +1,6 @@ +nimTitle asyncmacro asyncmacro.html module std/asyncmacro 0 +nim await asyncmacro.html#await.t,typed template await(f: typed): untyped 158 +nim await asyncmacro.html#await.t,Future[T] template await[T](f: Future[T]): auto 162 +nim async asyncmacro.html#async.m,untyped macro async(prc: untyped): untyped 315 +nim multisync asyncmacro.html#multisync.m,untyped macro multisync(prc: untyped): untyped 374 +nimgrp await asyncmacro.html#await-templates-all template 158 diff --git a/asyncnet.html b/asyncnet.html new file mode 100644 index 0000000000000..2455f0d34b085 --- /dev/null +++ b/asyncnet.html @@ -0,0 +1,880 @@ + + + + + + + +std/asyncnet + + + + + + + + + + + + + + + + +
+
+

std/asyncnet

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a high-level asynchronous sockets API based on the asynchronous dispatcher defined in the asyncdispatch module. +

Asynchronous IO in Nim

Async IO in Nim consists of multiple layers (from highest to lowest):

+
  • asyncnet module
  • +
  • Async await
  • +
  • asyncdispatch module (event loop)
  • +
  • selectors module
  • +
+

Each builds on top of the layers below it. The selectors module is an abstraction for the various system select() mechanisms such as epoll or kqueue. If you wish you can use it directly, and some people have done so successfully. But you must be aware that on Windows it only supports select().

+

The async dispatcher implements the proactor pattern and also has an implementation of IOCP. It implements the proactor pattern for other OS' via the selectors module. Futures are also implemented here, and indeed all the procedures return a future.

+

The final layer is the async await transformation. This allows you to write asynchronous code in a synchronous style and works similar to C#'s await. The transformation works by converting any async procedures into an iterator.

+

This is all single threaded, fully non-blocking and does give you a lot of control. In theory you should be able to work with any of these layers interchangeably (as long as you only care about non-Windows platforms).

+

For most applications using asyncnet is the way to go as it builds over all the layers, providing some extra features such as buffering.

+ +

SSL

SSL can be enabled by compiling with the -d:ssl flag.

+

You must create a new SSL context with the newContext function defined in the net module. You may then call wrapSocket on your socket using the newly created SSL context to get an SSL socket.

+ +

Examples

+

Chat server

The following example demonstrates a simple chat server.

+

import std/[asyncnet, asyncdispatch]
+
+var clients {.threadvar.}: seq[AsyncSocket]
+
+proc processClient(client: AsyncSocket) {.async.} =
+  while true:
+    let line = await client.recvLine()
+    if line.len == 0: break
+    for c in clients:
+      await c.send(line & "\c\L")
+
+proc serve() {.async.} =
+  clients = @[]
+  var server = newAsyncSocket()
+  server.setSockOpt(OptReuseAddr, true)
+  server.bindAddr(Port(12345))
+  server.listen()
+  
+  while true:
+    let client = await server.accept()
+    clients.add client
+    
+    asyncCheck processClient(client)
+
+asyncCheck serve()
+runForever()

+

+ +
+

Types

+
+
+
AsyncSocket = ref AsyncSocketDesc
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc accept(socket: AsyncSocket; flags = {SafeDisconn}): owned(
+    Future[AsyncSocket]) {....raises: [ValueError, OSError, Exception],
+                           tags: [RootEffect], forbids: [].}
+
+ + Accepts a new connection. Returns a future containing the client socket corresponding to that connection. If inheritable is false (the default), the resulting client socket will not be inheritable by child processes. The future will complete when the connection is successfully accepted. + Source   +Edit   + +
+
+ +
+
+
+
proc acceptAddr(socket: AsyncSocket; flags = {SafeDisconn};
+                inheritable = defined(nimInheritHandles)): owned(
+    Future[tuple[address: string, client: AsyncSocket]]) {.
+    ...raises: [ValueError, OSError, Exception], tags: [RootEffect], forbids: [].}
+
+ +

Accepts a new connection. Returns a future containing the client socket corresponding to that connection and the remote address of the client.

+

If inheritable is false (the default), the resulting client socket will not be inheritable by child processes.

+

The future will complete when the connection is successfully accepted.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc bindAddr(socket: AsyncSocket; port = Port(0); address = "") {.
+    ...tags: [ReadIOEffect], raises: [ValueError, OSError], forbids: [].}
+
+ +

Binds address:port to the socket.

+

If address is "" then ADDR_ANY will be bound.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc bindUnix(socket: AsyncSocket; path: string) {....tags: [ReadIOEffect],
+    raises: [], forbids: [].}
+
+ + Binds Unix socket to path. This only works on Unix-style systems: Mac OS X, BSD and Linux + Source   +Edit   + +
+
+ +
+
+
+
proc close(socket: AsyncSocket) {....raises: [LibraryError, Exception, SslError],
+                                  tags: [RootEffect], forbids: [].}
+
+ + Closes the socket. + Source   +Edit   + +
+
+ +
+
+
+
proc connect(socket: AsyncSocket; address: string; port: Port): owned(
+    Future[void]) {....stackTrace: false, raises: [Exception], tags: [RootEffect],
+                    forbids: [].}
+
+ +

Connects socket to server at address:port.

+

Returns a Future which will complete when the connection succeeds or an error occurs.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc connectUnix(socket: AsyncSocket; path: string): owned(Future[void]) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Binds Unix socket to path. This only works on Unix-style systems: Mac OS X, BSD and Linux + Source   +Edit   + +
+
+ +
+
+
+
proc dial(address: string; port: Port; protocol = IPPROTO_TCP; buffered = true): owned(
+    Future[AsyncSocket]) {....stackTrace: false, raises: [Exception, ValueError],
+                           tags: [RootEffect], forbids: [].}
+
+ + Establishes connection to the specified address:port pair via the specified protocol. The procedure iterates through possible resolutions of the address until it succeeds, meaning that it seamlessly works with both IPv4 and IPv6. Returns AsyncSocket ready to send or receive data. + Source   +Edit   + +
+
+ +
+
+
+
proc getFd(socket: AsyncSocket): SocketHandle {....raises: [], tags: [],
+    forbids: [].}
+
+ + Returns the socket's file descriptor. + Source   +Edit   + +
+
+ +
+
+
+
proc getLocalAddr(socket: AsyncSocket): (string, Port) {.
+    ...raises: [OSError, Exception], tags: [], forbids: [].}
+
+ +

Get the socket's local address and port number.

+

This is high-level interface for getsockname.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getPeerAddr(socket: AsyncSocket): (string, Port) {.
+    ...raises: [OSError, Exception], tags: [], forbids: [].}
+
+ +

Get the socket's peer address and port number.

+

This is high-level interface for getpeername.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getPeerCertificates(socket: AsyncSocket): seq[Certificate] {.
+    ...raises: [Exception], tags: [], forbids: [].}
+
+ + Returns the certificate chain received by the peer we are connected to through the given socket. The handshake must have been completed and the certificate chain must have been verified successfully or else an empty sequence is returned. The chain is ordered from leaf certificate to root certificate. + Source   +Edit   + +
+
+ +
+
+
+
proc getSockOpt(socket: AsyncSocket; opt: SOBool; level = SOL_SOCKET): bool {.
+    ...tags: [ReadIOEffect], raises: [OSError], forbids: [].}
+
+ + Retrieves option opt as a boolean value. + Source   +Edit   + +
+
+ +
+
+
+
proc hasDataBuffered(s: AsyncSocket): bool {....raises: [], tags: [], forbids: [].}
+
+ + Determines whether an AsyncSocket has data buffered. + Source   +Edit   + +
+
+ +
+
+
+
proc isClosed(socket: AsyncSocket): bool {....raises: [], tags: [], forbids: [].}
+
+ + Determines whether the socket has been closed. + Source   +Edit   + +
+
+ +
+
+
+
proc isSsl(socket: AsyncSocket): bool {....raises: [], tags: [], forbids: [].}
+
+ + Determines whether socket is a SSL socket. + Source   +Edit   + +
+
+ +
+
+
+
proc listen(socket: AsyncSocket; backlog = SOMAXCONN) {....tags: [ReadIOEffect],
+    raises: [OSError], forbids: [].}
+
+ +

Marks socket as accepting connections. Backlog specifies the maximum length of the queue of pending connections.

+

Raises an OSError error upon failure.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newAsyncSocket(domain, sockType, protocol: cint; buffered = true;
+                    inheritable = defined(nimInheritHandles)): owned(AsyncSocket) {.
+    ...raises: [OSError], tags: [], forbids: [].}
+
+ +

Creates a new asynchronous socket.

+

This procedure will also create a brand new file descriptor for this socket.

+

If inheritable is false (the default), the new file descriptor will not be inheritable by child processes.

+ + Source   +Edit   + +
+
+
+
proc newAsyncSocket(domain: Domain = AF_INET; sockType: SockType = SOCK_STREAM;
+                    protocol: Protocol = IPPROTO_TCP; buffered = true;
+                    inheritable = defined(nimInheritHandles)): owned(AsyncSocket) {.
+    ...raises: [OSError], tags: [], forbids: [].}
+
+ +

Creates a new asynchronous socket.

+

This procedure will also create a brand new file descriptor for this socket.

+

If inheritable is false (the default), the new file descriptor will not be inheritable by child processes.

+ + Source   +Edit   + +
+
+
+
proc newAsyncSocket(fd: AsyncFD; domain: Domain = AF_INET;
+                    sockType: SockType = SOCK_STREAM;
+                    protocol: Protocol = IPPROTO_TCP; buffered = true;
+                    inheritable = defined(nimInheritHandles)): owned(AsyncSocket) {.
+    ...raises: [OSError], tags: [], forbids: [].}
+
+ +

Creates a new AsyncSocket based on the supplied params.

+

The supplied fd's non-blocking state will be enabled implicitly.

+

If inheritable is false (the default), the supplied fd will not be inheritable by child processes.

+

Note: This procedure will NOT register fd with the global async dispatcher. You need to do this manually. If you have used newAsyncNativeSocket to create fd then it's already registered.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc recv(socket: AsyncSocket; size: int; flags = {SafeDisconn}): owned(
+    Future[string]) {....stackTrace: false, raises: [Exception, ValueError],
+                      tags: [RootEffect], forbids: [].}
+
+ +

Reads up to size bytes from socket.

+

For buffered sockets this function will attempt to read all the requested data. It will read this data in BufferSize chunks.

+

For unbuffered sockets this function makes no effort to read all the data requested. It will return as much data as the operating system gives it.

+

If socket is disconnected during the recv operation then the future may complete with only a part of the requested data.

+

If socket is disconnected and no data is available to be read then the future will complete with a value of "".

+ + Source   +Edit   + +
+
+ +
+
+
+
proc recvFrom(socket: AsyncSocket; data: FutureVar[string]; size: int;
+              address: FutureVar[string]; port: FutureVar[Port];
+              flags = {SafeDisconn}): owned(Future[int]) {....stackTrace: false,
+    raises: [ValueError, Exception], tags: [RootEffect], forbids: [].}
+
+ +

Receives a datagram data from socket into data, which must be at least of size size. The address and port of datagram's sender will be stored into address and port, respectively. Returned future will complete once one datagram has been received, and will return size of packet received.

+

If an error occurs an OSError exception will be raised.

+

This proc is normally used with connectionless sockets (UDP sockets).

+

Notes

+
  • data must be initialized to the length of size.
  • +
  • address must be initialized to 46 in length.
  • +
+ + Source   +Edit   + +
+
+
+
proc recvFrom(socket: AsyncSocket; size: int; flags = {SafeDisconn}): owned(
+    Future[tuple[data: string, address: string, port: Port]]) {.
+    ...stackTrace: false, raises: [Exception, ValueError], tags: [RootEffect],
+    forbids: [].}
+
+ +

Receives a datagram data from socket, which must be at least of size size. Returned future will complete once one datagram has been received and will return tuple with: data of packet received; and address and port of datagram's sender.

+

If an error occurs an OSError exception will be raised.

+

This proc is normally used with connectionless sockets (UDP sockets).

+ + Source   +Edit   + +
+
+ +
+
+
+
proc recvInto(socket: AsyncSocket; buf: pointer; size: int;
+              flags = {SafeDisconn}): owned(Future[int]) {....stackTrace: false,
+    raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}
+
+ +

Reads up to size bytes from socket into buf.

+

For buffered sockets this function will attempt to read all the requested data. It will read this data in BufferSize chunks.

+

For unbuffered sockets this function makes no effort to read all the data requested. It will return as much data as the operating system gives it.

+

If socket is disconnected during the recv operation then the future may complete with only a part of the requested data.

+

If socket is disconnected and no data is available to be read then the future will complete with a value of 0.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc recvLine(socket: AsyncSocket; flags = {SafeDisconn};
+              maxLength = MaxLineLength): owned(Future[string]) {.
+    ...stackTrace: false, raises: [Exception, ValueError], tags: [RootEffect],
+    forbids: [].}
+
+ +

Reads a line of data from socket. Returned future will complete once a full line is read or an error occurs.

+

If a full line is read \r\L is not added to line, however if solely \r\L is read then line will be set to it.

+

If the socket is disconnected, line will be set to "".

+

If the socket is disconnected in the middle of a line (before \r\L is read) then line will be set to "". The partial line will be lost.

+

The maxLength parameter determines the maximum amount of characters that can be read. The result is truncated after that.

+
Warning: +The Peek flag is not yet implemented.
+
Warning: +recvLine on unbuffered sockets assumes that the protocol uses \r\L to delimit a new line.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc recvLineInto(socket: AsyncSocket; resString: FutureVar[string];
+                  flags = {SafeDisconn}; maxLength = MaxLineLength): owned(
+    Future[void]) {....stackTrace: false, raises: [ValueError, Exception],
+                    tags: [RootEffect], forbids: [].}
+
+ +

Reads a line of data from socket into resString.

+

If a full line is read \r\L is not added to line, however if solely \r\L is read then line will be set to it.

+

If the socket is disconnected, line will be set to "".

+

If the socket is disconnected in the middle of a line (before \r\L is read) then line will be set to "". The partial line will be lost.

+

The maxLength parameter determines the maximum amount of characters that can be read. resString will be truncated after that.

+
Warning: +The Peek flag is not yet implemented.
+
Warning: +recvLineInto on unbuffered sockets assumes that the protocol uses \r\L to delimit a new line.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc send(socket: AsyncSocket; buf: pointer; size: int; flags = {SafeDisconn}): owned(
+    Future[void]) {....stackTrace: false, raises: [Exception], tags: [RootEffect],
+                    forbids: [].}
+
+ + Sends size bytes from buf to socket. The returned future will complete once all data has been sent. + Source   +Edit   + +
+
+
+
proc send(socket: AsyncSocket; data: string; flags = {SafeDisconn}): owned(
+    Future[void]) {....stackTrace: false, raises: [Exception], tags: [RootEffect],
+                    forbids: [].}
+
+ + Sends data to socket. The returned future will complete once all data has been sent. + Source   +Edit   + +
+
+ +
+
+
+
proc sendTo(socket: AsyncSocket; address: string; port: Port; data: string;
+            flags = {SafeDisconn}): owned(Future[void]) {....stackTrace: false,
+    raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ +

This proc sends data to the specified address, which may be an IP address or a hostname. If a hostname is specified this function will try each IP of that hostname. The returned future will complete once all data has been sent.

+

If an error occurs an OSError exception will be raised.

+

This proc is normally used with connectionless sockets (UDP sockets).

+ + Source   +Edit   + +
+
+ +
+
+
+
proc setSockOpt(socket: AsyncSocket; opt: SOBool; value: bool;
+                level = SOL_SOCKET) {....tags: [WriteIOEffect], raises: [OSError],
+                                      forbids: [].}
+
+ + Sets option opt to a boolean value specified by value. + Source   +Edit   + +
+
+ +
+
+
+
proc sslHandle(self: AsyncSocket): SslPtr {....raises: [], tags: [], forbids: [].}
+
+ + Retrieve the ssl pointer of socket. Useful for interfacing with openssl. + Source   +Edit   + +
+
+ +
+
+
+
proc wrapConnectedSocket(ctx: SslContext; socket: AsyncSocket;
+                         handshake: SslHandshakeType; hostname: string = "") {.
+    ...raises: [SslError], tags: [], forbids: [].}
+
+ +

Wraps a connected socket in an SSL context. This function effectively turns socket into an SSL socket. hostname should be specified so that the client knows which hostname the server certificate should be validated against.

+

This should be called on a connected socket, and will perform an SSL handshake immediately.

+

Disclaimer: This code is not well tested, may be very unsafe and prone to security vulnerabilities.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc wrapSocket(ctx: SslContext; socket: AsyncSocket) {....raises: [SslError],
+    tags: [], forbids: [].}
+
+ +

Wraps a socket in an SSL context. This function effectively turns socket into an SSL socket.

+

Disclaimer: This code is not well tested, may be very unsafe and prone to security vulnerabilities.

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/asyncnet.idx b/asyncnet.idx new file mode 100644 index 0000000000000..1d8b26c7edb16 --- /dev/null +++ b/asyncnet.idx @@ -0,0 +1,44 @@ +nimTitle asyncnet asyncnet.html module std/asyncnet 0 +nim AsyncSocket asyncnet.html#AsyncSocket type AsyncSocket 135 +nim newAsyncSocket asyncnet.html#newAsyncSocket,AsyncFD,Domain,SockType,Protocol proc newAsyncSocket(fd: AsyncFD; domain: Domain = AF_INET;\n sockType: SockType = SOCK_STREAM;\n protocol: Protocol = IPPROTO_TCP; buffered = true;\n inheritable = defined(nimInheritHandles)): owned(AsyncSocket) 137 +nim newAsyncSocket asyncnet.html#newAsyncSocket,Domain,SockType,Protocol proc newAsyncSocket(domain: Domain = AF_INET; sockType: SockType = SOCK_STREAM;\n protocol: Protocol = IPPROTO_TCP; buffered = true;\n inheritable = defined(nimInheritHandles)): owned(AsyncSocket) 165 +nim getLocalAddr asyncnet.html#getLocalAddr,AsyncSocket proc getLocalAddr(socket: AsyncSocket): (string, Port) 180 +nim getPeerAddr asyncnet.html#getPeerAddr,AsyncSocket proc getPeerAddr(socket: AsyncSocket): (string, Port) 187 +nim newAsyncSocket asyncnet.html#newAsyncSocket,cint,cint,cint proc newAsyncSocket(domain, sockType, protocol: cint; buffered = true;\n inheritable = defined(nimInheritHandles)): owned(AsyncSocket) 193 +nim dial asyncnet.html#dial,string,Port proc dial(address: string; port: Port; protocol = IPPROTO_TCP; buffered = true): owned(\n Future[AsyncSocket]) 290 +nim connect asyncnet.html#connect,AsyncSocket,string,Port proc connect(socket: AsyncSocket; address: string; port: Port): owned(\n Future[void]) 301 +nim recvInto asyncnet.html#recvInto,AsyncSocket,pointer,int proc recvInto(socket: AsyncSocket; buf: pointer; size: int; flags = {SafeDisconn}): owned(\n Future[int]) 343 +nim recv asyncnet.html#recv,AsyncSocket,int proc recv(socket: AsyncSocket; size: int; flags = {SafeDisconn}): owned(\n Future[string]) 391 +nim send asyncnet.html#send,AsyncSocket,pointer,int proc send(socket: AsyncSocket; buf: pointer; size: int; flags = {SafeDisconn}): owned(\n Future[void]) 444 +nim send asyncnet.html#send,AsyncSocket,string proc send(socket: AsyncSocket; data: string; flags = {SafeDisconn}): owned(\n Future[void]) 458 +nim acceptAddr asyncnet.html#acceptAddr,AsyncSocket proc acceptAddr(socket: AsyncSocket; flags = {SafeDisconn};\n inheritable = defined(nimInheritHandles)): owned(\n Future[tuple[address: string, client: AsyncSocket]]) 471 +nim accept asyncnet.html#accept,AsyncSocket proc accept(socket: AsyncSocket; flags = {SafeDisconn}): owned(Future[AsyncSocket]) 495 +nim recvLineInto asyncnet.html#recvLineInto,AsyncSocket,FutureVar[string] proc recvLineInto(socket: AsyncSocket; resString: FutureVar[string];\n flags = {SafeDisconn}; maxLength = MaxLineLength): owned(\n Future[void]) 514 +nim recvLine asyncnet.html#recvLine,AsyncSocket proc recvLine(socket: AsyncSocket; flags = {SafeDisconn}; maxLength = MaxLineLength): owned(\n Future[string]) 606 +nim listen asyncnet.html#listen,AsyncSocket proc listen(socket: AsyncSocket; backlog = SOMAXCONN) 634 +nim bindAddr asyncnet.html#bindAddr,AsyncSocket,string proc bindAddr(socket: AsyncSocket; port = Port(0); address = "") 643 +nim hasDataBuffered asyncnet.html#hasDataBuffered,AsyncSocket proc hasDataBuffered(s: AsyncSocket): bool 663 +nim connectUnix asyncnet.html#connectUnix,AsyncSocket,string proc connectUnix(socket: AsyncSocket; path: string): owned(Future[void]) 670 +nim bindUnix asyncnet.html#bindUnix,AsyncSocket,string proc bindUnix(socket: AsyncSocket; path: string) 701 +nim close asyncnet.html#close,AsyncSocket proc close(socket: AsyncSocket) 723 +nim sslHandle asyncnet.html#sslHandle,AsyncSocket proc sslHandle(self: AsyncSocket): SslPtr 749 +nim wrapSocket asyncnet.html#wrapSocket,SslContext,AsyncSocket proc wrapSocket(ctx: SslContext; socket: AsyncSocket) 754 +nim wrapConnectedSocket asyncnet.html#wrapConnectedSocket,SslContext,AsyncSocket,SslHandshakeType,string proc wrapConnectedSocket(ctx: SslContext; socket: AsyncSocket;\n handshake: SslHandshakeType; hostname: string = "") 772 +nim getPeerCertificates asyncnet.html#getPeerCertificates,AsyncSocket proc getPeerCertificates(socket: AsyncSocket): seq[Certificate] 797 +nim getSockOpt asyncnet.html#getSockOpt,AsyncSocket,SOBool proc getSockOpt(socket: AsyncSocket; opt: SOBool; level = SOL_SOCKET): bool 808 +nim setSockOpt asyncnet.html#setSockOpt,AsyncSocket,SOBool,bool proc setSockOpt(socket: AsyncSocket; opt: SOBool; value: bool; level = SOL_SOCKET) 814 +nim isSsl asyncnet.html#isSsl,AsyncSocket proc isSsl(socket: AsyncSocket): bool 820 +nim getFd asyncnet.html#getFd,AsyncSocket proc getFd(socket: AsyncSocket): SocketHandle 824 +nim isClosed asyncnet.html#isClosed,AsyncSocket proc isClosed(socket: AsyncSocket): bool 828 +nim sendTo asyncnet.html#sendTo,AsyncSocket,string,Port,string proc sendTo(socket: AsyncSocket; address: string; port: Port; data: string;\n flags = {SafeDisconn}): owned(Future[void]) 834 +nim recvFrom asyncnet.html#recvFrom,AsyncSocket,FutureVar[string],int,FutureVar[string],FutureVar[Port] proc recvFrom(socket: AsyncSocket; data: FutureVar[string]; size: int;\n address: FutureVar[string]; port: FutureVar[Port];\n flags = {SafeDisconn}): owned(Future[int]) 881 +nim recvFrom asyncnet.html#recvFrom,AsyncSocket,int proc recvFrom(socket: AsyncSocket; size: int; flags = {SafeDisconn}): owned(\n Future[tuple[data: string, address: string, port: Port]]) 935 +heading Asynchronous IO in Nim asyncnet.html#asynchronous-io-in-nim Asynchronous IO in Nim 0 +heading SSL asyncnet.html#ssl SSL 0 +heading Examples asyncnet.html#examples Examples 0 +heading Chat server asyncnet.html#examples-chat-server Chat server 0 +idx getpeername asyncnet.html#getpeername_1 Chat server 0 +idx getsockname asyncnet.html#getsockname_1 Chat server 0 +nimgrp recvfrom asyncnet.html#recvFrom-procs-all proc 878 +nimgrp newasyncsocket asyncnet.html#newAsyncSocket-procs-all proc 137 +nimgrp send asyncnet.html#send-procs-all proc 443 diff --git a/asyncstreams.html b/asyncstreams.html new file mode 100644 index 0000000000000..9541c8ecc4d05 --- /dev/null +++ b/asyncstreams.html @@ -0,0 +1,297 @@ + + + + + + + +std/asyncstreams + + + + + + + + + + + + + + + + +
+
+

std/asyncstreams

+
+ +
+ Source   +Edit   + +
+ +

Unstable API.

+ +
+

Types

+
+
+
FutureStream[T] = ref object
+  error*: ref Exception
+
+ + Special future that acts as a queue. Its API is still experimental and so is subject to change. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc callback=[T](future: FutureStream[T];
+                  cb: proc (future: FutureStream[T]) {.closure, ...gcsafe.})
+
+ +

Sets the callback proc to be called when data was placed inside the future stream.

+

The callback is also called when the future is completed. So you should use finished to check whether data is available.

+

If the future stream already has data or is finished then cb will be called immediately.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc complete[T](future: FutureStream[T])
+
+ + Completes a FutureStream signalling the end of data. + Source   +Edit   + +
+
+ +
+
+
+
proc fail[T](future: FutureStream[T]; error: ref Exception)
+
+ + Completes future with error. + Source   +Edit   + +
+
+ +
+
+
+
proc failed[T](future: FutureStream[T]): bool
+
+ + Determines whether future completed with an error. + Source   +Edit   + +
+
+ +
+
+
+
proc finished[T](future: FutureStream[T]): bool
+
+ + Check if a FutureStream is finished. true value means that no more data will be placed inside the stream and that there is no data waiting to be retrieved. + Source   +Edit   + +
+
+ +
+
+
+
proc len[T](future: FutureStream[T]): int
+
+ + Returns the amount of data pieces inside the stream. + Source   +Edit   + +
+
+ +
+
+
+
proc newFutureStream[T](fromProc = "unspecified"): FutureStream[T]
+
+ + Create a new FutureStream. This future's callback is activated when two events occur:
  • New data is written into the future stream.
  • +
  • The future stream is completed (this means that no more data will be written).
  • +
+

Specifying fromProc, which is a string specifying the name of the proc that this future belongs to, is a good habit as it helps with debugging.

+

Note: The API of FutureStream is still new and so has a higher likelihood of changing in the future.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc read[T](future: FutureStream[T]): owned(Future[(bool, T)])
+
+ +

Returns a future that will complete when the FutureStream has data placed into it. The future will be completed with the oldest value stored inside the stream. The return value will also determine whether data was retrieved, false means that the future stream was completed and no data was retrieved.

+

This function will remove the data that was returned from the underlying FutureStream.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc write[T](future: FutureStream[T]; value: T): Future[void]
+
+ +

Writes the specified value inside the specified future stream.

+

This will raise ValueError if future is finished.

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/asyncstreams.idx b/asyncstreams.idx new file mode 100644 index 0000000000000..c9465bffe37e9 --- /dev/null +++ b/asyncstreams.idx @@ -0,0 +1,11 @@ +nimTitle asyncstreams asyncstreams.html module std/asyncstreams 0 +nim FutureStream asyncstreams.html#FutureStream type FutureStream 20 +nim newFutureStream asyncstreams.html#newFutureStream,string proc newFutureStream[T](fromProc = "unspecified"): FutureStream[T] 29 +nim complete asyncstreams.html#complete,FutureStream[T] proc complete[T](future: FutureStream[T]) 45 +nim fail asyncstreams.html#fail,FutureStream[T],ref.Exception proc fail[T](future: FutureStream[T]; error: ref Exception) 52 +nim callback= asyncstreams.html#callback=,FutureStream[T],proc(FutureStream[T]) proc callback=[T](future: FutureStream[T];\n cb: proc (future: FutureStream[T]) {.closure, gcsafe.}) 60 +nim finished asyncstreams.html#finished,FutureStream[T] proc finished[T](future: FutureStream[T]): bool 75 +nim failed asyncstreams.html#failed,FutureStream[T] proc failed[T](future: FutureStream[T]): bool 81 +nim write asyncstreams.html#write,FutureStream[T],T proc write[T](future: FutureStream[T]; value: T): Future[void] 85 +nim read asyncstreams.html#read,FutureStream[T] proc read[T](future: FutureStream[T]): owned(Future[(bool, T)]) 100 +nim len asyncstreams.html#len,FutureStream[T] proc len[T](future: FutureStream[T]): int 145 diff --git a/atlas.html b/atlas.html new file mode 100644 index 0000000000000..72349a753796f --- /dev/null +++ b/atlas.html @@ -0,0 +1,157 @@ + + + + + + + +doc/atlas + + + + + + + + + + + + + + + + +
+
+

doc/atlas

+ +

Atlas Package Cloner

Atlas is a simple package cloner tool. It manages an isolated workspace that contains projects and dependencies.

+

Atlas is compatible with Nimble in the sense that it supports the Nimble file format.

+ +

Concepts

Atlas uses three concepts:

+
  1. Workspaces
  2. +
  3. Projects
  4. +
  5. Dependencies
  6. +
+ +

Workspaces

Every workspace is isolated, nothing is shared between workspaces. A workspace is a directory that has a file atlas.workspace inside it. Use atlas init to create a workspace out of the current working directory.

+

Projects plus their dependencies are stored in a workspace:

+

  $workspace / main project
+  $workspace / other project
+  $workspace / _deps / dependency A
+  $workspace / _deps / dependency B

+

The deps directory can be set via --deps:DIR during atlas init.

+ +

Projects

A workspace contains one or multiple "projects". These projects can use each other and it is easy to develop multiple projects at the same time.

+ +

Dependencies

Inside a workspace there can be a _deps directory where your dependencies are kept. It is easy to move a dependency one level up and out the _deps directory, turning it into a project. Likewise, you can move a project to the _deps directory, turning it into a dependency.

+

The only distinction between a project and a dependency is its location. For dependency resolution a project always has a higher priority than a dependency.

+ +

No magic

Atlas works by managing two files for you, the project.nimble file and the nim.cfg file. You can edit these manually too, Atlas doesn't touch what should be left untouched.

+ +

How it works

Atlas uses git commits internally; version requirements are translated to git commits via git show-ref --tags.

+

Atlas uses URLs internally; Nimble package names are translated to URLs via Nimble's packages.json file.

+

Atlas does not call the Nim compiler for a build, instead it creates/patches a nim.cfg file for the compiler. For example:

+

############# begin Atlas config section ##########
+--noNimblePath
+--path:"../nimx"
+--path:"../sdl2/src"
+--path:"../opengl/src"
+############# end Atlas config section   ##########

+

The version selection is deterministic, it picks up the minimum required version. Thanks to this design, lock files are much less important.

+ +

Commands

Atlas supports the following commands:

+ +

Use <url> / <package name>

Clone the package behind url or package name and its dependencies into the _deps directory and make it available for your current project which should be in the current working directory. Atlas will create or patch the files $project.nimble and nim.cfg for you so that you can simply import the required modules.

+

For example:

+

  mkdir newproject
+  cd newproject
+  git init
+  atlas use lexim
+  # add `import lexim` to your example.nim file
+  nim c example.nim
+

+ +

Clone/Update <url>/<package name>

Clones a URL and all of its dependencies (recursively) into the workspace. Creates or patches a nim.cfg file with the required --path entries.

+

Note: Due to the used algorithms an update is the same as a clone.

+

If a <package name> is given instead the name is first translated into an URL via packages.json or via a github search.

+ +

Search <term term2 term3 ...>

Search the package index packages.json for a package that the given terms in its description (or name or list of tags).

+ +

Install <proj.nimble>

Use the .nimble file to setup the project's dependencies.

+ +

UpdateProjects / updateDeps filter

Update every project / dependency in the workspace that has a remote URL that matches filter if a filter is given. The project / dependency is only updated if there are no uncommitted changes.

+ +

Others

Run atlas --help for more features.

+ +

Overrides

You can override how Atlas resolves a package name or a URL. The overrides use a simple pattern matching language and are flexible enough to integrate private gitlab repositories.

+

To setup an override file, edit the $workspace/atlas.workspace file to contain a line like overrides="urls.rules". Then create a file urls.rules that can contain lines like:

+

customProject -> https://gitlab.company.com/customProject
+https://github.com/araq/ormin -> https://github.com/useMyForkInstead/ormin

+

The $ has a special meaning in a pattern:

+ + + + + + + +
SyntaxMeaning
$$Matches a single dollar sign.
$*Matches until the token following the $* was found.
The match is allowed to be of 0 length.
$+Matches until the token following the $+ was found.
The match must consist of at least one char.
$sSkips optional whitespace.

For example, here is how to override any github link:

+

https://github.com/$+ -> https://utopia.forall/$#

+

You can use $1 or $# to refer to captures.

+ +

Virtual Nim environments

Atlas supports setting up a virtual Nim environment via the env command. You can even install multiple different Nim versions into the same workspace.

+

For example:

+

atlas env 1.6.12
+atlas env devel

+

When completed, run source nim-1.6.12/activate.sh on UNIX and nim-1.6.12/activate.bat on Windows.

+ +

Dependency resolution

To change the used dependency resolution mechanism, edit the resolver value of your atlas.workspace file. The possible values are:

+ +

MaxVer

The default resolution mechanism is called "MaxVer" where the highest available version is selected that still fits the requirements.

+

Suppose you have a dependency called "mylibrary" with the following available versions: 1.0.0, 1.1.0, and 2.0.0. MaxVer selects the version 2.0.0.

+ +

SemVer

Adhere to Semantic Versioning (SemVer) by selecting the highest version that satisfies the specified version range. SemVer follows the format of MAJOR.MINOR.PATCH, where:

+

MAJOR version indicates incompatible changes.

+

MINOR version indicates backward-compatible new features.

+

PATCH version indicates backward-compatible bug fixes.

+

Consider the same "mylibrary" dependency with versions 1.0.0, 1.1.0, and 2.0.0. If you set the resolver to SemVer and specify a version range requirement of >= 1.0.0, the highest version that satisfies the range that does not introduce incompatible changes will be selected. In this case, the selected version would be 1.1.0.

+ +

MinVer

For the "mylibrary" dependency with versions 1.0.0, 1.1.0, and 2.0.0, if you set the resolver to MinVer and specify multiple minimum versions, the highest version among the minimum required versions will be selected. For example, if you specify a minimum requirement of both >=1.0.0 and >=2.0.0, the selected version would be 2.0.0.

+ +

Reproducible builds / lockfiles

Atlas supports lockfiles for reproducible builds via its pin and rep commands.

+

Notice: Atlas helps with reproducible builds, but it is not a complete solution. For a truely reproducible build you also need to pin the used C++ compiler, any third party dependencies ("libc" etc.) and the version of your operating system.

+ +

pin atlas.lock

atlas pin can be run either in the workspace or in a specific project. It "pins" the used repositories to their current commit hashes. If run in the workspace the entire workspace is "pinned" in the atlas.lock file. If run in a project the project's dependencies but not the project itself is "pinned" in the lock file.

+ +

rep atlas.lock

The rep command replays or repeats the projects to use the pinned commit hashes. If the projects have any "build" instructions these are performed too unless the --noexec switch is used.

+ +

Plugins

Atlas operates on a graph of dependencies. A dependency is a git project of a specific commit. The graph and version selection algorithms are mostly programming language agnostic. Thus it is easy to integrate foreign projects as dependencies into your project.

+

This is accomplished by Atlas plugins. A plugin is a NimScript snippet that can call into external tools via exec.

+

To enable plugins, add the line plugins="_plugins" to your atlas.workspace file. Then create a directory _plugins in your workspace. Every *.nims file inside the plugins directory is integrated into Atlas.

+ +

Builders

A builder is a build tool like make or cmake. What tool to use is determined by the existence of certain files in the project's top level directory. For example, a file CMakeLists.txt indicates a cmake based build:

+

+builder "CMakeLists.txt":
+  mkDir "build"
+  withDir "build":
+    exec "cmake .."
+    exec "cmake --build . --config Release"
+

+

Save this as _plugins/cmake.nims. Then every dependency that contains a CMakeLists.txt file will be build with cmake.

+

Note: To disable any kind of action that might run arbitrary code, use the --noexec switch.

+ + + + +
+
+ + + + diff --git a/atlas.idx b/atlas.idx new file mode 100644 index 0000000000000..2fcdbdf89e2e3 --- /dev/null +++ b/atlas.idx @@ -0,0 +1,26 @@ +markupTitle atlas.md atlas.html atlas.md 0 +heading Atlas Package Cloner atlas.html#atlas-package-cloner Atlas Package Cloner 0 +heading Concepts atlas.html#concepts Concepts 0 +heading Workspaces atlas.html#workspaces Workspaces 0 +heading Projects atlas.html#projects Projects 0 +heading Dependencies atlas.html#dependencies Dependencies 0 +heading No magic atlas.html#no-magic No magic 0 +heading How it works atlas.html#how-it-works How it works 0 +heading Commands atlas.html#commands Commands 0 +heading Use / atlas.html#use-lturlgt-slash-ltpackage-namegt Use <url> / <package name> 0 +heading Clone/Update / atlas.html#cloneslashupdate-lturlgtslashltpackage-namegt Clone/Update <url>/<package name> 0 +heading Search atlas.html#search-ltterm-term2-term3-dotdotdotgt Search <term term2 term3 ...> 0 +heading Install atlas.html#install-ltprojdotnimblegt Install <proj.nimble> 0 +heading UpdateProjects / updateDeps filterfilter atlas.html#updateprojects-slash-updatedeps-filterfilter UpdateProjects / updateDeps filter 0 +heading Others atlas.html#others Others 0 +heading Overrides atlas.html#overrides Overrides 0 +heading Virtual Nim environments atlas.html#virtual-nim-environments Virtual Nim environments 0 +heading Dependency resolution atlas.html#dependency-resolution Dependency resolution 0 +heading MaxVer atlas.html#maxver MaxVer 0 +heading SemVer atlas.html#semver SemVer 0 +heading MinVer atlas.html#minver MinVer 0 +heading Reproducible builds / lockfiles atlas.html#reproducible-builds-slash-lockfiles Reproducible builds / lockfiles 0 +heading pin atlas.lockatlas.lock atlas.html#pin-atlasdotlockatlasdotlock pin atlas.lock 0 +heading rep atlas.lockatlas.lock atlas.html#rep-atlasdotlockatlasdotlock rep atlas.lock 0 +heading Plugins atlas.html#plugins Plugins 0 +heading Builders atlas.html#builders Builders 0 diff --git a/atomics.html b/atomics.html new file mode 100644 index 0000000000000..42af270151910 --- /dev/null +++ b/atomics.html @@ -0,0 +1,611 @@ + + + + + + + +std/atomics + + + + + + + + + + + + + + + + +
+
+

std/atomics

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Types and operations for atomic operations and lockless algorithms.

+

Unstable API.

+

By default, C++ uses C11 atomic primitives. To use C++ std::atomic, -d:nimUseCppAtomics can be defined.

+ +

Example:

+
import std/atomics
+# Atomic
+var loc: Atomic[int]
+loc.store(4)
+assert loc.load == 4
+loc.store(2)
+assert loc.load(moRelaxed) == 2
+loc.store(9)
+assert loc.load(moAcquire) == 9
+loc.store(0, moRelease)
+assert loc.load == 0
+
+assert loc.exchange(7) == 0
+assert loc.load == 7
+
+var expected = 7
+assert loc.compareExchange(expected, 5, moRelaxed, moRelaxed)
+assert expected == 7
+assert loc.load == 5
+
+assert not loc.compareExchange(expected, 12, moRelaxed, moRelaxed)
+assert expected == 5
+assert loc.load == 5
+
+assert loc.fetchAdd(1) == 5
+assert loc.fetchAdd(2) == 6
+assert loc.fetchSub(3) == 8
+
+loc.atomicInc(1)
+assert loc.load == 6
+
+# AtomicFlag
+var flag: AtomicFlag
+
+assert not flag.testAndSet
+assert flag.testAndSet
+flag.clear(moRelaxed)
+assert not flag.testAndSet

+
+

Types

+
+
+
Atomic[T] {.importcpp: "std::atomic", completeStruct.} = object
+
+ + An atomic object with underlying type T. + Source   +Edit   + +
+
+
+
AtomicFlag {.importcpp: "std::atomic_flag", size: 1.} = object
+
+ + An atomic boolean state. + Source   +Edit   + +
+
+
+
MemoryOrder {.importcpp: "std::memory_order".} = enum
+  moRelaxed, ## No ordering constraints. Only the atomicity and ordering against
+              ## other atomic operations is guaranteed.
+  moConsume, ## This ordering is currently discouraged as it's semantics are
+              ## being revised. Acquire operations should be preferred.
+  moAcquire, ## When applied to a load operation, no reads or writes in the
+              ## current thread can be reordered before this operation.
+  moRelease, ## When applied to a store operation, no reads or writes in the
+              ## current thread can be reorderd after this operation.
+  moAcquireRelease, ## When applied to a read-modify-write operation, this behaves like
+                     ## both an acquire and a release operation.
+  moSequentiallyConsistent ## Behaves like Acquire when applied to load, like Release when
+                           ## applied to a store and like AcquireRelease when applied to a
+                           ## read-modify-write operation.
+                           ## Also guarantees that all threads observe the same total ordering
+                           ## with other moSequentiallyConsistent operations.
+
+ + Specifies how non-atomic operations can be reordered around atomic operations. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `+=`[T: SomeInteger](location: var Atomic[T]; value: T) {.inline.}
+
+ + Atomically increments the atomic integer by some value. + Source   +Edit   + +
+
+ +
+
+
+
proc `-=`[T: SomeInteger](location: var Atomic[T]; value: T) {.inline.}
+
+ + Atomically decrements the atomic integer by some value. + Source   +Edit   + +
+
+ +
+
+
+
proc atomicDec[T: SomeInteger](location: var Atomic[T]; value: T = 1) {.inline.}
+
+ + Atomically decrements the atomic integer by some value. + Source   +Edit   + +
+
+ +
+
+
+
proc atomicInc[T: SomeInteger](location: var Atomic[T]; value: T = 1) {.inline.}
+
+ + Atomically increments the atomic integer by some value. + Source   +Edit   + +
+
+ +
+
+
+
proc clear(location: var AtomicFlag;
+           order: MemoryOrder = moSequentiallyConsistent) {.
+    importcpp: "#.clear(@)", header: "<atomic>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + Atomically sets the value of the atomic flag to false. + Source   +Edit   + +
+
+ +
+
+
+
proc compareExchange[T](location: var Atomic[T]; expected: var T; desired: T;
+                        order: MemoryOrder = moSequentiallyConsistent): bool {.
+    importcpp: "#.compare_exchange_strong(@)", header: "<atomic>", ...raises: [],
+    tags: [], forbids: [].}
+
+ + Atomically compares the value of the atomic object with the expected value and performs exchange with the desired one if equal or load if not. Returns true if the exchange was successful. + Source   +Edit   + +
+
+
+
proc compareExchange[T](location: var Atomic[T]; expected: var T; desired: T;
+                        success, failure: MemoryOrder): bool {.
+    importcpp: "#.compare_exchange_strong(@)", header: "<atomic>", ...raises: [],
+    tags: [], forbids: [].}
+
+ + Same as above, but allows for different memory orders for success and failure. + Source   +Edit   + +
+
+ +
+
+
+
proc compareExchangeWeak[T](location: var Atomic[T]; expected: var T;
+                            desired: T;
+                            order: MemoryOrder = moSequentiallyConsistent): bool {.
+    importcpp: "#.compare_exchange_weak(@)", header: "<atomic>", ...raises: [],
+    tags: [], forbids: [].}
+
+ + Same as above, but is allowed to fail spuriously. + Source   +Edit   + +
+
+
+
proc compareExchangeWeak[T](location: var Atomic[T]; expected: var T;
+                            desired: T; success, failure: MemoryOrder): bool {.
+    importcpp: "#.compare_exchange_weak(@)", header: "<atomic>", ...raises: [],
+    tags: [], forbids: [].}
+
+ + Same as above, but allows for different memory orders for success and failure. + Source   +Edit   + +
+
+ +
+
+
+
proc exchange[T](location: var Atomic[T]; desired: T;
+                 order: MemoryOrder = moSequentiallyConsistent): T {.
+    importcpp: "#.exchange(@)", header: "<atomic>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + Atomically replaces the value of the atomic object with the desired value and returns the old value. + Source   +Edit   + +
+
+ +
+
+
+
proc fence(order: MemoryOrder) {.importcpp: "std::atomic_thread_fence(@)",
+                                 header: "<atomic>", ...raises: [], tags: [],
+                                 forbids: [].}
+
+ + Ensures memory ordering without using atomic operations. + Source   +Edit   + +
+
+ +
+
+
+
proc fetchAdd[T: SomeInteger](location: var Atomic[T]; value: T;
+                              order: MemoryOrder = moSequentiallyConsistent): T {.
+    importcpp: "#.fetch_add(@)", header: "<atomic>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + Atomically adds a value to the atomic integer and returns the original value. + Source   +Edit   + +
+
+ +
+
+
+
proc fetchAnd[T: SomeInteger](location: var Atomic[T]; value: T;
+                              order: MemoryOrder = moSequentiallyConsistent): T {.
+    importcpp: "#.fetch_and(@)", header: "<atomic>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + Atomically replaces the atomic integer with it's bitwise AND with the specified value and returns the original value. + Source   +Edit   + +
+
+ +
+
+
+
proc fetchOr[T: SomeInteger](location: var Atomic[T]; value: T;
+                             order: MemoryOrder = moSequentiallyConsistent): T {.
+    importcpp: "#.fetch_or(@)", header: "<atomic>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + Atomically replaces the atomic integer with it's bitwise OR with the specified value and returns the original value. + Source   +Edit   + +
+
+ +
+
+
+
proc fetchSub[T: SomeInteger](location: var Atomic[T]; value: T;
+                              order: MemoryOrder = moSequentiallyConsistent): T {.
+    importcpp: "#.fetch_sub(@)", header: "<atomic>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + Atomically subtracts a value to the atomic integer and returns the original value. + Source   +Edit   + +
+
+ +
+
+
+
proc fetchXor[T: SomeInteger](location: var Atomic[T]; value: T;
+                              order: MemoryOrder = moSequentiallyConsistent): T {.
+    importcpp: "#.fetch_xor(@)", header: "<atomic>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + Atomically replaces the atomic integer with it's bitwise XOR with the specified value and returns the original value. + Source   +Edit   + +
+
+ +
+
+
+
proc load[T](location: var Atomic[T];
+             order: MemoryOrder = moSequentiallyConsistent): T {.
+    importcpp: "#.load(@)", header: "<atomic>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + Atomically obtains the value of the atomic object. + Source   +Edit   + +
+
+ +
+
+
+
proc signalFence(order: MemoryOrder) {.importcpp: "std::atomic_signal_fence(@)",
+                                       header: "<atomic>", ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + Prevents reordering of accesses by the compiler as would fence, but inserts no CPU instructions for memory ordering. + Source   +Edit   + +
+
+ +
+
+
+
proc store[T](location: var Atomic[T]; desired: T;
+              order: MemoryOrder = moSequentiallyConsistent) {.
+    importcpp: "#.store(@)", header: "<atomic>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + Atomically replaces the value of the atomic object with the desired value. + Source   +Edit   + +
+
+ +
+
+
+
proc testAndSet(location: var AtomicFlag;
+                order: MemoryOrder = moSequentiallyConsistent): bool {.
+    importcpp: "#.test_and_set(@)", header: "<atomic>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + Atomically sets the atomic flag to true and returns the original value. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/atomics.idx b/atomics.idx new file mode 100644 index 0000000000000..7eae8df4cf51b --- /dev/null +++ b/atomics.idx @@ -0,0 +1,26 @@ +nimTitle atomics atomics.html module std/atomics 0 +nim MemoryOrder atomics.html#MemoryOrder enum MemoryOrder 62 +nim Atomic atomics.html#Atomic object Atomic 94 +nim AtomicFlag atomics.html#AtomicFlag object AtomicFlag 98 +nim load atomics.html#load,Atomic[T],MemoryOrder proc load[T](location: var Atomic[T]; order: MemoryOrder = moSequentiallyConsistent): T 103 +nim store atomics.html#store,Atomic[T],T,MemoryOrder proc store[T](location: var Atomic[T]; desired: T;\n order: MemoryOrder = moSequentiallyConsistent) 106 +nim exchange atomics.html#exchange,Atomic[T],T,MemoryOrder proc exchange[T](location: var Atomic[T]; desired: T;\n order: MemoryOrder = moSequentiallyConsistent): T 110 +nim compareExchange atomics.html#compareExchange,Atomic[T],T,T,MemoryOrder proc compareExchange[T](location: var Atomic[T]; expected: var T; desired: T;\n order: MemoryOrder = moSequentiallyConsistent): bool 114 +nim compareExchange atomics.html#compareExchange,Atomic[T],T,T,MemoryOrder,MemoryOrder proc compareExchange[T](location: var Atomic[T]; expected: var T; desired: T;\n success, failure: MemoryOrder): bool 119 +nim compareExchangeWeak atomics.html#compareExchangeWeak,Atomic[T],T,T,MemoryOrder proc compareExchangeWeak[T](location: var Atomic[T]; expected: var T; desired: T;\n order: MemoryOrder = moSequentiallyConsistent): bool 123 +nim compareExchangeWeak atomics.html#compareExchangeWeak,Atomic[T],T,T,MemoryOrder,MemoryOrder proc compareExchangeWeak[T](location: var Atomic[T]; expected: var T; desired: T;\n success, failure: MemoryOrder): bool 126 +nim fetchAdd atomics.html#fetchAdd,Atomic[T: SomeInteger],T,MemoryOrder proc fetchAdd[T: SomeInteger](location: var Atomic[T]; value: T;\n order: MemoryOrder = moSequentiallyConsistent): T 132 +nim fetchSub atomics.html#fetchSub,Atomic[T: SomeInteger],T,MemoryOrder proc fetchSub[T: SomeInteger](location: var Atomic[T]; value: T;\n order: MemoryOrder = moSequentiallyConsistent): T 136 +nim fetchAnd atomics.html#fetchAnd,Atomic[T: SomeInteger],T,MemoryOrder proc fetchAnd[T: SomeInteger](location: var Atomic[T]; value: T;\n order: MemoryOrder = moSequentiallyConsistent): T 140 +nim fetchOr atomics.html#fetchOr,Atomic[T: SomeInteger],T,MemoryOrder proc fetchOr[T: SomeInteger](location: var Atomic[T]; value: T;\n order: MemoryOrder = moSequentiallyConsistent): T 144 +nim fetchXor atomics.html#fetchXor,Atomic[T: SomeInteger],T,MemoryOrder proc fetchXor[T: SomeInteger](location: var Atomic[T]; value: T;\n order: MemoryOrder = moSequentiallyConsistent): T 148 +nim testAndSet atomics.html#testAndSet,AtomicFlag,MemoryOrder proc testAndSet(location: var AtomicFlag;\n order: MemoryOrder = moSequentiallyConsistent): bool 154 +nim clear atomics.html#clear,AtomicFlag,MemoryOrder proc clear(location: var AtomicFlag; order: MemoryOrder = moSequentiallyConsistent) 157 +nim fence atomics.html#fence,MemoryOrder proc fence(order: MemoryOrder) 160 +nim signalFence atomics.html#signalFence,MemoryOrder proc signalFence(order: MemoryOrder) 163 +nim atomicInc atomics.html#atomicInc,Atomic[T: SomeInteger],T proc atomicInc[T: SomeInteger](location: var Atomic[T]; value: T = 1) 419 +nim atomicDec atomics.html#atomicDec,Atomic[T: SomeInteger],T proc atomicDec[T: SomeInteger](location: var Atomic[T]; value: T = 1) 423 +nim `+=` atomics.html#+=,Atomic[T: SomeInteger],T proc `+=`[T: SomeInteger](location: var Atomic[T]; value: T) 427 +nim `-=` atomics.html#-=,Atomic[T: SomeInteger],T proc `-=`[T: SomeInteger](location: var Atomic[T]; value: T) 431 +nimgrp compareexchange atomics.html#compareExchange-procs-all proc 114 +nimgrp compareexchangeweak atomics.html#compareExchangeWeak-procs-all proc 123 diff --git a/backends.html b/backends.html new file mode 100644 index 0000000000000..c63e58de9ca4f --- /dev/null +++ b/backends.html @@ -0,0 +1,237 @@ + + + + + + + +Nim Backend Integration + + + + + + + + + + + + + + + + +
+
+

Nim Backend Integration

+
+ +
+ Source   +Edit   + +
+ +

+ +
Author:Puppet Master
Version:2.2.1

"Heresy grows from idleness." -- Unknown.

+ +

Introduction

The Nim Compiler User Guide documents the typical compiler invocation, using the compile or c command to transform a .nim file into one or more .c files which are then compiled with the platform's C compiler into a static binary. However, there are other commands to compile to C++, Objective-C, or JavaScript. This document tries to concentrate in a single place all the backend and interfacing options.

+

The Nim compiler supports mainly two backend families: the C, C++ and Objective-C targets and the JavaScript target. The C like targets creates source files that can be compiled into a library or a final executable. The JavaScript target can generate a .js file which you reference from an HTML file or create a standalone Node.js program.

+

On top of generating libraries or standalone applications, Nim offers bidirectional interfacing with the backend targets through generic and specific pragmas.

+ +

Backends

+

The C like targets

The commands to compile to either C, C++ or Objective-C are:

+
compileToC, cc
compile project with C code generator
+
compileToCpp, cpp
compile project to C++ code
+
compileToOC, objc
compile project to Objective C code
+

The most significant difference between these commands is that if you look into the nimcache directory you will find .c, .cpp or .m files, other than that all of them will produce a native binary for your project. This allows you to take the generated code and place it directly into a project using any of these languages. Here are some typical command- line invocations:

+

nim c hallo.nim
+nim cpp hallo.nim
+nim objc hallo.nim

+

The compiler commands select the target backend, but if needed you can specify additional switches for cross-compilation to select the target CPU, operative system or compiler/linker commands.

+ +

The JavaScript target

Nim can also generate JavaScript code through the js command.

+

Nim targets JavaScript 1.5 which is supported by any widely used browser. Since JavaScript does not have a portable means to include another module, Nim just generates a long .js file.

+

Features or modules that the JavaScript platform does not support are not available. This includes:

+
  • manual memory management (alloc, etc.)
  • +
  • casting and other unsafe operations (cast operator, zeroMem, etc.)
  • +
  • file management
  • +
  • OS-specific operations
  • +
  • threading, coroutines
  • +
  • some modules of the standard library
  • +
+

To compensate, the standard library has modules catered to the JS backend and more support will come in the future (for instance, Node.js bindings to get OS info).

+

To compile a Nim module into a .js file use the js command; the default is a .js file that is supposed to be referenced in an .html file. However, you can also run the code with nodejs (https://nodejs.org):

+

nim js -r examples/hallo.nim

+

If you experience errors saying that globalThis is not defined, be sure to run a recent version of Node.js (at least 12.0).

+ +

Interfacing

Nim offers bidirectional interfacing with the target backend. This means that you can call backend code from Nim and Nim code can be called by the backend code. Usually the direction of which calls which depends on your software architecture (is Nim your main program or is Nim providing a component?).

+ +

Nim code calling the backend

Nim code can interface with the backend through the Foreign function interface mainly through the importc pragma. The importc pragma is the generic way of making backend symbols available in Nim and is available in all the target backends (JavaScript too). The C++ or Objective-C backends have their respective ImportCpp and ImportObjC pragmas to call methods from classes.

+

Whenever you use any of these pragmas you need to integrate native code into your final binary. In the case of JavaScript this is no problem at all, the same HTML file which hosts the generated JavaScript will likely provide other JavaScript functions which you are importing with importc.

+

However, for the C like targets you need to link external code either statically or dynamically. The preferred way of integrating native code is to use dynamic linking because it allows you to compile Nim programs without the need for having the related development libraries installed. This is done through the dynlib pragma for import, though more specific control can be gained using the dynlib module.

+

The dynlibOverride command line switch allows to avoid dynamic linking if you need to statically link something instead. Nim wrappers designed to statically link source files can use the compile pragma if there are few sources or providing them along the Nim code is easier than using a system library. Libraries installed on the host system can be linked in with the PassL pragma.

+

To wrap native code, take a look at the c2nim tool which helps with the process of scanning and transforming header files into a Nim interface.

+ +

C invocation example

Create a logic.c file with the following content:

+

int addTwoIntegers(int a, int b)
+{
+  return a + b;
+}

+

Create a calculator.nim file with the following content:

+

{.compile: "logic.c".}
+proc addTwoIntegers(a, b: cint): cint {.importc.}
+
+when isMainModule:
+  echo addTwoIntegers(3, 7)

+

With these two files in place, you can run nim c -r calculator.nim and the Nim compiler will compile the logic.c file in addition to calculator.nim and link both into an executable, which outputs 10 when run. Another way to link the C file statically and get the same effect would be to remove the line with the compile pragma and run the following typical Unix commands:

+

gcc -c logic.c
+ar rvs mylib.a logic.o
+nim c --passL:mylib.a -r calculator.nim

+

Just like in this example we pass the path to the mylib.a library (and we could as well pass logic.o) we could be passing switches to link any other static C library.

+ +

JavaScript invocation example

Create a host.html file with the following content:

+

<html><body>
+<script type="text/javascript">
+function addTwoIntegers(a, b)
+{
+  return a + b;
+}
+</script>
+<script type="text/javascript" src="calculator.js"></script>
+</body></html>

+

Create a calculator.nim file with the following content (or reuse the one from the previous section):

+

proc addTwoIntegers(a, b: int): int {.importc.}
+
+when isMainModule:
+  echo addTwoIntegers(3, 7)

+

Compile the Nim code to JavaScript with nim js -o:calculator.js calculator.nim and open host.html in a browser. If the browser supports javascript, you should see the value 10 in the browser's console. Use the dom module for specific DOM querying and modification procs or take a look at karax for how to develop browser-based applications.

+ +

Backend code calling Nim

Backend code can interface with Nim code exposed through the exportc pragma. The exportc pragma is the generic way of making Nim symbols available to the backends. By default, the Nim compiler will mangle all the Nim symbols to avoid any name collision, so the most significant thing the exportc pragma does is maintain the Nim symbol name, or if specified, use an alternative symbol for the backend in case the symbol rules don't match.

+

The JavaScript target doesn't have any further interfacing considerations since it also has garbage collection, but the C targets require you to initialize Nim's internals, which is done calling a NimMain function. Also, C code requires you to specify a forward declaration for functions or the compiler will assume certain types for the return value and parameters which will likely make your program crash at runtime.

+

The name NimMain can be influenced via the --nimMainPrefix:prefix switch. Use --nimMainPrefix:MyLib and the function to call is named MyLibNimMain.

+

When compiling to static or dynamic libraries, they don't call destructors of global variables as normal Nim programs would do. A C API NimDestroyGlobals is provided to call these global destructors.

+ +

Nim invocation example from C

Create a fib.nim file with the following content:

+

proc fib(a: cint): cint {.exportc.} =
+  if a <= 2:
+    result = 1
+  else:
+    result = fib(a - 1) + fib(a - 2)

+

Create a maths.c file with the following content:

+

#include <stdio.h>
+
+int fib(int a);
+void NimMain();
+
+int main(void)
+{
+  NimMain();
+  for (int f = 0; f < 10; f++)
+    printf("Fib of %d is %d\n", f, fib(f));
+  return 0;
+}

+

Now you can run the following Unix like commands to first generate C sources from the Nim code, then link them into a static binary along your main C program:

+

nim c --noMain --noLinking fib.nim
+gcc -o m -I$HOME/.cache/nim/fib_d -Ipath/to/nim/lib $HOME/.cache/nim/fib_d/*.c maths.c

+

The first command runs the Nim compiler with three special options to avoid generating a main() function in the generated files and to avoid linking the object files into a final binary. All the generated files are placed into the nimcache directory. That's why the next command compiles the maths.c source plus all the .c files from nimcache. In addition to this path, you also have to tell the C compiler where to find Nim's nimbase.h header file.

+

Instead of depending on the generation of the individual .c files you can also ask the Nim compiler to generate a statically linked library:

+

nim c --app:staticLib fib.nim
+gcc -o m -Inimcache -Ipath/to/nim/lib maths.c libfib.nim.a

+

The Nim compiler will handle linking the source files generated in the nimcache directory into the libfib.nim.a static library, which you can then link into your C program. Note that these commands are generic and will vary for each system. For instance, on Linux systems you will likely need to use -ldl too to link in required dlopen functionality.

+ +

Nim invocation example from JavaScript

Create a mhost.html file with the following content:

+

<html><body>
+<script type="text/javascript" src="fib.js"></script>
+<script type="text/javascript">
+alert("Fib for 9 is " + fib(9));
+</script>
+</body></html>

+

Create a fib.nim file with the following content (or reuse the one from the previous section):

+

proc fib(a: cint): cint {.exportc.} =
+  if a <= 2:
+    result = 1
+  else:
+    result = fib(a - 1) + fib(a - 2)

+

Compile the Nim code to JavaScript with nim js -o:fib.js fib.nim and open mhost.html in a browser. If the browser supports javascript, you should see an alert box displaying the text Fib for 9 is 34. As mentioned earlier, JavaScript doesn't require an initialization call to NimMain or a similar function and you can call the exported Nim proc directly.

+ +

Nimcache naming logic

The nimcache directory is generated during compilation and will hold either temporary or final files depending on your backend target. The default name for the directory depends on the used backend and on your OS but you can use the --nimcache compiler switch to change it.

+ +

Memory management

In the previous sections, the NimMain() function reared its head. Since JavaScript already provides automatic memory management, you can freely pass objects between the two languages without problems. In C and derivate languages you need to be careful about what you do and how you share memory. The previous examples only dealt with simple scalar values, but passing a Nim string to C, or reading back a C string in Nim already requires you to be aware of who controls what to avoid crashing.

+ +

Strings and C strings

The manual mentions that Nim strings are implicitly convertible to cstrings which makes interaction usually painless. Most C functions accepting a Nim string converted to a cstring will likely not need to keep this string around and by the time they return the string won't be needed anymore.

+

A similar thing happens with C code invoking Nim code which returns a cstring. Consider the following proc:

+

proc gimme(): cstring {.exportc.} =
+  result = "Hey there C code! " & $rand(100)

+

Since Nim's reference counting mechanism is not aware of the C code, once the gimme proc has finished it can reclaim the memory of the cstring.

+ +

Custom data types

Just like strings, custom data types that are to be shared between Nim and the backend will need careful consideration of who controls who. If you want to hand a Nim reference to C code, you will need to use GC_ref to mark the reference as used, so it does not get freed. And for the C backend you will need to expose the GC_unref proc to clean up this memory when it is not required anymore.

+

Again, if you are wrapping a library which mallocs and frees data structures, you need to expose the appropriate free function to Nim so you can clean it up. And of course, once cleaned you should avoid accessing it from Nim (or C for that matter). Typically C data structures have their own malloc_structure and free_structure specific functions, so wrapping these for the Nim side should be enough.

+

+ +
+
+ + +
+
+ + + + diff --git a/backends.idx b/backends.idx new file mode 100644 index 0000000000000..dd7a22c50e1d8 --- /dev/null +++ b/backends.idx @@ -0,0 +1,19 @@ +markupTitle Nim Backend Integration backends.html Nim Backend Integration 0 +heading Introduction backends.html#introduction Introduction 0 +heading Backends backends.html#backends Backends 0 +heading The C like targets backends.html#backends-the-c-like-targets The C like targets 0 +heading The JavaScript target backends.html#backends-the-javascript-target The JavaScript target 0 +idx JavaScript backends.html#javascript_1 The JavaScript target 0 +idx nodejs backends.html#nodejs_1 The JavaScript target 0 +heading Interfacing backends.html#interfacing Interfacing 0 +heading Nim code calling the backend backends.html#interfacing-nim-code-calling-the-backend Nim code calling the backend 0 +heading C invocation example backends.html#nim-code-calling-the-backend-c-invocation-example C invocation example 0 +heading JavaScript invocation example backends.html#nim-code-calling-the-backend-javascript-invocation-example JavaScript invocation example 0 +heading Backend code calling Nim backends.html#interfacing-backend-code-calling-nim Backend code calling Nim 0 +heading Nim invocation example from C backends.html#backend-code-calling-nim-nim-invocation-example-from-c Nim invocation example from C 0 +heading Nim invocation example from JavaScript backends.html#backend-code-calling-nim-nim-invocation-example-from-javascript Nim invocation example from JavaScript 0 +heading Nimcache naming logic backends.html#interfacing-nimcache-naming-logic Nimcache naming logic 0 +idx nimcache backends.html#nimcache_1 Nimcache naming logic 0 +heading Memory management backends.html#memory-management Memory management 0 +heading Strings and C strings backends.html#memory-management-strings-and-c-strings Strings and C strings 0 +heading Custom data types backends.html#memory-management-custom-data-types Custom data types 0 diff --git a/base64.html b/base64.html new file mode 100644 index 0000000000000..ee1aaea33286c --- /dev/null +++ b/base64.html @@ -0,0 +1,244 @@ + + + + + + + +std/base64 + + + + + + + + + + + + + + + + +
+
+

std/base64

+
+ +
+ Source   +Edit   + +
+ +

This module implements a base64 encoder and decoder.

+

Unstable API.

+

Base64 is an encoding and decoding technique used to convert binary data to an ASCII string format. Each Base64 digit represents exactly 6 bits of data. Three 8-bit bytes (i.e., a total of 24 bits) can therefore be represented by four 6-bit Base64 digits.

+ +

Basic usage

+

Encoding data

+

Example:

+
import std/base64
+let encoded = encode("Hello World")
+assert encoded == "SGVsbG8gV29ybGQ="
Apart from strings you can also encode lists of integers or characters: +

Example:

+
import std/base64
+let encodedInts = encode([1'u8,2,3])
+assert encodedInts == "AQID"
+let encodedChars = encode(['h','e','y'])
+assert encodedChars == "aGV5"
+

Decoding data

+

Example:

+
import std/base64
+let decoded = decode("SGVsbG8gV29ybGQ=")
+assert decoded == "Hello World"
+

URL Safe Base64

+

Example:

+
import std/base64
+assert encode("c\xf7>", safe = true) == "Y_c-"
+assert encode("c\xf7>", safe = false) == "Y/c+"
+

See also

+

+
+

Procs

+
+
+
+
proc decode(s: string): string {....raises: [ValueError], tags: [], forbids: [].}
+
+ +

Decodes string s in base64 representation back into its original form. The initial whitespace is skipped.

+

See also:

+ + +

Example:

+
assert decode("SGVsbG8gV29ybGQ=") == "Hello World"
+assert decode("  SGVsbG8gV29ybGQ=") == "Hello World"
+ Source   +Edit   + +
+
+ +
+
+
+
proc encode[T: byte | char](s: openArray[T]; safe = false): string
+
+ +

Encodes s into base64 representation.

+

If safe is true then it will encode using the URL-Safe and Filesystem-safe standard alphabet characters, which substitutes - instead of + and _ instead of /.

+ +

See also:

+ + +

Example:

+
assert encode("Hello World") == "SGVsbG8gV29ybGQ="
+assert encode(['n', 'i', 'm']) == "bmlt"
+assert encode(@['n', 'i', 'm']) == "bmlt"
+assert encode([1'u8, 2, 3, 4, 5]) == "AQIDBAU="
+ Source   +Edit   + +
+
+
+
proc encode[T: SomeInteger and not byte](s: openArray[T]; safe = false): string {.
+    ...deprecated: "use `byte` or `char` instead".}
+
+
+ Deprecated: use `byte` or `char` instead +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc encodeMime(s: string; lineLen = 75.Positive; newLine = "\r\n"; safe = false): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Encodes s into base64 representation as lines. Used in email MIME format, use lineLen and newline.

+

This procedure encodes a string according to MIME spec.

+

If safe is true then it will encode using the URL-Safe and Filesystem-safe standard alphabet characters, which substitutes - instead of + and _ instead of /.

+ +

See also:

+ + +

Example:

+
assert encodeMime("Hello World", 4, "\n") == "SGVs\nbG8g\nV29y\nbGQ="
+ Source   +Edit   + +
+
+ +
+
+
+
proc initDecodeTable(): array[256, char] {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/base64.idx b/base64.idx new file mode 100644 index 0000000000000..3d71f8110a0ef --- /dev/null +++ b/base64.idx @@ -0,0 +1,12 @@ +nimTitle base64 base64.html module std/base64 0 +nim encode base64.html#encode,openArray[T] proc encode[T: byte | char](s: openArray[T]; safe = false): string 138 +nim encode base64.html#encode,openArray[T]_2 proc encode[T: SomeInteger and not byte](s: openArray[T]; safe = false): string 157 +nim encodeMime base64.html#encodeMime,string,string proc encodeMime(s: string; lineLen = 75.Positive; newLine = "\r\n"; safe = false): string 162 +nim initDecodeTable base64.html#initDecodeTable proc initDecodeTable(): array[256, char] 200 +nim decode base64.html#decode,string proc decode(s: string): string 215 +heading Basic usage base64.html#basic-usage Basic usage 0 +heading Encoding data base64.html#basic-usage-encoding-data Encoding data 0 +heading Decoding data base64.html#basic-usage-decoding-data Decoding data 0 +heading URL Safe Base64 base64.html#basic-usage-url-safe-base64 URL Safe Base64 0 +heading See also base64.html#see-also See also 0 +nimgrp encode base64.html#encode-procs-all proc 138 diff --git a/bcrypt.html b/bcrypt.html new file mode 100644 index 0000000000000..6898b84b967e5 --- /dev/null +++ b/bcrypt.html @@ -0,0 +1,275 @@ + + + + + + + +src/checksums/bcrypt + + + + + + + + + + + + + + + + +
+
+

src/checksums/bcrypt

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

bcrypt is a Blowfish-based password hashing algorithm that is designed to be adaptively expensive to provide resistance against brute force based attacks and additionally includes a salt for lookup table resistance.

+

Although bcrypt has been around for a long time, dating back to 1999, for many projects it is still a reasonable choice due to its adjustable cost factor that can provide security against all but the most well funded attackers.

+

This module's design is based loosely on Python's bcrypt module and supports generating the newer version 2b hashes as well as verifying the older 2a and the PHP equivalent of 2b called 2y.

+ +

Example:

+
import src/checksums/bcrypt
+
+# Generate a salt with a specific cost factor and use it to hash a password.
+let hashed = bcrypt("correct horse battery stape", generateSalt(8))
+

Example:

+
import src/checksums/bcrypt
+
+# Verify a password against a known good hash from i.e. a database.
+let knownGood = "$2b$06$LzUyyYdKBoEy9V4NTvxDH.O11KQP30/Zyp5pQAQ.0Cy89WnkD5Jjy"
+
+assert verify("correct horse battery staple", knownGood)

+
+

Types

+
+
+
CostFactor = range[4 .. 31]
+
+ + Adjustable cost factor. The value is a logarithm of 2, which means that a cost of 5 is twice as expensive as a cost of 4, and a cost of 16 is 2048 times more expensive than a cost of 5. + +
+
+
+
Hash = distinct HashBytes
+
+ + A 192 bit hash value produced by the bcrypt function. + +
+
+
+
Salt = object
+  costFactor*: CostFactor
+
+ + A random 128 bit salt used to provide security against rainbow table attacks that also includes the bcrypt version and cost factor. + +
+
+
+
SaltedHash = tuple[salt: Salt, hash: Hash]
+
+ + + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(s: Hash): string {....raises: [], tags: [], forbids: [].}
+
+ + Renders the given Hash into the canonical bcrypt-type Base64 representation. + +
+
+
+
proc `$`(s: Salt): string {....raises: [], tags: [], forbids: [].}
+
+ + Renders the given Salt into the canonical bcrypt-type Base64 representation along with its version and cost factor information. + +
+
+
+
proc `$`(s: SaltedHash): string {....raises: [], tags: [], forbids: [].}
+
+ + Renders the given SaltedHash into the canonical bcrypt-type Base64 representation resulting in the actual hash string to be stored. + +
+
+ +
+
+
+
proc bcrypt(password: openArray[char]; salt: Salt): SaltedHash {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Produces a SaltedHash from the given password string and salt.

+

Be careful when accepting a salt from a source outside of your control as a malicious user could pass in salts with a very high cost factor, resulting in denial of service attack.

+ +

Example:

+
let hashed = bcrypt("correct horse battery stape", generateSalt(8))
+ +
+
+ +
+
+
+
proc generateSalt(cost: CostFactor): Salt {....raises: ResourceExhaustedError,
+    tags: [], forbids: [].}
+
+ + Generates a new, random salt with the provided CostFactor. Only salts with subversion 2b are generated since it's the newest and default version of the reference bcrypt implementation. + +
+
+ +
+
+
+
proc parseSalt(salt: string): Salt {....raises: ValueError, tags: [], forbids: [].}
+
+ +

Parses a Salt from the given string (which may be a full bcrypt hash or only the preamble).

+

It accepts the 2a, 2b and 2y subversions.

+ +

Example:

+
# Parse full hash
+let salt1 = parseSalt "$2b$06$LzUyyYdKBoEy9V4NTvxDH."
+
+# Parse salt part
+let salt2 = parseSalt "$2b$06$LzUyyYdKBoEy9V4NTvxDH.PvwrAArbP0DUvDUFf8ChnJl6/79lh3C"
+
+assert $salt1 == "$2b$06$LzUyyYdKBoEy9V4NTvxDH."
+assert $salt2 == "$2b$06$LzUyyYdKBoEy9V4NTvxDH."
+ +
+
+ +
+
+
+
proc verify(password: openArray[char]; knownGood: string): bool {.
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ +

Verifies a given plaintext password against a hash from a known good source such as a database or other data storage.

+

Be careful when accepting a hash from a source outside of your control as a malicious user could pass salts with a very high cost factor, resulting in denial of service attack.

+ +

Example:

+
let knownGood = "$2b$06$LzUyyYdKBoEy9V4NTvxDH.O11KQP30/Zyp5pQAQ.0Cy89WnkD5Jjy"
+
+assert verify("correct horse battery staple", knownGood)
+ +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/bcrypt.idx b/bcrypt.idx new file mode 100644 index 0000000000000..935bffd755d2c --- /dev/null +++ b/bcrypt.idx @@ -0,0 +1,13 @@ +nimTitle bcrypt bcrypt.html module src/checksums/bcrypt 0 +nim CostFactor bcrypt.html#CostFactor type CostFactor 191 +nim Salt bcrypt.html#Salt object Salt 199 +nim Hash bcrypt.html#Hash type Hash 206 +nim SaltedHash bcrypt.html#SaltedHash tuple SaltedHash 209 +nim `$` bcrypt.html#$,Salt proc `$`(s: Salt): string 301 +nim `$` bcrypt.html#$,Hash proc `$`(s: Hash): string 306 +nim `$` bcrypt.html#$,SaltedHash proc `$`(s: SaltedHash): string 310 +nim parseSalt bcrypt.html#parseSalt,string proc parseSalt(salt: string): Salt 387 +nim generateSalt bcrypt.html#generateSalt,CostFactor proc generateSalt(cost: CostFactor): Salt 427 +nim bcrypt bcrypt.html#bcrypt,openArray[char],Salt proc bcrypt(password: openArray[char]; salt: Salt): SaltedHash 442 +nim verify bcrypt.html#verify,openArray[char],string proc verify(password: openArray[char]; knownGood: string): bool 499 +nimgrp $ bcrypt.html#$-procs-all proc 301 diff --git a/bitops.html b/bitops.html new file mode 100644 index 0000000000000..4f1c03b754914 --- /dev/null +++ b/bitops.html @@ -0,0 +1,975 @@ + + + + + + + +std/bitops + + + + + + + + + + + + + + + + +
+
+

std/bitops

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a series of low level methods for bit manipulation.

+

By default, compiler intrinsics are used where possible to improve performance on supported compilers: GCC, LLVM_GCC, CLANG, VCC, ICC.

+

The module will fallback to pure nim procs in case the backend is not supported. You can also use the flag noIntrinsicsBitOpts to disable compiler intrinsics.

+

This module is also compatible with other backends: JavaScript, NimScript as well as the compiletime VM.

+

As a result of using optimized functions/intrinsics, some functions can return undefined results if the input is invalid. You can use the flag noUndefinedBitOpts to force predictable behaviour for all input, causing a small performance hit.

+

At this time only fastLog2, firstSetBit, countLeadingZeroBits and countTrailingZeroBits may return undefined and/or platform dependent values if given invalid input.

+

+ +
+

Types

+
+
+
BitsRange[T] = range[0 .. sizeof(T) * 8 - 1]
+
+ + A range with all bit positions for type T. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func bitnot[T: SomeInteger](x: T): T {.magic: "BitnotI", ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + Computes the bitwise complement of the integer x. + Source   +Edit   + +
+
+ +
+
+
+
proc bitslice[T: SomeInteger](v: var T; slice: Slice[int]) {.inline.}
+
+ + Mutates v into an extracted (and shifted) slice of bits from v. +

Example:

+
var x = 0b101110
+x.bitslice(2 .. 4)
+doAssert x == 0b011
+ Source   +Edit   + +
+
+ +
+
+
+
func bitsliced[T: SomeInteger](v: T; slice: Slice[int]): T {.inline.}
+
+ + Returns an extracted (and shifted) slice of bits from v. +

Example:

+
doAssert 0b10111.bitsliced(2 .. 4) == 0b101
+doAssert 0b11100.bitsliced(0 .. 2) == 0b100
+doAssert 0b11100.bitsliced(0 ..< 3) == 0b100
+ Source   +Edit   + +
+
+ +
+
+
+
proc clearBit[T: SomeInteger](v: var T; bit: BitsRange[T]) {.inline.}
+
+ + Mutates v, with the bit at position bit set to 0. +

Example:

+
var v = 0b0000_0011'u8
+v.clearBit(1'u8)
+doAssert v == 0b0000_0001'u8
+ Source   +Edit   + +
+
+ +
+
+
+
proc clearMask[T: SomeInteger](v: var T; mask: T) {.inline.}
+
+ +

Mutates v, with all the 1 bits from mask set to 0.

+

Effectively maps to a bitand operation with an inverted mask.

+ +

Example:

+
var v = 0b0000_0011'u8
+v.clearMask(0b0000_1010'u8)
+doAssert v == 0b0000_0001'u8
+ Source   +Edit   + +
+
+
+
proc clearMask[T: SomeInteger](v: var T; slice: Slice[int]) {.inline.}
+
+ +

Mutates v, with all the 1 bits in the range of slice set to 0.

+

Effectively maps to a bitand operation with an inverted mask.

+ +

Example:

+
var v = 0b0000_0011'u8
+v.clearMask(1 .. 3)
+doAssert v == 0b0000_0001'u8
+ Source   +Edit   + +
+
+ +
+
+
+
func clearMasked[T: SomeInteger](v, mask: T): T {.inline.}
+
+ +

Returns v, with all the 1 bits from mask set to 0.

+

Effectively maps to a bitand operation with an inverted mask.

+ +

Example:

+
let v = 0b0000_0011'u8
+doAssert v.clearMasked(0b0000_1010'u8) == 0b0000_0001'u8
+ Source   +Edit   + +
+
+
+
func clearMasked[T: SomeInteger](v: T; slice: Slice[int]): T {.inline.}
+
+ +

Returns v, with all the 1 bits in the range of slice set to 0.

+

Effectively maps to a bitand operation with an inverted mask.

+ +

Example:

+
let v = 0b0000_0011'u8
+doAssert v.clearMasked(1 .. 3) == 0b0000_0001'u8
+ Source   +Edit   + +
+
+ +
+
+
+
func countLeadingZeroBits(x: SomeInteger): int {.inline.}
+
+ +

Returns the number of leading zero bits in an integer. If x is zero, when noUndefinedBitOpts is set, the result is 0, otherwise the result is undefined.

+

See also:

+ + +

Example:

+
doAssert countLeadingZeroBits(0b0000_0001'u8) == 7
+doAssert countLeadingZeroBits(0b0000_0010'u8) == 6
+doAssert countLeadingZeroBits(0b0000_0100'u8) == 5
+doAssert countLeadingZeroBits(0b0000_1000'u8) == 4
+doAssert countLeadingZeroBits(0b0000_1111'u8) == 4
+ Source   +Edit   + +
+
+ +
+
+
+
func countSetBits(x: SomeInteger): int {.inline.}
+
+ + Counts the set bits in an integer (also called Hamming weight). +

Example:

+
doAssert countSetBits(0b0000_0011'u8) == 2
+doAssert countSetBits(0b1010_1010'u8) == 4
+ Source   +Edit   + +
+
+ +
+
+
+
func countTrailingZeroBits(x: SomeInteger): int {.inline.}
+
+ +

Returns the number of trailing zeros in an integer. If x is zero, when noUndefinedBitOpts is set, the result is 0, otherwise the result is undefined.

+

See also:

+ + +

Example:

+
doAssert countTrailingZeroBits(0b0000_0001'u8) == 0
+doAssert countTrailingZeroBits(0b0000_0010'u8) == 1
+doAssert countTrailingZeroBits(0b0000_0100'u8) == 2
+doAssert countTrailingZeroBits(0b0000_1000'u8) == 3
+doAssert countTrailingZeroBits(0b0000_1111'u8) == 0
+ Source   +Edit   + +
+
+ +
+
+
+
func fastLog2(x: SomeInteger): int {.inline.}
+
+ + Quickly find the log base 2 of an integer. If x is zero, when noUndefinedBitOpts is set, the result is -1, otherwise the result is undefined. +

Example:

+
doAssert fastLog2(0b0000_0001'u8) == 0
+doAssert fastLog2(0b0000_0010'u8) == 1
+doAssert fastLog2(0b0000_0100'u8) == 2
+doAssert fastLog2(0b0000_1000'u8) == 3
+doAssert fastLog2(0b0000_1111'u8) == 3
+ Source   +Edit   + +
+
+ +
+
+
+
func firstSetBit(x: SomeInteger): int {.inline.}
+
+ + Returns the 1-based index of the least significant set bit of x. If x is zero, when noUndefinedBitOpts is set, the result is 0, otherwise the result is undefined. +

Example:

+
doAssert firstSetBit(0b0000_0001'u8) == 1
+doAssert firstSetBit(0b0000_0010'u8) == 2
+doAssert firstSetBit(0b0000_0100'u8) == 3
+doAssert firstSetBit(0b0000_1000'u8) == 4
+doAssert firstSetBit(0b0000_1111'u8) == 1
+ Source   +Edit   + +
+
+ +
+
+
+
proc flipBit[T: SomeInteger](v: var T; bit: BitsRange[T]) {.inline.}
+
+ + Mutates v, with the bit at position bit flipped. +

Example:

+
var v = 0b0000_0011'u8
+v.flipBit(1'u8)
+doAssert v == 0b0000_0001'u8
+
+v = 0b0000_0011'u8
+v.flipBit(2'u8)
+doAssert v == 0b0000_0111'u8
+ Source   +Edit   + +
+
+ +
+
+
+
proc flipMask[T: SomeInteger](v: var T; mask: T) {.inline.}
+
+ +

Mutates v, with all the 1 bits from mask flipped.

+

Effectively maps to a bitxor operation.

+ +

Example:

+
var v = 0b0000_0011'u8
+v.flipMask(0b0000_1010'u8)
+doAssert v == 0b0000_1001'u8
+ Source   +Edit   + +
+
+
+
proc flipMask[T: SomeInteger](v: var T; slice: Slice[int]) {.inline.}
+
+ +

Mutates v, with all the 1 bits in the range of slice flipped.

+

Effectively maps to a bitxor operation.

+ +

Example:

+
var v = 0b0000_0011'u8
+v.flipMask(1 .. 3)
+doAssert v == 0b0000_1101'u8
+ Source   +Edit   + +
+
+ +
+
+
+
func flipMasked[T: SomeInteger](v, mask: T): T {.inline.}
+
+ +

Returns v, with all the 1 bits from mask flipped.

+

Effectively maps to a bitxor operation.

+ +

Example:

+
let v = 0b0000_0011'u8
+doAssert v.flipMasked(0b0000_1010'u8) == 0b0000_1001'u8
+ Source   +Edit   + +
+
+
+
func flipMasked[T: SomeInteger](v: T; slice: Slice[int]): T {.inline.}
+
+ +

Returns v, with all the 1 bits in the range of slice flipped.

+

Effectively maps to a bitxor operation.

+ +

Example:

+
let v = 0b0000_0011'u8
+doAssert v.flipMasked(1 .. 3) == 0b0000_1101'u8
+ Source   +Edit   + +
+
+ +
+
+
+
proc mask[T: SomeInteger](v: var T; mask: T) {.inline.}
+
+ +

Mutates v, with only the 1 bits from mask matching those of v set to 1.

+

Effectively maps to a bitand operation.

+ +

Example:

+
var v = 0b0000_0011'u8
+v.mask(0b0000_1010'u8)
+doAssert v == 0b0000_0010'u8
+ Source   +Edit   + +
+
+
+
proc mask[T: SomeInteger](v: var T; slice: Slice[int]) {.inline.}
+
+ +

Mutates v, with only the 1 bits in the range of slice matching those of v set to 1.

+

Effectively maps to a bitand operation.

+ +

Example:

+
var v = 0b0000_1011'u8
+v.mask(1 .. 3)
+doAssert v == 0b0000_1010'u8
+ Source   +Edit   + +
+
+ +
+
+
+
proc masked[T: SomeInteger](v, mask: T): T {.inline.}
+
+ +

Returns v, with only the 1 bits from mask matching those of v set to 1.

+

Effectively maps to a bitand operation.

+ +

Example:

+
let v = 0b0000_0011'u8
+doAssert v.masked(0b0000_1010'u8) == 0b0000_0010'u8
+ Source   +Edit   + +
+
+
+
func masked[T: SomeInteger](v: T; slice: Slice[int]): T {.inline.}
+
+ +

Returns v, with only the 1 bits in the range of slice matching those of v set to 1.

+

Effectively maps to a bitand operation.

+ +

Example:

+
let v = 0b0000_1011'u8
+doAssert v.masked(1 .. 3) == 0b0000_1010'u8
+ Source   +Edit   + +
+
+ +
+
+
+
func parityBits(x: SomeInteger): int {.inline.}
+
+ + Calculate the bit parity in an integer. If the number of 1-bits is odd, the parity is 1, otherwise 0. +

Example:

+
doAssert parityBits(0b0000_0000'u8) == 0
+doAssert parityBits(0b0101_0001'u8) == 1
+doAssert parityBits(0b0110_1001'u8) == 0
+doAssert parityBits(0b0111_1111'u8) == 1
+ Source   +Edit   + +
+
+ +
+
+
+
func popcount(x: SomeInteger): int {.inline.}
+
+ + Alias for countSetBits (Hamming weight). + Source   +Edit   + +
+
+ +
+
+
+
func reverseBits[T: SomeUnsignedInt](x: T): T
+
+ + Return the bit reversal of x. +

Example:

+
doAssert reverseBits(0b10100100'u8) == 0b00100101'u8
+doAssert reverseBits(0xdd'u8) == 0xbb'u8
+doAssert reverseBits(0xddbb'u16) == 0xddbb'u16
+doAssert reverseBits(0xdeadbeef'u32) == 0xf77db57b'u32
+ Source   +Edit   + +
+
+ +
+
+
+
func rotateLeftBits[T: SomeUnsignedInt](value: T;
+                                        shift: range[0 .. (sizeof(T) * 8)]): T {.
+    inline.}
+
+ + Left-rotate bits in a value. +

Example:

+
doAssert rotateLeftBits(0b0110_1001'u8, 4) == 0b1001_0110'u8
+doAssert rotateLeftBits(0b00111100_11000011'u16, 8) ==
+  0b11000011_00111100'u16
+doAssert rotateLeftBits(0b0000111111110000_1111000000001111'u32, 16) ==
+  0b1111000000001111_0000111111110000'u32
+doAssert rotateLeftBits(0b00000000111111111111111100000000_11111111000000000000000011111111'u64, 32) ==
+  0b11111111000000000000000011111111_00000000111111111111111100000000'u64
+ Source   +Edit   + +
+
+ +
+
+
+
func rotateRightBits[T: SomeUnsignedInt](value: T;
+    shift: range[0 .. (sizeof(T) * 8)]): T {.inline.}
+
+ + Right-rotate bits in a value. +

Example:

+
doAssert rotateRightBits(0b0110_1001'u8, 4) == 0b1001_0110'u8
+doAssert rotateRightBits(0b00111100_11000011'u16, 8) ==
+  0b11000011_00111100'u16
+doAssert rotateRightBits(0b0000111111110000_1111000000001111'u32, 16) ==
+  0b1111000000001111_0000111111110000'u32
+doAssert rotateRightBits(0b00000000111111111111111100000000_11111111000000000000000011111111'u64, 32) ==
+  0b11111111000000000000000011111111_00000000111111111111111100000000'u64
+ Source   +Edit   + +
+
+ +
+
+
+
proc setBit[T: SomeInteger](v: var T; bit: BitsRange[T]) {.inline.}
+
+ + Mutates v, with the bit at position bit set to 1. +

Example:

+
var v = 0b0000_0011'u8
+v.setBit(5'u8)
+doAssert v == 0b0010_0011'u8
+ Source   +Edit   + +
+
+ +
+
+
+
proc setMask[T: SomeInteger](v: var T; mask: T) {.inline.}
+
+ +

Mutates v, with all the 1 bits from mask set to 1.

+

Effectively maps to a bitor operation.

+ +

Example:

+
var v = 0b0000_0011'u8
+v.setMask(0b0000_1010'u8)
+doAssert v == 0b0000_1011'u8
+ Source   +Edit   + +
+
+
+
proc setMask[T: SomeInteger](v: var T; slice: Slice[int]) {.inline.}
+
+ +

Mutates v, with all the 1 bits in the range of slice set to 1.

+

Effectively maps to a bitor operation.

+ +

Example:

+
var v = 0b0000_0011'u8
+v.setMask(2 .. 3)
+doAssert v == 0b0000_1111'u8
+ Source   +Edit   + +
+
+ +
+
+
+
func setMasked[T: SomeInteger](v, mask: T): T {.inline.}
+
+ +

Returns v, with all the 1 bits from mask set to 1.

+

Effectively maps to a bitor operation.

+ +

Example:

+
let v = 0b0000_0011'u8
+doAssert v.setMasked(0b0000_1010'u8) == 0b0000_1011'u8
+ Source   +Edit   + +
+
+
+
func setMasked[T: SomeInteger](v: T; slice: Slice[int]): T {.inline.}
+
+ +

Returns v, with all the 1 bits in the range of slice set to 1.

+

Effectively maps to a bitor operation.

+ +

Example:

+
let v = 0b0000_0011'u8
+doAssert v.setMasked(2 .. 3) == 0b0000_1111'u8
+ Source   +Edit   + +
+
+ +
+
+
+
proc testBit[T: SomeInteger](v: T; bit: BitsRange[T]): bool {.inline.}
+
+ + Returns true if the bit in v at positions bit is set to 1. +

Example:

+
let v = 0b0000_1111'u8
+doAssert v.testBit(0)
+doAssert not v.testBit(7)
+ Source   +Edit   + +
+
+ +
+
+
+
func toMask[T: SomeInteger](slice: Slice[int]): T {.inline.}
+
+ + Creates a bitmask based on a slice of bits. +

Example:

+
doAssert toMask[int32](1 .. 3) == 0b1110'i32
+doAssert toMask[int32](0 .. 3) == 0b1111'i32
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro bitand[T: SomeInteger](x, y: T; z: varargs[T]): T
+
+ + Computes the bitwise and of all arguments collectively. + Source   +Edit   + +
+
+ +
+
+
+
macro bitor[T: SomeInteger](x, y: T; z: varargs[T]): T
+
+ + Computes the bitwise or of all arguments collectively. + Source   +Edit   + +
+
+ +
+
+
+
macro bitxor[T: SomeInteger](x, y: T; z: varargs[T]): T
+
+ + Computes the bitwise xor of all arguments collectively. + Source   +Edit   + +
+
+ +
+
+
+
macro clearBits(v: typed; bits: varargs[typed]): untyped
+
+ + Mutates v, with the bits at positions bits set to 0. +

Example:

+
var v = 0b1111_1111'u8
+v.clearBits(1, 3, 5, 7)
+doAssert v == 0b0101_0101'u8
+ Source   +Edit   + +
+
+ +
+
+
+
macro flipBits(v: typed; bits: varargs[typed]): untyped
+
+ + Mutates v, with the bits at positions bits set to 0. +

Example:

+
var v = 0b0000_1111'u8
+v.flipBits(1, 3, 5, 7)
+doAssert v == 0b1010_0101'u8
+ Source   +Edit   + +
+
+ +
+
+
+
macro setBits(v: typed; bits: varargs[typed]): untyped
+
+ + Mutates v, with the bits at positions bits set to 1. +

Example:

+
var v = 0b0000_0011'u8
+v.setBits(3, 5, 7)
+doAssert v == 0b1010_1011'u8
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/bitops.idx b/bitops.idx new file mode 100644 index 0000000000000..47487577e5bcc --- /dev/null +++ b/bitops.idx @@ -0,0 +1,51 @@ +nimTitle bitops bitops.html module std/bitops 0 +nim bitnot bitops.html#bitnot,T proc bitnot[T: SomeInteger](x: T): T 32 +nim bitand bitops.html#bitand.m,T,T,varargs[T] macro bitand[T: SomeInteger](x, y: T; z: varargs[T]): T 41 +nim bitor bitops.html#bitor.m,T,T,varargs[T] macro bitor[T: SomeInteger](x, y: T; z: varargs[T]): T 48 +nim bitxor bitops.html#bitxor.m,T,T,varargs[T] macro bitxor[T: SomeInteger](x, y: T; z: varargs[T]): T 55 +nim BitsRange bitops.html#BitsRange type BitsRange 63 +nim bitsliced bitops.html#bitsliced,T,Slice[int] proc bitsliced[T: SomeInteger](v: T; slice: Slice[int]): T 72 +nim bitslice bitops.html#bitslice,T,Slice[int] proc bitslice[T: SomeInteger](v: var T; slice: Slice[int]) 84 +nim toMask bitops.html#toMask,Slice[int] proc toMask[T: SomeInteger](slice: Slice[int]): T 96 +nim masked bitops.html#masked,T,T proc masked[T: SomeInteger](v, mask: T): T 107 +nim masked bitops.html#masked,T,Slice[int] proc masked[T: SomeInteger](v: T; slice: Slice[int]): T 118 +nim mask bitops.html#mask,T,T proc mask[T: SomeInteger](v: var T; mask: T) 129 +nim mask bitops.html#mask,T,Slice[int] proc mask[T: SomeInteger](v: var T; slice: Slice[int]) 141 +nim setMasked bitops.html#setMasked,T,T proc setMasked[T: SomeInteger](v, mask: T): T 153 +nim setMasked bitops.html#setMasked,T,Slice[int] proc setMasked[T: SomeInteger](v: T; slice: Slice[int]): T 163 +nim setMask bitops.html#setMask,T,T proc setMask[T: SomeInteger](v: var T; mask: T) 173 +nim setMask bitops.html#setMask,T,Slice[int] proc setMask[T: SomeInteger](v: var T; slice: Slice[int]) 184 +nim clearMasked bitops.html#clearMasked,T,T proc clearMasked[T: SomeInteger](v, mask: T): T 195 +nim clearMasked bitops.html#clearMasked,T,Slice[int] proc clearMasked[T: SomeInteger](v: T; slice: Slice[int]): T 206 +nim clearMask bitops.html#clearMask,T,T proc clearMask[T: SomeInteger](v: var T; mask: T) 217 +nim clearMask bitops.html#clearMask,T,Slice[int] proc clearMask[T: SomeInteger](v: var T; slice: Slice[int]) 229 +nim flipMasked bitops.html#flipMasked,T,T proc flipMasked[T: SomeInteger](v, mask: T): T 241 +nim flipMasked bitops.html#flipMasked,T,Slice[int] proc flipMasked[T: SomeInteger](v: T; slice: Slice[int]): T 251 +nim flipMask bitops.html#flipMask,T,T proc flipMask[T: SomeInteger](v: var T; mask: T) 261 +nim flipMask bitops.html#flipMask,T,Slice[int] proc flipMask[T: SomeInteger](v: var T; slice: Slice[int]) 272 +nim setBit bitops.html#setBit,T,BitsRange[T: SomeInteger] proc setBit[T: SomeInteger](v: var T; bit: BitsRange[T]) 283 +nim clearBit bitops.html#clearBit,T,BitsRange[T: SomeInteger] proc clearBit[T: SomeInteger](v: var T; bit: BitsRange[T]) 292 +nim flipBit bitops.html#flipBit,T,BitsRange[T: SomeInteger] proc flipBit[T: SomeInteger](v: var T; bit: BitsRange[T]) 301 +nim setBits bitops.html#setBits.m,typed,varargs[typed] macro setBits(v: typed; bits: varargs[typed]): untyped 314 +nim clearBits bitops.html#clearBits.m,typed,varargs[typed] macro clearBits(v: typed; bits: varargs[typed]): untyped 326 +nim flipBits bitops.html#flipBits.m,typed,varargs[typed] macro flipBits(v: typed; bits: varargs[typed]): untyped 338 +nim testBit bitops.html#testBit,T,BitsRange[T: SomeInteger] proc testBit[T: SomeInteger](v: T; bit: BitsRange[T]): bool 351 +nim countSetBits bitops.html#countSetBits,SomeInteger proc countSetBits(x: SomeInteger): int 488 +nim popcount bitops.html#popcount,SomeInteger proc popcount(x: SomeInteger): int 496 +nim parityBits bitops.html#parityBits,SomeInteger proc parityBits(x: SomeInteger): int 500 +nim firstSetBit bitops.html#firstSetBit,SomeInteger proc firstSetBit(x: SomeInteger): int 522 +nim fastLog2 bitops.html#fastLog2,SomeInteger proc fastLog2(x: SomeInteger): int 565 +nim countLeadingZeroBits bitops.html#countLeadingZeroBits,SomeInteger proc countLeadingZeroBits(x: SomeInteger): int 604 +nim countTrailingZeroBits bitops.html#countTrailingZeroBits,SomeInteger proc countTrailingZeroBits(x: SomeInteger): int 632 +nim rotateLeftBits bitops.html#rotateLeftBits,T,range[] proc rotateLeftBits[T: SomeUnsignedInt](value: T; shift: range[0 .. (sizeof(T) * 8)]): T 785 +nim rotateRightBits bitops.html#rotateRightBits,T,range[] proc rotateRightBits[T: SomeUnsignedInt](value: T; shift: range[0 .. (sizeof(T) * 8)]): T 813 +nim reverseBits bitops.html#reverseBits,T proc reverseBits[T: SomeUnsignedInt](x: T): T 848 +idx Hamming weight bitops.html#hamming-weight_1 Module bitops 0 +nimgrp flipmask bitops.html#flipMask-procs-all proc 261 +nimgrp flipmasked bitops.html#flipMasked-procs-all proc 241 +nimgrp masked bitops.html#masked-procs-all proc 107 +nimgrp mask bitops.html#mask-procs-all proc 129 +nimgrp clearmask bitops.html#clearMask-procs-all proc 217 +nimgrp setmasked bitops.html#setMasked-procs-all proc 153 +nimgrp clearmasked bitops.html#clearMasked-procs-all proc 195 +nimgrp setmask bitops.html#setMask-procs-all proc 173 diff --git a/bitops_utils.html b/bitops_utils.html new file mode 100644 index 0000000000000..3d648b1ca2ae6 --- /dev/null +++ b/bitops_utils.html @@ -0,0 +1,182 @@ + + + + + + + +std/private/bitops_utils + + + + + + + + + + + + + + + + +
+
+

std/private/bitops_utils

+
+ +
+ Source   +Edit   + +
+ +

+
+

Templates

+
+
+
+
template castToUnsigned(x: int): uint
+
+ + + Source   +Edit   + +
+
+
+
template castToUnsigned(x: int8): uint8
+
+ + + Source   +Edit   + +
+
+
+
template castToUnsigned(x: int16): uint16
+
+ + + Source   +Edit   + +
+
+
+
template castToUnsigned(x: int32): uint32
+
+ + + Source   +Edit   + +
+
+
+
template castToUnsigned(x: int64): uint64
+
+ + + Source   +Edit   + +
+
+
+
template castToUnsigned[T: SomeUnsignedInt](x: T): T
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template forwardImpl(impl, arg) {.dirty.}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/bitops_utils.idx b/bitops_utils.idx new file mode 100644 index 0000000000000..b66cb9abb4416 --- /dev/null +++ b/bitops_utils.idx @@ -0,0 +1,9 @@ +nimTitle bitops_utils bitops_utils.html module std/private/bitops_utils 0 +nim forwardImpl bitops_utils.html#forwardImpl.t,, template forwardImpl(impl, arg) 1 +nim castToUnsigned bitops_utils.html#castToUnsigned.t,int8 template castToUnsigned(x: int8): uint8 17 +nim castToUnsigned bitops_utils.html#castToUnsigned.t,int16 template castToUnsigned(x: int16): uint16 18 +nim castToUnsigned bitops_utils.html#castToUnsigned.t,int32 template castToUnsigned(x: int32): uint32 19 +nim castToUnsigned bitops_utils.html#castToUnsigned.t,int64 template castToUnsigned(x: int64): uint64 20 +nim castToUnsigned bitops_utils.html#castToUnsigned.t,int template castToUnsigned(x: int): uint 21 +nim castToUnsigned bitops_utils.html#castToUnsigned.t,T template castToUnsigned[T: SomeUnsignedInt](x: T): T 22 +nimgrp casttounsigned bitops_utils.html#castToUnsigned-templates-all template 17 diff --git a/browsers.html b/browsers.html new file mode 100644 index 0000000000000..2f4304785f172 --- /dev/null +++ b/browsers.html @@ -0,0 +1,188 @@ + + + + + + + +std/browsers + + + + + + + + + + + + + + + + +
+
+

std/browsers

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a simple proc for opening URLs with the user's default browser.

+

Unstable API.

+

+ +
+

Consts

+
+
+
osOpenCmd = "xdg-open"
+
+ + +Alias for the operating system specific "open" command, "open" on OSX, MacOS and Windows, "xdg-open" on Linux, BSD, etc. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc openDefaultBrowser() {....deprecated: "not implemented, please open with a specific url instead",
+                            raises: [IOError],
+                            tags: [ExecIOEffect, ReadEnvEffect, RootEffect],
+                            forbids: [].}
+
+
+ Deprecated: not implemented, please open with a specific url instead +
+ +

Intends to open the user's default browser without any url (blank page). This does not block. Intends to implement IETF RFC-6694 Section 3, ("about:blank" is reserved for a blank page).

+

Beware that this intended behavior is not implemented and considered not worthy to implement here.

+

The following describes the behavior of current implementation:

+
  • Under Windows, this will only cause a pop-up dialog +asking the assocated application with about +(as Windows simply treats about: as a protocol like http).
  • +
  • Under Mac OS X the open "about:blank" command is used.
  • +
  • Under Unix, it is checked if xdg-open exists and used +if it does and open the application assocated with text/html mime +(not x-scheme-handler/http, so maybe html-viewer +other than your default browser is opened). +Otherwise the environment variable BROWSER is used +to determine the default browser to use.
  • +
+

This proc doesn't raise an exception on error, beware.

+

block: openDefaultBrowser()

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc openDefaultBrowser(url: string) {....raises: [IOError], tags: [ExecIOEffect,
+    ReadEnvEffect, RootEffect], forbids: [].}
+
+ +

Opens url with the user's default browser. This does not block. The URL must not be empty string, to open on a blank page see openDefaultBrowser().

+

Under Windows, ShellExecute is used. Under Mac OS X the open command is used. Under Unix, it is checked if xdg-open exists and used if it does. Otherwise the environment variable BROWSER is used to determine the default browser to use.

+

This proc doesn't raise an exception on error, beware.

+

block: openDefaultBrowser("https://nim-lang.org")

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/browsers.idx b/browsers.idx new file mode 100644 index 0000000000000..5c9c4398b4d3c --- /dev/null +++ b/browsers.idx @@ -0,0 +1,5 @@ +nimTitle browsers browsers.html module std/browsers 0 +nim osOpenCmd browsers.html#osOpenCmd const osOpenCmd 32 +nim openDefaultBrowser browsers.html#openDefaultBrowser,string proc openDefaultBrowser(url: string) 63 +nim openDefaultBrowser browsers.html#openDefaultBrowser proc openDefaultBrowser() 80 +nimgrp opendefaultbrowser browsers.html#openDefaultBrowser-procs-all proc 63 diff --git a/cgi.html b/cgi.html new file mode 100644 index 0000000000000..1f3dfc0941d11 --- /dev/null +++ b/cgi.html @@ -0,0 +1,981 @@ + + + + + + + +std/cgi + + + + + + + + + + + + + + + + +
+
+

std/cgi

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements helper procs for CGI applications. Example:

+

import std/[strtabs, cgi]
+
+# Fill the values when debugging:
+when debug:
+  setTestData("name", "Klaus", "password", "123456")
+# read the data into `myData`
+var myData = readData()
+# check that the data's variable names are "name" or "password"
+validateData(myData, "name", "password")
+# start generating content:
+writeContentType()
+# generate content:
+write(stdout, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n")
+write(stdout, "<html><head><title>Test</title></head><body>\n")
+writeLine(stdout, "your name: " & myData["name"])
+writeLine(stdout, "your password: " & myData["password"])
+writeLine(stdout, "</body></html>")

+

+ +
+

Types

+
+
+
CgiError = object of IOError
+
+ + Exception that is raised if a CGI error occurs. + Source   +Edit   + +
+
+
+
RequestMethod = enum
+  methodNone,               ## no REQUEST_METHOD environment variable
+  methodPost,               ## query uses the POST method
+  methodGet                  ## query uses the GET method
+
+ + The used request method. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc cgiError(msg: string) {.noreturn, ...raises: [CgiError], tags: [], forbids: [].}
+
+ + Raises a CgiError exception with message msg. + Source   +Edit   + +
+
+ +
+
+
+
proc existsCookie(name: string): bool {....raises: [], tags: [ReadEnvEffect],
+                                        forbids: [].}
+
+ + Checks if a cookie of name exists. + Source   +Edit   + +
+
+ +
+
+
+
proc getContentLength(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the CONTENT_LENGTH environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getContentType(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the CONTENT_TYPE environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getCookie(name: string): string {....raises: [], tags: [ReadEnvEffect],
+                                       forbids: [].}
+
+ + Gets a cookie. If no cookie of name exists, "" is returned. + Source   +Edit   + +
+
+ +
+
+
+
proc getDocumentRoot(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the DOCUMENT_ROOT environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getGatewayInterface(): string {....raises: [], tags: [ReadEnvEffect],
+                                     forbids: [].}
+
+ + Returns contents of the GATEWAY_INTERFACE environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getHttpAccept(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the HTTP_ACCEPT environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getHttpAcceptCharset(): string {....raises: [], tags: [ReadEnvEffect],
+                                      forbids: [].}
+
+ + Returns contents of the HTTP_ACCEPT_CHARSET environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getHttpAcceptEncoding(): string {....raises: [], tags: [ReadEnvEffect],
+                                       forbids: [].}
+
+ + Returns contents of the HTTP_ACCEPT_ENCODING environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getHttpAcceptLanguage(): string {....raises: [], tags: [ReadEnvEffect],
+                                       forbids: [].}
+
+ + Returns contents of the HTTP_ACCEPT_LANGUAGE environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getHttpConnection(): string {....raises: [], tags: [ReadEnvEffect],
+                                   forbids: [].}
+
+ + Returns contents of the HTTP_CONNECTION environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getHttpCookie(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the HTTP_COOKIE environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getHttpHost(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the HTTP_HOST environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getHttpReferer(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the HTTP_REFERER environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getHttpUserAgent(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the HTTP_USER_AGENT environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getPathInfo(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the PATH_INFO environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getPathTranslated(): string {....raises: [], tags: [ReadEnvEffect],
+                                   forbids: [].}
+
+ + Returns contents of the PATH_TRANSLATED environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getQueryString(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the QUERY_STRING environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getRemoteAddr(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the REMOTE_ADDR environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getRemoteHost(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the REMOTE_HOST environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getRemoteIdent(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the REMOTE_IDENT environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getRemotePort(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the REMOTE_PORT environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getRemoteUser(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the REMOTE_USER environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getRequestMethod(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the REQUEST_METHOD environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getRequestURI(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the REQUEST_URI environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getScriptFilename(): string {....raises: [], tags: [ReadEnvEffect],
+                                   forbids: [].}
+
+ + Returns contents of the SCRIPT_FILENAME environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getScriptName(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the SCRIPT_NAME environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getServerAddr(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the SERVER_ADDR environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getServerAdmin(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the SERVER_ADMIN environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getServerName(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the SERVER_NAME environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getServerPort(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns contents of the SERVER_PORT environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getServerProtocol(): string {....raises: [], tags: [ReadEnvEffect],
+                                   forbids: [].}
+
+ + Returns contents of the SERVER_PROTOCOL environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getServerSignature(): string {....raises: [], tags: [ReadEnvEffect],
+                                    forbids: [].}
+
+ + Returns contents of the SERVER_SIGNATURE environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc getServerSoftware(): string {....raises: [], tags: [ReadEnvEffect],
+                                   forbids: [].}
+
+ + Returns contents of the SERVER_SOFTWARE environment variable. + Source   +Edit   + +
+
+ +
+
+
+
proc readData(allowedMethods: set[RequestMethod] = {methodNone, methodPost,
+    methodGet}): StringTableRef {....raises: [CgiError, ValueError, IOError],
+                                  tags: [ReadEnvEffect, ReadIOEffect],
+                                  forbids: [].}
+
+ + Reads CGI data. If the client does not use a method listed in the allowedMethods set, a CgiError exception is raised. + Source   +Edit   + +
+
+
+
proc readData(data: string): StringTableRef {....raises: [], tags: [], forbids: [].}
+
+ + Reads CGI data from a string. + Source   +Edit   + +
+
+ +
+
+
+
proc setCookie(name, value: string) {....raises: [IOError], tags: [WriteIOEffect],
+                                      forbids: [].}
+
+ + Sets a cookie. + Source   +Edit   + +
+
+ +
+
+
+
proc setStackTraceStdout() {....raises: [], tags: [], forbids: [].}
+
+ + Makes Nim output stacktraces to stdout, instead of server log. + Source   +Edit   + +
+
+ +
+
+
+
proc setTestData(keysvalues: varargs[string]) {....raises: [OSError],
+    tags: [WriteEnvEffect], forbids: [].}
+
+ +

Fills the appropriate environment variables to test your CGI application. This can only simulate the 'GET' request method. keysvalues should provide embedded (name, value)-pairs. Example:

+

setTestData("name", "Hanz", "password", "12345")

+ + Source   +Edit   + +
+
+ +
+
+
+
proc validateData(data: StringTableRef; validKeys: varargs[string]) {.
+    ...raises: [CgiError], tags: [], forbids: [].}
+
+ + Validates data; raises CgiError if this fails. This checks that each variable name of the CGI data occurs in the validKeys array. + Source   +Edit   + +
+
+ +
+
+
+
proc writeContentType() {....raises: [IOError], tags: [WriteIOEffect], forbids: [].}
+
+ +

Calls this before starting to send your HTML data to stdout. This implements this part of the CGI protocol:

+

write(stdout, "Content-type: text/html\n\n")

+ + Source   +Edit   + +
+
+ +
+
+
+
proc writeErrorMessage(data: string) {....raises: [IOError], tags: [WriteIOEffect],
+                                       forbids: [].}
+
+ + Tries to reset browser state and writes data to stdout in <plaintext> tag. + Source   +Edit   + +
+
+ +
+
+
+
proc xmlEncode(s: string): string {....raises: [], tags: [], forbids: [].}
+
+ + Encodes a value to be XML safe:
  • " is replaced by &quot;
  • +
  • < is replaced by &lt;
  • +
  • > is replaced by &gt;
  • +
  • & is replaced by &amp;
  • +
  • every other character is carried over.
  • +
+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator decodeData(allowedMethods: set[RequestMethod] = {methodNone,
+    methodPost, methodGet}): tuple[key, value: string] {.
+    ...raises: [CgiError, ValueError, IOError],
+    tags: [ReadEnvEffect, ReadIOEffect], forbids: [].}
+
+ + Reads and decodes CGI data and yields the (name, value) pairs the data consists of. If the client does not use a method listed in the allowedMethods set, a CgiError exception is raised. + Source   +Edit   + +
+
+
+
iterator decodeData(data: string): tuple[key, value: string] {....raises: [],
+    tags: [], forbids: [].}
+
+ + Reads and decodes CGI data and yields the (name, value) pairs the data consists of. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/cgi.idx b/cgi.idx new file mode 100644 index 0000000000000..45a87677dd4f8 --- /dev/null +++ b/cgi.idx @@ -0,0 +1,54 @@ +nimTitle cgi cgi.html module std/cgi 0 +nim xmlEncode cgi.html#xmlEncode,string proc xmlEncode(s: string): string 47 +nim CgiError cgi.html#CgiError object CgiError 58 +nim methodNone cgi.html#methodNone RequestMethod.methodNone 59 +nim methodPost cgi.html#methodPost RequestMethod.methodPost 59 +nim methodGet cgi.html#methodGet RequestMethod.methodGet 59 +nim RequestMethod cgi.html#RequestMethod enum RequestMethod 59 +nim cgiError cgi.html#cgiError,string proc cgiError(msg: string) 64 +nim decodeData cgi.html#decodeData.i,string iterator decodeData(data: string): tuple[key, value: string] 87 +nim decodeData cgi.html#decodeData.i,set[RequestMethod] iterator decodeData(allowedMethods: set[RequestMethod] = {methodNone, methodPost,\n methodGet}): tuple[key, value: string] 93 +nim readData cgi.html#readData,set[RequestMethod] proc readData(allowedMethods: set[RequestMethod] = {methodNone, methodPost, methodGet}): StringTableRef 102 +nim readData cgi.html#readData,string proc readData(data: string): StringTableRef 110 +nim validateData cgi.html#validateData,StringTableRef,varargs[string] proc validateData(data: StringTableRef; validKeys: varargs[string]) 116 +nim getContentLength cgi.html#getContentLength proc getContentLength(): string 123 +nim getContentType cgi.html#getContentType proc getContentType(): string 127 +nim getDocumentRoot cgi.html#getDocumentRoot proc getDocumentRoot(): string 131 +nim getGatewayInterface cgi.html#getGatewayInterface proc getGatewayInterface(): string 135 +nim getHttpAccept cgi.html#getHttpAccept proc getHttpAccept(): string 139 +nim getHttpAcceptCharset cgi.html#getHttpAcceptCharset proc getHttpAcceptCharset(): string 143 +nim getHttpAcceptEncoding cgi.html#getHttpAcceptEncoding proc getHttpAcceptEncoding(): string 147 +nim getHttpAcceptLanguage cgi.html#getHttpAcceptLanguage proc getHttpAcceptLanguage(): string 151 +nim getHttpConnection cgi.html#getHttpConnection proc getHttpConnection(): string 155 +nim getHttpCookie cgi.html#getHttpCookie proc getHttpCookie(): string 159 +nim getHttpHost cgi.html#getHttpHost proc getHttpHost(): string 163 +nim getHttpReferer cgi.html#getHttpReferer proc getHttpReferer(): string 167 +nim getHttpUserAgent cgi.html#getHttpUserAgent proc getHttpUserAgent(): string 171 +nim getPathInfo cgi.html#getPathInfo proc getPathInfo(): string 175 +nim getPathTranslated cgi.html#getPathTranslated proc getPathTranslated(): string 179 +nim getQueryString cgi.html#getQueryString proc getQueryString(): string 183 +nim getRemoteAddr cgi.html#getRemoteAddr proc getRemoteAddr(): string 187 +nim getRemoteHost cgi.html#getRemoteHost proc getRemoteHost(): string 191 +nim getRemoteIdent cgi.html#getRemoteIdent proc getRemoteIdent(): string 195 +nim getRemotePort cgi.html#getRemotePort proc getRemotePort(): string 199 +nim getRemoteUser cgi.html#getRemoteUser proc getRemoteUser(): string 203 +nim getRequestMethod cgi.html#getRequestMethod proc getRequestMethod(): string 207 +nim getRequestURI cgi.html#getRequestURI proc getRequestURI(): string 211 +nim getScriptFilename cgi.html#getScriptFilename proc getScriptFilename(): string 215 +nim getScriptName cgi.html#getScriptName proc getScriptName(): string 219 +nim getServerAddr cgi.html#getServerAddr proc getServerAddr(): string 223 +nim getServerAdmin cgi.html#getServerAdmin proc getServerAdmin(): string 227 +nim getServerName cgi.html#getServerName proc getServerName(): string 231 +nim getServerPort cgi.html#getServerPort proc getServerPort(): string 235 +nim getServerProtocol cgi.html#getServerProtocol proc getServerProtocol(): string 239 +nim getServerSignature cgi.html#getServerSignature proc getServerSignature(): string 243 +nim getServerSoftware cgi.html#getServerSoftware proc getServerSoftware(): string 247 +nim setTestData cgi.html#setTestData,varargs[string] proc setTestData(keysvalues: varargs[string]) 251 +nim writeContentType cgi.html#writeContentType proc writeContentType() 269 +nim writeErrorMessage cgi.html#writeErrorMessage,string proc writeErrorMessage(data: string) 287 +nim setStackTraceStdout cgi.html#setStackTraceStdout proc setStackTraceStdout() 296 +nim setCookie cgi.html#setCookie,string,string proc setCookie(name, value: string) 300 +nim getCookie cgi.html#getCookie,string proc getCookie(name: string): string 307 +nim existsCookie cgi.html#existsCookie,string proc existsCookie(name: string): bool 312 +nimgrp readdata cgi.html#readData-procs-all proc 102 +nimgrp decodedata cgi.html#decodeData-iterators-all iterator 87 diff --git a/chains.html b/chains.html new file mode 100644 index 0000000000000..a7b0485c59024 --- /dev/null +++ b/chains.html @@ -0,0 +1,144 @@ + + + + + + + +std/chains + + + + + + + + + + + + + + + + +
+
+

std/chains

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Template based implementation of singly and doubly linked lists. The involved types should have 'prev' or 'next' fields and the list header should have 'head' or 'tail' fields.

+
+

Templates

+
+
+
+
template append(header, node)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template prepend(header, node)
+
+ + + Source   +Edit   + +
+
+ +
+ + +
+
+ +
+
+ + +
+
+ + + + diff --git a/chains.idx b/chains.idx new file mode 100644 index 0000000000000..317bc5d36b5da --- /dev/null +++ b/chains.idx @@ -0,0 +1,4 @@ +nimTitle chains chains.html module std/chains 0 +nim prepend chains.html#prepend.t,, template prepend(header, node) 14 +nim append chains.html#append.t,, template append(header, node) 25 +nim unlink chains.html#unlink.t,, template unlink(header, node) 36 diff --git a/cmdline.html b/cmdline.html new file mode 100644 index 0000000000000..e5e9fd978df24 --- /dev/null +++ b/cmdline.html @@ -0,0 +1,237 @@ + + + + + + + +std/cmdline + + + + + + + + + + + + + + + + +
+
+

std/cmdline

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module contains system facilities for reading command line parameters.See also:

+

+
+

Imports

+
+ widestrs, posix +
+
+
+

Procs

+
+
+
+
proc commandLineParams(): seq[string] {....raises: [], tags: [ReadIOEffect],
+                                        forbids: [].}
+
+ +

Convenience proc which returns the command line parameters.

+

This returns only the parameters. If you want to get the application executable filename, call getAppFilename().

+

Availability: On Posix there is no portable way to get the command line from a DLL and thus the proc isn't defined in this environment. You can test for its availability with declared().

+

See also:

+ +

Examples:

+

when declared(commandLineParams):
+  # Use commandLineParams() here
+else:
+  # Do something else!

+ + Source   +Edit   + +
+
+ +
+
+
+
proc paramCount(): int {....tags: [ReadIOEffect], raises: [], forbids: [].}
+
+ +

Returns the number of command line arguments given to the application.

+

Unlike argc in C, if your binary was called without parameters this will return zero. You can query each individual parameter with paramStr proc or retrieve all of them in one go with commandLineParams proc.

+

Availability: When generating a dynamic library (see --app:lib) on Posix this proc is not defined. Test for availability using declared().

+

See also:

+ +

Examples:

+

when declared(paramCount):
+  # Use paramCount() here
+else:
+  # Do something else!

+ + Source   +Edit   + +
+
+ +
+
+
+
proc paramStr(i: int): string {....tags: [ReadIOEffect], raises: [], forbids: [].}
+
+ +

Returns the i-th command line argument given to the application.

+

i should be in the range 1..paramCount(), the IndexDefect exception will be raised for invalid values. Instead of iterating over paramCount() with this proc you can call the convenience commandLineParams().

+

Similarly to argv in C, it is possible to call paramStr(0) but this will return OS specific contents (usually the name of the invoked executable). You should avoid this and call getAppFilename() instead.

+

Availability: When generating a dynamic library (see --app:lib) on Posix this proc is not defined. Test for availability using declared().

+

See also:

+ +

Examples:

+

when declared(paramStr):
+  # Use paramStr() here
+else:
+  # Do something else!

+ + Source   +Edit   + +
+
+ +
+
+
+
proc parseCmdLine(c: string): seq[string] {.noSideEffect, ...gcsafe,
+    extern: "nos$1", raises: [], tags: [], forbids: [].}
+
+ +

Splits a command line into several components.

+

Note: This proc is only occasionally useful, better use the parseopt module.

+

On Windows, it uses the following parsing rules:

+
  • Arguments are delimited by white space, which is either a space or a tab.
  • +
  • The caret character (^) is not recognized as an escape character or delimiter. The character is handled completely by the command-line parser in the operating system before being passed to the argv array in the program.
  • +
  • A string surrounded by double quotation marks ("string") is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument.
  • +
  • A double quotation mark preceded by a backslash (") is interpreted as a literal double quotation mark character (").
  • +
  • Backslashes are interpreted literally, unless they immediately precede a double quotation mark.
  • +
  • If an even number of backslashes is followed by a double quotation mark, one backslash is placed in the argv array for every pair of backslashes, and the double quotation mark is interpreted as a string delimiter.
  • +
  • If an odd number of backslashes is followed by a double quotation mark, one backslash is placed in the argv array for every pair of backslashes, and the double quotation mark is "escaped" by the remaining backslash, causing a literal double quotation mark (") to be placed in argv.
  • +
+

On Posix systems, it uses the following parsing rules: Components are separated by whitespace unless the whitespace occurs within " or ' quotes.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/cmdline.idx b/cmdline.idx new file mode 100644 index 0000000000000..6969c70e11fd5 --- /dev/null +++ b/cmdline.idx @@ -0,0 +1,10 @@ +nimTitle cmdline cmdline.html module std/cmdline 0 +nim parseCmdLine cmdline.html#parseCmdLine,string proc parseCmdLine(c: string): seq[string] 46 +nim paramCount cmdline.html#paramCount proc paramCount(): int 145 +nim paramStr cmdline.html#paramStr,int proc paramStr(i: int): string 173 +nim commandLineParams cmdline.html#commandLineParams proc commandLineParams(): seq[string] 281 +idx command line argument cmdline.html#command-line-argument_1 Module cmdline 0 +idx argv cmdline.html#argv_1 Module cmdline 0 +idx command line arguments cmdline.html#command-line-arguments_1 Module cmdline 0 +idx argc cmdline.html#argc_1 Module cmdline 0 +idx command line cmdline.html#command-line_1 Module cmdline 0 diff --git a/colors.html b/colors.html new file mode 100644 index 0000000000000..6f83a04027cbf --- /dev/null +++ b/colors.html @@ -0,0 +1,2027 @@ + + + + + + + +std/colors + + + + + + + + + + + + + + + + +
+
+

std/colors

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements color handling for Nim, namely color mixing and parsing the CSS color names.

+ +
+

Types

+
+
+
Color = distinct int
+
+ + A color stored as RGB, e.g. 0xff00cc. + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
colAliceBlue = 15792383
+
+ + + Source   +Edit   + +
+
+
+
colAntiqueWhite = 16444375
+
+ + + Source   +Edit   + +
+
+
+
colAqua = 65535
+
+ + + Source   +Edit   + +
+
+
+
colAquamarine = 8388564
+
+ + + Source   +Edit   + +
+
+
+
colAzure = 15794175
+
+ + + Source   +Edit   + +
+
+
+
colBeige = 16119260
+
+ + + Source   +Edit   + +
+
+
+
colBisque = 16770244
+
+ + + Source   +Edit   + +
+
+
+
colBlack = 0
+
+ + + Source   +Edit   + +
+
+
+
colBlanchedAlmond = 16772045
+
+ + + Source   +Edit   + +
+
+
+
colBlue = 255
+
+ + + Source   +Edit   + +
+
+
+
colBlueViolet = 9055202
+
+ + + Source   +Edit   + +
+
+
+
colBrown = 10824234
+
+ + + Source   +Edit   + +
+
+
+
colBurlyWood = 14596231
+
+ + + Source   +Edit   + +
+
+
+
colCadetBlue = 6266528
+
+ + + Source   +Edit   + +
+
+
+
colChartreuse = 8388352
+
+ + + Source   +Edit   + +
+
+
+
colChocolate = 13789470
+
+ + + Source   +Edit   + +
+
+
+
colCoral = 16744272
+
+ + + Source   +Edit   + +
+
+
+
colCornflowerBlue = 6591981
+
+ + + Source   +Edit   + +
+
+
+
colCornsilk = 16775388
+
+ + + Source   +Edit   + +
+
+
+
colCrimson = 14423100
+
+ + + Source   +Edit   + +
+
+
+
colCyan = 65535
+
+ + + Source   +Edit   + +
+
+
+
colDarkBlue = 139
+
+ + + Source   +Edit   + +
+
+
+
colDarkCyan = 35723
+
+ + + Source   +Edit   + +
+
+
+
colDarkGoldenRod = 12092939
+
+ + + Source   +Edit   + +
+
+
+
colDarkGray = 11119017
+
+ + + Source   +Edit   + +
+
+
+
colDarkGreen = 25600
+
+ + + Source   +Edit   + +
+
+
+
colDarkGrey = 11119017
+
+ + + Source   +Edit   + +
+
+
+
colDarkKhaki = 12433259
+
+ + + Source   +Edit   + +
+
+
+
colDarkMagenta = 9109643
+
+ + + Source   +Edit   + +
+
+
+
colDarkOliveGreen = 5597999
+
+ + + Source   +Edit   + +
+
+
+
colDarkorange = 16747520
+
+ + + Source   +Edit   + +
+
+
+
colDarkOrchid = 10040012
+
+ + + Source   +Edit   + +
+
+
+
colDarkRed = 9109504
+
+ + + Source   +Edit   + +
+
+
+
colDarkSalmon = 15308410
+
+ + + Source   +Edit   + +
+
+
+
colDarkSeaGreen = 9419919
+
+ + + Source   +Edit   + +
+
+
+
colDarkSlateBlue = 4734347
+
+ + + Source   +Edit   + +
+
+
+
colDarkSlateGray = 3100495
+
+ + + Source   +Edit   + +
+
+
+
colDarkSlateGrey = 3100495
+
+ + + Source   +Edit   + +
+
+
+
colDarkTurquoise = 52945
+
+ + + Source   +Edit   + +
+
+
+
colDarkViolet = 9699539
+
+ + + Source   +Edit   + +
+
+
+
colDeepPink = 16716947
+
+ + + Source   +Edit   + +
+
+
+
colDeepSkyBlue = 49151
+
+ + + Source   +Edit   + +
+
+
+
colDimGray = 6908265
+
+ + + Source   +Edit   + +
+
+
+
colDimGrey = 6908265
+
+ + + Source   +Edit   + +
+
+
+
colDodgerBlue = 2003199
+
+ + + Source   +Edit   + +
+
+
+
colFireBrick = 11674146
+
+ + + Source   +Edit   + +
+
+
+
colFloralWhite = 16775920
+
+ + + Source   +Edit   + +
+
+
+
colForestGreen = 2263842
+
+ + + Source   +Edit   + +
+
+
+
colFuchsia = 16711935
+
+ + + Source   +Edit   + +
+
+
+
colGainsboro = 14474460
+
+ + + Source   +Edit   + +
+
+
+
colGhostWhite = 16316671
+
+ + + Source   +Edit   + +
+
+
+
colGold = 16766720
+
+ + + Source   +Edit   + +
+
+
+
colGoldenRod = 14329120
+
+ + + Source   +Edit   + +
+
+
+
colGray = 8421504
+
+ + + Source   +Edit   + +
+
+
+
colGreen = 32768
+
+ + + Source   +Edit   + +
+
+
+
colGreenYellow = 11403055
+
+ + + Source   +Edit   + +
+
+
+
colGrey = 8421504
+
+ + + Source   +Edit   + +
+
+
+
colHoneyDew = 15794160
+
+ + + Source   +Edit   + +
+
+
+
colHotPink = 16738740
+
+ + + Source   +Edit   + +
+
+
+
colIndianRed = 13458524
+
+ + + Source   +Edit   + +
+
+
+
colIndigo = 4915330
+
+ + + Source   +Edit   + +
+
+
+
colIvory = 16777200
+
+ + + Source   +Edit   + +
+
+
+
colKhaki = 15787660
+
+ + + Source   +Edit   + +
+
+
+
colLavender = 15132410
+
+ + + Source   +Edit   + +
+
+
+
colLavenderBlush = 16773365
+
+ + + Source   +Edit   + +
+
+
+
colLawnGreen = 8190976
+
+ + + Source   +Edit   + +
+
+
+
colLemonChiffon = 16775885
+
+ + + Source   +Edit   + +
+
+
+
colLightBlue = 11393254
+
+ + + Source   +Edit   + +
+
+
+
colLightCoral = 15761536
+
+ + + Source   +Edit   + +
+
+
+
colLightCyan = 14745599
+
+ + + Source   +Edit   + +
+
+
+
colLightGoldenRodYellow = 16448210
+
+ + + Source   +Edit   + +
+
+
+
colLightGray = 13882323
+
+ + + Source   +Edit   + +
+
+
+
colLightGreen = 9498256
+
+ + + Source   +Edit   + +
+
+
+
colLightGrey = 13882323
+
+ + + Source   +Edit   + +
+
+
+
colLightPink = 16758465
+
+ + + Source   +Edit   + +
+
+
+
colLightSalmon = 16752762
+
+ + + Source   +Edit   + +
+
+
+
colLightSeaGreen = 2142890
+
+ + + Source   +Edit   + +
+
+
+
colLightSkyBlue = 8900346
+
+ + + Source   +Edit   + +
+
+
+
colLightSlateGray = 7833753
+
+ + + Source   +Edit   + +
+
+
+
colLightSlateGrey = 7833753
+
+ + + Source   +Edit   + +
+
+
+
colLightSteelBlue = 11584734
+
+ + + Source   +Edit   + +
+
+
+
colLightYellow = 16777184
+
+ + + Source   +Edit   + +
+
+
+
colLime = 65280
+
+ + + Source   +Edit   + +
+
+
+
colLimeGreen = 3329330
+
+ + + Source   +Edit   + +
+
+
+
colLinen = 16445670
+
+ + + Source   +Edit   + +
+
+
+
colMagenta = 16711935
+
+ + + Source   +Edit   + +
+
+
+
colMaroon = 8388608
+
+ + + Source   +Edit   + +
+
+
+
colMediumAquaMarine = 6737322
+
+ + + Source   +Edit   + +
+
+
+
colMediumBlue = 205
+
+ + + Source   +Edit   + +
+
+
+
colMediumOrchid = 12211667
+
+ + + Source   +Edit   + +
+
+
+
colMediumPurple = 9662683
+
+ + + Source   +Edit   + +
+
+
+
colMediumSeaGreen = 3978097
+
+ + + Source   +Edit   + +
+
+
+
colMediumSlateBlue = 8087790
+
+ + + Source   +Edit   + +
+
+
+
colMediumSpringGreen = 64154
+
+ + + Source   +Edit   + +
+
+
+
colMediumTurquoise = 4772300
+
+ + + Source   +Edit   + +
+
+
+
colMediumVioletRed = 13047173
+
+ + + Source   +Edit   + +
+
+
+
colMidnightBlue = 1644912
+
+ + + Source   +Edit   + +
+
+
+
colMintCream = 16121850
+
+ + + Source   +Edit   + +
+
+
+
colMistyRose = 16770273
+
+ + + Source   +Edit   + +
+
+
+
colMoccasin = 16770229
+
+ + + Source   +Edit   + +
+
+
+
colNavajoWhite = 16768685
+
+ + + Source   +Edit   + +
+
+
+
colNavy = 128
+
+ + + Source   +Edit   + +
+
+
+
colOldLace = 16643558
+
+ + + Source   +Edit   + +
+
+
+
colOlive = 8421376
+
+ + + Source   +Edit   + +
+
+
+
colOliveDrab = 7048739
+
+ + + Source   +Edit   + +
+
+
+
colOrange = 16753920
+
+ + + Source   +Edit   + +
+
+
+
colOrangeRed = 16729344
+
+ + + Source   +Edit   + +
+
+
+
colOrchid = 14315734
+
+ + + Source   +Edit   + +
+
+
+
colPaleGoldenRod = 15657130
+
+ + + Source   +Edit   + +
+
+
+
colPaleGreen = 10025880
+
+ + + Source   +Edit   + +
+
+
+
colPaleTurquoise = 11529966
+
+ + + Source   +Edit   + +
+
+
+
colPaleVioletRed = 14381203
+
+ + + Source   +Edit   + +
+
+
+
colPapayaWhip = 16773077
+
+ + + Source   +Edit   + +
+
+
+
colPeachPuff = 16767673
+
+ + + Source   +Edit   + +
+
+
+
colPeru = 13468991
+
+ + + Source   +Edit   + +
+
+
+
colPink = 16761035
+
+ + + Source   +Edit   + +
+
+
+
colPlum = 14524637
+
+ + + Source   +Edit   + +
+
+
+
colPowderBlue = 11591910
+
+ + + Source   +Edit   + +
+
+
+
colPurple = 8388736
+
+ + + Source   +Edit   + +
+
+
+
colRebeccaPurple = 6697881
+
+ + + Source   +Edit   + +
+
+
+
colRed = 16711680
+
+ + + Source   +Edit   + +
+
+
+
colRosyBrown = 12357519
+
+ + + Source   +Edit   + +
+
+
+
colRoyalBlue = 4286945
+
+ + + Source   +Edit   + +
+
+
+
colSaddleBrown = 9127187
+
+ + + Source   +Edit   + +
+
+
+
colSalmon = 16416882
+
+ + + Source   +Edit   + +
+
+
+
colSandyBrown = 16032864
+
+ + + Source   +Edit   + +
+
+
+
colSeaGreen = 3050327
+
+ + + Source   +Edit   + +
+
+
+
colSeaShell = 16774638
+
+ + + Source   +Edit   + +
+
+
+
colSienna = 10506797
+
+ + + Source   +Edit   + +
+
+
+
colSilver = 12632256
+
+ + + Source   +Edit   + +
+
+
+
colSkyBlue = 8900331
+
+ + + Source   +Edit   + +
+
+
+
colSlateBlue = 6970061
+
+ + + Source   +Edit   + +
+
+
+
colSlateGray = 7372944
+
+ + + Source   +Edit   + +
+
+
+
colSlateGrey = 7372944
+
+ + + Source   +Edit   + +
+
+
+
colSnow = 16775930
+
+ + + Source   +Edit   + +
+
+
+
colSpringGreen = 65407
+
+ + + Source   +Edit   + +
+
+
+
colSteelBlue = 4620980
+
+ + + Source   +Edit   + +
+
+
+
colTan = 13808780
+
+ + + Source   +Edit   + +
+
+
+
colTeal = 32896
+
+ + + Source   +Edit   + +
+
+
+
colThistle = 14204888
+
+ + + Source   +Edit   + +
+
+
+
colTomato = 16737095
+
+ + + Source   +Edit   + +
+
+
+
colTurquoise = 4251856
+
+ + + Source   +Edit   + +
+
+
+
colViolet = 15631086
+
+ + + Source   +Edit   + +
+
+
+
colWheat = 16113331
+
+ + + Source   +Edit   + +
+
+
+
colWhite = 16777215
+
+ + + Source   +Edit   + +
+
+
+
colWhiteSmoke = 16119285
+
+ + + Source   +Edit   + +
+
+
+
colYellow = 16776960
+
+ + + Source   +Edit   + +
+
+
+
colYellowGreen = 10145074
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(c: Color): string {....raises: [], tags: [], forbids: [].}
+
+ + Converts a color into its textual representation. +

Example:

+
assert $colFuchsia == "#FF00FF"
+ Source   +Edit   + +
+
+ +
+
+
+
proc `+`(a, b: Color): Color {....raises: [], tags: [], forbids: [].}
+
+ +

Adds two colors.

+

This uses saturated arithmetic, so that each color component cannot overflow (255 is used as a maximum).

+ +

Example:

+
var
+  a = Color(0xaa_00_ff)
+  b = Color(0x11_cc_cc)
+assert a + b == Color(0xbb_cc_ff)
+ Source   +Edit   + +
+
+ +
+
+
+
proc `-`(a, b: Color): Color {....raises: [], tags: [], forbids: [].}
+
+ +

Subtracts two colors.

+

This uses saturated arithmetic, so that each color component cannot underflow (0 is used as a minimum).

+ +

Example:

+
var
+  a = Color(0xff_33_ff)
+  b = Color(0x11_ff_cc)
+assert a - b == Color(0xee_00_33)
+ Source   +Edit   + +
+
+ +
+
+
+
proc `==`(a, b: Color): bool {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ +

Compares two colors.

+

var
+  a = Color(0xff_00_ff)
+  b = colFuchsia
+  c = Color(0x00_ff_cc)
+assert a == b
+assert not (a == c)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc extractRGB(a: Color): tuple[r, g, b: range[0 .. 255]] {....raises: [],
+    tags: [], forbids: [].}
+
+ + Extracts the red/green/blue components of the color a. +

Example:

+
var
+  a = Color(0xff_00_ff)
+  b = Color(0x00_ff_cc)
+type
+  Col = range[0..255]
+# assert extractRGB(a) == (r: 255.Col, g: 0.Col, b: 255.Col)
+# assert extractRGB(b) == (r: 0.Col, g: 255.Col, b: 204.Col)
+echo extractRGB(a)
+echo typeof(extractRGB(a))
+echo extractRGB(b)
+echo typeof(extractRGB(b))
+ Source   +Edit   + +
+
+ +
+
+
+
proc intensity(a: Color; f: float): Color {....raises: [], tags: [], forbids: [].}
+
+ + Returns a with intensity f. f should be a float from 0.0 (completely dark) to 1.0 (full color intensity). +

Example:

+
var
+  a = Color(0xff_00_ff)
+  b = Color(0x00_42_cc)
+assert a.intensity(0.5) == Color(0x80_00_80)
+assert b.intensity(0.5) == Color(0x00_21_66)
+ Source   +Edit   + +
+
+ +
+
+
+
proc isColor(name: string): bool {....raises: [], tags: [], forbids: [].}
+
+ + Returns true if name is a known color name or a hexadecimal color prefixed with #. Case insensitive. +

Example:

+
var
+  a = "silver"
+  b = "#0179fc"
+  c = "#zzmmtt"
+assert a.isColor
+assert b.isColor
+assert not c.isColor
+ Source   +Edit   + +
+
+ +
+
+
+
proc parseColor(name: string): Color {....raises: [ValueError], tags: [],
+                                       forbids: [].}
+
+ +

Parses name to a color value.

+

If no valid color could be parsed ValueError is raised. Case insensitive.

+ +

Example:

+
var
+  a = "silver"
+  b = "#0179fc"
+  c = "#zzmmtt"
+assert parseColor(a) == Color(0xc0_c0_c0)
+assert parseColor(b) == Color(0x01_79_fc)
+doAssertRaises(ValueError): discard parseColor(c)
+ Source   +Edit   + +
+
+ +
+
+
+
proc rgb(r, g, b: range[0 .. 255]): Color {....raises: [], tags: [], forbids: [].}
+
+ + Constructs a color from RGB values. +

Example:

+
assert rgb(0, 255, 128) == Color(0x00_ff_80)
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template mix(a, b: Color; fn: untyped): untyped
+
+ +

Uses fn to mix the colors a and b.

+

fn is invoked for each component R, G, and B. If fn's result is not in the range[0..255], it will be saturated to be so.

+ +

Example:

+
var
+  a = Color(0x0a2814)
+  b = Color(0x050a03)
+
+proc myMix(x, y: int): int =
+  2 * x - 3 * y
+
+assert mix(a, b, myMix) == Color(0x05_32_1f)
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/colors.idx b/colors.idx new file mode 100644 index 0000000000000..3b07c938ae23b --- /dev/null +++ b/colors.idx @@ -0,0 +1,160 @@ +nimTitle colors colors.html module std/colors 0 +nim Color colors.html#Color type Color 16 +nim `==` colors.html#==,Color,Color proc `==`(a, b: Color): bool 18 +nim `+` colors.html#+,Color,Color proc `+`(a, b: Color): Color 51 +nim `-` colors.html#-,Color,Color proc `-`(a, b: Color): Color 65 +nim extractRGB colors.html#extractRGB,Color proc extractRGB(a: Color): tuple[r, g, b: range[0 .. 255]] 79 +nim intensity colors.html#intensity,Color,float proc intensity(a: Color; f: float): Color 99 +nim mix colors.html#mix.t,Color,Color,untyped template mix(a, b: Color; fn: untyped): untyped 118 +nim colAliceBlue colors.html#colAliceBlue const colAliceBlue 149 +nim colAntiqueWhite colors.html#colAntiqueWhite const colAntiqueWhite 150 +nim colAqua colors.html#colAqua const colAqua 151 +nim colAquamarine colors.html#colAquamarine const colAquamarine 152 +nim colAzure colors.html#colAzure const colAzure 153 +nim colBeige colors.html#colBeige const colBeige 154 +nim colBisque colors.html#colBisque const colBisque 155 +nim colBlack colors.html#colBlack const colBlack 156 +nim colBlanchedAlmond colors.html#colBlanchedAlmond const colBlanchedAlmond 157 +nim colBlue colors.html#colBlue const colBlue 158 +nim colBlueViolet colors.html#colBlueViolet const colBlueViolet 159 +nim colBrown colors.html#colBrown const colBrown 160 +nim colBurlyWood colors.html#colBurlyWood const colBurlyWood 161 +nim colCadetBlue colors.html#colCadetBlue const colCadetBlue 162 +nim colChartreuse colors.html#colChartreuse const colChartreuse 163 +nim colChocolate colors.html#colChocolate const colChocolate 164 +nim colCoral colors.html#colCoral const colCoral 165 +nim colCornflowerBlue colors.html#colCornflowerBlue const colCornflowerBlue 166 +nim colCornsilk colors.html#colCornsilk const colCornsilk 167 +nim colCrimson colors.html#colCrimson const colCrimson 168 +nim colCyan colors.html#colCyan const colCyan 169 +nim colDarkBlue colors.html#colDarkBlue const colDarkBlue 170 +nim colDarkCyan colors.html#colDarkCyan const colDarkCyan 171 +nim colDarkGoldenRod colors.html#colDarkGoldenRod const colDarkGoldenRod 172 +nim colDarkGray colors.html#colDarkGray const colDarkGray 173 +nim colDarkGreen colors.html#colDarkGreen const colDarkGreen 174 +nim colDarkGrey colors.html#colDarkGrey const colDarkGrey 175 +nim colDarkKhaki colors.html#colDarkKhaki const colDarkKhaki 176 +nim colDarkMagenta colors.html#colDarkMagenta const colDarkMagenta 177 +nim colDarkOliveGreen colors.html#colDarkOliveGreen const colDarkOliveGreen 178 +nim colDarkorange colors.html#colDarkorange const colDarkorange 179 +nim colDarkOrchid colors.html#colDarkOrchid const colDarkOrchid 180 +nim colDarkRed colors.html#colDarkRed const colDarkRed 181 +nim colDarkSalmon colors.html#colDarkSalmon const colDarkSalmon 182 +nim colDarkSeaGreen colors.html#colDarkSeaGreen const colDarkSeaGreen 183 +nim colDarkSlateBlue colors.html#colDarkSlateBlue const colDarkSlateBlue 184 +nim colDarkSlateGray colors.html#colDarkSlateGray const colDarkSlateGray 185 +nim colDarkSlateGrey colors.html#colDarkSlateGrey const colDarkSlateGrey 186 +nim colDarkTurquoise colors.html#colDarkTurquoise const colDarkTurquoise 187 +nim colDarkViolet colors.html#colDarkViolet const colDarkViolet 188 +nim colDeepPink colors.html#colDeepPink const colDeepPink 189 +nim colDeepSkyBlue colors.html#colDeepSkyBlue const colDeepSkyBlue 190 +nim colDimGray colors.html#colDimGray const colDimGray 191 +nim colDimGrey colors.html#colDimGrey const colDimGrey 192 +nim colDodgerBlue colors.html#colDodgerBlue const colDodgerBlue 193 +nim colFireBrick colors.html#colFireBrick const colFireBrick 194 +nim colFloralWhite colors.html#colFloralWhite const colFloralWhite 195 +nim colForestGreen colors.html#colForestGreen const colForestGreen 196 +nim colFuchsia colors.html#colFuchsia const colFuchsia 197 +nim colGainsboro colors.html#colGainsboro const colGainsboro 198 +nim colGhostWhite colors.html#colGhostWhite const colGhostWhite 199 +nim colGold colors.html#colGold const colGold 200 +nim colGoldenRod colors.html#colGoldenRod const colGoldenRod 201 +nim colGray colors.html#colGray const colGray 202 +nim colGreen colors.html#colGreen const colGreen 203 +nim colGreenYellow colors.html#colGreenYellow const colGreenYellow 204 +nim colGrey colors.html#colGrey const colGrey 205 +nim colHoneyDew colors.html#colHoneyDew const colHoneyDew 206 +nim colHotPink colors.html#colHotPink const colHotPink 207 +nim colIndianRed colors.html#colIndianRed const colIndianRed 208 +nim colIndigo colors.html#colIndigo const colIndigo 209 +nim colIvory colors.html#colIvory const colIvory 210 +nim colKhaki colors.html#colKhaki const colKhaki 211 +nim colLavender colors.html#colLavender const colLavender 212 +nim colLavenderBlush colors.html#colLavenderBlush const colLavenderBlush 213 +nim colLawnGreen colors.html#colLawnGreen const colLawnGreen 214 +nim colLemonChiffon colors.html#colLemonChiffon const colLemonChiffon 215 +nim colLightBlue colors.html#colLightBlue const colLightBlue 216 +nim colLightCoral colors.html#colLightCoral const colLightCoral 217 +nim colLightCyan colors.html#colLightCyan const colLightCyan 218 +nim colLightGoldenRodYellow colors.html#colLightGoldenRodYellow const colLightGoldenRodYellow 219 +nim colLightGray colors.html#colLightGray const colLightGray 220 +nim colLightGreen colors.html#colLightGreen const colLightGreen 221 +nim colLightGrey colors.html#colLightGrey const colLightGrey 222 +nim colLightPink colors.html#colLightPink const colLightPink 223 +nim colLightSalmon colors.html#colLightSalmon const colLightSalmon 224 +nim colLightSeaGreen colors.html#colLightSeaGreen const colLightSeaGreen 225 +nim colLightSkyBlue colors.html#colLightSkyBlue const colLightSkyBlue 226 +nim colLightSlateGray colors.html#colLightSlateGray const colLightSlateGray 227 +nim colLightSlateGrey colors.html#colLightSlateGrey const colLightSlateGrey 228 +nim colLightSteelBlue colors.html#colLightSteelBlue const colLightSteelBlue 229 +nim colLightYellow colors.html#colLightYellow const colLightYellow 230 +nim colLime colors.html#colLime const colLime 231 +nim colLimeGreen colors.html#colLimeGreen const colLimeGreen 232 +nim colLinen colors.html#colLinen const colLinen 233 +nim colMagenta colors.html#colMagenta const colMagenta 234 +nim colMaroon colors.html#colMaroon const colMaroon 235 +nim colMediumAquaMarine colors.html#colMediumAquaMarine const colMediumAquaMarine 236 +nim colMediumBlue colors.html#colMediumBlue const colMediumBlue 237 +nim colMediumOrchid colors.html#colMediumOrchid const colMediumOrchid 238 +nim colMediumPurple colors.html#colMediumPurple const colMediumPurple 239 +nim colMediumSeaGreen colors.html#colMediumSeaGreen const colMediumSeaGreen 240 +nim colMediumSlateBlue colors.html#colMediumSlateBlue const colMediumSlateBlue 241 +nim colMediumSpringGreen colors.html#colMediumSpringGreen const colMediumSpringGreen 242 +nim colMediumTurquoise colors.html#colMediumTurquoise const colMediumTurquoise 243 +nim colMediumVioletRed colors.html#colMediumVioletRed const colMediumVioletRed 244 +nim colMidnightBlue colors.html#colMidnightBlue const colMidnightBlue 245 +nim colMintCream colors.html#colMintCream const colMintCream 246 +nim colMistyRose colors.html#colMistyRose const colMistyRose 247 +nim colMoccasin colors.html#colMoccasin const colMoccasin 248 +nim colNavajoWhite colors.html#colNavajoWhite const colNavajoWhite 249 +nim colNavy colors.html#colNavy const colNavy 250 +nim colOldLace colors.html#colOldLace const colOldLace 251 +nim colOlive colors.html#colOlive const colOlive 252 +nim colOliveDrab colors.html#colOliveDrab const colOliveDrab 253 +nim colOrange colors.html#colOrange const colOrange 254 +nim colOrangeRed colors.html#colOrangeRed const colOrangeRed 255 +nim colOrchid colors.html#colOrchid const colOrchid 256 +nim colPaleGoldenRod colors.html#colPaleGoldenRod const colPaleGoldenRod 257 +nim colPaleGreen colors.html#colPaleGreen const colPaleGreen 258 +nim colPaleTurquoise colors.html#colPaleTurquoise const colPaleTurquoise 259 +nim colPaleVioletRed colors.html#colPaleVioletRed const colPaleVioletRed 260 +nim colPapayaWhip colors.html#colPapayaWhip const colPapayaWhip 261 +nim colPeachPuff colors.html#colPeachPuff const colPeachPuff 262 +nim colPeru colors.html#colPeru const colPeru 263 +nim colPink colors.html#colPink const colPink 264 +nim colPlum colors.html#colPlum const colPlum 265 +nim colPowderBlue colors.html#colPowderBlue const colPowderBlue 266 +nim colPurple colors.html#colPurple const colPurple 267 +nim colRebeccaPurple colors.html#colRebeccaPurple const colRebeccaPurple 268 +nim colRed colors.html#colRed const colRed 269 +nim colRosyBrown colors.html#colRosyBrown const colRosyBrown 270 +nim colRoyalBlue colors.html#colRoyalBlue const colRoyalBlue 271 +nim colSaddleBrown colors.html#colSaddleBrown const colSaddleBrown 272 +nim colSalmon colors.html#colSalmon const colSalmon 273 +nim colSandyBrown colors.html#colSandyBrown const colSandyBrown 274 +nim colSeaGreen colors.html#colSeaGreen const colSeaGreen 275 +nim colSeaShell colors.html#colSeaShell const colSeaShell 276 +nim colSienna colors.html#colSienna const colSienna 277 +nim colSilver colors.html#colSilver const colSilver 278 +nim colSkyBlue colors.html#colSkyBlue const colSkyBlue 279 +nim colSlateBlue colors.html#colSlateBlue const colSlateBlue 280 +nim colSlateGray colors.html#colSlateGray const colSlateGray 281 +nim colSlateGrey colors.html#colSlateGrey const colSlateGrey 282 +nim colSnow colors.html#colSnow const colSnow 283 +nim colSpringGreen colors.html#colSpringGreen const colSpringGreen 284 +nim colSteelBlue colors.html#colSteelBlue const colSteelBlue 285 +nim colTan colors.html#colTan const colTan 286 +nim colTeal colors.html#colTeal const colTeal 287 +nim colThistle colors.html#colThistle const colThistle 288 +nim colTomato colors.html#colTomato const colTomato 289 +nim colTurquoise colors.html#colTurquoise const colTurquoise 290 +nim colViolet colors.html#colViolet const colViolet 291 +nim colWheat colors.html#colWheat const colWheat 292 +nim colWhite colors.html#colWhite const colWhite 293 +nim colWhiteSmoke colors.html#colWhiteSmoke const colWhiteSmoke 294 +nim colYellow colors.html#colYellow const colYellow 295 +nim colYellowGreen colors.html#colYellowGreen const colYellowGreen 296 +nim `$` colors.html#$,Color proc `$`(c: Color): string 448 +nim parseColor colors.html#parseColor,string proc parseColor(name: string): Color 458 +nim isColor colors.html#isColor,string proc isColor(name: string): bool 480 +nim rgb colors.html#rgb,range[],range[],range[] proc rgb(r, g, b: range[0 .. 255]): Color 501 diff --git a/compiler/aliasanalysis.html b/compiler/aliasanalysis.html new file mode 100644 index 0000000000000..c42852baabefe --- /dev/null +++ b/compiler/aliasanalysis.html @@ -0,0 +1,219 @@ + + + + + + + +aliasanalysis + + + + + + + + + + + + + + + + +
+
+

aliasanalysis

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ ast +
+
+
+

Types

+
+
+
AliasKind = enum
+  yes, no, maybe
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
PathKinds0 = {nkDotExpr, nkCheckedFieldExpr, nkBracketExpr, nkDerefExpr,
+              nkHiddenDeref, nkAddr, nkHiddenAddr, nkObjDownConv, nkObjUpConv}
+
+ + + Source   +Edit   + +
+
+
+
PathKinds1 = {nkHiddenStdConv, nkHiddenSubConv}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc aliases(obj, field: PNode): AliasKind {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isAnalysableFieldAccess(orig: PNode; owner: PSym): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipConvDfa(n: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/aliasanalysis.idx b/compiler/aliasanalysis.idx new file mode 100644 index 0000000000000..771d39a021a44 --- /dev/null +++ b/compiler/aliasanalysis.idx @@ -0,0 +1,10 @@ +nimTitle aliasanalysis aliasanalysis.html module aliasanalysis 0 +nim PathKinds0 aliasanalysis.html#PathKinds0 const PathKinds0 7 +nim PathKinds1 aliasanalysis.html#PathKinds1 const PathKinds1 11 +nim skipConvDfa aliasanalysis.html#skipConvDfa,PNode proc skipConvDfa(n: PNode): PNode 13 +nim isAnalysableFieldAccess aliasanalysis.html#isAnalysableFieldAccess,PNode,PSym proc isAnalysableFieldAccess(orig: PNode; owner: PSym): bool 23 +nim yes aliasanalysis.html#yes AliasKind.yes 56 +nim no aliasanalysis.html#no AliasKind.no 56 +nim maybe aliasanalysis.html#maybe AliasKind.maybe 56 +nim AliasKind aliasanalysis.html#AliasKind enum AliasKind 56 +nim aliases aliasanalysis.html#aliases,PNode,PNode proc aliases(obj, field: PNode): AliasKind 59 diff --git a/compiler/aliases.html b/compiler/aliases.html new file mode 100644 index 0000000000000..00210ee3d9ac2 --- /dev/null +++ b/compiler/aliases.html @@ -0,0 +1,166 @@ + + + + + + + +aliases + + + + + + + + + + + + + + + + +
+
+

aliases

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Simple alias analysis for the HLO and the code generators.

+
+

Imports

+
+ ast, astalgo, types, trees +
+
+
+

Types

+
+
+
TAnalysisResult = enum
+  arNo, arMaybe, arYes
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc isPartOf(a, b: PNode): TAnalysisResult {.
+    ...raises: [KeyError, Exception, ValueError, ERecoverableError],
+    tags: [RootEffect], forbids: [].}
+
+ +

checks if location a can be part of location b. We treat seqs and strings as pointers because the code gen often just passes them as such.

+

Note: a can only be part of b, if a's type can be part of b's type. Since however type analysis is more expensive, we perform it only if necessary.

+

cases:

+

YES-cases:

+

x    <| x   # for general trees
+x[]  <| x
+x[i] <| x
+x.f  <| x

+

NO-cases:

+

x           !<| y    # depending on type and symbol kind
+x[constA]   !<| x[constB]
+x.f         !<| x.g
+x.f         !<| y.f  iff x !<= y

+

MAYBE-cases:

+

x[] ?<| y[]   iff compatible type
+
+
+x[]  ?<| y  depending on type

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/aliases.idx b/compiler/aliases.idx new file mode 100644 index 0000000000000..dea688ca9da34 --- /dev/null +++ b/compiler/aliases.idx @@ -0,0 +1,6 @@ +nimTitle aliases aliases.html module aliases 0 +nim arNo aliases.html#arNo TAnalysisResult.arNo 21 +nim arMaybe aliases.html#arMaybe TAnalysisResult.arMaybe 21 +nim arYes aliases.html#arYes TAnalysisResult.arYes 21 +nim TAnalysisResult aliases.html#TAnalysisResult enum TAnalysisResult 21 +nim isPartOf aliases.html#isPartOf,PNode,PNode proc isPartOf(a, b: PNode): TAnalysisResult 73 diff --git a/compiler/ast.html b/compiler/ast.html new file mode 100644 index 0000000000000..a3ab8ec3137d7 --- /dev/null +++ b/compiler/ast.html @@ -0,0 +1,5672 @@ + + + + + + + +ast + + + + + + + + + + + + + + + + +
+
+

ast

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
CompilesId = int
+
+ + id that is used for the caching logic within system.compiles. See the seminst module. + Source   +Edit   + +
+
+
+
IdGenerator = ref object
+  module*: int32
+  symId*: int32
+  typeId*: int32
+  sealed*: bool
+  disambTable*: CountTable[PIdent]
+
+ + + Source   +Edit   + +
+
+
+
ItemId = object
+  module*: int32
+  item*: int32
+
+ + + Source   +Edit   + +
+
+
+
PInstantiation = ref TInstantiation
+
+ + + Source   +Edit   + +
+
+
+
PLib = ref TLib
+
+ + + Source   +Edit   + +
+
+
+
PNode = ref TNode
+
+ + + Source   +Edit   + +
+
+
+
PScope = ref TScope
+
+ + + Source   +Edit   + +
+
+
+
PSym = ref TSym
+
+ + + Source   +Edit   + +
+
+
+
PType = ref TType
+
+ + + Source   +Edit   + +
+
+
+
SymMapping = Table[ItemId, PSym]
+
+ + + Source   +Edit   + +
+
+
+
TCallingConvention = enum
+  ccNimCall = "nimcall", ccStdCall = "stdcall", ccCDecl = "cdecl",
+  ccSafeCall = "safecall", ccSysCall = "syscall", ccInline = "inline",
+  ccNoInline = "noinline", ccFastCall = "fastcall", ccThisCall = "thiscall",
+  ccClosure = "closure", ccNoConvention = "noconv", ccMember = "member"
+
+ + + Source   +Edit   + +
+
+
+
TImplication = enum
+  impUnknown, impNo, impYes
+
+ + + Source   +Edit   + +
+
+
+
TInstantiation = object
+  sym*: PSym
+  concreteTypes*: seq[PType]
+  compilesId*: CompilesId
+
+ + + Source   +Edit   + +
+
+
+
TLib = object
+  kind*: TLibKind
+  generated*: bool
+  isOverridden*: bool
+  name*: Rope
+  path*: PNode
+
+ + + Source   +Edit   + +
+
+
+
TLibKind = enum
+  libHeader, libDynamic
+
+ + + Source   +Edit   + +
+
+
+
TLoc = object
+  k*: TLocKind
+  storage*: TStorageLoc
+  flags*: TLocFlags
+  lode*: PNode
+  snippet*: Rope
+
+ + + Source   +Edit   + +
+
+
+
TLocFlag = enum
+  lfIndirect, lfNoDeepCopy, lfNoDecl, lfDynamicLib, lfExportLib, lfHeader,
+  lfImportCompilerProc, lfSingleUse, lfEnforceDeref, lfPrepareForMutation
+
+ + + Source   +Edit   + +
+
+
+
TLocFlags = set[TLocFlag]
+
+ + + Source   +Edit   + +
+
+
+
TLocKind = enum
+  locNone, locTemp, locLocalVar, locGlobalVar, locParam, locField, locExpr,
+  locProc, locData, locCall, locOther
+
+ + + Source   +Edit   + +
+
+
+
TMagic = enum
+  mNone, mDefined, mDeclared, mDeclaredInScope, mCompiles, mArrGet, mArrPut,
+  mAsgn, mLow, mHigh, mSizeOf, mAlignOf, mOffsetOf, mTypeTrait, mIs, mOf, mAddr,
+  mType, mTypeOf, mPlugin, mEcho, mShallowCopy, mSlurp, mStaticExec, mStatic,
+  mParseExprToAst, mParseStmtToAst, mExpandToAst, mQuoteAst, mInc, mDec, mOrd,
+  mNew, mNewFinalize, mNewSeq, mNewSeqOfCap, mLengthOpenArray, mLengthStr,
+  mLengthArray, mLengthSeq, mIncl, mExcl, mCard, mChr, mGCref, mGCunref, mAddI,
+  mSubI, mMulI, mDivI, mModI, mSucc, mPred, mAddF64, mSubF64, mMulF64, mDivF64,
+  mShrI, mShlI, mAshrI, mBitandI, mBitorI, mBitxorI, mMinI, mMaxI, mAddU, mSubU,
+  mMulU, mDivU, mModU, mEqI, mLeI, mLtI, mEqF64, mLeF64, mLtF64, mLeU, mLtU,
+  mEqEnum, mLeEnum, mLtEnum, mEqCh, mLeCh, mLtCh, mEqB, mLeB, mLtB, mEqRef,
+  mLePtr, mLtPtr, mXor, mEqCString, mEqProc, mUnaryMinusI, mUnaryMinusI64,
+  mAbsI, mNot, mUnaryPlusI, mBitnotI, mUnaryPlusF64, mUnaryMinusF64, mCharToStr,
+  mBoolToStr, mCStrToStr, mStrToStr, mEnumToStr, mAnd, mOr, mImplies, mIff,
+  mExists, mForall, mOld, mEqStr, mLeStr, mLtStr, mEqSet, mLeSet, mLtSet,
+  mMulSet, mPlusSet, mMinusSet, mXorSet, mConStrStr, mSlice, mDotDot, mFields,
+  mFieldPairs, mOmpParFor, mAppendStrCh, mAppendStrStr, mAppendSeqElem, mInSet,
+  mRepr, mExit, mSetLengthStr, mSetLengthSeq, mIsPartOf, mAstToStr, mParallel,
+  mSwap, mIsNil, mArrToSeq, mOpenArrayToSeq, mNewString, mNewStringOfCap,
+  mParseBiggestFloat, mMove, mEnsureMove, mWasMoved, mDup, mDestroy, mTrace,
+  mDefault, mUnown, mFinished, mIsolate, mAccessEnv, mAccessTypeField, mArray,
+  mOpenArray, mRange, mSet, mSeq, mVarargs, mRef, mPtr, mVar, mDistinct, mVoid,
+  mTuple, mOrdinal, mIterableType, mInt, mInt8, mInt16, mInt32, mInt64, mUInt,
+  mUInt8, mUInt16, mUInt32, mUInt64, mFloat, mFloat32, mFloat64, mFloat128,
+  mBool, mChar, mString, mCstring, mPointer, mNil, mExpr, mStmt, mTypeDesc,
+  mVoidType, mPNimrodNode, mSpawn, mDeepCopy, mIsMainModule, mCompileDate,
+  mCompileTime, mProcCall, mCpuEndian, mHostOS, mHostCPU, mBuildOS, mBuildCPU,
+  mAppType, mCompileOption, mCompileOptionArg, mNLen, mNChild, mNSetChild,
+  mNAdd, mNAddMultiple, mNDel, mNKind, mNSymKind, mNccValue, mNccInc, mNcsAdd,
+  mNcsIncl, mNcsLen, mNcsAt, mNctPut, mNctLen, mNctGet, mNctHasNext, mNctNext,
+  mNIntVal, mNFloatVal, mNSymbol, mNIdent, mNGetType, mNStrVal, mNSetIntVal,
+  mNSetFloatVal, mNSetSymbol, mNSetIdent, mNSetStrVal, mNLineInfo, mNNewNimNode,
+  mNCopyNimNode, mNCopyNimTree, mStrToIdent, mNSigHash, mNSizeOf, mNBindSym,
+  mNCallSite, mEqIdent, mEqNimrodNode, mSameNodeType, mGetImpl, mNGenSym,
+  mNHint, mNWarning, mNError, mInstantiationInfo, mGetTypeInfo, mGetTypeInfoV2,
+  mNimvm, mIntDefine, mStrDefine, mBoolDefine, mGenericDefine,
+  mRunnableExamples, mException, mBuiltinType, mSymOwner, mUncheckedArray,
+  mGetImplTransf, mSymIsInstantiationOf, mNodeId, mPrivateAccess, mZeroDefault
+
+ + + Source   +Edit   + +
+
+
+
TNode {.final, acyclic.} = object
+  when defined(useNodeIds):
+    id*: int
+  info*: TLineInfo
+  flags*: TNodeFlags
+  case kind*: TNodeKind
+  of nkCharLit .. nkUInt64Lit:
+    intVal*: BiggestInt
+  of nkFloatLit .. nkFloat128Lit:
+    floatVal*: BiggestFloat
+  of nkStrLit .. nkTripleStrLit:
+    strVal*: string
+  of nkSym:
+    sym*: PSym
+  of nkIdent:
+    ident*: PIdent
+  else:
+    sons*: TNodeSeq
+  when defined(nimsuggest):
+    endInfo*: TLineInfo
+
+ + + Source   +Edit   + +
+
+
+
TNodeFlag = enum
+  nfNone, nfBase2, nfBase8, nfBase16, nfAllConst, nfTransf, nfNoRewrite, nfSem,
+  nfLL, nfDotField, nfDotSetter, nfExplicitCall, nfExprCall, nfIsRef, nfIsPtr,
+  nfPreventCg, nfBlockArg, nfFromTemplate, nfDefaultParam, nfDefaultRefsParam,
+  nfExecuteOnReload, nfLastRead, nfFirstWrite, nfHasComment,
+  nfSkipFieldChecking, nfDisabledOpenSym
+
+ + + Source   +Edit   + +
+
+
+
TNodeFlags = set[TNodeFlag]
+
+ + + Source   +Edit   + +
+
+
+
TNodeKinds = set[TNodeKind]
+
+ + + Source   +Edit   + +
+
+
+
TNodePair = object
+  h*: Hash
+  key*: PNode
+  val*: int
+
+ + + Source   +Edit   + +
+
+
+
TNodePairSeq = seq[TNodePair]
+
+ + + Source   +Edit   + +
+
+
+
TNodeSeq = seq[PNode]
+
+ + + Source   +Edit   + +
+
+
+
TNodeTable = object
+  counter*: int
+  data*: TNodePairSeq
+
+ + + Source   +Edit   + +
+
+
+
TObjectSeq = seq[RootRef]
+
+ + + Source   +Edit   + +
+
+
+
TObjectSet = object
+  counter*: int
+  data*: TObjectSeq
+
+ + + Source   +Edit   + +
+
+
+
TPair = object
+  key*, val*: RootRef
+
+ + + Source   +Edit   + +
+
+
+
TPairSeq = seq[TPair]
+
+ + + Source   +Edit   + +
+
+
+
TScope {.acyclic.} = object
+  depthLevel*: int
+  symbols*: TStrTable
+  parent*: PScope
+  allowPrivateAccess*: seq[PSym]
+
+ + + Source   +Edit   + +
+
+
+
TStorageLoc = enum
+  OnUnknown, OnStatic, OnStack, OnHeap
+
+ + + Source   +Edit   + +
+
+
+
TStrTable = object
+  counter*: int
+  data*: seq[PSym]
+
+ + + Source   +Edit   + +
+
+
+
TSym {.acyclic.} = object
+  itemId*: ItemId
+  case kind*: TSymKind
+  of routineKinds:
+    gcUnsafetyReason*: PSym
+    transformedBody*: PNode
+  of skLet, skVar, skField, skForVar:
+    guard*: PSym
+    bitsize*: int
+    alignment*: int
+  else:
+    nil
+  magic*: TMagic
+  typ*: PType
+  name*: PIdent
+  info*: TLineInfo
+  when defined(nimsuggest):
+    endInfo*: TLineInfo
+    hasUserSpecifiedType*: bool
+  flags*: TSymFlags
+  ast*: PNode
+  options*: TOptions
+  position*: int
+  offset*: int32
+  disamb*: int32
+  loc*: TLoc
+  annex*: PLib
+  when hasFFI:
+    cname*: string
+  constraint*: PNode
+  instantiatedFrom*: PSym
+  when defined(nimsuggest):
+    allUsages*: seq[TLineInfo]
+
+ + + Source   +Edit   + +
+
+
+
TSymFlag = enum
+  sfUsed, sfExported, sfFromGeneric, sfGlobal, sfForward, sfWasForwarded,
+  sfImportc, sfExportc, sfMangleCpp, sfVolatile, sfRegister, sfPure,
+  sfNoSideEffect, sfSideEffect, sfMainModule, sfSystemModule, sfNoReturn,
+  sfAddrTaken, sfCompilerProc, sfEscapes, sfDiscriminant, sfRequiresInit,
+  sfDeprecated, sfExplain, sfError, sfShadowed, sfThread, sfCppNonPod,
+  sfCompileTime, sfConstructor, sfDispatcher, sfBorrow, sfInfixCall,
+  sfNamedParamCall, sfDiscardable, sfOverridden, sfCallsite, sfGenSym,
+  sfNonReloadable, sfGeneratedOp, sfTemplateParam, sfCursor,
+  sfInjectDestructors, sfNeverRaises, sfSystemRaisesDefect,
+  sfUsedInFinallyOrExcept, sfSingleUsedTemp, sfNoalias, sfEffectsDelayed,
+  sfGeneratedType, sfVirtual, sfByCopy, sfMember, sfCodegenDecl, sfWasGenSym,
+  sfForceLift, sfDirty, sfCustomPragma, sfBase, sfGoto, sfAnon, sfAllUntyped,
+  sfTemplateRedefinition
+
+ + + Source   +Edit   + +
+
+
+
TSymFlags = set[TSymFlag]
+
+ + + Source   +Edit   + +
+
+
+
TSymKind = enum
+  skUnknown, skConditional, skDynLib, skParam, skGenericParam, skTemp, skModule,
+  skType, skVar, skLet, skConst, skResult, skProc, skFunc, skMethod, skIterator,
+  skConverter, skMacro, skTemplate, skField, skEnumField, skForVar, skLabel,
+  skStub, skPackage
+
+ + + Source   +Edit   + +
+
+
+
TSymKinds = set[TSymKind]
+
+ + + Source   +Edit   + +
+
+
+
TType {.acyclic.} = object
+  itemId*: ItemId
+  kind*: TTypeKind
+  callConv*: TCallingConvention
+  flags*: TTypeFlags
+  n*: PNode
+  sym*: PSym
+  size*: BiggestInt
+  align*: int16
+  paddingAtEnd*: int16
+  loc*: TLoc
+  typeInst*: PType
+  uniqueId*: ItemId
+
+ + + Source   +Edit   + +
+
+
+
TTypeAttachedOp = enum
+  attachedWasMoved, attachedDestructor, attachedAsgn, attachedDup, attachedSink,
+  attachedTrace, attachedDeepCopy
+
+ + as usual, order is important here + Source   +Edit   + +
+
+
+
TTypeFlag = enum
+  tfVarargs, tfNoSideEffect, tfFinal, tfInheritable, tfHasOwned, tfEnumHasHoles,
+  tfShallow, tfThread, tfFromGeneric, tfUnresolved, tfResolved, tfRetType,
+  tfCapturesEnv, tfByCopy, tfByRef, tfIterator, tfPartial, tfNotNil,
+  tfRequiresInit, tfNeedsFullInit, tfVarIsPtr, tfHasMeta, tfHasGCedMem,
+  tfPacked, tfHasStatic, tfGenericTypeParam, tfImplicitTypeParam,
+  tfInferrableStatic, tfConceptMatchedTypeSym, tfExplicit, tfWildcard,
+  tfHasAsgn, tfBorrowDot, tfTriggersCompileTime, tfRefsAnonObj, tfCovariant,
+  tfWeakCovariant, tfContravariant, tfCheckedForDestructor, tfAcyclic,
+  tfIncompleteStruct, tfCompleteStruct, tfExplicitCallConv, tfIsConstructor,
+  tfEffectSystemWorkaround, tfIsOutParam, tfSendable, tfImplicitStatic
+
+ + + Source   +Edit   + +
+
+
+
TTypeFlags = set[TTypeFlag]
+
+ + + Source   +Edit   + +
+
+
+
TTypeKind = enum
+  tyNone, tyBool, tyChar, tyEmpty, tyAlias, tyNil, tyUntyped, tyTyped,
+  tyTypeDesc, tyGenericInvocation, tyGenericBody, tyGenericInst, tyGenericParam,
+  tyDistinct, tyEnum, tyOrdinal, tyArray, tyObject, tyTuple, tySet, tyRange,
+  tyPtr, tyRef, tyVar, tySequence, tyProc, tyPointer, tyOpenArray, tyString,
+  tyCstring, tyForward, tyInt, tyInt8, tyInt16, tyInt32, tyInt64, tyFloat,
+  tyFloat32, tyFloat64, tyFloat128, tyUInt, tyUInt8, tyUInt16, tyUInt32,
+  tyUInt64, tyOwned, tySink, tyLent, tyVarargs, tyUncheckedArray, tyError,
+  tyBuiltInTypeClass, tyUserTypeClass, tyUserTypeClassInst,
+  tyCompositeTypeClass, tyInferred, tyAnd, tyOr, tyNot, tyAnything, tyStatic,
+  tyFromExpr, tyConcept, tyVoid, tyIterable
+
+ + + Source   +Edit   + +
+
+
+
TTypeKinds = set[TTypeKind]
+
+ + + Source   +Edit   + +
+
+
+
TTypeSeq = seq[PType]
+
+ + + Source   +Edit   + +
+
+
+
TypeMapping = Table[ItemId, PType]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
eqTypeFlags = {tfIterator, tfNotNil, tfVarIsPtr, tfGcSafe, tfNoSideEffect,
+               tfIsOutParam}
+
+ + type flags that are essential for type equality. This is now a variable because for emulation of version:1.0 we might exclude {tfGcSafe, tfNoSideEffect}. + Source   +Edit   + +
+
+
+
ggDebug {....deprecated.}: bool
+
+ + convenience switch for trying out things + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
abstractInst = {tyGenericInst, tyDistinct, tyOrdinal, tyTypeDesc, tyAlias,
+                tyInferred, tySink, tyOwned}
+
+ + + Source   +Edit   + +
+
+
+
abstractVarRange = {tyGenericInst, tyRange, tyVar, tyDistinct, tyOrdinal,
+                    tyTypeDesc, tyAlias, tyInferred, tySink, tyOwned}
+
+ + + Source   +Edit   + +
+
+
+
AttachedOpToStr: array[TTypeAttachedOp, string] = ["=wasMoved", "=destroy",
+    "=copy", "=dup", "=sink", "=trace", "=deepcopy"]
+
+ + + Source   +Edit   + +
+
+
+
bodyPos = 6
+
+ + + Source   +Edit   + +
+
+
+
callableDefs = {nkLambda..nkDo, nkProcDef..nkIteratorDef, nkFuncDef}
+
+ + + Source   +Edit   + +
+
+
+
ConcreteTypes: TTypeKinds = {tyBool, tyChar, tyEnum, tyArray, tyObject, tySet,
+                             tyTuple, tyRange, tyPtr, tyRef, tyVar, tyLent,
+                             tySequence, tyProc, tyPointer, tyOpenArray,
+                             tyString, tyCstring, tyInt..tyInt64,
+                             tyFloat..tyFloat128, tyUInt..tyUInt64}
+
+ + + Source   +Edit   + +
+
+
+
ConstantDataTypes: TTypeKinds = {tyArray, tySet, tyTuple, tySequence}
+
+ + + Source   +Edit   + +
+
+
+
ctfeWhitelist = {mNone, mSucc, mPred, mInc, mDec, mOrd, mLengthOpenArray,
+                 mLengthStr, mLengthArray, mLengthSeq, mArrGet, mArrPut, mAsgn,
+                 mDestroy, mIncl, mExcl, mCard, mChr, mAddI, mSubI, mMulI,
+                 mDivI, mModI, mAddF64, mSubF64, mMulF64, mDivF64, mShrI, mShlI,
+                 mBitandI, mBitorI, mBitxorI, mMinI, mMaxI, mAddU, mSubU, mMulU,
+                 mDivU, mModU, mEqI, mLeI, mLtI, mEqF64, mLeF64, mLtF64, mLeU,
+                 mLtU, mEqEnum, mLeEnum, mLtEnum, mEqCh, mLeCh, mLtCh, mEqB,
+                 mLeB, mLtB, mEqRef, mEqProc, mLePtr, mLtPtr, mEqCString, mXor,
+                 mUnaryMinusI, mUnaryMinusI64, mAbsI, mNot, mUnaryPlusI,
+                 mBitnotI, mUnaryPlusF64, mUnaryMinusF64, mCharToStr,
+                 mBoolToStr, mCStrToStr, mStrToStr, mEnumToStr, mAnd, mOr,
+                 mEqStr, mLeStr, mLtStr, mEqSet, mLeSet, mLtSet, mMulSet,
+                 mPlusSet, mMinusSet, mXorSet, mConStrStr, mAppendStrCh,
+                 mAppendStrStr, mAppendSeqElem, mInSet, mRepr, mOpenArrayToSeq}
+
+ + + Source   +Edit   + +
+
+
+
declarativeDefs = {nkProcDef, nkFuncDef, nkMethodDef, nkIteratorDef,
+                   nkConverterDef}
+
+ + + Source   +Edit   + +
+
+
+
defaultOffset = -1
+
+ + + Source   +Edit   + +
+
+
+
dispatcherPos = 8
+
+ + + Source   +Edit   + +
+
+
+
effectListLen = 6
+
+ + + Source   +Edit   + +
+
+
+
ensuresEffects = 2
+
+ + + Source   +Edit   + +
+
+
+
exceptionEffects = 0
+
+ + + Source   +Edit   + +
+
+
+
ExportableSymKinds = {skType..skConst, skProc..skTemplate, skEnumField, skStub}
+
+ + + Source   +Edit   + +
+
+
+
FirstGenericParamAt = 1
+
+ + + Source   +Edit   + +
+
+
+
FirstParamAt = 1
+
+ + + Source   +Edit   + +
+
+
+
forbiddenEffects = 5
+
+ + + Source   +Edit   + +
+
+
+
GcTypeKinds = {tyRef, tySequence, tyString}
+
+ + + Source   +Edit   + +
+
+
+
generatedMagics = {mNone, mIsolate, mFinished, mOpenArrayToSeq}
+
+ + magics that are generated as normal procs in the backend + Source   +Edit   + +
+
+
+
genericParamsPos = 2
+
+ + + Source   +Edit   + +
+
+
+
GenericTypes: TTypeKinds = {tyGenericInvocation, tyGenericBody, tyGenericParam}
+
+ + + Source   +Edit   + +
+
+
+
GrowthFactor = 2
+
+ + + Source   +Edit   + +
+
+
+
IntegralTypes = {tyBool, tyChar, tyEnum, tyInt..tyInt64, tyFloat..tyFloat128,
+                 tyUInt..tyUInt64}
+
+ + + Source   +Edit   + +
+
+
+
miscPos = 5
+
+ + + Source   +Edit   + +
+
+
+
namePos = 0
+
+ + + Source   +Edit   + +
+
+
+
nfAllFieldsSet = nfBase2
+
+ + + Source   +Edit   + +
+
+
+
NilableTypes: TTypeKinds = {tyPointer, tyCstring, tyRef, tyPtr, tyProc, tyError}
+
+ + + Source   +Edit   + +
+
+
+
nkEffectList = nkArgList
+
+ + + Source   +Edit   + +
+
+
+
nkFloatLiterals = {nkFloatLit..nkFloat128Lit}
+
+ + + Source   +Edit   + +
+
+
+
nkIdentKinds = {nkIdent, nkSym, nkAccQuoted, nkOpenSymChoice, nkClosedSymChoice,
+                nkOpenSym}
+
+ + + Source   +Edit   + +
+
+
+
nkLambdaKinds = {nkLambda, nkDo}
+
+ + + Source   +Edit   + +
+
+
+
nkLastBlockStmts = {nkRaiseStmt, nkReturnStmt, nkBreakStmt, nkContinueStmt}
+
+ + + Source   +Edit   + +
+
+
+
nkLiterals = {nkCharLit..nkTripleStrLit}
+
+ + + Source   +Edit   + +
+
+
+
nkPragmaCallKinds = {nkExprColonExpr, nkCall, nkCallStrLit}
+
+ + + Source   +Edit   + +
+
+
+
nkStrKinds = {nkStrLit..nkTripleStrLit}
+
+ + + Source   +Edit   + +
+
+
+
nkSymChoices = {nkClosedSymChoice, nkOpenSymChoice}
+
+ + + Source   +Edit   + +
+
+
+
nkWhen = nkWhenStmt
+
+ + + Source   +Edit   + +
+
+
+
nkWhenExpr = nkWhenStmt
+
+ + + Source   +Edit   + +
+
+
+
nodesToIgnoreSet = {nkNone..nkIdent, nkType..nkNilLit, nkTypeSection, nkProcDef,
+                    nkConverterDef, nkMethodDef, nkIteratorDef, nkMacroDef,
+                    nkTemplateDef, nkLambda, nkDo, nkFuncDef, nkConstSection,
+                    nkConstDef, nkIncludeStmt, nkImportStmt, nkExportStmt,
+                    nkPragma, nkCommentStmt, nkBreakState, nkTypeOfExpr,
+                    nkMixinStmt, nkBindStmt}
+
+ + + Source   +Edit   + +
+
+
+
OverloadableSyms = {skProc, skFunc, skMethod, skIterator, skConverter, skModule,
+                    skTemplate, skMacro, skEnumField}
+
+ + + Source   +Edit   + +
+
+
+
PackageModuleId = -3'i32
+
+ + + Source   +Edit   + +
+
+
+
paramsPos = 3
+
+ + + Source   +Edit   + +
+
+
+
patternPos = 1
+
+ + + Source   +Edit   + +
+
+
+
PersistentNodeFlags: TNodeFlags = {nfBase2, nfBase8, nfBase16, nfDotSetter,
+                                   nfDotField, nfIsRef, nfIsPtr, nfPreventCg,
+                                   nfLL, nfFromTemplate, nfDefaultRefsParam,
+                                   nfExecuteOnReload, nfLastRead, nfFirstWrite,
+                                   nfSkipFieldChecking, nfDisabledOpenSym}
+
+ + + Source   +Edit   + +
+
+
+
pragmasEffects = 4
+
+ + + Source   +Edit   + +
+
+
+
pragmasPos = 4
+
+ + + Source   +Edit   + +
+
+
+
procDefs = {nkLambda..nkDo, nkProcDef..nkConverterDef, nkIteratorDef, nkFuncDef}
+
+ + + Source   +Edit   + +
+
+
+
PtrLikeKinds: TTypeKinds = {tyPointer, tyPtr}
+
+ + + Source   +Edit   + +
+
+
+
requiresEffects = 1
+
+ + + Source   +Edit   + +
+
+
+
resultPos = 7
+
+ + + Source   +Edit   + +
+
+
+
routineDefs = {nkProcDef..nkIteratorDef, nkFuncDef}
+
+ + + Source   +Edit   + +
+
+
+
routineKinds = {skProc, skFunc, skMethod, skIterator, skConverter, skMacro,
+                skTemplate}
+
+ + + Source   +Edit   + +
+
+
+
sfCompileToCpp = sfInfixCall
+
+ + + Source   +Edit   + +
+
+
+
sfCompileToObjc = sfNamedParamCall
+
+ + + Source   +Edit   + +
+
+
+
sfCppMember = {sfVirtual, sfMember, sfConstructor}
+
+ + + Source   +Edit   + +
+
+
+
sfExperimental = sfOverridden
+
+ + + Source   +Edit   + +
+
+
+
sfNoForward = sfRegister
+
+ + + Source   +Edit   + +
+
+
+
sfNoInit = sfMainModule
+
+ + + Source   +Edit   + +
+
+
+
sfReorder = sfForward
+
+ + + Source   +Edit   + +
+
+
+
sfWrittenTo = sfBorrow
+
+ + + Source   +Edit   + +
+
+
+
skError = skUnknown
+
+ + + Source   +Edit   + +
+
+
+
skLocalVars = {skVar, skLet, skForVar, skParam, skResult}
+
+ + + Source   +Edit   + +
+
+
+
skProcKinds = {skProc, skFunc, skTemplate, skMacro, skIterator, skMethod,
+               skConverter}
+
+ + + Source   +Edit   + +
+
+
+
StartSize = 8
+
+ + + Source   +Edit   + +
+
+
+
StructuralEquivTypes: TTypeKinds = {tyNil, tyTuple, tyArray, tySet, tyRange,
+                                    tyPtr, tyRef, tyVar, tyLent, tySequence,
+                                    tyProc, tyOpenArray, tyVarargs}
+
+ + + Source   +Edit   + +
+
+
+
tagEffects = 3
+
+ + + Source   +Edit   + +
+
+
+
tfGcSafe = tfThread
+
+ + + Source   +Edit   + +
+
+
+
tfGenericHasDestructor = tfExplicitCallConv
+
+ + tyGenericBody where an instance has a generated destructor + Source   +Edit   + +
+
+
+
tfNonConstExpr = tfExplicitCallConv
+
+ + tyFromExpr where the expression shouldn't be evaluated as a static value + Source   +Edit   + +
+
+
+
tfObjHasKids = tfEnumHasHoles
+
+ + + Source   +Edit   + +
+
+
+
tfReturnsNew = tfInheritable
+
+ + + Source   +Edit   + +
+
+
+
tfUnion = tfNoSideEffect
+
+ + + Source   +Edit   + +
+
+
+
tyMetaTypes = {tyUntyped, tyTypeDesc, tyGenericParam,
+               tyBuiltInTypeClass..tyCompositeTypeClass, tyAnd..tyAnything,
+               tyConcept}
+
+ + + Source   +Edit   + +
+
+
+
tyPureObject = tyTuple
+
+ + + Source   +Edit   + +
+
+
+
tyTypeClasses = {tyBuiltInTypeClass, tyCompositeTypeClass, tyUserTypeClass,
+                 tyUserTypeClassInst, tyConcept, tyAnd, tyOr, tyNot, tyAnything}
+
+ + + Source   +Edit   + +
+
+
+
tyUserTypeClasses = {tyUserTypeClass, tyUserTypeClassInst}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(s: PSym): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `$`(x: ItemId): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(a, b: ItemId): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc add(father, son: PNode) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc add(father, son: PType) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addAllowNil(father, son: PNode) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc addAllowNil(father, son: PType) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addParam(procType: PType; param: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addSonNilAllowed(father, son: PNode) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc appendToModule(m: PSym; n: PNode) {....raises: [], tags: [], forbids: [].}
+
+ + The compiler will use this internally to add nodes that will be appended to the module after the sem pass + Source   +Edit   + +
+
+ +
+
+
+
proc assignType(dest, src: PType) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc astdef(s: PSym): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc base(t: PType): PType {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc baseClass(n: PType): PType {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc canRaise(fn: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc canRaiseConservative(fn: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc comment(n: PNode): string {....raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc comment=(n: PNode; a: string) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc containsNode(n: PNode; kinds: TNodeKinds): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc copyNode(src: PNode): PNode {....raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc copyObjectSet(dest: var TObjectSet; src: TObjectSet) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc copyStrTable(dest: var TStrTable; src: TStrTable) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc copySym(s: PSym; idgen: IdGenerator): PSym {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc copyTree(src: PNode): PNode {....raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc copyTreeWithoutNode(src, skippedNode: PNode): PNode {....raises: [KeyError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc copyType(t: PType; idgen: IdGenerator; owner: PSym): PType {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createModuleAlias(s: PSym; idgen: IdGenerator; newIdent: PIdent;
+                       info: TLineInfo; options: TOptions): PSym {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc delSon(father: PNode; idx: int) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc discardSons(father: PNode) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc elementType(n: PType): PType {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc exactReplica(t: PType): PType {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc extractPragma(s: PSym): PNode {....raises: [], tags: [], forbids: [].}
+
+ + gets the pragma node of routine/type/var/let/const symbol s + Source   +Edit   + +
+
+ +
+
+
+
proc findUnresolvedStatic(n: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc firstGenericParam(n: PType): PType {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc firstParamType(n: PType): PType {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genericConstraint(t: PType): PType {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genericHead(n: PType): PType {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genericInvocationParamsLen(t: PType): int {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genericParamHasConstraints(t: PType): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genericParamsLen(t: PType): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getDeclPragma(n: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + return the nkPragma node for declaration n, or nil if no pragma was found. Currently only supports routineDefs + {nkTypeDef}. + Source   +Edit   + +
+
+ +
+
+
+
proc getFloat(a: PNode): BiggestFloat {....raises: [ERecoverableError], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getInt(a: PNode): Int128 {....raises: [ERecoverableError], tags: [],
+                                forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getInt64(a: PNode): int64 {....deprecated: "use getInt",
+                                 raises: [ERecoverableError], tags: [],
+                                 forbids: [].}
+
+
+ Deprecated: use getInt +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getPIdent(a: PNode): PIdent {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Returns underlying PIdent for {nkSym, nkIdent}, or nil. + Source   +Edit   + +
+
+ +
+
+
+
proc getStr(a: PNode): string {....raises: [ERecoverableError], tags: [],
+                                forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getStrOrChar(a: PNode): string {....raises: [ERecoverableError], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasElementType(t: PType): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hash(x: ItemId): Hash {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasNilSon(n: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasPattern(s: PSym): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasSonWith(n: PNode; kind: TNodeKind): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasSubnodeWith(n: PNode; kind: TNodeKind): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc idGeneratorForPackage(nextIdWillBe: int32): IdGenerator {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc idGeneratorFromModule(m: PSym): IdGenerator {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc indexType(n: PType): PType {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initNodeTable(): TNodeTable {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initObjectSet(): TObjectSet {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initStrTable(): TStrTable {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isAtom(n: PNode): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isCallExpr(n: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isClosure(typ: PType): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isClosureIterator(typ: PType): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isCompileTimeProc(s: PSym): bool {.inline, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isEmptyTupleType(t: PType): bool {.inline, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isEmptyType(t: PType): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + 'void' and 'typed' types are often equivalent to 'nil' these days: + Source   +Edit   + +
+
+ +
+
+
+
proc isExplicitCallConv(s: PSym): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isGCedMem(t: PType): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isGenericParams(n: PNode): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + used to judge whether a node is generic params. + Source   +Edit   + +
+
+ +
+
+
+
proc isGenericRoutine(n: PNode): bool {.inline, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc isGenericRoutine(s: PSym): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

determines if this symbol represents a generic routine or an instance of one. This should be renamed accordingly and isGenericRoutineStrict should take this name instead.

+

Warning/XXX: Unfortunately, it considers a proc kind symbol flagged with sfFromGeneric as a generic routine. Instead this should likely not be the case and the concepts should be teased apart:

+
  • generic definition
  • +
  • generic instance
  • +
  • either generic definition or instance
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
proc isGenericRoutineStrict(s: PSym): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + determines if this symbol represents a generic routine the unusual name is so it doesn't collide and eventually replaces isGenericRoutine + Source   +Edit   + +
+
+ +
+
+
+
proc isImportedException(t: PType; conf: ConfigRef): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isInfixAs(n: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isInlineIterator(typ: PType): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isIterator(typ: PType): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isMetaType(t: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isNewStyleConcept(n: PNode): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isNimcall(s: PSym): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isOutParam(t: PType): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isRoutine(s: PSym): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isSingletonTupleType(t: PType): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isSinkParam(s: PSym): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isSinkType(t: PType): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isTrue(n: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isUnresolvedStatic(t: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc kidsLen(t: PType): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc last(n: PType): PType {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lastSon(n: PNode): PNode {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc len(n: PNode): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc len(n: PType): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc linkTo(s: PSym; t: PType): PSym {.discardable, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc linkTo(t: PType; s: PSym): PType {.discardable, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeStmtList(n: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newAtom(ident: PIdent; info: TLineInfo): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newAtom(kind: TNodeKind; floatVal: BiggestFloat; info: TLineInfo): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newAtom(kind: TNodeKind; intVal: BiggestInt; info: TLineInfo): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newAtom(kind: TNodeKind; strVal: sink string; info: TLineInfo): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newFloatNode(kind: TNodeKind; floatVal: BiggestFloat): PNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newIdentNode(ident: PIdent; info: TLineInfo): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newIntNode(kind: TNodeKind; intVal: BiggestInt): PNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newIntNode(kind: TNodeKind; intVal: Int128): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newIntTypeNode(intVal: BiggestInt; typ: PType): PNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newIntTypeNode(intVal: Int128; typ: PType): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newNode(kind: TNodeKind): PNode {....raises: [], tags: [], forbids: [].}
+
+ + new node with unknown line info, no type, and no children + Source   +Edit   + +
+
+
+
proc newNode(kind: TNodeKind; info: TLineInfo): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + new node with line info, no type, and no children + Source   +Edit   + +
+
+ +
+
+
+
proc newNodeI(kind: TNodeKind; info: TLineInfo): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + new node with line info, no type, and no children + Source   +Edit   + +
+
+
+
proc newNodeI(kind: TNodeKind; info: TLineInfo; children: int): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + new node with line info, type, and children + Source   +Edit   + +
+
+ +
+
+
+
proc newNodeIT(kind: TNodeKind; info: TLineInfo; typ: PType): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + new node with line info, type, and no children + Source   +Edit   + +
+
+ +
+
+
+
proc newOpenSym(n: PNode): PNode {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newProcNode(kind: TNodeKind; info: TLineInfo; body: PNode; params, name,
+    pattern, genericParams, pragmas, exceptions: PNode): PNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newProcType(info: TLineInfo; idgen: IdGenerator; owner: PSym): PType {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newSons(father: PNode; length: int) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newSons(father: PType; length: int) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newStrNode(kind: TNodeKind; strVal: string): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newStrNode(strVal: string; info: TLineInfo): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newSym(symKind: TSymKind; name: PIdent; idgen: IdGenerator; owner: PSym;
+            info: TLineInfo; options: TOptions = {}): PSym {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newSymNode(sym: PSym): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newSymNode(sym: PSym; info: TLineInfo): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newTree(kind: TNodeKind; children: varargs[PNode]): PNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newTree(kind: TNodeKind; info: TLineInfo; children: varargs[PNode]): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newTreeI(kind: TNodeKind; info: TLineInfo; children: varargs[PNode]): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newTreeIT(kind: TNodeKind; info: TLineInfo; typ: PType;
+               children: varargs[PNode]): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newType(kind: TTypeKind; idgen: IdGenerator; owner: PSym;
+             son: sink PType = nil): PType {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nextTypeId(x: IdGenerator): ItemId {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc originatingModule(s: PSym): PSym {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc owner(s: PSym | PType): PSym {.inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc paramsLen(t: PType): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc propagateToOwner(owner, elem: PType; propagateHasAsgn = true) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rawAddSon(father, son: PType; propagateHasAsgn = true) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc replaceFirstSon(n, newson: PNode) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc replaceSon(n: PNode; i: int; newson: PNode) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc returnType(n: PType): PType {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc safeArrLen(n: PNode): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + works for array-like objects (strings passed as openArray in VM). + Source   +Edit   + +
+
+ +
+
+
+
proc safeLen(n: PNode): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + works even for leaves. + Source   +Edit   + +
+
+ +
+
+
+
proc sameTupleLengths(a, b: PType): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setIndexType(n, idx: PType) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setInfoRecursive(n: PNode; info: TLineInfo) {....raises: [], tags: [],
+    forbids: [].}
+
+ + set line info recursively + Source   +Edit   + +
+
+ +
+
+
+
proc setOwner(s: PSym | PType; owner: PSym) {.inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setReturnType(n, r: PType) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setSon(dest: PType; son: sink PType) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setSons(dest: PType; sons: sink seq[PType]) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setSonsLen(dest: PType; len: int) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setUseIc(useIc: bool) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc shallowCopy(src: PNode): PNode {....raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc signatureLen(t: PType): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipColon(n: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipGenericOwner(s: PSym): PSym {....raises: [], tags: [], forbids: [].}
+
+ + Generic instantiations are owned by their originating generic symbol. This proc skips such owners and goes straight to the owner of the generic itself (the module or the enclosing proc). + Source   +Edit   + +
+
+ +
+
+
+
proc skipHiddenAddr(n: PNode): PNode {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipModifier(n: PType): PType {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipPragmaExpr(n: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + if pragma expr, give the node the pragmas are applied to, otherwise give node itself + Source   +Edit   + +
+
+ +
+
+
+
proc skipStmtList(n: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipTypes(t: PType; kinds: TTypeKinds): PType {....raises: [], tags: [],
+    forbids: [].}
+
+ + Used throughout the compiler code to test whether a type tree contains or doesn't contain a specific type/types - it is often the case that only the last child nodes of a type tree need to be searched. This is a really hot path within the compiler! + Source   +Edit   + +
+
+
+
proc skipTypes(t: PType; kinds: TTypeKinds; maxIters: int): PType {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipTypesOrNil(t: PType; kinds: TTypeKinds): PType {....raises: [], tags: [],
+    forbids: [].}
+
+ + same as skipTypes but handles 'nil' + Source   +Edit   + +
+
+ +
+
+
+
proc toHumanStr(kind: TSymKind): string {....raises: [], tags: [], forbids: [].}
+
+ + strips leading sk + Source   +Edit   + +
+
+
+
proc toHumanStr(kind: TTypeKind): string {....raises: [], tags: [], forbids: [].}
+
+ + strips leading tk + Source   +Edit   + +
+
+ +
+
+
+
proc toObject(typ: PType): PType {....raises: [], tags: [], forbids: [].}
+
+ + If typ is a tyRef then its immediate son is returned (which in many cases should be a tyObject). Otherwise typ is simply returned as-is. + Source   +Edit   + +
+
+ +
+
+
+
proc toObjectFromRefPtrGeneric(typ: PType): PType {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toRef(typ: PType; idgen: IdGenerator): PType {....raises: [], tags: [],
+    forbids: [].}
+
+ + If typ is a tyObject then it is converted into a ref <typ> and returned. Otherwise typ is simply returned as-is. + Source   +Edit   + +
+
+ +
+
+
+
proc toVar(typ: PType; kind: TTypeKind; idgen: IdGenerator): PType {....raises: [],
+    tags: [], forbids: [].}
+
+ + If typ is not a tyVar then it is converted into a var <typ> and returned. Otherwise typ is simply returned as-is. + Source   +Edit   + +
+
+ +
+
+
+
proc transitionGenericParamToType(s: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc transitionIntKind(n: PNode; kind: range[nkCharLit .. nkUInt64Lit]) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc transitionIntToFloatKind(n: PNode; kind: range[nkFloatLit .. nkFloat128Lit]) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc transitionNoneToSym(n: PNode) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc transitionRoutineSymKind(s: PSym; kind: range[skProc .. skTemplate]) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc transitionSonsKind(n: PNode; kind: range[nkComesFrom .. nkTupleConstr]) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc transitionToLet(s: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc truncateInferredTypeCandidates(t: PType) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc typeBodyImpl(n: PType): PType {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc withInfo(n: PNode; info: TLineInfo): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator genericBodyParams(t: PType): (int, PType) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator genericInstParamPairs(a, b: PType): (int, PType, PType) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator genericInstParams(t: PType): (bool, PType) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator genericInvocationAndBodyElements(a, b: PType): (PType, PType) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator genericInvocationParamPairs(a, b: PType): (bool, PType, PType) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator genericInvocationParams(t: PType): (bool, PType) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator ikids(t: PType): (int, PType) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator items(n: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator kids(t: PType): PType {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator pairs(n: PNode): tuple[i: int, n: PNode] {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator paramTypePairs(a, b: PType): (PType, PType) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator paramTypes(t: PType): (int, PType) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator signature(t: PType): PType {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator tupleTypePairs(a, b: PType): (int, PType, PType) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator underspecifiedPairs(a, b: PType; start = 0; without = 0): (PType, PType) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator userTypeClassInstParams(t: PType): (bool, PType) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template `[]`(n: PNode; i: BackwardsIndex): PNode
+
+ + + Source   +Edit   + +
+
+
+
template `[]`(n: PNode; i: int): PNode
+
+ + + Source   +Edit   + +
+
+
+
template `[]`(n: PType; i: BackwardsIndex): PType
+
+ + + Source   +Edit   + +
+
+
+
template `[]`(n: PType; i: int): PType
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template `[]=`(n: PNode; i: BackwardsIndex; x: PNode)
+
+ + + Source   +Edit   + +
+
+
+
template `[]=`(n: PNode; i: int; x: PNode)
+
+ + + Source   +Edit   + +
+
+
+
template `[]=`(n: PType; i: BackwardsIndex; x: PType)
+
+ + + Source   +Edit   + +
+
+
+
template `[]=`(n: PType; i: int; x: PType)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template detailedInfo(sym: PSym): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template fileIdx(c: PSym): FileIndex
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template filename(c: PSym): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template firstSon(n: PNode): PNode
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template has2Sons(n: PNode): bool
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template hasDestructor(t: PType): bool
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template hasSon(n: PNode): bool
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template id(a: PType | PSym): int
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template idTableGet(tab: typed; key: PSym | PType): untyped
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template idTablePut(tab: typed; key, val: PSym | PType)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template incompleteType(t: PType): bool
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template initSymMapping(): Table[ItemId, PSym]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template initTypeMapping(): Table[ItemId, PType]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template paramTypeToNodeIndex(x: int): int
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template previouslyInferred(t: PType): PType
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template resetIdTable(tab: Table[ItemId, PSym])
+
+ + + Source   +Edit   + +
+
+
+
template resetIdTable(tab: Table[ItemId, PType])
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template secondSon(n: PNode): PNode
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template setLastSon(n: PNode; s: PNode)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template transitionSymKindCommon(k: TSymKind)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template typ(n: PNode): PType
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template typeCompleted(s: PSym)
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/ast.idx b/compiler/ast.idx new file mode 100644 index 0000000000000..22094867d56b7 --- /dev/null +++ b/compiler/ast.idx @@ -0,0 +1,918 @@ +nimTitle ast ast.html module ast 0 +nim ccNimCall ast.html#ccNimCall TCallingConvention.ccNimCall 27 +nim ccStdCall ast.html#ccStdCall TCallingConvention.ccStdCall 27 +nim ccCDecl ast.html#ccCDecl TCallingConvention.ccCDecl 27 +nim ccSafeCall ast.html#ccSafeCall TCallingConvention.ccSafeCall 27 +nim ccSysCall ast.html#ccSysCall TCallingConvention.ccSysCall 27 +nim ccInline ast.html#ccInline TCallingConvention.ccInline 27 +nim ccNoInline ast.html#ccNoInline TCallingConvention.ccNoInline 27 +nim ccFastCall ast.html#ccFastCall TCallingConvention.ccFastCall 27 +nim ccThisCall ast.html#ccThisCall TCallingConvention.ccThisCall 27 +nim ccClosure ast.html#ccClosure TCallingConvention.ccClosure 27 +nim ccNoConvention ast.html#ccNoConvention TCallingConvention.ccNoConvention 27 +nim ccMember ast.html#ccMember TCallingConvention.ccMember 27 +nim TCallingConvention ast.html#TCallingConvention enum TCallingConvention 27 +nim TNodeKinds ast.html#TNodeKinds type TNodeKinds 41 +nim sfUsed ast.html#sfUsed TSymFlag.sfUsed 44 +nim sfExported ast.html#sfExported TSymFlag.sfExported 44 +nim sfFromGeneric ast.html#sfFromGeneric TSymFlag.sfFromGeneric 44 +nim sfGlobal ast.html#sfGlobal TSymFlag.sfGlobal 44 +nim sfForward ast.html#sfForward TSymFlag.sfForward 44 +nim sfWasForwarded ast.html#sfWasForwarded TSymFlag.sfWasForwarded 44 +nim sfImportc ast.html#sfImportc TSymFlag.sfImportc 44 +nim sfExportc ast.html#sfExportc TSymFlag.sfExportc 44 +nim sfMangleCpp ast.html#sfMangleCpp TSymFlag.sfMangleCpp 44 +nim sfVolatile ast.html#sfVolatile TSymFlag.sfVolatile 44 +nim sfRegister ast.html#sfRegister TSymFlag.sfRegister 44 +nim sfPure ast.html#sfPure TSymFlag.sfPure 44 +nim sfNoSideEffect ast.html#sfNoSideEffect TSymFlag.sfNoSideEffect 44 +nim sfSideEffect ast.html#sfSideEffect TSymFlag.sfSideEffect 44 +nim sfMainModule ast.html#sfMainModule TSymFlag.sfMainModule 44 +nim sfSystemModule ast.html#sfSystemModule TSymFlag.sfSystemModule 44 +nim sfNoReturn ast.html#sfNoReturn TSymFlag.sfNoReturn 44 +nim sfAddrTaken ast.html#sfAddrTaken TSymFlag.sfAddrTaken 44 +nim sfCompilerProc ast.html#sfCompilerProc TSymFlag.sfCompilerProc 44 +nim sfEscapes ast.html#sfEscapes TSymFlag.sfEscapes 44 +nim sfDiscriminant ast.html#sfDiscriminant TSymFlag.sfDiscriminant 44 +nim sfRequiresInit ast.html#sfRequiresInit TSymFlag.sfRequiresInit 44 +nim sfDeprecated ast.html#sfDeprecated TSymFlag.sfDeprecated 44 +nim sfExplain ast.html#sfExplain TSymFlag.sfExplain 44 +nim sfError ast.html#sfError TSymFlag.sfError 44 +nim sfShadowed ast.html#sfShadowed TSymFlag.sfShadowed 44 +nim sfThread ast.html#sfThread TSymFlag.sfThread 44 +nim sfCppNonPod ast.html#sfCppNonPod TSymFlag.sfCppNonPod 44 +nim sfCompileTime ast.html#sfCompileTime TSymFlag.sfCompileTime 44 +nim sfConstructor ast.html#sfConstructor TSymFlag.sfConstructor 44 +nim sfDispatcher ast.html#sfDispatcher TSymFlag.sfDispatcher 44 +nim sfBorrow ast.html#sfBorrow TSymFlag.sfBorrow 44 +nim sfInfixCall ast.html#sfInfixCall TSymFlag.sfInfixCall 44 +nim sfNamedParamCall ast.html#sfNamedParamCall TSymFlag.sfNamedParamCall 44 +nim sfDiscardable ast.html#sfDiscardable TSymFlag.sfDiscardable 44 +nim sfOverridden ast.html#sfOverridden TSymFlag.sfOverridden 44 +nim sfCallsite ast.html#sfCallsite TSymFlag.sfCallsite 44 +nim sfGenSym ast.html#sfGenSym TSymFlag.sfGenSym 44 +nim sfNonReloadable ast.html#sfNonReloadable TSymFlag.sfNonReloadable 44 +nim sfGeneratedOp ast.html#sfGeneratedOp TSymFlag.sfGeneratedOp 44 +nim sfTemplateParam ast.html#sfTemplateParam TSymFlag.sfTemplateParam 44 +nim sfCursor ast.html#sfCursor TSymFlag.sfCursor 44 +nim sfInjectDestructors ast.html#sfInjectDestructors TSymFlag.sfInjectDestructors 44 +nim sfNeverRaises ast.html#sfNeverRaises TSymFlag.sfNeverRaises 44 +nim sfSystemRaisesDefect ast.html#sfSystemRaisesDefect TSymFlag.sfSystemRaisesDefect 44 +nim sfUsedInFinallyOrExcept ast.html#sfUsedInFinallyOrExcept TSymFlag.sfUsedInFinallyOrExcept 44 +nim sfSingleUsedTemp ast.html#sfSingleUsedTemp TSymFlag.sfSingleUsedTemp 44 +nim sfNoalias ast.html#sfNoalias TSymFlag.sfNoalias 44 +nim sfEffectsDelayed ast.html#sfEffectsDelayed TSymFlag.sfEffectsDelayed 44 +nim sfGeneratedType ast.html#sfGeneratedType TSymFlag.sfGeneratedType 44 +nim sfVirtual ast.html#sfVirtual TSymFlag.sfVirtual 44 +nim sfByCopy ast.html#sfByCopy TSymFlag.sfByCopy 44 +nim sfMember ast.html#sfMember TSymFlag.sfMember 44 +nim sfCodegenDecl ast.html#sfCodegenDecl TSymFlag.sfCodegenDecl 44 +nim sfWasGenSym ast.html#sfWasGenSym TSymFlag.sfWasGenSym 44 +nim sfForceLift ast.html#sfForceLift TSymFlag.sfForceLift 44 +nim sfDirty ast.html#sfDirty TSymFlag.sfDirty 44 +nim sfCustomPragma ast.html#sfCustomPragma TSymFlag.sfCustomPragma 44 +nim sfBase ast.html#sfBase TSymFlag.sfBase 44 +nim sfGoto ast.html#sfGoto TSymFlag.sfGoto 44 +nim sfAnon ast.html#sfAnon TSymFlag.sfAnon 44 +nim sfAllUntyped ast.html#sfAllUntyped TSymFlag.sfAllUntyped 44 +nim sfTemplateRedefinition ast.html#sfTemplateRedefinition TSymFlag.sfTemplateRedefinition 44 +nim TSymFlag ast.html#TSymFlag enum TSymFlag 44 +nim TSymFlags ast.html#TSymFlags type TSymFlags 143 +nim sfNoInit ast.html#sfNoInit const sfNoInit 146 +nim sfNoForward ast.html#sfNoForward const sfNoForward 148 +nim sfReorder ast.html#sfReorder const sfReorder 150 +nim sfCompileToCpp ast.html#sfCompileToCpp const sfCompileToCpp 153 +nim sfCompileToObjc ast.html#sfCompileToObjc const sfCompileToObjc 154 +nim sfExperimental ast.html#sfExperimental const sfExperimental 155 +nim sfWrittenTo ast.html#sfWrittenTo const sfWrittenTo 156 +nim sfCppMember ast.html#sfCppMember const sfCppMember 158 +nim nkWhen ast.html#nkWhen const nkWhen 162 +nim nkWhenExpr ast.html#nkWhenExpr const nkWhenExpr 163 +nim nkEffectList ast.html#nkEffectList const nkEffectList 164 +nim exceptionEffects ast.html#exceptionEffects const exceptionEffects 166 +nim requiresEffects ast.html#requiresEffects const requiresEffects 167 +nim ensuresEffects ast.html#ensuresEffects const ensuresEffects 168 +nim tagEffects ast.html#tagEffects const tagEffects 169 +nim pragmasEffects ast.html#pragmasEffects const pragmasEffects 170 +nim forbiddenEffects ast.html#forbiddenEffects const forbiddenEffects 171 +nim effectListLen ast.html#effectListLen const effectListLen 172 +nim nkLastBlockStmts ast.html#nkLastBlockStmts const nkLastBlockStmts 173 +nim tyNone ast.html#tyNone TTypeKind.tyNone 177 +nim tyBool ast.html#tyBool TTypeKind.tyBool 177 +nim tyChar ast.html#tyChar TTypeKind.tyChar 177 +nim tyEmpty ast.html#tyEmpty TTypeKind.tyEmpty 177 +nim tyAlias ast.html#tyAlias TTypeKind.tyAlias 177 +nim tyNil ast.html#tyNil TTypeKind.tyNil 177 +nim tyUntyped ast.html#tyUntyped TTypeKind.tyUntyped 177 +nim tyTyped ast.html#tyTyped TTypeKind.tyTyped 177 +nim tyTypeDesc ast.html#tyTypeDesc TTypeKind.tyTypeDesc 177 +nim tyGenericInvocation ast.html#tyGenericInvocation TTypeKind.tyGenericInvocation 177 +nim tyGenericBody ast.html#tyGenericBody TTypeKind.tyGenericBody 177 +nim tyGenericInst ast.html#tyGenericInst TTypeKind.tyGenericInst 177 +nim tyGenericParam ast.html#tyGenericParam TTypeKind.tyGenericParam 177 +nim tyDistinct ast.html#tyDistinct TTypeKind.tyDistinct 177 +nim tyEnum ast.html#tyEnum TTypeKind.tyEnum 177 +nim tyOrdinal ast.html#tyOrdinal TTypeKind.tyOrdinal 177 +nim tyArray ast.html#tyArray TTypeKind.tyArray 177 +nim tyObject ast.html#tyObject TTypeKind.tyObject 177 +nim tyTuple ast.html#tyTuple TTypeKind.tyTuple 177 +nim tySet ast.html#tySet TTypeKind.tySet 177 +nim tyRange ast.html#tyRange TTypeKind.tyRange 177 +nim tyPtr ast.html#tyPtr TTypeKind.tyPtr 177 +nim tyRef ast.html#tyRef TTypeKind.tyRef 177 +nim tyVar ast.html#tyVar TTypeKind.tyVar 177 +nim tySequence ast.html#tySequence TTypeKind.tySequence 177 +nim tyProc ast.html#tyProc TTypeKind.tyProc 177 +nim tyPointer ast.html#tyPointer TTypeKind.tyPointer 177 +nim tyOpenArray ast.html#tyOpenArray TTypeKind.tyOpenArray 177 +nim tyString ast.html#tyString TTypeKind.tyString 177 +nim tyCstring ast.html#tyCstring TTypeKind.tyCstring 177 +nim tyForward ast.html#tyForward TTypeKind.tyForward 177 +nim tyInt ast.html#tyInt TTypeKind.tyInt 177 +nim tyInt8 ast.html#tyInt8 TTypeKind.tyInt8 177 +nim tyInt16 ast.html#tyInt16 TTypeKind.tyInt16 177 +nim tyInt32 ast.html#tyInt32 TTypeKind.tyInt32 177 +nim tyInt64 ast.html#tyInt64 TTypeKind.tyInt64 177 +nim tyFloat ast.html#tyFloat TTypeKind.tyFloat 177 +nim tyFloat32 ast.html#tyFloat32 TTypeKind.tyFloat32 177 +nim tyFloat64 ast.html#tyFloat64 TTypeKind.tyFloat64 177 +nim tyFloat128 ast.html#tyFloat128 TTypeKind.tyFloat128 177 +nim tyUInt ast.html#tyUInt TTypeKind.tyUInt 177 +nim tyUInt8 ast.html#tyUInt8 TTypeKind.tyUInt8 177 +nim tyUInt16 ast.html#tyUInt16 TTypeKind.tyUInt16 177 +nim tyUInt32 ast.html#tyUInt32 TTypeKind.tyUInt32 177 +nim tyUInt64 ast.html#tyUInt64 TTypeKind.tyUInt64 177 +nim tyOwned ast.html#tyOwned TTypeKind.tyOwned 177 +nim tySink ast.html#tySink TTypeKind.tySink 177 +nim tyLent ast.html#tyLent TTypeKind.tyLent 177 +nim tyVarargs ast.html#tyVarargs TTypeKind.tyVarargs 177 +nim tyUncheckedArray ast.html#tyUncheckedArray TTypeKind.tyUncheckedArray 177 +nim tyError ast.html#tyError TTypeKind.tyError 177 +nim tyBuiltInTypeClass ast.html#tyBuiltInTypeClass TTypeKind.tyBuiltInTypeClass 177 +nim tyUserTypeClass ast.html#tyUserTypeClass TTypeKind.tyUserTypeClass 177 +nim tyUserTypeClassInst ast.html#tyUserTypeClassInst TTypeKind.tyUserTypeClassInst 177 +nim tyCompositeTypeClass ast.html#tyCompositeTypeClass TTypeKind.tyCompositeTypeClass 177 +nim tyInferred ast.html#tyInferred TTypeKind.tyInferred 177 +nim tyAnd ast.html#tyAnd TTypeKind.tyAnd 177 +nim tyOr ast.html#tyOr TTypeKind.tyOr 177 +nim tyNot ast.html#tyNot TTypeKind.tyNot 177 +nim tyAnything ast.html#tyAnything TTypeKind.tyAnything 177 +nim tyStatic ast.html#tyStatic TTypeKind.tyStatic 177 +nim tyFromExpr ast.html#tyFromExpr TTypeKind.tyFromExpr 177 +nim tyConcept ast.html#tyConcept TTypeKind.tyConcept 177 +nim tyVoid ast.html#tyVoid TTypeKind.tyVoid 177 +nim tyIterable ast.html#tyIterable TTypeKind.tyIterable 177 +nim TTypeKind ast.html#TTypeKind enum TTypeKind 177 +nim tyPureObject ast.html#tyPureObject const tyPureObject 278 +nim GcTypeKinds ast.html#GcTypeKinds const GcTypeKinds 279 +nim tyTypeClasses ast.html#tyTypeClasses const tyTypeClasses 281 +nim tyMetaTypes ast.html#tyMetaTypes const tyMetaTypes 285 +nim tyUserTypeClasses ast.html#tyUserTypeClasses const tyUserTypeClasses 286 +nim abstractVarRange ast.html#abstractVarRange const abstractVarRange 288 +nim abstractInst ast.html#abstractInst const abstractInst 290 +nim TTypeKinds ast.html#TTypeKinds type TTypeKinds 294 +nim nfNone ast.html#nfNone TNodeFlag.nfNone 296 +nim nfBase2 ast.html#nfBase2 TNodeFlag.nfBase2 296 +nim nfBase8 ast.html#nfBase8 TNodeFlag.nfBase8 296 +nim nfBase16 ast.html#nfBase16 TNodeFlag.nfBase16 296 +nim nfAllConst ast.html#nfAllConst TNodeFlag.nfAllConst 296 +nim nfTransf ast.html#nfTransf TNodeFlag.nfTransf 296 +nim nfNoRewrite ast.html#nfNoRewrite TNodeFlag.nfNoRewrite 296 +nim nfSem ast.html#nfSem TNodeFlag.nfSem 296 +nim nfLL ast.html#nfLL TNodeFlag.nfLL 296 +nim nfDotField ast.html#nfDotField TNodeFlag.nfDotField 296 +nim nfDotSetter ast.html#nfDotSetter TNodeFlag.nfDotSetter 296 +nim nfExplicitCall ast.html#nfExplicitCall TNodeFlag.nfExplicitCall 296 +nim nfExprCall ast.html#nfExprCall TNodeFlag.nfExprCall 296 +nim nfIsRef ast.html#nfIsRef TNodeFlag.nfIsRef 296 +nim nfIsPtr ast.html#nfIsPtr TNodeFlag.nfIsPtr 296 +nim nfPreventCg ast.html#nfPreventCg TNodeFlag.nfPreventCg 296 +nim nfBlockArg ast.html#nfBlockArg TNodeFlag.nfBlockArg 296 +nim nfFromTemplate ast.html#nfFromTemplate TNodeFlag.nfFromTemplate 296 +nim nfDefaultParam ast.html#nfDefaultParam TNodeFlag.nfDefaultParam 296 +nim nfDefaultRefsParam ast.html#nfDefaultRefsParam TNodeFlag.nfDefaultRefsParam 296 +nim nfExecuteOnReload ast.html#nfExecuteOnReload TNodeFlag.nfExecuteOnReload 296 +nim nfLastRead ast.html#nfLastRead TNodeFlag.nfLastRead 296 +nim nfFirstWrite ast.html#nfFirstWrite TNodeFlag.nfFirstWrite 296 +nim nfHasComment ast.html#nfHasComment TNodeFlag.nfHasComment 296 +nim nfSkipFieldChecking ast.html#nfSkipFieldChecking TNodeFlag.nfSkipFieldChecking 296 +nim nfDisabledOpenSym ast.html#nfDisabledOpenSym TNodeFlag.nfDisabledOpenSym 296 +nim TNodeFlag ast.html#TNodeFlag enum TNodeFlag 296 +nim TNodeFlags ast.html#TNodeFlags type TNodeFlags 329 +nim tfVarargs ast.html#tfVarargs TTypeFlag.tfVarargs 330 +nim tfNoSideEffect ast.html#tfNoSideEffect TTypeFlag.tfNoSideEffect 330 +nim tfFinal ast.html#tfFinal TTypeFlag.tfFinal 330 +nim tfInheritable ast.html#tfInheritable TTypeFlag.tfInheritable 330 +nim tfHasOwned ast.html#tfHasOwned TTypeFlag.tfHasOwned 330 +nim tfEnumHasHoles ast.html#tfEnumHasHoles TTypeFlag.tfEnumHasHoles 330 +nim tfShallow ast.html#tfShallow TTypeFlag.tfShallow 330 +nim tfThread ast.html#tfThread TTypeFlag.tfThread 330 +nim tfFromGeneric ast.html#tfFromGeneric TTypeFlag.tfFromGeneric 330 +nim tfUnresolved ast.html#tfUnresolved TTypeFlag.tfUnresolved 330 +nim tfResolved ast.html#tfResolved TTypeFlag.tfResolved 330 +nim tfRetType ast.html#tfRetType TTypeFlag.tfRetType 330 +nim tfCapturesEnv ast.html#tfCapturesEnv TTypeFlag.tfCapturesEnv 330 +nim tfByCopy ast.html#tfByCopy TTypeFlag.tfByCopy 330 +nim tfByRef ast.html#tfByRef TTypeFlag.tfByRef 330 +nim tfIterator ast.html#tfIterator TTypeFlag.tfIterator 330 +nim tfPartial ast.html#tfPartial TTypeFlag.tfPartial 330 +nim tfNotNil ast.html#tfNotNil TTypeFlag.tfNotNil 330 +nim tfRequiresInit ast.html#tfRequiresInit TTypeFlag.tfRequiresInit 330 +nim tfNeedsFullInit ast.html#tfNeedsFullInit TTypeFlag.tfNeedsFullInit 330 +nim tfVarIsPtr ast.html#tfVarIsPtr TTypeFlag.tfVarIsPtr 330 +nim tfHasMeta ast.html#tfHasMeta TTypeFlag.tfHasMeta 330 +nim tfHasGCedMem ast.html#tfHasGCedMem TTypeFlag.tfHasGCedMem 330 +nim tfPacked ast.html#tfPacked TTypeFlag.tfPacked 330 +nim tfHasStatic ast.html#tfHasStatic TTypeFlag.tfHasStatic 330 +nim tfGenericTypeParam ast.html#tfGenericTypeParam TTypeFlag.tfGenericTypeParam 330 +nim tfImplicitTypeParam ast.html#tfImplicitTypeParam TTypeFlag.tfImplicitTypeParam 330 +nim tfInferrableStatic ast.html#tfInferrableStatic TTypeFlag.tfInferrableStatic 330 +nim tfConceptMatchedTypeSym ast.html#tfConceptMatchedTypeSym TTypeFlag.tfConceptMatchedTypeSym 330 +nim tfExplicit ast.html#tfExplicit TTypeFlag.tfExplicit 330 +nim tfWildcard ast.html#tfWildcard TTypeFlag.tfWildcard 330 +nim tfHasAsgn ast.html#tfHasAsgn TTypeFlag.tfHasAsgn 330 +nim tfBorrowDot ast.html#tfBorrowDot TTypeFlag.tfBorrowDot 330 +nim tfTriggersCompileTime ast.html#tfTriggersCompileTime TTypeFlag.tfTriggersCompileTime 330 +nim tfRefsAnonObj ast.html#tfRefsAnonObj TTypeFlag.tfRefsAnonObj 330 +nim tfCovariant ast.html#tfCovariant TTypeFlag.tfCovariant 330 +nim tfWeakCovariant ast.html#tfWeakCovariant TTypeFlag.tfWeakCovariant 330 +nim tfContravariant ast.html#tfContravariant TTypeFlag.tfContravariant 330 +nim tfCheckedForDestructor ast.html#tfCheckedForDestructor TTypeFlag.tfCheckedForDestructor 330 +nim tfAcyclic ast.html#tfAcyclic TTypeFlag.tfAcyclic 330 +nim tfIncompleteStruct ast.html#tfIncompleteStruct TTypeFlag.tfIncompleteStruct 330 +nim tfCompleteStruct ast.html#tfCompleteStruct TTypeFlag.tfCompleteStruct 330 +nim tfExplicitCallConv ast.html#tfExplicitCallConv TTypeFlag.tfExplicitCallConv 330 +nim tfIsConstructor ast.html#tfIsConstructor TTypeFlag.tfIsConstructor 330 +nim tfEffectSystemWorkaround ast.html#tfEffectSystemWorkaround TTypeFlag.tfEffectSystemWorkaround 330 +nim tfIsOutParam ast.html#tfIsOutParam TTypeFlag.tfIsOutParam 330 +nim tfSendable ast.html#tfSendable TTypeFlag.tfSendable 330 +nim tfImplicitStatic ast.html#tfImplicitStatic TTypeFlag.tfImplicitStatic 330 +nim TTypeFlag ast.html#TTypeFlag enum TTypeFlag 330 +nim TTypeFlags ast.html#TTypeFlags type TTypeFlags 403 +nim skUnknown ast.html#skUnknown TSymKind.skUnknown 405 +nim skConditional ast.html#skConditional TSymKind.skConditional 405 +nim skDynLib ast.html#skDynLib TSymKind.skDynLib 405 +nim skParam ast.html#skParam TSymKind.skParam 405 +nim skGenericParam ast.html#skGenericParam TSymKind.skGenericParam 405 +nim skTemp ast.html#skTemp TSymKind.skTemp 405 +nim skModule ast.html#skModule TSymKind.skModule 405 +nim skType ast.html#skType TSymKind.skType 405 +nim skVar ast.html#skVar TSymKind.skVar 405 +nim skLet ast.html#skLet TSymKind.skLet 405 +nim skConst ast.html#skConst TSymKind.skConst 405 +nim skResult ast.html#skResult TSymKind.skResult 405 +nim skProc ast.html#skProc TSymKind.skProc 405 +nim skFunc ast.html#skFunc TSymKind.skFunc 405 +nim skMethod ast.html#skMethod TSymKind.skMethod 405 +nim skIterator ast.html#skIterator TSymKind.skIterator 405 +nim skConverter ast.html#skConverter TSymKind.skConverter 405 +nim skMacro ast.html#skMacro TSymKind.skMacro 405 +nim skTemplate ast.html#skTemplate TSymKind.skTemplate 405 +nim skField ast.html#skField TSymKind.skField 405 +nim skEnumField ast.html#skEnumField TSymKind.skEnumField 405 +nim skForVar ast.html#skForVar TSymKind.skForVar 405 +nim skLabel ast.html#skLabel TSymKind.skLabel 405 +nim skStub ast.html#skStub TSymKind.skStub 405 +nim skPackage ast.html#skPackage TSymKind.skPackage 405 +nim TSymKind ast.html#TSymKind enum TSymKind 405 +nim TSymKinds ast.html#TSymKinds type TSymKinds 437 +nim routineKinds ast.html#routineKinds const routineKinds 440 +nim ExportableSymKinds ast.html#ExportableSymKinds const ExportableSymKinds 442 +nim tfUnion ast.html#tfUnion const tfUnion 444 +nim tfGcSafe ast.html#tfGcSafe const tfGcSafe 445 +nim tfObjHasKids ast.html#tfObjHasKids const tfObjHasKids 446 +nim tfReturnsNew ast.html#tfReturnsNew const tfReturnsNew 447 +nim tfNonConstExpr ast.html#tfNonConstExpr const tfNonConstExpr 448 +nim tfGenericHasDestructor ast.html#tfGenericHasDestructor const tfGenericHasDestructor 450 +nim skError ast.html#skError const skError 452 +nim eqTypeFlags ast.html#eqTypeFlags var eqTypeFlags 455 +nim mNone ast.html#mNone TMagic.mNone 461 +nim mDefined ast.html#mDefined TMagic.mDefined 461 +nim mDeclared ast.html#mDeclared TMagic.mDeclared 461 +nim mDeclaredInScope ast.html#mDeclaredInScope TMagic.mDeclaredInScope 461 +nim mCompiles ast.html#mCompiles TMagic.mCompiles 461 +nim mArrGet ast.html#mArrGet TMagic.mArrGet 461 +nim mArrPut ast.html#mArrPut TMagic.mArrPut 461 +nim mAsgn ast.html#mAsgn TMagic.mAsgn 461 +nim mLow ast.html#mLow TMagic.mLow 461 +nim mHigh ast.html#mHigh TMagic.mHigh 461 +nim mSizeOf ast.html#mSizeOf TMagic.mSizeOf 461 +nim mAlignOf ast.html#mAlignOf TMagic.mAlignOf 461 +nim mOffsetOf ast.html#mOffsetOf TMagic.mOffsetOf 461 +nim mTypeTrait ast.html#mTypeTrait TMagic.mTypeTrait 461 +nim mIs ast.html#mIs TMagic.mIs 461 +nim mOf ast.html#mOf TMagic.mOf 461 +nim mAddr ast.html#mAddr TMagic.mAddr 461 +nim mType ast.html#mType TMagic.mType 461 +nim mTypeOf ast.html#mTypeOf TMagic.mTypeOf 461 +nim mPlugin ast.html#mPlugin TMagic.mPlugin 461 +nim mEcho ast.html#mEcho TMagic.mEcho 461 +nim mShallowCopy ast.html#mShallowCopy TMagic.mShallowCopy 461 +nim mSlurp ast.html#mSlurp TMagic.mSlurp 461 +nim mStaticExec ast.html#mStaticExec TMagic.mStaticExec 461 +nim mStatic ast.html#mStatic TMagic.mStatic 461 +nim mParseExprToAst ast.html#mParseExprToAst TMagic.mParseExprToAst 461 +nim mParseStmtToAst ast.html#mParseStmtToAst TMagic.mParseStmtToAst 461 +nim mExpandToAst ast.html#mExpandToAst TMagic.mExpandToAst 461 +nim mQuoteAst ast.html#mQuoteAst TMagic.mQuoteAst 461 +nim mInc ast.html#mInc TMagic.mInc 461 +nim mDec ast.html#mDec TMagic.mDec 461 +nim mOrd ast.html#mOrd TMagic.mOrd 461 +nim mNew ast.html#mNew TMagic.mNew 461 +nim mNewFinalize ast.html#mNewFinalize TMagic.mNewFinalize 461 +nim mNewSeq ast.html#mNewSeq TMagic.mNewSeq 461 +nim mNewSeqOfCap ast.html#mNewSeqOfCap TMagic.mNewSeqOfCap 461 +nim mLengthOpenArray ast.html#mLengthOpenArray TMagic.mLengthOpenArray 461 +nim mLengthStr ast.html#mLengthStr TMagic.mLengthStr 461 +nim mLengthArray ast.html#mLengthArray TMagic.mLengthArray 461 +nim mLengthSeq ast.html#mLengthSeq TMagic.mLengthSeq 461 +nim mIncl ast.html#mIncl TMagic.mIncl 461 +nim mExcl ast.html#mExcl TMagic.mExcl 461 +nim mCard ast.html#mCard TMagic.mCard 461 +nim mChr ast.html#mChr TMagic.mChr 461 +nim mGCref ast.html#mGCref TMagic.mGCref 461 +nim mGCunref ast.html#mGCunref TMagic.mGCunref 461 +nim mAddI ast.html#mAddI TMagic.mAddI 461 +nim mSubI ast.html#mSubI TMagic.mSubI 461 +nim mMulI ast.html#mMulI TMagic.mMulI 461 +nim mDivI ast.html#mDivI TMagic.mDivI 461 +nim mModI ast.html#mModI TMagic.mModI 461 +nim mSucc ast.html#mSucc TMagic.mSucc 461 +nim mPred ast.html#mPred TMagic.mPred 461 +nim mAddF64 ast.html#mAddF64 TMagic.mAddF64 461 +nim mSubF64 ast.html#mSubF64 TMagic.mSubF64 461 +nim mMulF64 ast.html#mMulF64 TMagic.mMulF64 461 +nim mDivF64 ast.html#mDivF64 TMagic.mDivF64 461 +nim mShrI ast.html#mShrI TMagic.mShrI 461 +nim mShlI ast.html#mShlI TMagic.mShlI 461 +nim mAshrI ast.html#mAshrI TMagic.mAshrI 461 +nim mBitandI ast.html#mBitandI TMagic.mBitandI 461 +nim mBitorI ast.html#mBitorI TMagic.mBitorI 461 +nim mBitxorI ast.html#mBitxorI TMagic.mBitxorI 461 +nim mMinI ast.html#mMinI TMagic.mMinI 461 +nim mMaxI ast.html#mMaxI TMagic.mMaxI 461 +nim mAddU ast.html#mAddU TMagic.mAddU 461 +nim mSubU ast.html#mSubU TMagic.mSubU 461 +nim mMulU ast.html#mMulU TMagic.mMulU 461 +nim mDivU ast.html#mDivU TMagic.mDivU 461 +nim mModU ast.html#mModU TMagic.mModU 461 +nim mEqI ast.html#mEqI TMagic.mEqI 461 +nim mLeI ast.html#mLeI TMagic.mLeI 461 +nim mLtI ast.html#mLtI TMagic.mLtI 461 +nim mEqF64 ast.html#mEqF64 TMagic.mEqF64 461 +nim mLeF64 ast.html#mLeF64 TMagic.mLeF64 461 +nim mLtF64 ast.html#mLtF64 TMagic.mLtF64 461 +nim mLeU ast.html#mLeU TMagic.mLeU 461 +nim mLtU ast.html#mLtU TMagic.mLtU 461 +nim mEqEnum ast.html#mEqEnum TMagic.mEqEnum 461 +nim mLeEnum ast.html#mLeEnum TMagic.mLeEnum 461 +nim mLtEnum ast.html#mLtEnum TMagic.mLtEnum 461 +nim mEqCh ast.html#mEqCh TMagic.mEqCh 461 +nim mLeCh ast.html#mLeCh TMagic.mLeCh 461 +nim mLtCh ast.html#mLtCh TMagic.mLtCh 461 +nim mEqB ast.html#mEqB TMagic.mEqB 461 +nim mLeB ast.html#mLeB TMagic.mLeB 461 +nim mLtB ast.html#mLtB TMagic.mLtB 461 +nim mEqRef ast.html#mEqRef TMagic.mEqRef 461 +nim mLePtr ast.html#mLePtr TMagic.mLePtr 461 +nim mLtPtr ast.html#mLtPtr TMagic.mLtPtr 461 +nim mXor ast.html#mXor TMagic.mXor 461 +nim mEqCString ast.html#mEqCString TMagic.mEqCString 461 +nim mEqProc ast.html#mEqProc TMagic.mEqProc 461 +nim mUnaryMinusI ast.html#mUnaryMinusI TMagic.mUnaryMinusI 461 +nim mUnaryMinusI64 ast.html#mUnaryMinusI64 TMagic.mUnaryMinusI64 461 +nim mAbsI ast.html#mAbsI TMagic.mAbsI 461 +nim mNot ast.html#mNot TMagic.mNot 461 +nim mUnaryPlusI ast.html#mUnaryPlusI TMagic.mUnaryPlusI 461 +nim mBitnotI ast.html#mBitnotI TMagic.mBitnotI 461 +nim mUnaryPlusF64 ast.html#mUnaryPlusF64 TMagic.mUnaryPlusF64 461 +nim mUnaryMinusF64 ast.html#mUnaryMinusF64 TMagic.mUnaryMinusF64 461 +nim mCharToStr ast.html#mCharToStr TMagic.mCharToStr 461 +nim mBoolToStr ast.html#mBoolToStr TMagic.mBoolToStr 461 +nim mCStrToStr ast.html#mCStrToStr TMagic.mCStrToStr 461 +nim mStrToStr ast.html#mStrToStr TMagic.mStrToStr 461 +nim mEnumToStr ast.html#mEnumToStr TMagic.mEnumToStr 461 +nim mAnd ast.html#mAnd TMagic.mAnd 461 +nim mOr ast.html#mOr TMagic.mOr 461 +nim mImplies ast.html#mImplies TMagic.mImplies 461 +nim mIff ast.html#mIff TMagic.mIff 461 +nim mExists ast.html#mExists TMagic.mExists 461 +nim mForall ast.html#mForall TMagic.mForall 461 +nim mOld ast.html#mOld TMagic.mOld 461 +nim mEqStr ast.html#mEqStr TMagic.mEqStr 461 +nim mLeStr ast.html#mLeStr TMagic.mLeStr 461 +nim mLtStr ast.html#mLtStr TMagic.mLtStr 461 +nim mEqSet ast.html#mEqSet TMagic.mEqSet 461 +nim mLeSet ast.html#mLeSet TMagic.mLeSet 461 +nim mLtSet ast.html#mLtSet TMagic.mLtSet 461 +nim mMulSet ast.html#mMulSet TMagic.mMulSet 461 +nim mPlusSet ast.html#mPlusSet TMagic.mPlusSet 461 +nim mMinusSet ast.html#mMinusSet TMagic.mMinusSet 461 +nim mXorSet ast.html#mXorSet TMagic.mXorSet 461 +nim mConStrStr ast.html#mConStrStr TMagic.mConStrStr 461 +nim mSlice ast.html#mSlice TMagic.mSlice 461 +nim mDotDot ast.html#mDotDot TMagic.mDotDot 461 +nim mFields ast.html#mFields TMagic.mFields 461 +nim mFieldPairs ast.html#mFieldPairs TMagic.mFieldPairs 461 +nim mOmpParFor ast.html#mOmpParFor TMagic.mOmpParFor 461 +nim mAppendStrCh ast.html#mAppendStrCh TMagic.mAppendStrCh 461 +nim mAppendStrStr ast.html#mAppendStrStr TMagic.mAppendStrStr 461 +nim mAppendSeqElem ast.html#mAppendSeqElem TMagic.mAppendSeqElem 461 +nim mInSet ast.html#mInSet TMagic.mInSet 461 +nim mRepr ast.html#mRepr TMagic.mRepr 461 +nim mExit ast.html#mExit TMagic.mExit 461 +nim mSetLengthStr ast.html#mSetLengthStr TMagic.mSetLengthStr 461 +nim mSetLengthSeq ast.html#mSetLengthSeq TMagic.mSetLengthSeq 461 +nim mIsPartOf ast.html#mIsPartOf TMagic.mIsPartOf 461 +nim mAstToStr ast.html#mAstToStr TMagic.mAstToStr 461 +nim mParallel ast.html#mParallel TMagic.mParallel 461 +nim mSwap ast.html#mSwap TMagic.mSwap 461 +nim mIsNil ast.html#mIsNil TMagic.mIsNil 461 +nim mArrToSeq ast.html#mArrToSeq TMagic.mArrToSeq 461 +nim mOpenArrayToSeq ast.html#mOpenArrayToSeq TMagic.mOpenArrayToSeq 461 +nim mNewString ast.html#mNewString TMagic.mNewString 461 +nim mNewStringOfCap ast.html#mNewStringOfCap TMagic.mNewStringOfCap 461 +nim mParseBiggestFloat ast.html#mParseBiggestFloat TMagic.mParseBiggestFloat 461 +nim mMove ast.html#mMove TMagic.mMove 461 +nim mEnsureMove ast.html#mEnsureMove TMagic.mEnsureMove 461 +nim mWasMoved ast.html#mWasMoved TMagic.mWasMoved 461 +nim mDup ast.html#mDup TMagic.mDup 461 +nim mDestroy ast.html#mDestroy TMagic.mDestroy 461 +nim mTrace ast.html#mTrace TMagic.mTrace 461 +nim mDefault ast.html#mDefault TMagic.mDefault 461 +nim mUnown ast.html#mUnown TMagic.mUnown 461 +nim mFinished ast.html#mFinished TMagic.mFinished 461 +nim mIsolate ast.html#mIsolate TMagic.mIsolate 461 +nim mAccessEnv ast.html#mAccessEnv TMagic.mAccessEnv 461 +nim mAccessTypeField ast.html#mAccessTypeField TMagic.mAccessTypeField 461 +nim mArray ast.html#mArray TMagic.mArray 461 +nim mOpenArray ast.html#mOpenArray TMagic.mOpenArray 461 +nim mRange ast.html#mRange TMagic.mRange 461 +nim mSet ast.html#mSet TMagic.mSet 461 +nim mSeq ast.html#mSeq TMagic.mSeq 461 +nim mVarargs ast.html#mVarargs TMagic.mVarargs 461 +nim mRef ast.html#mRef TMagic.mRef 461 +nim mPtr ast.html#mPtr TMagic.mPtr 461 +nim mVar ast.html#mVar TMagic.mVar 461 +nim mDistinct ast.html#mDistinct TMagic.mDistinct 461 +nim mVoid ast.html#mVoid TMagic.mVoid 461 +nim mTuple ast.html#mTuple TMagic.mTuple 461 +nim mOrdinal ast.html#mOrdinal TMagic.mOrdinal 461 +nim mIterableType ast.html#mIterableType TMagic.mIterableType 461 +nim mInt ast.html#mInt TMagic.mInt 461 +nim mInt8 ast.html#mInt8 TMagic.mInt8 461 +nim mInt16 ast.html#mInt16 TMagic.mInt16 461 +nim mInt32 ast.html#mInt32 TMagic.mInt32 461 +nim mInt64 ast.html#mInt64 TMagic.mInt64 461 +nim mUInt ast.html#mUInt TMagic.mUInt 461 +nim mUInt8 ast.html#mUInt8 TMagic.mUInt8 461 +nim mUInt16 ast.html#mUInt16 TMagic.mUInt16 461 +nim mUInt32 ast.html#mUInt32 TMagic.mUInt32 461 +nim mUInt64 ast.html#mUInt64 TMagic.mUInt64 461 +nim mFloat ast.html#mFloat TMagic.mFloat 461 +nim mFloat32 ast.html#mFloat32 TMagic.mFloat32 461 +nim mFloat64 ast.html#mFloat64 TMagic.mFloat64 461 +nim mFloat128 ast.html#mFloat128 TMagic.mFloat128 461 +nim mBool ast.html#mBool TMagic.mBool 461 +nim mChar ast.html#mChar TMagic.mChar 461 +nim mString ast.html#mString TMagic.mString 461 +nim mCstring ast.html#mCstring TMagic.mCstring 461 +nim mPointer ast.html#mPointer TMagic.mPointer 461 +nim mNil ast.html#mNil TMagic.mNil 461 +nim mExpr ast.html#mExpr TMagic.mExpr 461 +nim mStmt ast.html#mStmt TMagic.mStmt 461 +nim mTypeDesc ast.html#mTypeDesc TMagic.mTypeDesc 461 +nim mVoidType ast.html#mVoidType TMagic.mVoidType 461 +nim mPNimrodNode ast.html#mPNimrodNode TMagic.mPNimrodNode 461 +nim mSpawn ast.html#mSpawn TMagic.mSpawn 461 +nim mDeepCopy ast.html#mDeepCopy TMagic.mDeepCopy 461 +nim mIsMainModule ast.html#mIsMainModule TMagic.mIsMainModule 461 +nim mCompileDate ast.html#mCompileDate TMagic.mCompileDate 461 +nim mCompileTime ast.html#mCompileTime TMagic.mCompileTime 461 +nim mProcCall ast.html#mProcCall TMagic.mProcCall 461 +nim mCpuEndian ast.html#mCpuEndian TMagic.mCpuEndian 461 +nim mHostOS ast.html#mHostOS TMagic.mHostOS 461 +nim mHostCPU ast.html#mHostCPU TMagic.mHostCPU 461 +nim mBuildOS ast.html#mBuildOS TMagic.mBuildOS 461 +nim mBuildCPU ast.html#mBuildCPU TMagic.mBuildCPU 461 +nim mAppType ast.html#mAppType TMagic.mAppType 461 +nim mCompileOption ast.html#mCompileOption TMagic.mCompileOption 461 +nim mCompileOptionArg ast.html#mCompileOptionArg TMagic.mCompileOptionArg 461 +nim mNLen ast.html#mNLen TMagic.mNLen 461 +nim mNChild ast.html#mNChild TMagic.mNChild 461 +nim mNSetChild ast.html#mNSetChild TMagic.mNSetChild 461 +nim mNAdd ast.html#mNAdd TMagic.mNAdd 461 +nim mNAddMultiple ast.html#mNAddMultiple TMagic.mNAddMultiple 461 +nim mNDel ast.html#mNDel TMagic.mNDel 461 +nim mNKind ast.html#mNKind TMagic.mNKind 461 +nim mNSymKind ast.html#mNSymKind TMagic.mNSymKind 461 +nim mNccValue ast.html#mNccValue TMagic.mNccValue 461 +nim mNccInc ast.html#mNccInc TMagic.mNccInc 461 +nim mNcsAdd ast.html#mNcsAdd TMagic.mNcsAdd 461 +nim mNcsIncl ast.html#mNcsIncl TMagic.mNcsIncl 461 +nim mNcsLen ast.html#mNcsLen TMagic.mNcsLen 461 +nim mNcsAt ast.html#mNcsAt TMagic.mNcsAt 461 +nim mNctPut ast.html#mNctPut TMagic.mNctPut 461 +nim mNctLen ast.html#mNctLen TMagic.mNctLen 461 +nim mNctGet ast.html#mNctGet TMagic.mNctGet 461 +nim mNctHasNext ast.html#mNctHasNext TMagic.mNctHasNext 461 +nim mNctNext ast.html#mNctNext TMagic.mNctNext 461 +nim mNIntVal ast.html#mNIntVal TMagic.mNIntVal 461 +nim mNFloatVal ast.html#mNFloatVal TMagic.mNFloatVal 461 +nim mNSymbol ast.html#mNSymbol TMagic.mNSymbol 461 +nim mNIdent ast.html#mNIdent TMagic.mNIdent 461 +nim mNGetType ast.html#mNGetType TMagic.mNGetType 461 +nim mNStrVal ast.html#mNStrVal TMagic.mNStrVal 461 +nim mNSetIntVal ast.html#mNSetIntVal TMagic.mNSetIntVal 461 +nim mNSetFloatVal ast.html#mNSetFloatVal TMagic.mNSetFloatVal 461 +nim mNSetSymbol ast.html#mNSetSymbol TMagic.mNSetSymbol 461 +nim mNSetIdent ast.html#mNSetIdent TMagic.mNSetIdent 461 +nim mNSetStrVal ast.html#mNSetStrVal TMagic.mNSetStrVal 461 +nim mNLineInfo ast.html#mNLineInfo TMagic.mNLineInfo 461 +nim mNNewNimNode ast.html#mNNewNimNode TMagic.mNNewNimNode 461 +nim mNCopyNimNode ast.html#mNCopyNimNode TMagic.mNCopyNimNode 461 +nim mNCopyNimTree ast.html#mNCopyNimTree TMagic.mNCopyNimTree 461 +nim mStrToIdent ast.html#mStrToIdent TMagic.mStrToIdent 461 +nim mNSigHash ast.html#mNSigHash TMagic.mNSigHash 461 +nim mNSizeOf ast.html#mNSizeOf TMagic.mNSizeOf 461 +nim mNBindSym ast.html#mNBindSym TMagic.mNBindSym 461 +nim mNCallSite ast.html#mNCallSite TMagic.mNCallSite 461 +nim mEqIdent ast.html#mEqIdent TMagic.mEqIdent 461 +nim mEqNimrodNode ast.html#mEqNimrodNode TMagic.mEqNimrodNode 461 +nim mSameNodeType ast.html#mSameNodeType TMagic.mSameNodeType 461 +nim mGetImpl ast.html#mGetImpl TMagic.mGetImpl 461 +nim mNGenSym ast.html#mNGenSym TMagic.mNGenSym 461 +nim mNHint ast.html#mNHint TMagic.mNHint 461 +nim mNWarning ast.html#mNWarning TMagic.mNWarning 461 +nim mNError ast.html#mNError TMagic.mNError 461 +nim mInstantiationInfo ast.html#mInstantiationInfo TMagic.mInstantiationInfo 461 +nim mGetTypeInfo ast.html#mGetTypeInfo TMagic.mGetTypeInfo 461 +nim mGetTypeInfoV2 ast.html#mGetTypeInfoV2 TMagic.mGetTypeInfoV2 461 +nim mNimvm ast.html#mNimvm TMagic.mNimvm 461 +nim mIntDefine ast.html#mIntDefine TMagic.mIntDefine 461 +nim mStrDefine ast.html#mStrDefine TMagic.mStrDefine 461 +nim mBoolDefine ast.html#mBoolDefine TMagic.mBoolDefine 461 +nim mGenericDefine ast.html#mGenericDefine TMagic.mGenericDefine 461 +nim mRunnableExamples ast.html#mRunnableExamples TMagic.mRunnableExamples 461 +nim mException ast.html#mException TMagic.mException 461 +nim mBuiltinType ast.html#mBuiltinType TMagic.mBuiltinType 461 +nim mSymOwner ast.html#mSymOwner TMagic.mSymOwner 461 +nim mUncheckedArray ast.html#mUncheckedArray TMagic.mUncheckedArray 461 +nim mGetImplTransf ast.html#mGetImplTransf TMagic.mGetImplTransf 461 +nim mSymIsInstantiationOf ast.html#mSymIsInstantiationOf TMagic.mSymIsInstantiationOf 461 +nim mNodeId ast.html#mNodeId TMagic.mNodeId 461 +nim mPrivateAccess ast.html#mPrivateAccess TMagic.mPrivateAccess 461 +nim mZeroDefault ast.html#mZeroDefault TMagic.mZeroDefault 461 +nim TMagic ast.html#TMagic enum TMagic 461 +nim ctfeWhitelist ast.html#ctfeWhitelist const ctfeWhitelist 540 +nim generatedMagics ast.html#generatedMagics const generatedMagics 568 +nim ItemId ast.html#ItemId object ItemId 572 +nim `$` ast.html#$,ItemId proc `$`(x: ItemId): string 576 +nim `==` ast.html#==,ItemId,ItemId proc `==`(a, b: ItemId): bool 579 +nim hash ast.html#hash,ItemId proc hash(x: ItemId): Hash 582 +nim PNode ast.html#PNode type PNode 589 +nim TNodeSeq ast.html#TNodeSeq type TNodeSeq 590 +nim PType ast.html#PType type PType 591 +nim PSym ast.html#PSym type PSym 592 +nim TNode ast.html#TNode object TNode 593 +nim TStrTable ast.html#TStrTable object TStrTable 615 +nim locNone ast.html#locNone TLocKind.locNone 620 +nim locTemp ast.html#locTemp TLocKind.locTemp 620 +nim locLocalVar ast.html#locLocalVar TLocKind.locLocalVar 620 +nim locGlobalVar ast.html#locGlobalVar TLocKind.locGlobalVar 620 +nim locParam ast.html#locParam TLocKind.locParam 620 +nim locField ast.html#locField TLocKind.locField 620 +nim locExpr ast.html#locExpr TLocKind.locExpr 620 +nim locProc ast.html#locProc TLocKind.locProc 620 +nim locData ast.html#locData TLocKind.locData 620 +nim locCall ast.html#locCall TLocKind.locCall 620 +nim locOther ast.html#locOther TLocKind.locOther 620 +nim TLocKind ast.html#TLocKind enum TLocKind 620 +nim lfIndirect ast.html#lfIndirect TLocFlag.lfIndirect 632 +nim lfNoDeepCopy ast.html#lfNoDeepCopy TLocFlag.lfNoDeepCopy 632 +nim lfNoDecl ast.html#lfNoDecl TLocFlag.lfNoDecl 632 +nim lfDynamicLib ast.html#lfDynamicLib TLocFlag.lfDynamicLib 632 +nim lfExportLib ast.html#lfExportLib TLocFlag.lfExportLib 632 +nim lfHeader ast.html#lfHeader TLocFlag.lfHeader 632 +nim lfImportCompilerProc ast.html#lfImportCompilerProc TLocFlag.lfImportCompilerProc 632 +nim lfSingleUse ast.html#lfSingleUse TLocFlag.lfSingleUse 632 +nim lfEnforceDeref ast.html#lfEnforceDeref TLocFlag.lfEnforceDeref 632 +nim lfPrepareForMutation ast.html#lfPrepareForMutation TLocFlag.lfPrepareForMutation 632 +nim TLocFlag ast.html#TLocFlag enum TLocFlag 632 +nim OnUnknown ast.html#OnUnknown TStorageLoc.OnUnknown 645 +nim OnStatic ast.html#OnStatic TStorageLoc.OnStatic 645 +nim OnStack ast.html#OnStack TStorageLoc.OnStack 645 +nim OnHeap ast.html#OnHeap TStorageLoc.OnHeap 645 +nim TStorageLoc ast.html#TStorageLoc enum TStorageLoc 645 +nim TLocFlags ast.html#TLocFlags type TLocFlags 651 +nim TLoc ast.html#TLoc object TLoc 652 +nim libHeader ast.html#libHeader TLibKind.libHeader 661 +nim libDynamic ast.html#libDynamic TLibKind.libDynamic 661 +nim TLibKind ast.html#TLibKind enum TLibKind 661 +nim TLib ast.html#TLib object TLib 664 +nim CompilesId ast.html#CompilesId type CompilesId 673 +nim TInstantiation ast.html#TInstantiation object TInstantiation 675 +nim PInstantiation ast.html#PInstantiation type PInstantiation 680 +nim TScope ast.html#TScope object TScope 682 +nim PScope ast.html#PScope type PScope 688 +nim PLib ast.html#PLib type PLib 690 +nim TSym ast.html#TSym object TSym 691 +nim TTypeSeq ast.html#TTypeSeq type TTypeSeq 750 +nim attachedWasMoved ast.html#attachedWasMoved TTypeAttachedOp.attachedWasMoved 752 +nim attachedDestructor ast.html#attachedDestructor TTypeAttachedOp.attachedDestructor 752 +nim attachedAsgn ast.html#attachedAsgn TTypeAttachedOp.attachedAsgn 752 +nim attachedDup ast.html#attachedDup TTypeAttachedOp.attachedDup 752 +nim attachedSink ast.html#attachedSink TTypeAttachedOp.attachedSink 752 +nim attachedTrace ast.html#attachedTrace TTypeAttachedOp.attachedTrace 752 +nim attachedDeepCopy ast.html#attachedDeepCopy TTypeAttachedOp.attachedDeepCopy 752 +nim TTypeAttachedOp ast.html#TTypeAttachedOp enum TTypeAttachedOp 752 +nim TType ast.html#TType object TType 761 +nim TPair ast.html#TPair object TPair 793 +nim TPairSeq ast.html#TPairSeq type TPairSeq 796 +nim TNodePair ast.html#TNodePair object TNodePair 798 +nim TNodePairSeq ast.html#TNodePairSeq type TNodePairSeq 803 +nim TNodeTable ast.html#TNodeTable object TNodeTable 804 +nim TObjectSeq ast.html#TObjectSeq type TObjectSeq 809 +nim TObjectSet ast.html#TObjectSet object TObjectSet 810 +nim impUnknown ast.html#impUnknown TImplication.impUnknown 814 +nim impNo ast.html#impNo TImplication.impNo 814 +nim impYes ast.html#impYes TImplication.impYes 814 +nim TImplication ast.html#TImplication enum TImplication 814 +nim typ ast.html#typ.t,PNode template typ(n: PNode): PType 819 +nim owner ast.html#owner proc owner(s: PSym | PType): PSym 822 +nim setOwner ast.html#setOwner,,PSym proc setOwner(s: PSym | PType; owner: PSym) 825 +nim setUseIc ast.html#setUseIc,bool proc setUseIc(useIc: bool) 836 +nim comment ast.html#comment,PNode proc comment(n: PNode): string 838 +nim comment= ast.html#comment=,PNode,string proc comment=(n: PNode; a: string) 845 +nim OverloadableSyms ast.html#OverloadableSyms const OverloadableSyms 865 +nim GenericTypes ast.html#GenericTypes const GenericTypes 868 +nim StructuralEquivTypes ast.html#StructuralEquivTypes const StructuralEquivTypes 871 +nim ConcreteTypes ast.html#ConcreteTypes const ConcreteTypes 875 +nim IntegralTypes ast.html#IntegralTypes const IntegralTypes 882 +nim ConstantDataTypes ast.html#ConstantDataTypes const ConstantDataTypes 884 +nim NilableTypes ast.html#NilableTypes const NilableTypes 886 +nim PtrLikeKinds ast.html#PtrLikeKinds const PtrLikeKinds 888 +nim PersistentNodeFlags ast.html#PersistentNodeFlags const PersistentNodeFlags 889 +nim namePos ast.html#namePos const namePos 896 +nim patternPos ast.html#patternPos const patternPos 897 +nim genericParamsPos ast.html#genericParamsPos const genericParamsPos 898 +nim paramsPos ast.html#paramsPos const paramsPos 899 +nim pragmasPos ast.html#pragmasPos const pragmasPos 900 +nim miscPos ast.html#miscPos const miscPos 901 +nim bodyPos ast.html#bodyPos const bodyPos 902 +nim resultPos ast.html#resultPos const resultPos 903 +nim dispatcherPos ast.html#dispatcherPos const dispatcherPos 904 +nim nfAllFieldsSet ast.html#nfAllFieldsSet const nfAllFieldsSet 906 +nim nkIdentKinds ast.html#nkIdentKinds const nkIdentKinds 908 +nim nkPragmaCallKinds ast.html#nkPragmaCallKinds const nkPragmaCallKinds 911 +nim nkLiterals ast.html#nkLiterals const nkLiterals 912 +nim nkFloatLiterals ast.html#nkFloatLiterals const nkFloatLiterals 913 +nim nkLambdaKinds ast.html#nkLambdaKinds const nkLambdaKinds 914 +nim declarativeDefs ast.html#declarativeDefs const declarativeDefs 915 +nim routineDefs ast.html#routineDefs const routineDefs 916 +nim procDefs ast.html#procDefs const procDefs 917 +nim callableDefs ast.html#callableDefs const callableDefs 918 +nim nkSymChoices ast.html#nkSymChoices const nkSymChoices 920 +nim nkStrKinds ast.html#nkStrKinds const nkStrKinds 921 +nim skLocalVars ast.html#skLocalVars const skLocalVars 923 +nim skProcKinds ast.html#skProcKinds const skProcKinds 924 +nim defaultOffset ast.html#defaultOffset const defaultOffset 929 +nim getPIdent ast.html#getPIdent,PNode proc getPIdent(a: PNode): PIdent 931 +nim id ast.html#id.t template id(a: PType | PSym): int 943 +nim IdGenerator ast.html#IdGenerator type IdGenerator 948 +nim PackageModuleId ast.html#PackageModuleId const PackageModuleId 956 +nim idGeneratorFromModule ast.html#idGeneratorFromModule,PSym proc idGeneratorFromModule(m: PSym): IdGenerator 958 +nim idGeneratorForPackage ast.html#idGeneratorForPackage,int32 proc idGeneratorForPackage(nextIdWillBe: int32): IdGenerator 962 +nim nextTypeId ast.html#nextTypeId,IdGenerator proc nextTypeId(x: IdGenerator): ItemId 970 +nim ggDebug ast.html#ggDebug var ggDebug 988 +nim isCallExpr ast.html#isCallExpr,PNode proc isCallExpr(n: PNode): bool 990 +nim discardSons ast.html#discardSons,PNode proc discardSons(father: PNode) 993 +nim len ast.html#len,PNode proc len(n: PNode): int 995 +nim safeLen ast.html#safeLen,PNode proc safeLen(n: PNode): int 998 +nim safeArrLen ast.html#safeArrLen,PNode proc safeArrLen(n: PNode): int 1003 +nim add ast.html#add,PNode,PNode proc add(father, son: PNode) 1009 +nim addAllowNil ast.html#addAllowNil,PNode,PNode proc addAllowNil(father, son: PNode) 1013 +nim `[]` ast.html#[].t,PNode,int template `[]`(n: PNode; i: int): PNode 1016 +nim `[]=` ast.html#[]=.t,PNode,int,PNode template `[]=`(n: PNode; i: int; x: PNode) 1017 +nim `[]` ast.html#[].t,PNode,BackwardsIndex template `[]`(n: PNode; i: BackwardsIndex): PNode 1019 +nim `[]=` ast.html#[]=.t,PNode,BackwardsIndex,PNode template `[]=`(n: PNode; i: BackwardsIndex; x: PNode) 1020 +nim add ast.html#add,PType,PType proc add(father, son: PType) 1022 +nim addAllowNil ast.html#addAllowNil,PType,PType proc addAllowNil(father, son: PType) 1026 +nim `[]` ast.html#[].t,PType,int template `[]`(n: PType; i: int): PType 1029 +nim `[]=` ast.html#[]=.t,PType,int,PType template `[]=`(n: PType; i: int; x: PType) 1030 +nim `[]` ast.html#[].t,PType,BackwardsIndex template `[]`(n: PType; i: BackwardsIndex): PType 1032 +nim `[]=` ast.html#[]=.t,PType,BackwardsIndex,PType template `[]=`(n: PType; i: BackwardsIndex; x: PType) 1033 +nim getDeclPragma ast.html#getDeclPragma,PNode proc getDeclPragma(n: PNode): PNode 1035 +nim extractPragma ast.html#extractPragma,PSym proc extractPragma(s: PSym): PNode 1069 +nim skipPragmaExpr ast.html#skipPragmaExpr,PNode proc skipPragmaExpr(n: PNode): PNode 1089 +nim setInfoRecursive ast.html#setInfoRecursive,PNode,TLineInfo proc setInfoRecursive(n: PNode; info: TLineInfo) 1097 +nim newNode ast.html#newNode,TNodeKind proc newNode(kind: TNodeKind): PNode 1125 +nim newNodeI ast.html#newNodeI,TNodeKind,TLineInfo proc newNodeI(kind: TNodeKind; info: TLineInfo): PNode 1130 +nim newNodeI ast.html#newNodeI,TNodeKind,TLineInfo,int proc newNodeI(kind: TNodeKind; info: TLineInfo; children: int): PNode 1135 +nim newNodeIT ast.html#newNodeIT,TNodeKind,TLineInfo,PType proc newNodeIT(kind: TNodeKind; info: TLineInfo; typ: PType): PNode 1142 +nim newNode ast.html#newNode,TNodeKind,TLineInfo proc newNode(kind: TNodeKind; info: TLineInfo): PNode 1148 +nim newAtom ast.html#newAtom,PIdent,TLineInfo proc newAtom(ident: PIdent; info: TLineInfo): PNode 1153 +nim newAtom ast.html#newAtom,TNodeKind,BiggestInt,TLineInfo proc newAtom(kind: TNodeKind; intVal: BiggestInt; info: TLineInfo): PNode 1157 +nim newAtom ast.html#newAtom,TNodeKind,BiggestFloat,TLineInfo proc newAtom(kind: TNodeKind; floatVal: BiggestFloat; info: TLineInfo): PNode 1161 +nim newAtom ast.html#newAtom,TNodeKind,sinkstring,TLineInfo proc newAtom(kind: TNodeKind; strVal: sink string; info: TLineInfo): PNode 1165 +nim newTree ast.html#newTree,TNodeKind,TLineInfo,varargs[PNode] proc newTree(kind: TNodeKind; info: TLineInfo; children: varargs[PNode]): PNode 1169 +nim newTree ast.html#newTree,TNodeKind,varargs[PNode] proc newTree(kind: TNodeKind; children: varargs[PNode]): PNode 1175 +nim newTreeI ast.html#newTreeI,TNodeKind,TLineInfo,varargs[PNode] proc newTreeI(kind: TNodeKind; info: TLineInfo; children: varargs[PNode]): PNode 1181 +nim newTreeIT ast.html#newTreeIT,TNodeKind,TLineInfo,PType,varargs[PNode] proc newTreeIT(kind: TNodeKind; info: TLineInfo; typ: PType; children: varargs[PNode]): PNode 1187 +nim previouslyInferred ast.html#previouslyInferred.t,PType template previouslyInferred(t: PType): PType 1193 +nim newSym ast.html#newSym,TSymKind,PIdent,IdGenerator,PSym,TLineInfo,TOptions proc newSym(symKind: TSymKind; name: PIdent; idgen: IdGenerator; owner: PSym;\n info: TLineInfo; options: TOptions = {}): PSym 1205 +nim astdef ast.html#astdef,PSym proc astdef(s: PSym): PNode 1220 +nim isMetaType ast.html#isMetaType,PType proc isMetaType(t: PType): bool 1227 +nim isUnresolvedStatic ast.html#isUnresolvedStatic,PType proc isUnresolvedStatic(t: PType): bool 1232 +nim linkTo ast.html#linkTo,PType,PSym proc linkTo(t: PType; s: PSym): PType 1235 +nim linkTo ast.html#linkTo,PSym,PType proc linkTo(s: PSym; t: PType): PSym 1240 +nim fileIdx ast.html#fileIdx.t,PSym template fileIdx(c: PSym): FileIndex 1245 +nim filename ast.html#filename.t,PSym template filename(c: PSym): string 1249 +nim appendToModule ast.html#appendToModule,PSym,PNode proc appendToModule(m: PSym; n: PNode) 1253 +nim GrowthFactor ast.html#GrowthFactor const GrowthFactor 1264 +nim StartSize ast.html#StartSize const StartSize 1265 +nim copyStrTable ast.html#copyStrTable,TStrTable,TStrTable proc copyStrTable(dest: var TStrTable; src: TStrTable) 1267 +nim copyObjectSet ast.html#copyObjectSet,TObjectSet,TObjectSet proc copyObjectSet(dest: var TObjectSet; src: TObjectSet) 1272 +nim withInfo ast.html#withInfo,PNode,TLineInfo proc withInfo(n: PNode; info: TLineInfo): PNode 1280 +nim newIdentNode ast.html#newIdentNode,PIdent,TLineInfo proc newIdentNode(ident: PIdent; info: TLineInfo): PNode 1284 +nim newSymNode ast.html#newSymNode,PSym proc newSymNode(sym: PSym): PNode 1289 +nim newSymNode ast.html#newSymNode,PSym,TLineInfo proc newSymNode(sym: PSym; info: TLineInfo): PNode 1295 +nim newOpenSym ast.html#newOpenSym,PNode proc newOpenSym(n: PNode): PNode 1301 +nim newIntNode ast.html#newIntNode,TNodeKind,BiggestInt proc newIntNode(kind: TNodeKind; intVal: BiggestInt): PNode 1304 +nim newIntNode ast.html#newIntNode,TNodeKind,Int128 proc newIntNode(kind: TNodeKind; intVal: Int128): PNode 1308 +nim lastSon ast.html#lastSon,PNode proc lastSon(n: PNode): PNode 1312 +nim setLastSon ast.html#setLastSon.t,PNode,PNode template setLastSon(n: PNode; s: PNode) 1313 +nim firstSon ast.html#firstSon.t,PNode template firstSon(n: PNode): PNode 1315 +nim secondSon ast.html#secondSon.t,PNode template secondSon(n: PNode): PNode 1316 +nim hasSon ast.html#hasSon.t,PNode template hasSon(n: PNode): bool 1318 +nim has2Sons ast.html#has2Sons.t,PNode template has2Sons(n: PNode): bool 1319 +nim replaceFirstSon ast.html#replaceFirstSon,PNode,PNode proc replaceFirstSon(n, newson: PNode) 1321 +nim replaceSon ast.html#replaceSon,PNode,int,PNode proc replaceSon(n: PNode; i: int; newson: PNode) 1324 +nim last ast.html#last,PType proc last(n: PType): PType 1327 +nim elementType ast.html#elementType,PType proc elementType(n: PType): PType 1329 +nim skipModifier ast.html#skipModifier,PType proc skipModifier(n: PType): PType 1330 +nim indexType ast.html#indexType,PType proc indexType(n: PType): PType 1332 +nim baseClass ast.html#baseClass,PType proc baseClass(n: PType): PType 1333 +nim base ast.html#base,PType proc base(t: PType): PType 1335 +nim returnType ast.html#returnType,PType proc returnType(n: PType): PType 1338 +nim setReturnType ast.html#setReturnType,PType,PType proc setReturnType(n, r: PType) 1339 +nim setIndexType ast.html#setIndexType,PType,PType proc setIndexType(n, idx: PType) 1340 +nim firstParamType ast.html#firstParamType,PType proc firstParamType(n: PType): PType 1342 +nim firstGenericParam ast.html#firstGenericParam,PType proc firstGenericParam(n: PType): PType 1343 +nim typeBodyImpl ast.html#typeBodyImpl,PType proc typeBodyImpl(n: PType): PType 1345 +nim genericHead ast.html#genericHead,PType proc genericHead(n: PType): PType 1347 +nim skipTypes ast.html#skipTypes,PType,TTypeKinds proc skipTypes(t: PType; kinds: TTypeKinds): PType 1349 +nim newIntTypeNode ast.html#newIntTypeNode,BiggestInt,PType proc newIntTypeNode(intVal: BiggestInt; typ: PType): PNode 1357 +nim newIntTypeNode ast.html#newIntTypeNode,Int128,PType proc newIntTypeNode(intVal: Int128; typ: PType): PNode 1380 +nim newFloatNode ast.html#newFloatNode,TNodeKind,BiggestFloat proc newFloatNode(kind: TNodeKind; floatVal: BiggestFloat): PNode 1384 +nim newStrNode ast.html#newStrNode,TNodeKind,string proc newStrNode(kind: TNodeKind; strVal: string): PNode 1388 +nim newStrNode ast.html#newStrNode,string,TLineInfo proc newStrNode(strVal: string; info: TLineInfo): PNode 1392 +nim newProcNode ast.html#newProcNode,TNodeKind,TLineInfo,PNode,PNode,PNode,PNode,PNode,PNode,PNode proc newProcNode(kind: TNodeKind; info: TLineInfo; body: PNode;\n params, name, pattern, genericParams, pragmas, exceptions: PNode): PNode 1396 +nim AttachedOpToStr ast.html#AttachedOpToStr const AttachedOpToStr 1405 +nim `$` ast.html#$,PSym proc `$`(s: PSym): string 1408 +nim len ast.html#len,PType proc len(n: PType): int 1422 +nim sameTupleLengths ast.html#sameTupleLengths,PType,PType proc sameTupleLengths(a, b: PType): bool 1425 +nim tupleTypePairs ast.html#tupleTypePairs.i,PType,PType iterator tupleTypePairs(a, b: PType): (int, PType, PType) 1428 +nim underspecifiedPairs ast.html#underspecifiedPairs.i,PType,PType,int,int iterator underspecifiedPairs(a, b: PType; start = 0; without = 0): (PType, PType) 1432 +nim signatureLen ast.html#signatureLen,PType proc signatureLen(t: PType): int 1437 +nim paramsLen ast.html#paramsLen,PType proc paramsLen(t: PType): int 1440 +nim genericParamsLen ast.html#genericParamsLen,PType proc genericParamsLen(t: PType): int 1443 +nim genericInvocationParamsLen ast.html#genericInvocationParamsLen,PType proc genericInvocationParamsLen(t: PType): int 1447 +nim kidsLen ast.html#kidsLen,PType proc kidsLen(t: PType): int 1451 +nim genericParamHasConstraints ast.html#genericParamHasConstraints,PType proc genericParamHasConstraints(t: PType): bool 1454 +nim hasElementType ast.html#hasElementType,PType proc hasElementType(t: PType): bool 1456 +nim isEmptyTupleType ast.html#isEmptyTupleType,PType proc isEmptyTupleType(t: PType): bool 1457 +nim isSingletonTupleType ast.html#isSingletonTupleType,PType proc isSingletonTupleType(t: PType): bool 1458 +nim genericConstraint ast.html#genericConstraint,PType proc genericConstraint(t: PType): PType 1460 +nim genericInstParams ast.html#genericInstParams.i,PType iterator genericInstParams(t: PType): (bool, PType) 1462 +nim genericInstParamPairs ast.html#genericInstParamPairs.i,PType,PType iterator genericInstParamPairs(a, b: PType): (int, PType, PType) 1466 +nim genericInvocationParams ast.html#genericInvocationParams.i,PType iterator genericInvocationParams(t: PType): (bool, PType) 1470 +nim genericInvocationAndBodyElements ast.html#genericInvocationAndBodyElements.i,PType,PType iterator genericInvocationAndBodyElements(a, b: PType): (PType, PType) 1474 +nim genericInvocationParamPairs ast.html#genericInvocationParamPairs.i,PType,PType iterator genericInvocationParamPairs(a, b: PType): (bool, PType, PType) 1478 +nim genericBodyParams ast.html#genericBodyParams.i,PType iterator genericBodyParams(t: PType): (int, PType) 1485 +nim userTypeClassInstParams ast.html#userTypeClassInstParams.i,PType iterator userTypeClassInstParams(t: PType): (bool, PType) 1489 +nim ikids ast.html#ikids.i,PType iterator ikids(t: PType): (int, PType) 1493 +nim FirstParamAt ast.html#FirstParamAt const FirstParamAt 1497 +nim FirstGenericParamAt ast.html#FirstGenericParamAt const FirstGenericParamAt 1498 +nim paramTypes ast.html#paramTypes.i,PType iterator paramTypes(t: PType): (int, PType) 1500 +nim paramTypePairs ast.html#paramTypePairs.i,PType,PType iterator paramTypePairs(a, b: PType): (PType, PType) 1503 +nim paramTypeToNodeIndex ast.html#paramTypeToNodeIndex.t,int template paramTypeToNodeIndex(x: int): int 1506 +nim kids ast.html#kids.i,PType iterator kids(t: PType): PType 1508 +nim signature ast.html#signature.i,PType iterator signature(t: PType): PType 1511 +nim newType ast.html#newType,TTypeKind,IdGenerator,PSym,sinkPType proc newType(kind: TTypeKind; idgen: IdGenerator; owner: PSym; son: sink PType = nil): PType 1515 +nim setSons ast.html#setSons,PType,sinkseq[PType] proc setSons(dest: PType; sons: sink seq[PType]) 1526 +nim setSon ast.html#setSon,PType,sinkPType proc setSon(dest: PType; son: sink PType) 1527 +nim setSonsLen ast.html#setSonsLen,PType,int proc setSonsLen(dest: PType; len: int) 1528 +nim newSons ast.html#newSons,PNode,int proc newSons(father: PNode; length: int) 1537 +nim newSons ast.html#newSons,PType,int proc newSons(father: PType; length: int) 1540 +nim truncateInferredTypeCandidates ast.html#truncateInferredTypeCandidates,PType proc truncateInferredTypeCandidates(t: PType) 1543 +nim assignType ast.html#assignType,PType,PType proc assignType(dest, src: PType) 1548 +nim copyType ast.html#copyType,PType,IdGenerator,PSym proc copyType(t: PType; idgen: IdGenerator; owner: PSym): PType 1566 +nim exactReplica ast.html#exactReplica,PType proc exactReplica(t: PType): PType 1571 +nim copySym ast.html#copySym,PSym,IdGenerator proc copySym(s: PSym; idgen: IdGenerator): PSym 1578 +nim createModuleAlias ast.html#createModuleAlias,PSym,IdGenerator,PIdent,TLineInfo,TOptions proc createModuleAlias(s: PSym; idgen: IdGenerator; newIdent: PIdent;\n info: TLineInfo; options: TOptions): PSym 1594 +nim initStrTable ast.html#initStrTable proc initStrTable(): TStrTable 1606 +nim initObjectSet ast.html#initObjectSet proc initObjectSet(): TObjectSet 1610 +nim initNodeTable ast.html#initNodeTable proc initNodeTable(): TNodeTable 1614 +nim skipTypes ast.html#skipTypes,PType,TTypeKinds,int proc skipTypes(t: PType; kinds: TTypeKinds; maxIters: int): PType 1618 +nim skipTypesOrNil ast.html#skipTypesOrNil,PType,TTypeKinds proc skipTypesOrNil(t: PType; kinds: TTypeKinds): PType 1626 +nim isGCedMem ast.html#isGCedMem,PType proc isGCedMem(t: PType): bool 1633 +nim propagateToOwner ast.html#propagateToOwner,PType,PType proc propagateToOwner(owner, elem: PType; propagateHasAsgn = true) 1637 +nim rawAddSon ast.html#rawAddSon,PType,PType proc rawAddSon(father, son: PType; propagateHasAsgn = true) 1662 +nim addSonNilAllowed ast.html#addSonNilAllowed,PNode,PNode proc addSonNilAllowed(father, son: PNode) 1666 +nim delSon ast.html#delSon,PNode,int proc delSon(father: PNode; idx: int) 1669 +nim copyNode ast.html#copyNode,PNode proc copyNode(src: PNode): PNode 1674 +nim transitionSonsKind ast.html#transitionSonsKind,PNode,range[] proc transitionSonsKind(n: PNode; kind: range[nkComesFrom .. nkTupleConstr]) 1703 +nim transitionIntKind ast.html#transitionIntKind,PNode,range[] proc transitionIntKind(n: PNode; kind: range[nkCharLit .. nkUInt64Lit]) 1707 +nim transitionIntToFloatKind ast.html#transitionIntToFloatKind,PNode,range[] proc transitionIntToFloatKind(n: PNode; kind: range[nkFloatLit .. nkFloat128Lit]) 1711 +nim transitionNoneToSym ast.html#transitionNoneToSym,PNode proc transitionNoneToSym(n: PNode) 1715 +nim transitionSymKindCommon ast.html#transitionSymKindCommon.t,TSymKind template transitionSymKindCommon(k: TSymKind) 1718 +nim transitionGenericParamToType ast.html#transitionGenericParamToType,PSym proc transitionGenericParamToType(s: PSym) 1729 +nim transitionRoutineSymKind ast.html#transitionRoutineSymKind,PSym,range[] proc transitionRoutineSymKind(s: PSym; kind: range[skProc .. skTemplate]) 1732 +nim transitionToLet ast.html#transitionToLet,PSym proc transitionToLet(s: PSym) 1737 +nim shallowCopy ast.html#shallowCopy,PNode proc shallowCopy(src: PNode): PNode 1763 +nim copyTree ast.html#copyTree,PNode proc copyTree(src: PNode): PNode 1768 +nim copyTreeWithoutNode ast.html#copyTreeWithoutNode,PNode,PNode proc copyTreeWithoutNode(src, skippedNode: PNode): PNode 1775 +nim hasSonWith ast.html#hasSonWith,PNode,TNodeKind proc hasSonWith(n: PNode; kind: TNodeKind): bool 1782 +nim hasNilSon ast.html#hasNilSon,PNode proc hasNilSon(n: PNode): bool 1788 +nim containsNode ast.html#containsNode,PNode,TNodeKinds proc containsNode(n: PNode; kinds: TNodeKinds): bool 1796 +nim hasSubnodeWith ast.html#hasSubnodeWith,PNode,TNodeKind proc hasSubnodeWith(n: PNode; kind: TNodeKind): bool 1805 +nim getInt ast.html#getInt,PNode proc getInt(a: PNode): Int128 1814 +nim getInt64 ast.html#getInt64,PNode proc getInt64(a: PNode): int64 1827 +nim getFloat ast.html#getFloat,PNode proc getFloat(a: PNode): BiggestFloat 1834 +nim getStr ast.html#getStr,PNode proc getStr(a: PNode): string 1845 +nim getStrOrChar ast.html#getStrOrChar,PNode proc getStrOrChar(a: PNode): string 1857 +nim isGenericParams ast.html#isGenericParams,PNode proc isGenericParams(n: PNode): bool 1867 +nim isGenericRoutine ast.html#isGenericRoutine,PNode proc isGenericRoutine(n: PNode): bool 1871 +nim isGenericRoutineStrict ast.html#isGenericRoutineStrict,PSym proc isGenericRoutineStrict(s: PSym): bool 1874 +nim isGenericRoutine ast.html#isGenericRoutine,PSym proc isGenericRoutine(s: PSym): bool 1880 +nim skipGenericOwner ast.html#skipGenericOwner,PSym proc skipGenericOwner(s: PSym): PSym 1894 +nim originatingModule ast.html#originatingModule,PSym proc originatingModule(s: PSym): PSym 1905 +nim isRoutine ast.html#isRoutine,PSym proc isRoutine(s: PSym): bool 1909 +nim isCompileTimeProc ast.html#isCompileTimeProc,PSym proc isCompileTimeProc(s: PSym): bool 1912 +nim hasPattern ast.html#hasPattern,PSym proc hasPattern(s: PSym): bool 1916 +nim items ast.html#items.i,PNode iterator items(n: PNode): PNode 1919 +nim pairs ast.html#pairs.i,PNode iterator pairs(n: PNode): tuple[i: int, n: PNode] 1922 +nim isAtom ast.html#isAtom,PNode proc isAtom(n: PNode): bool 1925 +nim isEmptyType ast.html#isEmptyType,PType proc isEmptyType(t: PType): bool 1928 +nim makeStmtList ast.html#makeStmtList,PNode proc makeStmtList(n: PNode): PNode 1932 +nim skipStmtList ast.html#skipStmtList,PNode proc skipStmtList(n: PNode): PNode 1939 +nim toVar ast.html#toVar,PType,TTypeKind,IdGenerator proc toVar(typ: PType; kind: TTypeKind; idgen: IdGenerator): PType 1947 +nim toRef ast.html#toRef,PType,IdGenerator proc toRef(typ: PType; idgen: IdGenerator): PType 1954 +nim toObject ast.html#toObject,PType proc toObject(typ: PType): PType 1961 +nim toObjectFromRefPtrGeneric ast.html#toObjectFromRefPtrGeneric,PType proc toObjectFromRefPtrGeneric(typ: PType): PType 1969 +nim isImportedException ast.html#isImportedException,PType,ConfigRef proc isImportedException(t: PType; conf: ConfigRef): bool 1989 +nim isInfixAs ast.html#isInfixAs,PNode proc isInfixAs(n: PNode): bool 1998 +nim skipColon ast.html#skipColon,PNode proc skipColon(n: PNode): PNode 2001 +nim findUnresolvedStatic ast.html#findUnresolvedStatic,PNode proc findUnresolvedStatic(n: PNode): PNode 2006 +nim hasDestructor ast.html#hasDestructor.t,PType template hasDestructor(t: PType): bool 2027 +nim incompleteType ast.html#incompleteType.t,PType template incompleteType(t: PType): bool 2029 +nim typeCompleted ast.html#typeCompleted.t,PSym template typeCompleted(s: PSym) 2032 +nim detailedInfo ast.html#detailedInfo.t,PSym template detailedInfo(sym: PSym): string 2035 +nim isInlineIterator ast.html#isInlineIterator,PType proc isInlineIterator(typ: PType): bool 2038 +nim isIterator ast.html#isIterator,PType proc isIterator(typ: PType): bool 2041 +nim isClosureIterator ast.html#isClosureIterator,PType proc isClosureIterator(typ: PType): bool 2044 +nim isClosure ast.html#isClosure,PType proc isClosure(typ: PType): bool 2047 +nim isNimcall ast.html#isNimcall,PSym proc isNimcall(s: PSym): bool 2050 +nim isExplicitCallConv ast.html#isExplicitCallConv,PSym proc isExplicitCallConv(s: PSym): bool 2053 +nim isSinkParam ast.html#isSinkParam,PSym proc isSinkParam(s: PSym): bool 2056 +nim isSinkType ast.html#isSinkType,PType proc isSinkType(t: PType): bool 2059 +nim newProcType ast.html#newProcType,TLineInfo,IdGenerator,PSym proc newProcType(info: TLineInfo; idgen: IdGenerator; owner: PSym): PType 2062 +nim addParam ast.html#addParam,PType,PSym proc addParam(procType: PType; param: PSym) 2071 +nim canRaiseConservative ast.html#canRaiseConservative,PNode proc canRaiseConservative(fn: PNode): bool 2079 +nim canRaise ast.html#canRaise,PNode proc canRaise(fn: PNode): bool 2085 +nim toHumanStr ast.html#toHumanStr,TSymKind proc toHumanStr(kind: TSymKind): string 2106 +nim toHumanStr ast.html#toHumanStr,TTypeKind proc toHumanStr(kind: TTypeKind): string 2110 +nim skipHiddenAddr ast.html#skipHiddenAddr,PNode proc skipHiddenAddr(n: PNode): PNode 2114 +nim isNewStyleConcept ast.html#isNewStyleConcept,PNode proc isNewStyleConcept(n: PNode): bool 2117 +nim isOutParam ast.html#isOutParam,PType proc isOutParam(t: PType): bool 2121 +nim nodesToIgnoreSet ast.html#nodesToIgnoreSet const nodesToIgnoreSet 2124 +nim isTrue ast.html#isTrue,PNode proc isTrue(n: PNode): bool 2131 +nim TypeMapping ast.html#TypeMapping type TypeMapping 2136 +nim SymMapping ast.html#SymMapping type SymMapping 2137 +nim idTableGet ast.html#idTableGet.t,typed, template idTableGet(tab: typed; key: PSym | PType): untyped 2139 +nim idTablePut ast.html#idTablePut.t,typed,, template idTablePut(tab: typed; key, val: PSym | PType) 2140 +nim initSymMapping ast.html#initSymMapping.t template initSymMapping(): Table[ItemId, PSym] 2142 +nim initTypeMapping ast.html#initTypeMapping.t template initTypeMapping(): Table[ItemId, PType] 2143 +nim resetIdTable ast.html#resetIdTable.t,Table[ItemId,PSym] template resetIdTable(tab: Table[ItemId, PSym]) 2145 +nim resetIdTable ast.html#resetIdTable.t,Table[ItemId,PType] template resetIdTable(tab: Table[ItemId, PType]) 2146 +nimgrp newnodei ast.html#newNodeI-procs-all proc 1130 +nimgrp newstrnode ast.html#newStrNode-procs-all proc 1388 +nimgrp addallownil ast.html#addAllowNil-procs-all proc 1013 +nimgrp isgenericroutine ast.html#isGenericRoutine-procs-all proc 1871 +nimgrp newnode ast.html#newNode-procs-all proc 1125 +nimgrp newsons ast.html#newSons-procs-all proc 1537 +nimgrp newsymnode ast.html#newSymNode-procs-all proc 1289 +nimgrp newintnode ast.html#newIntNode-procs-all proc 1304 +nimgrp newinttypenode ast.html#newIntTypeNode-procs-all proc 1357 +nimgrp skiptypes ast.html#skipTypes-procs-all proc 1349 +nimgrp len ast.html#len-procs-all proc 995 +nimgrp newtree ast.html#newTree-procs-all proc 1169 +nimgrp add ast.html#add-procs-all proc 1009 +nimgrp tohumanstr ast.html#toHumanStr-procs-all proc 2106 +nimgrp linkto ast.html#linkTo-procs-all proc 1235 +nimgrp $ ast.html#$-procs-all proc 576 +nimgrp newatom ast.html#newAtom-procs-all proc 1153 +nimgrp []= ast.html#[]=-templates-all template 1017 +nimgrp [] ast.html#[]-templates-all template 1016 +nimgrp resetidtable ast.html#resetIdTable-templates-all template 2145 diff --git a/compiler/astalgo.html b/compiler/astalgo.html new file mode 100644 index 0000000000000..b68219c74ee36 --- /dev/null +++ b/compiler/astalgo.html @@ -0,0 +1,929 @@ + + + + + + + +astalgo + + + + + + + + + + + + + + + + +
+
+

astalgo

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
TIdentIter = object
+  h*: Hash
+  name*: PIdent
+
+ + + Source   +Edit   + +
+
+
+
TIIPair {.final.} = object
+  key*, val*: int
+
+ + + Source   +Edit   + +
+
+
+
TIIPairSeq = seq[TIIPair]
+
+ + + Source   +Edit   + +
+
+
+
TIITable {.final.} = object
+  counter*: int
+  data*: TIIPairSeq
+
+ + + Source   +Edit   + +
+
+
+
TTabIter = object
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
InvalidKey = -9223372036854775808
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc debug(n: PNode; conf: ConfigRef = nil) {.exportc: "debugNode", ...deprecated,
+    raises: [KeyError, ValueError, Exception], tags: [RootEffect], forbids: [].}
+
+
+ Deprecated +
+ + + Source   +Edit   + +
+
+
+
proc debug(n: PSym; conf: ConfigRef = nil) {.exportc: "debugSym", ...deprecated,
+    raises: [Exception], tags: [RootEffect], forbids: [].}
+
+
+ Deprecated +
+ + + Source   +Edit   + +
+
+
+
proc debug(n: PType; conf: ConfigRef = nil) {.exportc: "debugType", ...deprecated,
+    raises: [Exception], tags: [RootEffect], forbids: [].}
+
+
+ Deprecated +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc firstIdentExcluding(ti: var TIdentIter; tab: TStrTable; s: PIdent;
+                         excluding: IntSet): PSym {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fromSystem(op: PSym): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getModule(s: PSym): PSym {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getNamedParamFromList(list: PNode; ident: PIdent): PSym {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Named parameters are special because a named parameter can be gensym'ed and then they have '`<number>' suffix that we need to ignore, see compiler / evaltempl.nim, snippet:

+

result.add newIdentNode(getIdent(c.ic, x.name.s & "\`gensym" & $x.id),
+         if c.instLines: actual.info else: templ.info)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getSymFromList(list: PNode; ident: PIdent; start: int = 0): PSym {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hashNode(p: RootRef): Hash {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc iiTableGet(t: TIITable; key: int): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc iiTablePut(t: var TIITable; key, val: int) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initIdentIter(ti: var TIdentIter; tab: TStrTable; s: PIdent): PSym {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initIITable(x: var TIITable) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initTabIter(ti: var TTabIter; tab: TStrTable): PSym {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isDiscriminantField(n: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc leValue(a, b: PNode): bool {....raises: [ERecoverableError], tags: [],
+                                  forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc listSymbolNames(symbols: openArray[PSym]): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lookupInRecord(n: PNode; field: PIdent): PSym {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mustRehash(length, counter: int): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nextIdentExcluding(ti: var TIdentIter; tab: TStrTable; excluding: IntSet): PSym {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nextIdentIter(ti: var TIdentIter; tab: TStrTable): PSym {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nextIter(ti: var TTabIter; tab: TStrTable): PSym {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nextTry(h, maxHash: Hash): Hash {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc objectSetContains(t: TObjectSet; obj: RootRef): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc objectSetContainsOrIncl(t: var TObjectSet; obj: RootRef): bool {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc objectSetIncl(t: var TObjectSet; obj: RootRef) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sameValue(a, b: PNode): bool {....raises: [ERecoverableError], tags: [],
+                                    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipConvCastAndClosure(n: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc strTableAdd(t: var TStrTable; n: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc strTableContains(t: TStrTable; n: PSym): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc strTableGet(t: TStrTable; name: PIdent): PSym {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc strTableIncl(t: var TStrTable; n: PSym; onConflictKeepOld = false): bool {.
+    discardable, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc strTableInclReportConflict(t: var TStrTable; n: PSym;
+                                onConflictKeepOld = false): PSym {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc symTabReplace(t: var TStrTable; prevSym: PSym; newSym: PSym) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc weakLeValue(a, b: PNode): TImplication {....raises: [ERecoverableError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator items(tab: TStrTable): PSym {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template debug(x: auto) {....deprecated.}
+
+
+ Deprecated +
+ + + Source   +Edit   + +
+
+
+
template debug(x: PSym | PType | PNode) {....deprecated.}
+
+
+ Deprecated +
+ + + Source   +Edit   + +
+
+ +
+
+
+
template mdbg(): bool {....deprecated.}
+
+
+ Deprecated +
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/astalgo.idx b/compiler/astalgo.idx new file mode 100644 index 0000000000000..ddd29a0eae0c2 --- /dev/null +++ b/compiler/astalgo.idx @@ -0,0 +1,48 @@ +nimTitle astalgo astalgo.html module astalgo 0 +nim hashNode astalgo.html#hashNode,RootRef proc hashNode(p: RootRef): Hash 26 +nim debug astalgo.html#debug,PSym,ConfigRef proc debug(n: PSym; conf: ConfigRef = nil) 30 +nim debug astalgo.html#debug,PType,ConfigRef proc debug(n: PType; conf: ConfigRef = nil) 31 +nim debug astalgo.html#debug,PNode,ConfigRef proc debug(n: PNode; conf: ConfigRef = nil) 32 +nim debug astalgo.html#debug.t template debug(x: PSym | PType | PNode) 34 +nim debug astalgo.html#debug.t,auto template debug(x: auto) 42 +nim mdbg astalgo.html#mdbg.t template mdbg(): bool 45 +nim lookupInRecord astalgo.html#lookupInRecord,PNode,PIdent proc lookupInRecord(n: PNode; field: PIdent): PSym 70 +nim mustRehash astalgo.html#mustRehash,int,int proc mustRehash(length, counter: int): bool 71 +nim nextTry astalgo.html#nextTry,Hash,Hash proc nextTry(h, maxHash: Hash): Hash 72 +nim InvalidKey astalgo.html#InvalidKey const InvalidKey 76 +nim TIIPair astalgo.html#TIIPair object TIIPair 79 +nim TIIPairSeq astalgo.html#TIIPairSeq type TIIPairSeq 82 +nim TIITable astalgo.html#TIITable object TIITable 83 +nim initIITable astalgo.html#initIITable,TIITable proc initIITable(x: var TIITable) 88 +nim iiTableGet astalgo.html#iiTableGet,TIITable,int proc iiTableGet(t: TIITable; key: int): int 89 +nim iiTablePut astalgo.html#iiTablePut,TIITable,int,int proc iiTablePut(t: var TIITable; key, val: int) 90 +nim skipConvCastAndClosure astalgo.html#skipConvCastAndClosure,PNode proc skipConvCastAndClosure(n: PNode): PNode 94 +nim sameValue astalgo.html#sameValue,PNode,PNode proc sameValue(a, b: PNode): bool 105 +nim leValue astalgo.html#leValue,PNode,PNode proc leValue(a, b: PNode): bool 119 +nim weakLeValue astalgo.html#weakLeValue,PNode,PNode proc weakLeValue(a, b: PNode): TImplication 134 +nim getModule astalgo.html#getModule,PSym proc getModule(s: PSym): PSym 161 +nim fromSystem astalgo.html#fromSystem,PSym proc fromSystem(op: PSym): bool 166 +nim getSymFromList astalgo.html#getSymFromList,PNode,PIdent,int proc getSymFromList(list: PNode; ident: PIdent; start: int = 0): PSym 167 +nim getNamedParamFromList astalgo.html#getNamedParamFromList,PNode,PIdent proc getNamedParamFromList(list: PNode; ident: PIdent): PSym 202 +nim objectSetContains astalgo.html#objectSetContains,TObjectSet,RootRef proc objectSetContains(t: TObjectSet; obj: RootRef): bool 493 +nim objectSetIncl astalgo.html#objectSetIncl,TObjectSet,RootRef proc objectSetIncl(t: var TObjectSet; obj: RootRef) 517 +nim objectSetContainsOrIncl astalgo.html#objectSetContainsOrIncl,TObjectSet,RootRef proc objectSetContainsOrIncl(t: var TObjectSet; obj: RootRef): bool 522 +nim strTableContains astalgo.html#strTableContains,TStrTable,PSym proc strTableContains(t: TStrTable; n: PSym): bool 540 +nim symTabReplace astalgo.html#symTabReplace,TStrTable,PSym,PSym proc symTabReplace(t: var TStrTable; prevSym: PSym; newSym: PSym) 569 +nim strTableAdd astalgo.html#strTableAdd,TStrTable,PSym proc strTableAdd(t: var TStrTable; n: PSym) 579 +nim strTableInclReportConflict astalgo.html#strTableInclReportConflict,TStrTable,PSym proc strTableInclReportConflict(t: var TStrTable; n: PSym; onConflictKeepOld = false): PSym 584 +nim strTableIncl astalgo.html#strTableIncl,TStrTable,PSym proc strTableIncl(t: var TStrTable; n: PSym; onConflictKeepOld = false): bool 617 +nim strTableGet astalgo.html#strTableGet,TStrTable,PIdent proc strTableGet(t: TStrTable; name: PIdent): PSym 621 +nim TIdentIter astalgo.html#TIdentIter object TIdentIter 631 +nim nextIdentIter astalgo.html#nextIdentIter,TIdentIter,TStrTable proc nextIdentIter(ti: var TIdentIter; tab: TStrTable): PSym 635 +nim initIdentIter astalgo.html#initIdentIter,TIdentIter,TStrTable,PIdent proc initIdentIter(ti: var TIdentIter; tab: TStrTable; s: PIdent): PSym 653 +nim nextIdentExcluding astalgo.html#nextIdentExcluding,TIdentIter,TStrTable,IntSet proc nextIdentExcluding(ti: var TIdentIter; tab: TStrTable; excluding: IntSet): PSym 659 +nim firstIdentExcluding astalgo.html#firstIdentExcluding,TIdentIter,TStrTable,PIdent,IntSet proc firstIdentExcluding(ti: var TIdentIter; tab: TStrTable; s: PIdent;\n excluding: IntSet): PSym 675 +nim TTabIter astalgo.html#TTabIter object TTabIter 683 +nim nextIter astalgo.html#nextIter,TTabIter,TStrTable proc nextIter(ti: var TTabIter; tab: TStrTable): PSym 686 +nim initTabIter astalgo.html#initTabIter,TTabIter,TStrTable proc initTabIter(ti: var TTabIter; tab: TStrTable): PSym 702 +nim items astalgo.html#items.i,TStrTable iterator items(tab: TStrTable): PSym 709 +nim listSymbolNames astalgo.html#listSymbolNames,openArray[PSym] proc listSymbolNames(symbols: openArray[PSym]): string 761 +nim isDiscriminantField astalgo.html#isDiscriminantField,PNode proc isDiscriminantField(n: PNode): bool 768 +nimgrp debug astalgo.html#debug-procs-all proc 30 +nimgrp debug astalgo.html#debug-templates-all template 34 diff --git a/compiler/astmsgs.html b/compiler/astmsgs.html new file mode 100644 index 0000000000000..55518ed54c560 --- /dev/null +++ b/compiler/astmsgs.html @@ -0,0 +1,252 @@ + + + + + + + +astmsgs + + + + + + + + + + + + + + + + +
+
+

astmsgs

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ options, ast, msgs +
+
+
+

Procs

+
+
+
+
proc addDeclaredLoc(result: var string; conf: ConfigRef; sym: PSym) {.
+    ...raises: [ValueError, Exception, KeyError],
+    tags: [RootEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc addDeclaredLoc(result: var string; conf: ConfigRef; typ: PType) {.
+    ...raises: [ValueError, Exception, KeyError],
+    tags: [RootEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addDeclaredLocMaybe(result: var string; conf: ConfigRef; sym: PSym) {.
+    ...raises: [ValueError, Exception, KeyError],
+    tags: [RootEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc addDeclaredLocMaybe(result: var string; conf: ConfigRef; typ: PType) {.
+    ...raises: [ValueError, Exception, KeyError],
+    tags: [RootEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addTypeNodeDeclaredLoc(result: var string; conf: ConfigRef; typ: PType) {.
+    ...raises: [ValueError, Exception, KeyError],
+    tags: [RootEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genFieldDefect(conf: ConfigRef; field: string; disc: PSym): string {.
+    ...raises: [ValueError, Exception, KeyError],
+    tags: [RootEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc typSym(t: PType): PSym {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template quoteExpr(a: string): untyped
+
+ + can be used for quoting expressions in error msgs. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/astmsgs.idx b/compiler/astmsgs.idx new file mode 100644 index 0000000000000..684b540c92eed --- /dev/null +++ b/compiler/astmsgs.idx @@ -0,0 +1,11 @@ +nimTitle astmsgs astmsgs.html module astmsgs 0 +nim typSym astmsgs.html#typSym,PType proc typSym(t: PType): PSym 5 +nim addDeclaredLoc astmsgs.html#addDeclaredLoc,string,ConfigRef,PSym proc addDeclaredLoc(result: var string; conf: ConfigRef; sym: PSym) 10 +nim addDeclaredLocMaybe astmsgs.html#addDeclaredLocMaybe,string,ConfigRef,PSym proc addDeclaredLocMaybe(result: var string; conf: ConfigRef; sym: PSym) 13 +nim addDeclaredLoc astmsgs.html#addDeclaredLoc,string,ConfigRef,PType proc addDeclaredLoc(result: var string; conf: ConfigRef; typ: PType) 17 +nim addTypeNodeDeclaredLoc astmsgs.html#addTypeNodeDeclaredLoc,string,ConfigRef,PType proc addTypeNodeDeclaredLoc(result: var string; conf: ConfigRef; typ: PType) 27 +nim addDeclaredLocMaybe astmsgs.html#addDeclaredLocMaybe,string,ConfigRef,PType proc addDeclaredLocMaybe(result: var string; conf: ConfigRef; typ: PType) 33 +nim quoteExpr astmsgs.html#quoteExpr.t,string template quoteExpr(a: string): untyped 36 +nim genFieldDefect astmsgs.html#genFieldDefect,ConfigRef,string,PSym proc genFieldDefect(conf: ConfigRef; field: string; disc: PSym): string 40 +nimgrp adddeclaredloc astmsgs.html#addDeclaredLoc-procs-all proc 10 +nimgrp adddeclaredlocmaybe astmsgs.html#addDeclaredLocMaybe-procs-all proc 13 diff --git a/compiler/astyaml.html b/compiler/astyaml.html new file mode 100644 index 0000000000000..58e7bcb6caa97 --- /dev/null +++ b/compiler/astyaml.html @@ -0,0 +1,194 @@ + + + + + + + +astyaml + + + + + + + + + + + + + + + + +
+
+

astyaml

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc addYamlString(res: var string; s: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lineInfoToStr(conf: ConfigRef; info: TLineInfo): string {.
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc symToYaml(conf: ConfigRef; n: PSym; indent: int = 0; maxRecDepth: int = -1): string {.
+    ...raises: [ValueError, Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc treeToYaml(conf: ConfigRef; n: PNode; indent: int = 0;
+                maxRecDepth: int = -1): string {.
+    ...raises: [ValueError, Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc typeToYaml(conf: ConfigRef; n: PType; indent: int = 0;
+                maxRecDepth: int = -1): string {.
+    ...raises: [ValueError, Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/astyaml.idx b/compiler/astyaml.idx new file mode 100644 index 0000000000000..6332f33ee9356 --- /dev/null +++ b/compiler/astyaml.idx @@ -0,0 +1,6 @@ +nimTitle astyaml astyaml.html module astyaml 0 +nim addYamlString astyaml.html#addYamlString,string,string proc addYamlString(res: var string; s: string) 15 +nim lineInfoToStr astyaml.html#lineInfoToStr,ConfigRef,TLineInfo proc lineInfoToStr(conf: ConfigRef; info: TLineInfo): string 43 +nim treeToYaml astyaml.html#treeToYaml,ConfigRef,PNode,int,int proc treeToYaml(conf: ConfigRef; n: PNode; indent: int = 0; maxRecDepth: int = -1): string 141 +nim typeToYaml astyaml.html#typeToYaml,ConfigRef,PType,int,int proc typeToYaml(conf: ConfigRef; n: PType; indent: int = 0; maxRecDepth: int = -1): string 146 +nim symToYaml astyaml.html#symToYaml,ConfigRef,PSym,int,int proc symToYaml(conf: ConfigRef; n: PSym; indent: int = 0; maxRecDepth: int = -1): string 151 diff --git a/compiler/bitsets.html b/compiler/bitsets.html new file mode 100644 index 0000000000000..b5925a4a36888 --- /dev/null +++ b/compiler/bitsets.html @@ -0,0 +1,353 @@ + + + + + + + +bitsets + + + + + + + + + + + + + + + + +
+
+

bitsets

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Types

+
+
+
TBitSet = seq[ElemType]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
ElemSize = 8
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc bitSetCard(x: TBitSet): BiggestInt {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bitSetContains(x, y: TBitSet): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bitSetDiff(x: var TBitSet; y: TBitSet) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bitSetEquals(x, y: TBitSet): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bitSetExcl(x: var TBitSet; elem: BiggestInt) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bitSetIn(x: TBitSet; e: BiggestInt): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bitSetIncl(x: var TBitSet; elem: BiggestInt) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bitSetInit(b: var TBitSet; length: int) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bitSetIntersect(x: var TBitSet; y: TBitSet) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bitSetSymDiff(x: var TBitSet; y: TBitSet) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bitSetToWord(s: TBitSet; size: int): BiggestUInt {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bitSetUnion(x: var TBitSet; y: TBitSet) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/bitsets.idx b/compiler/bitsets.idx new file mode 100644 index 0000000000000..fc11af8595e67 --- /dev/null +++ b/compiler/bitsets.idx @@ -0,0 +1,15 @@ +nimTitle bitsets bitsets.html module bitsets 0 +nim TBitSet bitsets.html#TBitSet type TBitSet 18 +nim ElemSize bitsets.html#ElemSize const ElemSize 22 +nim bitSetIn bitsets.html#bitSetIn,TBitSet,BiggestInt proc bitSetIn(x: TBitSet; e: BiggestInt): bool 29 +nim bitSetIncl bitsets.html#bitSetIncl,TBitSet,BiggestInt proc bitSetIncl(x: var TBitSet; elem: BiggestInt) 32 +nim bitSetExcl bitsets.html#bitSetExcl,TBitSet,BiggestInt proc bitSetExcl(x: var TBitSet; elem: BiggestInt) 37 +nim bitSetInit bitsets.html#bitSetInit,TBitSet,int proc bitSetInit(b: var TBitSet; length: int) 41 +nim bitSetUnion bitsets.html#bitSetUnion,TBitSet,TBitSet proc bitSetUnion(x: var TBitSet; y: TBitSet) 44 +nim bitSetDiff bitsets.html#bitSetDiff,TBitSet,TBitSet proc bitSetDiff(x: var TBitSet; y: TBitSet) 47 +nim bitSetSymDiff bitsets.html#bitSetSymDiff,TBitSet,TBitSet proc bitSetSymDiff(x: var TBitSet; y: TBitSet) 50 +nim bitSetIntersect bitsets.html#bitSetIntersect,TBitSet,TBitSet proc bitSetIntersect(x: var TBitSet; y: TBitSet) 53 +nim bitSetEquals bitsets.html#bitSetEquals,TBitSet,TBitSet proc bitSetEquals(x, y: TBitSet): bool 56 +nim bitSetContains bitsets.html#bitSetContains,TBitSet,TBitSet proc bitSetContains(x, y: TBitSet): bool 62 +nim bitSetCard bitsets.html#bitSetCard,TBitSet proc bitSetCard(x: TBitSet): BiggestInt 89 +nim bitSetToWord bitsets.html#bitSetToWord,TBitSet,int proc bitSetToWord(s: TBitSet; size: int): BiggestUInt 94 diff --git a/compiler/btrees.html b/compiler/btrees.html new file mode 100644 index 0000000000000..a60d9cee7aec4 --- /dev/null +++ b/compiler/btrees.html @@ -0,0 +1,270 @@ + + + + + + + +btrees + + + + + + + + + + + + + + + + +
+
+

btrees

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

BTree implementation with few features, but good enough for the Nim compiler's needs.

+
+

Types

+
+
+
BTree[Key; Val] = object
+  ## number of key-value pairs
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc add[Key, Val](b: var BTree[Key, Val]; key: Key; val: Val)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc contains[Key, Val](b: BTree[Key, Val]; key: Key): bool
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getOrDefault[Key, Val](b: BTree[Key, Val]; key: Key): Val
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasNext[Key, Val](b: BTree[Key, Val]; index: int): bool
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initBTree[Key, Val](): BTree[Key, Val]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc len[Key, Val](b: BTree[Key, Val]): int {.inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc next[Key, Val](b: BTree[Key, Val]; index: int): (Key, Val, int)
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator pairs[Key, Val](b: BTree[Key, Val]): (Key, Val)
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/btrees.idx b/compiler/btrees.idx new file mode 100644 index 0000000000000..439f8f485363b --- /dev/null +++ b/compiler/btrees.idx @@ -0,0 +1,10 @@ +nimTitle btrees btrees.html module btrees 0 +nim BTree btrees.html#BTree object BTree 30 +nim initBTree btrees.html#initBTree proc initBTree[Key, Val](): BTree[Key, Val] 34 +nim getOrDefault btrees.html#getOrDefault,BTree[Key,Val],Key proc getOrDefault[Key, Val](b: BTree[Key, Val]; key: Key): Val 40 +nim contains btrees.html#contains,BTree[Key,Val],Key proc contains[Key, Val](b: BTree[Key, Val]; key: Key): bool 52 +nim add btrees.html#add,BTree[Key,Val],Key,Val proc add[Key, Val](b: var BTree[Key, Val]; key: Key; val: Val) 121 +nim hasNext btrees.html#hasNext,BTree[Key,Val],int proc hasNext[Key, Val](b: BTree[Key, Val]; index: int): bool 148 +nim next btrees.html#next,BTree[Key,Val],int proc next[Key, Val](b: BTree[Key, Val]; index: int): (Key, Val, int) 158 +nim pairs btrees.html#pairs.i,BTree[Key,Val] iterator pairs[Key, Val](b: BTree[Key, Val]): (Key, Val) 173 +nim len btrees.html#len,BTree[Key,Val] proc len[Key, Val](b: BTree[Key, Val]): int 180 diff --git a/compiler/cbuilderbase.html b/compiler/cbuilderbase.html new file mode 100644 index 0000000000000..6035d607a61b2 --- /dev/null +++ b/compiler/cbuilderbase.html @@ -0,0 +1,1002 @@ + + + + + + + +cbuilderbase + + + + + + + + + + + + + + + + +
+
+

cbuilderbase

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ ropes, int128 +
+
+
+

Types

+
+
+
Builder = object
+  buf*: string
+  indents*: int
+
+ + + Source   +Edit   + +
+
+
+
IfBuilder = object
+  state*: IfBuilderState
+
+ + + Source   +Edit   + +
+
+
+
IfBuilderState = enum
+  WaitingIf, WaitingElseIf, InBlock
+
+ + + Source   +Edit   + +
+
+
+
Snippet = string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
CChar = "char"
+
+ + + Source   +Edit   + +
+
+
+
CConstPointer = "NIM_CONST void*"
+
+ + + Source   +Edit   + +
+
+
+
CInt = "int"
+
+ + + Source   +Edit   + +
+
+
+
CNil = "NULL"
+
+ + + Source   +Edit   + +
+
+
+
CPointer = "void*"
+
+ + + Source   +Edit   + +
+
+
+
CVoid = "void"
+
+ + + Source   +Edit   + +
+
+
+
NimBool = "NIM_BOOL"
+
+ + + Source   +Edit   + +
+
+
+
NimChar = "NIM_CHAR"
+
+ + + Source   +Edit   + +
+
+
+
NimCstring = "NCSTRING"
+
+ + + Source   +Edit   + +
+
+
+
NimFalse = "NIM_FALSE"
+
+ + + Source   +Edit   + +
+
+
+
NimFloat = "NF"
+
+ + + Source   +Edit   + +
+
+
+
NimFloat32 = "NF32"
+
+ + + Source   +Edit   + +
+
+
+
NimFloat64 = "NF64"
+
+ + + Source   +Edit   + +
+
+
+
NimFloat128 = "NF128"
+
+ + + Source   +Edit   + +
+
+
+
NimInf = "INF"
+
+ + + Source   +Edit   + +
+
+
+
NimInt = "NI"
+
+ + + Source   +Edit   + +
+
+
+
NimInt8 = "NI8"
+
+ + + Source   +Edit   + +
+
+
+
NimInt16 = "NI16"
+
+ + + Source   +Edit   + +
+
+
+
NimInt32 = "NI32"
+
+ + + Source   +Edit   + +
+
+
+
NimInt64 = "NI64"
+
+ + + Source   +Edit   + +
+
+
+
NimNan = "NAN"
+
+ + + Source   +Edit   + +
+
+
+
NimNil = "NIM_NIL"
+
+ + + Source   +Edit   + +
+
+
+
NimStrlitFlag = "NIM_STRLIT_FLAG"
+
+ + + Source   +Edit   + +
+
+
+
NimTrue = "NIM_TRUE"
+
+ + + Source   +Edit   + +
+
+
+
NimUint = "NU"
+
+ + + Source   +Edit   + +
+
+
+
NimUint8 = "NU8"
+
+ + + Source   +Edit   + +
+
+
+
NimUint16 = "NU16"
+
+ + + Source   +Edit   + +
+
+
+
NimUint32 = "NU32"
+
+ + + Source   +Edit   + +
+
+
+
NimUint64 = "NU64"
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc add(builder: var Builder; s: char) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc add(builder: var Builder; s: string) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addDedent(builder: var Builder; s: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addFloatValue(builder: var Builder; val: float) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addInt64Literal(result: var Builder; i: BiggestInt) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addIntLiteral(result: var Builder; i: BiggestInt) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc addIntLiteral(result: var Builder; i: Int128) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addIntValue(builder: var Builder; val: int) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc addIntValue(builder: var Builder; val: int64) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc addIntValue(builder: var Builder; val: Int128) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc addIntValue(builder: var Builder; val: uint64) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addLineComment(builder: var Builder; comment: string) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addLineEnd(builder: var Builder; s: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addLineEndDedent(builder: var Builder; s: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addLineEndIndent(builder: var Builder; s: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addNewline(builder: var Builder) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addUint64Literal(result: var Builder; i: uint64) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cInt64Literal(i: BiggestInt): Snippet {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cIntLiteral(i: BiggestInt): Snippet {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc cIntLiteral(i: Int128): Snippet {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cIntType(bits: BiggestInt): Snippet {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cUint64Literal(i: uint64): Snippet {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cUintType(bits: BiggestInt): Snippet {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc extract(builder: Builder): Snippet {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template cFloatValue(val: float): Snippet
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template cIntValue(val: int): Snippet
+
+ + + Source   +Edit   + +
+
+
+
template cIntValue(val: int64): Snippet
+
+ + + Source   +Edit   + +
+
+
+
template cIntValue(val: Int128): Snippet
+
+ + + Source   +Edit   + +
+
+
+
template cIntValue(val: uint64): Snippet
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template cUintValue(val: uint): Snippet
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template newBuilder(s: string): Builder
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/cbuilderbase.idx b/compiler/cbuilderbase.idx new file mode 100644 index 0000000000000..e58e3dc36b21b --- /dev/null +++ b/compiler/cbuilderbase.idx @@ -0,0 +1,73 @@ +nimTitle cbuilderbase cbuilderbase.html module cbuilderbase 0 +nim Snippet cbuilderbase.html#Snippet type Snippet 4 +nim Builder cbuilderbase.html#Builder object Builder 5 +nim newBuilder cbuilderbase.html#newBuilder.t,string template newBuilder(s: string): Builder 9 +nim extract cbuilderbase.html#extract,Builder proc extract(builder: Builder): Snippet 12 +nim add cbuilderbase.html#add,Builder,string proc add(builder: var Builder; s: string) 15 +nim add cbuilderbase.html#add,Builder,char proc add(builder: var Builder; s: char) 18 +nim addNewline cbuilderbase.html#addNewline,Builder proc addNewline(builder: var Builder) 21 +nim addLineEnd cbuilderbase.html#addLineEnd,Builder,string proc addLineEnd(builder: var Builder; s: string) 26 +nim addLineEndIndent cbuilderbase.html#addLineEndIndent,Builder,string proc addLineEndIndent(builder: var Builder; s: string) 30 +nim addDedent cbuilderbase.html#addDedent,Builder,string proc addDedent(builder: var Builder; s: string) 35 +nim addLineEndDedent cbuilderbase.html#addLineEndDedent,Builder,string proc addLineEndDedent(builder: var Builder; s: string) 41 +nim addLineComment cbuilderbase.html#addLineComment,Builder,string proc addLineComment(builder: var Builder; comment: string) 45 +nim addIntValue cbuilderbase.html#addIntValue,Builder,int proc addIntValue(builder: var Builder; val: int) 51 +nim addIntValue cbuilderbase.html#addIntValue,Builder,int64 proc addIntValue(builder: var Builder; val: int64) 54 +nim addIntValue cbuilderbase.html#addIntValue,Builder,uint64 proc addIntValue(builder: var Builder; val: uint64) 57 +nim addIntValue cbuilderbase.html#addIntValue,Builder,Int128 proc addIntValue(builder: var Builder; val: Int128) 60 +nim cIntValue cbuilderbase.html#cIntValue.t,int template cIntValue(val: int): Snippet 63 +nim cIntValue cbuilderbase.html#cIntValue.t,int64 template cIntValue(val: int64): Snippet 64 +nim cIntValue cbuilderbase.html#cIntValue.t,uint64 template cIntValue(val: uint64): Snippet 65 +nim cIntValue cbuilderbase.html#cIntValue.t,Int128 template cIntValue(val: Int128): Snippet 66 +nim cUintValue cbuilderbase.html#cUintValue.t,uint template cUintValue(val: uint): Snippet 68 +nim addFloatValue cbuilderbase.html#addFloatValue,Builder,float proc addFloatValue(builder: var Builder; val: float) 72 +nim cFloatValue cbuilderbase.html#cFloatValue.t,float template cFloatValue(val: float): Snippet 75 +nim addInt64Literal cbuilderbase.html#addInt64Literal,Builder,BiggestInt proc addInt64Literal(result: var Builder; i: BiggestInt) 77 +nim addUint64Literal cbuilderbase.html#addUint64Literal,Builder,uint64 proc addUint64Literal(result: var Builder; i: uint64) 83 +nim addIntLiteral cbuilderbase.html#addIntLiteral,Builder,BiggestInt proc addIntLiteral(result: var Builder; i: BiggestInt) 86 +nim addIntLiteral cbuilderbase.html#addIntLiteral,Builder,Int128 proc addIntLiteral(result: var Builder; i: Int128) 97 +nim cInt64Literal cbuilderbase.html#cInt64Literal,BiggestInt proc cInt64Literal(i: BiggestInt): Snippet 100 +nim cUint64Literal cbuilderbase.html#cUint64Literal,uint64 proc cUint64Literal(i: uint64): Snippet 106 +nim cIntLiteral cbuilderbase.html#cIntLiteral,BiggestInt proc cIntLiteral(i: BiggestInt): Snippet 109 +nim cIntLiteral cbuilderbase.html#cIntLiteral,Int128 proc cIntLiteral(i: Int128): Snippet 120 +nim NimInt cbuilderbase.html#NimInt const NimInt 124 +nim NimInt8 cbuilderbase.html#NimInt8 const NimInt8 125 +nim NimInt16 cbuilderbase.html#NimInt16 const NimInt16 126 +nim NimInt32 cbuilderbase.html#NimInt32 const NimInt32 127 +nim NimInt64 cbuilderbase.html#NimInt64 const NimInt64 128 +nim CInt cbuilderbase.html#CInt const CInt 129 +nim NimUint cbuilderbase.html#NimUint const NimUint 130 +nim NimUint8 cbuilderbase.html#NimUint8 const NimUint8 131 +nim NimUint16 cbuilderbase.html#NimUint16 const NimUint16 132 +nim NimUint32 cbuilderbase.html#NimUint32 const NimUint32 133 +nim NimUint64 cbuilderbase.html#NimUint64 const NimUint64 134 +nim NimFloat cbuilderbase.html#NimFloat const NimFloat 135 +nim NimFloat32 cbuilderbase.html#NimFloat32 const NimFloat32 136 +nim NimFloat64 cbuilderbase.html#NimFloat64 const NimFloat64 137 +nim NimFloat128 cbuilderbase.html#NimFloat128 const NimFloat128 138 +nim NimNan cbuilderbase.html#NimNan const NimNan 139 +nim NimInf cbuilderbase.html#NimInf const NimInf 140 +nim NimBool cbuilderbase.html#NimBool const NimBool 141 +nim NimTrue cbuilderbase.html#NimTrue const NimTrue 142 +nim NimFalse cbuilderbase.html#NimFalse const NimFalse 143 +nim NimChar cbuilderbase.html#NimChar const NimChar 144 +nim CChar cbuilderbase.html#CChar const CChar 145 +nim NimCstring cbuilderbase.html#NimCstring const NimCstring 146 +nim NimNil cbuilderbase.html#NimNil const NimNil 147 +nim CNil cbuilderbase.html#CNil const CNil 148 +nim NimStrlitFlag cbuilderbase.html#NimStrlitFlag const NimStrlitFlag 149 +nim CVoid cbuilderbase.html#CVoid const CVoid 150 +nim CPointer cbuilderbase.html#CPointer const CPointer 151 +nim CConstPointer cbuilderbase.html#CConstPointer const CConstPointer 152 +nim cIntType cbuilderbase.html#cIntType,BiggestInt proc cIntType(bits: BiggestInt): Snippet 154 +nim cUintType cbuilderbase.html#cUintType,BiggestInt proc cUintType(bits: BiggestInt): Snippet 157 +nim WaitingIf cbuilderbase.html#WaitingIf IfBuilderState.WaitingIf 161 +nim WaitingElseIf cbuilderbase.html#WaitingElseIf IfBuilderState.WaitingElseIf 161 +nim InBlock cbuilderbase.html#InBlock IfBuilderState.InBlock 161 +nim IfBuilderState cbuilderbase.html#IfBuilderState enum IfBuilderState 161 +nim IfBuilder cbuilderbase.html#IfBuilder object IfBuilder 163 +nimgrp cintliteral cbuilderbase.html#cIntLiteral-procs-all proc 109 +nimgrp addintvalue cbuilderbase.html#addIntValue-procs-all proc 51 +nimgrp addintliteral cbuilderbase.html#addIntLiteral-procs-all proc 86 +nimgrp add cbuilderbase.html#add-procs-all proc 15 +nimgrp cintvalue cbuilderbase.html#cIntValue-templates-all template 63 diff --git a/compiler/ccgutils.html b/compiler/ccgutils.html new file mode 100644 index 0000000000000..f728e500e803f --- /dev/null +++ b/compiler/ccgutils.html @@ -0,0 +1,278 @@ + + + + + + + +ccgutils + + + + + + + + + + + + + + + + +
+
+

ccgutils

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc ccgIntroducedPtr(conf: ConfigRef; s: PSym; retType: PType): bool {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc encodeName(name: string): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc encodeSym(m: BModule; s: PSym; makeUnique: bool = false): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc encodeType(m: BModule; t: PType): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getPragmaStmt(n: PNode; w: TSpecialWord): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hashString(conf: ConfigRef; s: string): BiggestInt {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeSingleLineCString(s: string): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc stmtsContainPragma(n: PNode; w: TSpecialWord): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template getUniqueType(key: PType): PType
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/ccgutils.idx b/compiler/ccgutils.idx new file mode 100644 index 0000000000000..f682e0c233161 --- /dev/null +++ b/compiler/ccgutils.idx @@ -0,0 +1,10 @@ +nimTitle ccgutils ccgutils.html module ccgutils 0 +nim getPragmaStmt ccgutils.html#getPragmaStmt,PNode,TSpecialWord proc getPragmaStmt(n: PNode; w: TSpecialWord): PNode 21 +nim stmtsContainPragma ccgutils.html#stmtsContainPragma,PNode,TSpecialWord proc stmtsContainPragma(n: PNode; w: TSpecialWord): bool 35 +nim hashString ccgutils.html#hashString,ConfigRef,string proc hashString(conf: ConfigRef; s: string): BiggestInt 38 +nim getUniqueType ccgutils.html#getUniqueType.t,PType template getUniqueType(key: PType): PType 63 +nim makeSingleLineCString ccgutils.html#makeSingleLineCString,string proc makeSingleLineCString(s: string): string 65 +nim ccgIntroducedPtr ccgutils.html#ccgIntroducedPtr,ConfigRef,PSym,PType proc ccgIntroducedPtr(conf: ConfigRef; s: PSym; retType: PType): bool 79 +nim encodeName ccgutils.html#encodeName,string proc encodeName(name: string): string 112 +nim encodeSym ccgutils.html#encodeSym,BModule,PSym,bool proc encodeSym(m: BModule; s: PSym; makeUnique: bool = false): string 123 +nim encodeType ccgutils.html#encodeType,BModule,PType proc encodeType(m: BModule; t: PType): string 130 diff --git a/compiler/cgen.html b/compiler/cgen.html new file mode 100644 index 0000000000000..1479e33c3d607 --- /dev/null +++ b/compiler/cgen.html @@ -0,0 +1,346 @@ + + + + + + + +cgen + + + + + + + + + + + + + + + + +
+
+

cgen

+
+ +
+ Source   +Edit   + +
+ +

This module implements the C code generator.This include file contains the logic to produce constant string and seq literals. The code here is responsible that const x = ["a", "b"] works without hidden runtime creation code. The price is that seqs and strings are not purely a library implementation.Generates traversal procs for the C backend.Code specialization instead of the old, incredibly slow 'genericReset' implementation.Thread var support for architectures that lack native support for thread local storage.

+ +
+

Procs

+
+
+
+
proc cgenWriteModules(backend: RootRef; config: ConfigRef) {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    TimeEffect, WriteDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fillObjectFields(m: BModule; typ: PType) {....raises: [Exception, ValueError,
+    KeyError, IOError, ERecoverableError, OSError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc finalCodegenActions(graph: ModuleGraph; m: BModule; n: PNode) {....raises: [
+    KeyError, Exception, ValueError, IOError, ERecoverableError, OSError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    TimeEffect], forbids: [].}
+
+ + Also called from IC. + Source   +Edit   + +
+
+ +
+
+
+
proc genProcAux(m: BModule; prc: PSym) {....raises: [OSError, Exception,
+    ERecoverableError, KeyError, ValueError, IOError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect, TimeEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genTopLevelStmt(m: BModule; n: PNode) {....raises: [Exception, ValueError,
+    KeyError, IOError, ERecoverableError, OSError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect, TimeEffect],
+    forbids: [].}
+
+ + Also called from ic/cbackend.nim. + Source   +Edit   + +
+
+ +
+
+
+
proc genTypeInfo(config: ConfigRef; m: BModule; t: PType; info: TLineInfo): Rope {....raises: [
+    OSError, Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc multiFormat(frmt: var string; chars: static openArray[char];
+                 args: openArray[seq[string]])
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newModule(g: BModuleList; module: PSym; conf: ConfigRef): BModule {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc registerInitProcs(g: BModuleList; m: PSym; flags: set[ModuleBackendFlag]) {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + Called from the IC backend. + Source   +Edit   + +
+
+ +
+
+
+
proc setupCgen(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext {.
+    ...raises: [OSError, IOError],
+    tags: [ReadEnvEffect, ReadIOEffect, WriteDirEffect, ReadDirEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc whichInitProcs(m: BModule): set[ModuleBackendFlag] {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template cgDeclFrmt(s: PSym): string
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/cgen.idx b/compiler/cgen.idx new file mode 100644 index 0000000000000..51791b78370eb --- /dev/null +++ b/compiler/cgen.idx @@ -0,0 +1,13 @@ +nimTitle cgen cgen.html module cgen 0 +nim cgDeclFrmt cgen.html#cgDeclFrmt.t,PSym template cgDeclFrmt(s: PSym): string 437 +nim multiFormat cgen.html#multiFormat,string,staticopenArray[char],openArray[seq[string]] proc multiFormat(frmt: var string; chars: static openArray[char];\n args: openArray[seq[string]]) 473 +nim fillObjectFields cgen.html#fillObjectFields,BModule,PType proc fillObjectFields(m: BModule; typ: PType) 756 +nim genTypeInfo cgen.html#genTypeInfo,ConfigRef,BModule,PType,TLineInfo proc genTypeInfo(config: ConfigRef; m: BModule; t: PType; info: TLineInfo): Rope 2034 +nim genProcAux cgen.html#genProcAux,BModule,PSym proc genProcAux(m: BModule; prc: PSym) 1272 +nim registerInitProcs cgen.html#registerInitProcs,BModuleList,PSym,set[ModuleBackendFlag] proc registerInitProcs(g: BModuleList; m: PSym; flags: set[ModuleBackendFlag]) 1881 +nim whichInitProcs cgen.html#whichInitProcs,BModule proc whichInitProcs(m: BModule): set[ModuleBackendFlag] 1901 +nim newModule cgen.html#newModule,BModuleList,PSym,ConfigRef proc newModule(g: BModuleList; module: PSym; conf: ConfigRef): BModule 2339 +nim setupCgen cgen.html#setupCgen,ModuleGraph,PSym,IdGenerator proc setupCgen(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext 2352 +nim genTopLevelStmt cgen.html#genTopLevelStmt,BModule,PNode proc genTopLevelStmt(m: BModule; n: PNode) 2422 +nim finalCodegenActions cgen.html#finalCodegenActions,ModuleGraph,BModule,PNode proc finalCodegenActions(graph: ModuleGraph; m: BModule; n: PNode) 2515 +nim cgenWriteModules cgen.html#cgenWriteModules,RootRef,ConfigRef proc cgenWriteModules(backend: RootRef; config: ConfigRef) 2595 diff --git a/compiler/cgendata.html b/compiler/cgendata.html new file mode 100644 index 0000000000000..1124b46681db0 --- /dev/null +++ b/compiler/cgendata.html @@ -0,0 +1,547 @@ + + + + + + + +cgendata + + + + + + + + + + + + + + + + +
+
+

cgendata

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module contains the data structures for the C code generation phase.

+ +
+

Types

+
+
+
BModule = ref TCGen
+
+ + + Source   +Edit   + +
+
+
+
BModuleList = ref object of RootObj
+  mainModProcs*, mainModInit*, otherModsInit*, mainDatInit*: Builder
+  mapping*: Rope
+  modules*: seq[BModule]
+  modulesClosed*: seq[BModule]
+  forwardedProcs*: seq[PSym]
+  generatedHeader*: BModule
+  typeInfoMarker*: TypeCacheWithOwner
+  typeInfoMarkerV2*: TypeCacheWithOwner
+  config*: ConfigRef
+  graph*: ModuleGraph
+  strVersion*, seqVersion*: int
+  nimtv*: Builder
+  nimtvDeps*: seq[PType]
+  nimtvDeclared*: IntSet
+  mangledPrcs*: HashSet[string]
+
+ + + Source   +Edit   + +
+
+
+
BProc = ref TCProc
+
+ + + Source   +Edit   + +
+
+
+
CodegenFlag = enum
+  preventStackTrace, usesThreadVars, frameDeclared, isHeaderFile,
+  includesStringh, objHasKidsValid, useAliveDataFromDce
+
+ + + Source   +Edit   + +
+
+
+
TBlock = object
+  id*: int
+  label*: Rope
+  sections*: TCProcSections
+  isLoop*: bool
+  nestedTryStmts*: int16
+  nestedExceptStmts*: int16
+  frameLen*: int16
+
+ + + Source   +Edit   + +
+
+
+
TCFileSection = enum
+  cfsHeaders, cfsFrameDefines, cfsForwardTypes, cfsTypes, cfsSeqTypes,
+  cfsTypeInfo, cfsProcHeaders, cfsStrData, cfsData, cfsVars, cfsProcs,
+  cfsInitProc, cfsDatInitProc, cfsTypeInit1, cfsTypeInit3, cfsDynLibInit
+
+ + + Source   +Edit   + +
+
+
+
TCFileSections = array[TCFileSection, Builder]
+
+ + + Source   +Edit   + +
+
+
+
TCProcFlag = enum
+  beforeRetNeeded, threadVarAccessed, hasCurFramePointer, noSafePoints,
+  nimErrorFlagAccessed, nimErrorFlagDeclared, nimErrorFlagDisabled
+
+ + + Source   +Edit   + +
+
+
+
TCProcSection = enum
+  cpsLocals, cpsInit, cpsStmts
+
+ + + Source   +Edit   + +
+
+
+
TCProcSections = array[TCProcSection, Builder]
+
+ + + Source   +Edit   + +
+
+
+
TCTypeKind = enum
+  ctVoid, ctChar, ctBool, ctInt, ctInt8, ctInt16, ctInt32, ctInt64, ctFloat,
+  ctFloat32, ctFloat64, ctFloat128, ctUInt, ctUInt8, ctUInt16, ctUInt32,
+  ctUInt64, ctArray, ctPtrToArray, ctStruct, ctPtr, ctNimStr, ctNimSeq, ctProc,
+  ctCString
+
+ + + Source   +Edit   + +
+
+
+
TLabel = Rope
+
+ + + Source   +Edit   + +
+
+
+
TTypeSeq = seq[PType]
+
+ + + Source   +Edit   + +
+
+
+
TypeCache = Table[SigHash, Rope]
+
+ + + Source   +Edit   + +
+
+
+
TypeCacheWithOwner = Table[SigHash, tuple[str: Rope, owner: int32]]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc includeHeader(this: BModule; header: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initBlock(): TBlock {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newModuleList(g: ModuleGraph): BModuleList {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newProc(prc: PSym; module: BModule): BProc {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc procSec(p: BProc; s: TCProcSection): var Builder {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc s(p: BProc; s: TCProcSection): var Builder {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator cgenModules(g: BModuleList): BModule {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template config(m: BModule): ConfigRef
+
+ + + Source   +Edit   + +
+
+
+
template config(p: BProc): ConfigRef
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template vccAndC(p: BProc): bool
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/cgendata.idx b/compiler/cgendata.idx new file mode 100644 index 0000000000000..2fcf268e94275 --- /dev/null +++ b/compiler/cgendata.idx @@ -0,0 +1,85 @@ +nimTitle cgendata cgendata.html module cgendata 0 +nim TLabel cgendata.html#TLabel type TLabel 19 +nim cfsHeaders cgendata.html#cfsHeaders TCFileSection.cfsHeaders 20 +nim cfsFrameDefines cgendata.html#cfsFrameDefines TCFileSection.cfsFrameDefines 20 +nim cfsForwardTypes cgendata.html#cfsForwardTypes TCFileSection.cfsForwardTypes 20 +nim cfsTypes cgendata.html#cfsTypes TCFileSection.cfsTypes 20 +nim cfsSeqTypes cgendata.html#cfsSeqTypes TCFileSection.cfsSeqTypes 20 +nim cfsTypeInfo cgendata.html#cfsTypeInfo TCFileSection.cfsTypeInfo 20 +nim cfsProcHeaders cgendata.html#cfsProcHeaders TCFileSection.cfsProcHeaders 20 +nim cfsStrData cgendata.html#cfsStrData TCFileSection.cfsStrData 20 +nim cfsData cgendata.html#cfsData TCFileSection.cfsData 20 +nim cfsVars cgendata.html#cfsVars TCFileSection.cfsVars 20 +nim cfsProcs cgendata.html#cfsProcs TCFileSection.cfsProcs 20 +nim cfsInitProc cgendata.html#cfsInitProc TCFileSection.cfsInitProc 20 +nim cfsDatInitProc cgendata.html#cfsDatInitProc TCFileSection.cfsDatInitProc 20 +nim cfsTypeInit1 cgendata.html#cfsTypeInit1 TCFileSection.cfsTypeInit1 20 +nim cfsTypeInit3 cgendata.html#cfsTypeInit3 TCFileSection.cfsTypeInit3 20 +nim cfsDynLibInit cgendata.html#cfsDynLibInit TCFileSection.cfsDynLibInit 20 +nim TCFileSection cgendata.html#TCFileSection enum TCFileSection 20 +nim ctVoid cgendata.html#ctVoid TCTypeKind.ctVoid 39 +nim ctChar cgendata.html#ctChar TCTypeKind.ctChar 39 +nim ctBool cgendata.html#ctBool TCTypeKind.ctBool 39 +nim ctInt cgendata.html#ctInt TCTypeKind.ctInt 39 +nim ctInt8 cgendata.html#ctInt8 TCTypeKind.ctInt8 39 +nim ctInt16 cgendata.html#ctInt16 TCTypeKind.ctInt16 39 +nim ctInt32 cgendata.html#ctInt32 TCTypeKind.ctInt32 39 +nim ctInt64 cgendata.html#ctInt64 TCTypeKind.ctInt64 39 +nim ctFloat cgendata.html#ctFloat TCTypeKind.ctFloat 39 +nim ctFloat32 cgendata.html#ctFloat32 TCTypeKind.ctFloat32 39 +nim ctFloat64 cgendata.html#ctFloat64 TCTypeKind.ctFloat64 39 +nim ctFloat128 cgendata.html#ctFloat128 TCTypeKind.ctFloat128 39 +nim ctUInt cgendata.html#ctUInt TCTypeKind.ctUInt 39 +nim ctUInt8 cgendata.html#ctUInt8 TCTypeKind.ctUInt8 39 +nim ctUInt16 cgendata.html#ctUInt16 TCTypeKind.ctUInt16 39 +nim ctUInt32 cgendata.html#ctUInt32 TCTypeKind.ctUInt32 39 +nim ctUInt64 cgendata.html#ctUInt64 TCTypeKind.ctUInt64 39 +nim ctArray cgendata.html#ctArray TCTypeKind.ctArray 39 +nim ctPtrToArray cgendata.html#ctPtrToArray TCTypeKind.ctPtrToArray 39 +nim ctStruct cgendata.html#ctStruct TCTypeKind.ctStruct 39 +nim ctPtr cgendata.html#ctPtr TCTypeKind.ctPtr 39 +nim ctNimStr cgendata.html#ctNimStr TCTypeKind.ctNimStr 39 +nim ctNimSeq cgendata.html#ctNimSeq TCTypeKind.ctNimSeq 39 +nim ctProc cgendata.html#ctProc TCTypeKind.ctProc 39 +nim ctCString cgendata.html#ctCString TCTypeKind.ctCString 39 +nim TCTypeKind cgendata.html#TCTypeKind enum TCTypeKind 39 +nim TCFileSections cgendata.html#TCFileSections type TCFileSections 46 +nim cpsLocals cgendata.html#cpsLocals TCProcSection.cpsLocals 47 +nim cpsInit cgendata.html#cpsInit TCProcSection.cpsInit 47 +nim cpsStmts cgendata.html#cpsStmts TCProcSection.cpsStmts 47 +nim TCProcSection cgendata.html#TCProcSection enum TCProcSection 47 +nim TCProcSections cgendata.html#TCProcSections type TCProcSections 51 +nim BModule cgendata.html#BModule type BModule 52 +nim BProc cgendata.html#BProc type BProc 53 +nim TBlock cgendata.html#TBlock object TBlock 54 +nim beforeRetNeeded cgendata.html#beforeRetNeeded TCProcFlag.beforeRetNeeded 64 +nim threadVarAccessed cgendata.html#threadVarAccessed TCProcFlag.threadVarAccessed 64 +nim hasCurFramePointer cgendata.html#hasCurFramePointer TCProcFlag.hasCurFramePointer 64 +nim noSafePoints cgendata.html#noSafePoints TCProcFlag.noSafePoints 64 +nim nimErrorFlagAccessed cgendata.html#nimErrorFlagAccessed TCProcFlag.nimErrorFlagAccessed 64 +nim nimErrorFlagDeclared cgendata.html#nimErrorFlagDeclared TCProcFlag.nimErrorFlagDeclared 64 +nim nimErrorFlagDisabled cgendata.html#nimErrorFlagDisabled TCProcFlag.nimErrorFlagDisabled 64 +nim TCProcFlag cgendata.html#TCProcFlag enum TCProcFlag 64 +nim TTypeSeq cgendata.html#TTypeSeq type TTypeSeq 102 +nim TypeCache cgendata.html#TypeCache type TypeCache 103 +nim TypeCacheWithOwner cgendata.html#TypeCacheWithOwner type TypeCacheWithOwner 104 +nim preventStackTrace cgendata.html#preventStackTrace CodegenFlag.preventStackTrace 106 +nim usesThreadVars cgendata.html#usesThreadVars CodegenFlag.usesThreadVars 106 +nim frameDeclared cgendata.html#frameDeclared CodegenFlag.frameDeclared 106 +nim isHeaderFile cgendata.html#isHeaderFile CodegenFlag.isHeaderFile 106 +nim includesStringh cgendata.html#includesStringh CodegenFlag.includesStringh 106 +nim objHasKidsValid cgendata.html#objHasKidsValid CodegenFlag.objHasKidsValid 106 +nim useAliveDataFromDce cgendata.html#useAliveDataFromDce CodegenFlag.useAliveDataFromDce 106 +nim CodegenFlag cgendata.html#CodegenFlag enum CodegenFlag 106 +nim BModuleList cgendata.html#BModuleList type BModuleList 117 +nim config cgendata.html#config.t,BModule template config(m: BModule): ConfigRef 177 +nim config cgendata.html#config.t,BProc template config(p: BProc): ConfigRef 178 +nim vccAndC cgendata.html#vccAndC.t,BProc template vccAndC(p: BProc): bool 179 +nim includeHeader cgendata.html#includeHeader,BModule,string proc includeHeader(this: BModule; header: string) 181 +nim s cgendata.html#s,BProc,TCProcSection proc s(p: BProc; s: TCProcSection): var Builder 185 +nim procSec cgendata.html#procSec,BProc,TCProcSection proc procSec(p: BProc; s: TCProcSection): var Builder 189 +nim initBlock cgendata.html#initBlock proc initBlock(): TBlock 193 +nim newProc cgendata.html#newProc,PSym,BModule proc newProc(prc: PSym; module: BModule): BProc 198 +nim newModuleList cgendata.html#newModuleList,ModuleGraph proc newModuleList(g: ModuleGraph): BModuleList 211 +nim cgenModules cgendata.html#cgenModules.i,BModuleList iterator cgenModules(g: BModuleList): BModule 215 +nimgrp config cgendata.html#config-templates-all template 177 diff --git a/compiler/cgmeth.html b/compiler/cgmeth.html new file mode 100644 index 0000000000000..cf332aeddc5af --- /dev/null +++ b/compiler/cgmeth.html @@ -0,0 +1,238 @@ + + + + + + + +cgmeth + + + + + + + + + + + + + + + + +
+
+

cgmeth

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module implements code generation for methods.

+ +
+

Procs

+
+
+
+
proc generateIfMethodDispatchers(g: ModuleGraph; idgen: IdGenerator) {.
+    ...raises: [Exception, KeyError, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genIfDispatcher(g: ModuleGraph; methods: seq[PSym]; relevantCols: IntSet;
+                     idgen: IdGenerator): PSym {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getDispatcher(s: PSym): PSym {....raises: [], tags: [], forbids: [].}
+
+ + can return nil if is has no dispatcher. + Source   +Edit   + +
+
+ +
+
+
+
proc methodCall(n: PNode; conf: ConfigRef): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc methodDef(g: ModuleGraph; idgen: IdGenerator; s: PSym) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc relevantCol(methods: seq[PSym]; col: int): bool {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sortBucket(a: var seq[PSym]; relevantCols: IntSet) {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/cgmeth.idx b/compiler/cgmeth.idx new file mode 100644 index 0000000000000..014a56c9938a0 --- /dev/null +++ b/compiler/cgmeth.idx @@ -0,0 +1,8 @@ +nimTitle cgmeth cgmeth.html module cgmeth 0 +nim getDispatcher cgmeth.html#getDispatcher,PSym proc getDispatcher(s: PSym): PSym 45 +nim methodCall cgmeth.html#methodCall,PNode,ConfigRef proc methodCall(n: PNode; conf: ConfigRef): PNode 53 +nim methodDef cgmeth.html#methodDef,ModuleGraph,IdGenerator,PSym proc methodDef(g: ModuleGraph; idgen: IdGenerator; s: PSym) 160 +nim relevantCol cgmeth.html#relevantCol,seq[PSym],int proc relevantCol(methods: seq[PSym]; col: int): bool 201 +nim sortBucket cgmeth.html#sortBucket,seq[PSym],IntSet proc sortBucket(a: var seq[PSym]; relevantCols: IntSet) 221 +nim genIfDispatcher cgmeth.html#genIfDispatcher,ModuleGraph,seq[PSym],IntSet,IdGenerator proc genIfDispatcher(g: ModuleGraph; methods: seq[PSym]; relevantCols: IntSet;\n idgen: IdGenerator): PSym 240 +nim generateIfMethodDispatchers cgmeth.html#generateIfMethodDispatchers,ModuleGraph,IdGenerator proc generateIfMethodDispatchers(g: ModuleGraph; idgen: IdGenerator) 299 diff --git a/compiler/closureiters.html b/compiler/closureiters.html new file mode 100644 index 0000000000000..6b04afe5ad98d --- /dev/null +++ b/compiler/closureiters.html @@ -0,0 +1,123 @@ + + + + + + + +closureiters + + + + + + + + + + + + + + + + +
+
+

closureiters

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc transformClosureIterator(g: ModuleGraph; idgen: IdGenerator; fn: PSym;
+                              n: PNode): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/closureiters.idx b/compiler/closureiters.idx new file mode 100644 index 0000000000000..d8b3607412d48 --- /dev/null +++ b/compiler/closureiters.idx @@ -0,0 +1,2 @@ +nimTitle closureiters closureiters.html module closureiters 0 +nim transformClosureIterator closureiters.html#transformClosureIterator,ModuleGraph,IdGenerator,PSym,PNode proc transformClosureIterator(g: ModuleGraph; idgen: IdGenerator; fn: PSym; n: PNode): PNode 1488 diff --git a/compiler/cmdlinehelper.html b/compiler/cmdlinehelper.html new file mode 100644 index 0000000000000..061af5f4115e3 --- /dev/null +++ b/compiler/cmdlinehelper.html @@ -0,0 +1,256 @@ + + + + + + + +cmdlinehelper + + + + + + + + + + + + + + + + +
+
+

cmdlinehelper

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Helpers for binaries that use compiler passes, e.g.: nim, nimsuggest

+ +
+

Types

+
+
+
NimProg = ref object
+  suggestMode*: bool
+  supportsStdinFile*: bool
+  processCmdLine*: proc (pass: TCmdLinePass; cmd: string; config: ConfigRef)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc addCmdPrefix(result: var string; kind: CmdLineKind) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initDefinesProg(self: NimProg; conf: ConfigRef; name: string) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc loadConfigsAndProcessCmdLine(self: NimProg; cache: IdentCache;
+                                  conf: ConfigRef; graph: ModuleGraph): bool {....raises: [
+    OSError, IOError, Exception, KeyError, ValueError, ERecoverableError,
+    EOFError, ESuggestDone], tags: [ReadIOEffect, ReadDirEffect, ReadEnvEffect,
+                                    RootEffect, WriteIOEffect, WriteEnvEffect,
+                                    WriteDirEffect, TimeEffect, ExecIOEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc loadConfigsAndRunMainCommand(self: NimProg; cache: IdentCache;
+                                  conf: ConfigRef; graph: ModuleGraph): bool {....raises: [
+    OSError, IOError, Exception, KeyError, ValueError, ERecoverableError,
+    EOFError, ESuggestDone], tags: [ReadIOEffect, ReadDirEffect, ReadEnvEffect,
+                                    RootEffect, WriteIOEffect, WriteEnvEffect,
+                                    WriteDirEffect, TimeEffect, ExecIOEffect],
+    forbids: [].}
+
+ + Alias for loadConfigsAndProcessCmdLine, here for backwards compatibility + Source   +Edit   + +
+
+ +
+
+
+
proc prependCurDir(f: AbsoluteFile): AbsoluteFile {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc processCmdLineAndProjectPath(self: NimProg; conf: ConfigRef) {.
+    ...raises: [Exception, OSError],
+    tags: [RootEffect, ReadEnvEffect, ReadIOEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/cmdlinehelper.idx b/compiler/cmdlinehelper.idx new file mode 100644 index 0000000000000..a4514d61bcbbc --- /dev/null +++ b/compiler/cmdlinehelper.idx @@ -0,0 +1,8 @@ +nimTitle cmdlinehelper cmdlinehelper.html module cmdlinehelper 0 +nim prependCurDir cmdlinehelper.html#prependCurDir,AbsoluteFile proc prependCurDir(f: AbsoluteFile): AbsoluteFile 18 +nim addCmdPrefix cmdlinehelper.html#addCmdPrefix,string,CmdLineKind proc addCmdPrefix(result: var string; kind: CmdLineKind) 25 +nim NimProg cmdlinehelper.html#NimProg type NimProg 33 +nim initDefinesProg cmdlinehelper.html#initDefinesProg,NimProg,ConfigRef,string proc initDefinesProg(self: NimProg; conf: ConfigRef; name: string) 38 +nim processCmdLineAndProjectPath cmdlinehelper.html#processCmdLineAndProjectPath,NimProg,ConfigRef proc processCmdLineAndProjectPath(self: NimProg; conf: ConfigRef) 42 +nim loadConfigsAndProcessCmdLine cmdlinehelper.html#loadConfigsAndProcessCmdLine,NimProg,IdentCache,ConfigRef,ModuleGraph proc loadConfigsAndProcessCmdLine(self: NimProg; cache: IdentCache; conf: ConfigRef;\n graph: ModuleGraph): bool 53 +nim loadConfigsAndRunMainCommand cmdlinehelper.html#loadConfigsAndRunMainCommand,NimProg,IdentCache,ConfigRef,ModuleGraph proc loadConfigsAndRunMainCommand(self: NimProg; cache: IdentCache; conf: ConfigRef;\n graph: ModuleGraph): bool 83 diff --git a/compiler/commands.html b/compiler/commands.html new file mode 100644 index 0000000000000..4a1b6f87ee880 --- /dev/null +++ b/compiler/commands.html @@ -0,0 +1,417 @@ + + + + + + + +commands + + + + + + + + + + + + + + + + +
+
+

commands

+
+ +
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
TCmdLinePass = enum
+  passCmd1, passCmd2, passPP
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc handleCmdInput(conf: ConfigRef) {....raises: [OSError],
+                                       tags: [ReadEnvEffect, ReadIOEffect],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc handleStdinInput(conf: ConfigRef) {....raises: [OSError],
+    tags: [ReadEnvEffect, ReadIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initOrcDefines(conf: ConfigRef) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc parseCommand(command: string): Command {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc processArgument(pass: TCmdLinePass; p: OptParser; argsCount: var int;
+                     config: ConfigRef): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc processCommand(switch: string; pass: TCmdLinePass; config: ConfigRef) {....raises: [
+    Exception, ValueError, KeyError, IOError, ERecoverableError, OSError,
+    EOFError], tags: [RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect,
+                      ReadEnvEffect, WriteDirEffect, WriteEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc processSpecificNote(arg: string; state: TSpecialWord; pass: TCmdLinePass;
+                         info: TLineInfo; orig: string; conf: ConfigRef) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc processSwitch(pass: TCmdLinePass; p: OptParser; config: ConfigRef) {....raises: [
+    Exception, ValueError, KeyError, IOError, ERecoverableError, OSError,
+    EOFError], tags: [RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect,
+                      ReadEnvEffect, WriteDirEffect, WriteEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc processSwitch(switch, arg: string; pass: TCmdLinePass; info: TLineInfo;
+                   conf: ConfigRef) {....raises: [Exception, ValueError, KeyError,
+    IOError, ERecoverableError, OSError, EOFError, Exception, ValueError,
+    KeyError, IOError, ERecoverableError, Exception, ValueError, KeyError,
+    IOError, ERecoverableError], tags: [RootEffect, ReadDirEffect,
+                                        WriteIOEffect, ReadIOEffect,
+                                        ReadEnvEffect, WriteDirEffect,
+                                        WriteEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setCmd(conf: ConfigRef; cmd: Command) {....raises: [], tags: [], forbids: [].}
+
+ + sets cmd, backend so subsequent flags can query it (e.g. so --gc:arc can be ignored for backendJs) + Source   +Edit   + +
+
+ +
+
+
+
proc setCommandEarly(conf: ConfigRef; command: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc testCompileOption(conf: ConfigRef; switch: string; info: TLineInfo): bool {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc testCompileOptionArg(conf: ConfigRef; switch, arg: string; info: TLineInfo): bool {....raises: [
+    Exception, ValueError, KeyError, IOError, ERecoverableError, Exception,
+    ValueError, KeyError, IOError, ERecoverableError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc unregisterArcOrc(conf: ConfigRef) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc writeCommandLineUsage(conf: ConfigRef) {.
+    ...raises: [Exception, IOError, ValueError], tags: [RootEffect, WriteIOEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/commands.idx b/compiler/commands.idx new file mode 100644 index 0000000000000..d83de25627f80 --- /dev/null +++ b/compiler/commands.idx @@ -0,0 +1,21 @@ +nimTitle commands commands.html module commands 0 +nim passCmd1 commands.html#passCmd1 TCmdLinePass.passCmd1 44 +nim passCmd2 commands.html#passCmd2 TCmdLinePass.passCmd2 44 +nim passPP commands.html#passPP TCmdLinePass.passPP 44 +nim TCmdLinePass commands.html#TCmdLinePass enum TCmdLinePass 44 +nim writeCommandLineUsage commands.html#writeCommandLineUsage,ConfigRef proc writeCommandLineUsage(conf: ConfigRef) 110 +nim processSpecificNote commands.html#processSpecificNote,string,TSpecialWord,TCmdLinePass,TLineInfo,string,ConfigRef proc processSpecificNote(arg: string; state: TSpecialWord; pass: TCmdLinePass;\n info: TLineInfo; orig: string; conf: ConfigRef) 185 +nim testCompileOptionArg commands.html#testCompileOptionArg,ConfigRef,string,string,TLineInfo proc testCompileOptionArg(conf: ConfigRef; switch, arg: string; info: TLineInfo): bool 259 +nim testCompileOption commands.html#testCompileOption,ConfigRef,string,TLineInfo proc testCompileOption(conf: ConfigRef; switch: string; info: TLineInfo): bool 317 +nim handleStdinInput commands.html#handleStdinInput,ConfigRef proc handleStdinInput(conf: ConfigRef) 460 +nim handleCmdInput commands.html#handleCmdInput,ConfigRef proc handleCmdInput(conf: ConfigRef) 465 +nim parseCommand commands.html#parseCommand,string proc parseCommand(command: string): Command 469 +nim setCmd commands.html#setCmd,ConfigRef,Command proc setCmd(conf: ConfigRef; cmd: Command) 500 +nim setCommandEarly commands.html#setCommandEarly,ConfigRef,string proc setCommandEarly(conf: ConfigRef; command: string) 511 +nim initOrcDefines commands.html#initOrcDefines,ConfigRef proc initOrcDefines(conf: ConfigRef) 538 +nim unregisterArcOrc commands.html#unregisterArcOrc,ConfigRef proc unregisterArcOrc(conf: ConfigRef) 559 +nim processSwitch commands.html#processSwitch,string,string,TCmdLinePass,TLineInfo,ConfigRef proc processSwitch(switch, arg: string; pass: TCmdLinePass; info: TLineInfo;\n conf: ConfigRef) 628 +nim processCommand commands.html#processCommand,string,TCmdLinePass,ConfigRef proc processCommand(switch: string; pass: TCmdLinePass; config: ConfigRef) 1154 +nim processSwitch commands.html#processSwitch,TCmdLinePass,OptParser,ConfigRef proc processSwitch(pass: TCmdLinePass; p: OptParser; config: ConfigRef) 1160 +nim processArgument commands.html#processArgument,TCmdLinePass,OptParser,int,ConfigRef proc processArgument(pass: TCmdLinePass; p: OptParser; argsCount: var int;\n config: ConfigRef): bool 1171 +nimgrp processswitch commands.html#processSwitch-procs-all proc 628 diff --git a/compiler/concepts.html b/compiler/concepts.html new file mode 100644 index 0000000000000..028a982145e02 --- /dev/null +++ b/compiler/concepts.html @@ -0,0 +1,147 @@ + + + + + + + +concepts + + + + + + + + + + + + + + + + +
+
+

concepts

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

New styled concepts for Nim. See https://github.com/nim-lang/RFCs/issues/168 for details. Note this is a first implementation and only the "Concept matching" section has been implemented. +

Code dealing with Concept declarations

+

Concept matching

+ +
+

Procs

+
+
+
+
proc conceptMatch(c: PContext; concpt, arg: PType; bindings: var LayeredIdTable;
+                  invocation: PType): bool {....raises: [KeyError, Exception],
+    tags: [ReadDirEffect, RootEffect], forbids: [].}
+
+ + Entry point from sigmatch. 'concpt' is the concept we try to match (here still a PType but we extract its AST via 'concpt.n.lastSon'). 'arg' is the type that might fulfill the concept's requirements. If so, we return true and fill the 'bindings' with pairs of (typeVar, instance) pairs. ('typeVar' is usually simply written as a generic 'T'.) 'invocation' can be nil for atomic concepts. For non-atomic concepts, it contains the C[S, T] parent type that we look for. We need this because we need to store bindings for 'S' and 'T' inside 'bindings' on a successful match. It is very important that we do not add any bindings at all on an unsuccessful match! + Source   +Edit   + +
+
+ +
+
+
+
proc semConceptDeclaration(c: PContext; n: PNode): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + Semantic checking for the concept declaration. Runs when we process the concept itself, not its matching process. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/concepts.idx b/compiler/concepts.idx new file mode 100644 index 0000000000000..265d27f271ac2 --- /dev/null +++ b/compiler/concepts.idx @@ -0,0 +1,5 @@ +nimTitle concepts concepts.html module concepts 0 +nim semConceptDeclaration concepts.html#semConceptDeclaration,PContext,PNode proc semConceptDeclaration(c: PContext; n: PNode): PNode 58 +nim conceptMatch concepts.html#conceptMatch,PContext,PType,PType,LayeredIdTableObj,PType proc conceptMatch(c: PContext; concpt, arg: PType; bindings: var LayeredIdTable;\n invocation: PType): bool 321 +heading Code dealing with Concept declarations concepts.html#code-dealing-with-concept-declarations Code dealing with Concept declarations 0 +heading Concept matching concepts.html#concept-matching Concept matching 0 diff --git a/compiler/condsyms.html b/compiler/condsyms.html new file mode 100644 index 0000000000000..5fb65fd1ef885 --- /dev/null +++ b/compiler/condsyms.html @@ -0,0 +1,205 @@ + + + + + + + +condsyms + + + + + + + + + + + + + + + + +
+
+

condsyms

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc countDefinedSymbols(symbols: StringTableRef): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc defineSymbol(symbols: StringTableRef; symbol: string;
+                  value: string = "true") {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initDefines(symbols: StringTableRef) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc undefSymbol(symbols: StringTableRef; symbol: string) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator definedSymbolNames(symbols: StringTableRef): string {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/condsyms.idx b/compiler/condsyms.idx new file mode 100644 index 0000000000000..823f35ca09521 --- /dev/null +++ b/compiler/condsyms.idx @@ -0,0 +1,6 @@ +nimTitle condsyms condsyms.html module condsyms 0 +nim defineSymbol condsyms.html#defineSymbol,StringTableRef,string,string proc defineSymbol(symbols: StringTableRef; symbol: string; value: string = "true") 18 +nim undefSymbol condsyms.html#undefSymbol,StringTableRef,string proc undefSymbol(symbols: StringTableRef; symbol: string) 21 +nim definedSymbolNames condsyms.html#definedSymbolNames.i,StringTableRef iterator definedSymbolNames(symbols: StringTableRef): string 27 +nim countDefinedSymbols condsyms.html#countDefinedSymbols,StringTableRef proc countDefinedSymbols(symbols: StringTableRef): int 31 +nim initDefines condsyms.html#initDefines,StringTableRef proc initDefines(symbols: StringTableRef) 34 diff --git a/compiler/depends.html b/compiler/depends.html new file mode 100644 index 0000000000000..6b71954939f60 --- /dev/null +++ b/compiler/depends.html @@ -0,0 +1,156 @@ + + + + + + + +depends + + + + + + + + + + + + + + + + +
+
+

depends

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc addDotDependency(c: PPassContext; n: PNode): PNode {....raises: [],
+    tags: [ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc generateDot(graph: ModuleGraph; project: AbsoluteFile) {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setupDependPass(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/depends.idx b/compiler/depends.idx new file mode 100644 index 0000000000000..2aa8ee88eeeba --- /dev/null +++ b/compiler/depends.idx @@ -0,0 +1,4 @@ +nimTitle depends depends.html module depends 0 +nim addDotDependency depends.html#addDotDependency,PPassContext,PNode proc addDotDependency(c: PPassContext; n: PNode): PNode 86 +nim generateDot depends.html#generateDot,ModuleGraph,AbsoluteFile proc generateDot(graph: ModuleGraph; project: AbsoluteFile) 101 +nim setupDependPass depends.html#setupDependPass,ModuleGraph,PSym,IdGenerator proc setupDependPass(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext 107 diff --git a/compiler/dfa.html b/compiler/dfa.html new file mode 100644 index 0000000000000..29bc702fa00af --- /dev/null +++ b/compiler/dfa.html @@ -0,0 +1,203 @@ + + + + + + + +dfa + + + + + + + + + + + + + + + + +
+
+

dfa

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Data flow analysis for Nim. We transform the AST into a linear list of instructions first to make this easier to handle: There are only 3 different branching instructions: 'goto X' is an unconditional goto, 'fork X' is a conditional goto (either the next instruction or 'X' can be taken), 'loop X' is the only jump that jumps back.

+

Exhaustive case statements are translated so that the last branch is transformed into an 'else' branch. return and break are all covered by 'goto'.

+

The data structures and algorithms used here are inspired by "A Graph–Free Approach to Data–Flow Analysis" by Markus Mohnen. https://link.springer.com/content/pdf/10.1007/3-540-45937-5_6.pdf

+

+ +
+

Types

+
+
+
ControlFlowGraph = seq[Instr]
+
+ + + Source   +Edit   + +
+
+
+
Instr = object
+  case kind*: InstrKind
+  of goto, fork, loop:
+    dest*: int
+  of def, use:
+    n*: PNode
+
+ + + Source   +Edit   + +
+
+
+
InstrKind = enum
+  goto, loop, fork, def, use
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc constructCfg(s: PSym; body: PNode; root: PSym): ControlFlowGraph {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + constructs a control flow graph for body. + Source   +Edit   + +
+
+ +
+
+
+
proc echoCfg(c: ControlFlowGraph; start = 0; last = -1) {....deprecated,
+    raises: [Exception, KeyError], tags: [RootEffect], forbids: [].}
+
+
+ Deprecated +
+ + echos the ControlFlowGraph for debugging purposes. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/dfa.idx b/compiler/dfa.idx new file mode 100644 index 0000000000000..d703382741a48 --- /dev/null +++ b/compiler/dfa.idx @@ -0,0 +1,11 @@ +nimTitle dfa dfa.html module dfa 0 +nim goto dfa.html#goto InstrKind.goto 33 +nim loop dfa.html#loop InstrKind.loop 33 +nim fork dfa.html#fork InstrKind.fork 33 +nim def dfa.html#def InstrKind.def 33 +nim use dfa.html#use InstrKind.use 33 +nim InstrKind dfa.html#InstrKind enum InstrKind 33 +nim Instr dfa.html#Instr object Instr 35 +nim ControlFlowGraph dfa.html#ControlFlowGraph type ControlFlowGraph 41 +nim echoCfg dfa.html#echoCfg,ControlFlowGraph,int,int proc echoCfg(c: ControlFlowGraph; start = 0; last = -1) 88 +nim constructCfg dfa.html#constructCfg,PSym,PNode,PSym proc constructCfg(s: PSym; body: PNode; root: PSym): ControlFlowGraph 479 diff --git a/compiler/docgen.html b/compiler/docgen.html new file mode 100644 index 0000000000000..c658b5bc89b25 --- /dev/null +++ b/compiler/docgen.html @@ -0,0 +1,495 @@ + + + + + + + +docgen + + + + + + + + + + + + + + + + +
+
+

docgen

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This is the Nim documentation generator. Cross-references are generated by knowing how the anchors are going to be named.

For corresponding users' documentation see Nim DocGen Tools Guide.

+

+ +
+

Types

+
+
+
PDoc = ref TDocumentor
+
+ + Alias to type less. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc commandBuildIndex(conf: ConfigRef; dir: string; outFile = RelativeFile"") {....raises: [
+    OSError, IOError, ValueError, Exception, Exception, ValueError, KeyError,
+    IOError, ERecoverableError], tags: [ReadDirEffect, ReadIOEffect, RootEffect,
+                                        ReadEnvEffect, TimeEffect, WriteIOEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc commandBuildIndexJson(conf: ConfigRef; dir: string;
+                           outFile = RelativeFile"") {....raises: [OSError,
+    IOError, ValueError, Exception, ValueError, KeyError, IOError,
+    ERecoverableError], tags: [ReadDirEffect, ReadIOEffect, WriteIOEffect,
+                               RootEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc commandDoc(cache: IdentCache; conf: ConfigRef) {....raises: [OSError,
+    Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    WriteDirEffect, ExecIOEffect, TimeEffect], forbids: [].}
+
+ + implementation of deprecated doc0 command (without semantic checking) + Source   +Edit   + +
+
+ +
+
+
+
proc commandJson(cache: IdentCache; conf: ConfigRef) {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, OSError, Exception,
+    ValueError, KeyError, IOError, ERecoverableError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect, WriteDirEffect],
+    forbids: [].}
+
+ + implementation of a deprecated jsondoc0 command + Source   +Edit   + +
+
+ +
+
+
+
proc commandRst2Html(cache: IdentCache; conf: ConfigRef; preferMarkdown = false) {....raises: [
+    OSError, IOError, Exception, KeyError, ValueError, ERecoverableError], tags: [
+    WriteDirEffect, ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect,
+    ReadEnvEffect, ExecIOEffect, TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc commandRst2TeX(cache: IdentCache; conf: ConfigRef; preferMarkdown = false) {....raises: [
+    OSError, IOError, Exception, KeyError, ValueError, ERecoverableError], tags: [
+    WriteDirEffect, ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect,
+    ReadEnvEffect, ExecIOEffect, TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc commandTags(cache: IdentCache; conf: ConfigRef) {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, OSError, Exception,
+    ValueError, KeyError, IOError, ERecoverableError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect, WriteDirEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc documentRaises(cache: IdentCache; n: PNode) {.
+    ...raises: [Exception, KeyError, ValueError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc finishGenerateDoc(d: var PDoc) {....raises: [Exception, ValueError, KeyError], tags: [
+    RootEffect, ReadIOEffect, ReadDirEffect, ReadEnvEffect], forbids: [].}
+
+ + Perform 2nd RST pass for resolution of links/footnotes/headings... + Source   +Edit   + +
+
+ +
+
+
+
proc generateDoc(d: PDoc; n, orig: PNode; config: ConfigRef;
+                 docFlags: DocFlags = kDefault) {....raises: [ValueError,
+    Exception, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    WriteDirEffect], forbids: [].}
+
+ + Goes through nim nodes recursively and collects doc comments. Main function for doc command, which is implemented in docgen2.nim. + Source   +Edit   + +
+
+ +
+
+
+
proc generateIndex(d: PDoc) {....raises: [OSError, Exception, KeyError, ValueError,
+                                       IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    WriteDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc generateJson(d: PDoc; n: PNode; config: ConfigRef;
+                  includeComments: bool = true) {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    WriteDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc generateTags(d: PDoc; n: PNode; r: var string) {.
+    ...raises: [KeyError, Exception, ValueError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc handleDocOutputOptions(conf: ConfigRef) {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newDocumentor(filename: AbsoluteFile; cache: IdentCache; conf: ConfigRef;
+                   outExt: string = HtmlExt; module: PSym = nil;
+                   standaloneDoc = false; preferMarkdown = true; hasToc = true): PDoc {....raises: [
+    OSError, IOError, Exception, KeyError, ValueError, ERecoverableError], tags: [
+    WriteDirEffect, ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect,
+    ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc presentationPath(conf: ConfigRef; file: AbsoluteFile): RelativeFile {....raises: [
+    Exception, KeyError, ValueError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + returns a relative file that will be appended to outDir + Source   +Edit   + +
+
+ +
+
+
+
proc writeOutput(d: PDoc; useWarning = false; groupedToc = false) {....raises: [
+    Exception, OSError, KeyError, ValueError, IOError, ERecoverableError,
+    Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    WriteDirEffect, ExecIOEffect, TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc writeOutputJson(d: PDoc; useWarning = false) {....raises: [OSError,
+    ValueError, IOError, Exception, KeyError, ERecoverableError], tags: [
+    ReadEnvEffect, ReadIOEffect, WriteIOEffect, ReadDirEffect, ExecIOEffect,
+    RootEffect, WriteDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/docgen.idx b/compiler/docgen.idx new file mode 100644 index 0000000000000..65f1a74582cbc --- /dev/null +++ b/compiler/docgen.idx @@ -0,0 +1,20 @@ +nimTitle docgen docgen.html module docgen 0 +nim PDoc docgen.html#PDoc type PDoc 111 +nim presentationPath docgen.html#presentationPath,ConfigRef,AbsoluteFile proc presentationPath(conf: ConfigRef; file: AbsoluteFile): RelativeFile 178 +nim newDocumentor docgen.html#newDocumentor,AbsoluteFile,IdentCache,ConfigRef,string,PSym proc newDocumentor(filename: AbsoluteFile; cache: IdentCache; conf: ConfigRef;\n outExt: string = HtmlExt; module: PSym = nil;\n standaloneDoc = false; preferMarkdown = true; hasToc = true): PDoc 324 +nim documentRaises docgen.html#documentRaises,IdentCache,PNode proc documentRaises(cache: IdentCache; n: PNode) 1345 +nim generateDoc docgen.html#generateDoc,PDoc,PNode,PNode,ConfigRef,DocFlags proc generateDoc(d: PDoc; n, orig: PNode; config: ConfigRef;\n docFlags: DocFlags = kDefault) 1365 +nim finishGenerateDoc docgen.html#finishGenerateDoc,PDoc proc finishGenerateDoc(d: var PDoc) 1450 +nim generateJson docgen.html#generateJson,PDoc,PNode,ConfigRef,bool proc generateJson(d: PDoc; n: PNode; config: ConfigRef; includeComments: bool = true) 1566 +nim generateTags docgen.html#generateTags,PDoc,PNode,string proc generateTags(d: PDoc; n: PNode; r: var string) 1611 +nim generateIndex docgen.html#generateIndex,PDoc proc generateIndex(d: PDoc) 1763 +nim writeOutput docgen.html#writeOutput,PDoc proc writeOutput(d: PDoc; useWarning = false; groupedToc = false) 1775 +nim writeOutputJson docgen.html#writeOutputJson,PDoc proc writeOutputJson(d: PDoc; useWarning = false) 1806 +nim handleDocOutputOptions docgen.html#handleDocOutputOptions,ConfigRef proc handleDocOutputOptions(conf: ConfigRef) 1830 +nim commandDoc docgen.html#commandDoc,IdentCache,ConfigRef proc commandDoc(cache: IdentCache; conf: ConfigRef) 1837 +nim commandRst2Html docgen.html#commandRst2Html,IdentCache,ConfigRef proc commandRst2Html(cache: IdentCache; conf: ConfigRef; preferMarkdown = false) 1865 +nim commandRst2TeX docgen.html#commandRst2TeX,IdentCache,ConfigRef proc commandRst2TeX(cache: IdentCache; conf: ConfigRef; preferMarkdown = false) 1869 +nim commandJson docgen.html#commandJson,IdentCache,ConfigRef proc commandJson(cache: IdentCache; conf: ConfigRef) 1873 +nim commandTags docgen.html#commandTags,IdentCache,ConfigRef proc commandTags(cache: IdentCache; conf: ConfigRef) 1897 +nim commandBuildIndex docgen.html#commandBuildIndex,ConfigRef,string proc commandBuildIndex(conf: ConfigRef; dir: string; outFile = RelativeFile"") 1919 +nim commandBuildIndexJson docgen.html#commandBuildIndexJson,ConfigRef,string proc commandBuildIndexJson(conf: ConfigRef; dir: string; outFile = RelativeFile"") 1942 diff --git a/compiler/docgen2.html b/compiler/docgen2.html new file mode 100644 index 0000000000000..c9180e1cbb750 --- /dev/null +++ b/compiler/docgen2.html @@ -0,0 +1,244 @@ + + + + + + + +docgen2 + + + + + + + + + + + + + + + + +
+
+

docgen2

+
+ +
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc closeDoc(graph: ModuleGraph; p: PPassContext; n: PNode): PNode {....raises: [
+    Exception, ValueError, KeyError, OSError, IOError, ERecoverableError,
+    OSError, Exception, KeyError, ValueError, ERecoverableError], tags: [
+    RootEffect, ReadIOEffect, ReadDirEffect, ReadEnvEffect, WriteIOEffect,
+    WriteDirEffect, ExecIOEffect, TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc closeJson(graph: ModuleGraph; p: PPassContext; n: PNode): PNode {....raises: [
+    Exception, ValueError, KeyError, OSError, IOError, ERecoverableError,
+    OSError, Exception, KeyError, ValueError, ERecoverableError], tags: [
+    RootEffect, ReadIOEffect, ReadDirEffect, ReadEnvEffect, WriteIOEffect,
+    ExecIOEffect, WriteDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc openHtml(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext {....raises: [
+    OSError, IOError, Exception, KeyError, ValueError, ERecoverableError], tags: [
+    WriteDirEffect, ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect,
+    ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc openJson(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext {....raises: [
+    OSError, IOError, Exception, KeyError, ValueError, ERecoverableError], tags: [
+    WriteDirEffect, ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect,
+    ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc openTex(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext {....raises: [
+    OSError, IOError, Exception, KeyError, ValueError, ERecoverableError], tags: [
+    WriteDirEffect, ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect,
+    ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc processNode(c: PPassContext; n: PNode): PNode {....raises: [ValueError,
+    Exception, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    WriteDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc processNodeJson(c: PPassContext; n: PNode): PNode {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    WriteDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/docgen2.idx b/compiler/docgen2.idx new file mode 100644 index 0000000000000..c0fa63aef55ff --- /dev/null +++ b/compiler/docgen2.idx @@ -0,0 +1,8 @@ +nimTitle docgen2 docgen2.html module docgen2 0 +nim closeDoc docgen2.html#closeDoc,ModuleGraph,PPassContext,PNode proc closeDoc(graph: ModuleGraph; p: PPassContext; n: PNode): PNode 41 +nim closeJson docgen2.html#closeJson,ModuleGraph,PPassContext,PNode proc closeJson(graph: ModuleGraph; p: PPassContext; n: PNode): PNode 46 +nim processNode docgen2.html#processNode,PPassContext,PNode proc processNode(c: PPassContext; n: PNode): PNode 51 +nim processNodeJson docgen2.html#processNodeJson,PPassContext,PNode proc processNodeJson(c: PPassContext; n: PNode): PNode 57 +nim openHtml docgen2.html#openHtml,ModuleGraph,PSym,IdGenerator proc openHtml(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext 73 +nim openTex docgen2.html#openTex,ModuleGraph,PSym,IdGenerator proc openTex(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext 76 +nim openJson docgen2.html#openJson,ModuleGraph,PSym,IdGenerator proc openJson(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext 79 diff --git a/compiler/dochack.js b/compiler/dochack.js new file mode 100644 index 0000000000000..d2a5732b97db8 --- /dev/null +++ b/compiler/dochack.js @@ -0,0 +1,1619 @@ +/* Generated by the Nim Compiler v2.2.1 */ +var framePtr = null; +var excHandler = 0; +var lastJSError = null; +var NTI33554466 = {size: 0,kind: 1,base: null,node: null,finalizer: null}; +var NTI687865870 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI33554435 = {size: 0,kind: 31,base: null,node: null,finalizer: null}; +var NTI922746960 = {size: 0,kind: 31,base: null,node: null,finalizer: null}; +var NTI922746967 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI134217745 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217749 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217751 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555167 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555175 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554449 = {size: 0,kind: 28,base: null,node: null,finalizer: null}; +var NTI33554450 = {size: 0,kind: 29,base: null,node: null,finalizer: null}; +var NTI33555174 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33555171 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555172 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217741 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217743 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NNI134217743 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217743.node = NNI134217743; +var NNI134217741 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217741.node = NNI134217741; +var NNI33555172 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555172.node = NNI33555172; +NTI33555174.base = NTI33555171; +NTI33555175.base = NTI33555171; +var NNI33555171 = {kind: 2, len: 5, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "parent", len: 0, typ: NTI33555174, name: "parent", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}, +{kind: 1, offset: "message", len: 0, typ: NTI33554449, name: "msg", sons: null}, +{kind: 1, offset: "trace", len: 0, typ: NTI33554449, name: "trace", sons: null}, +{kind: 1, offset: "up", len: 0, typ: NTI33555175, name: "up", sons: null}]}; +NTI33555171.node = NNI33555171; +var NNI33555167 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555167.node = NNI33555167; +NTI33555171.base = NTI33555167; +NTI33555172.base = NTI33555171; +NTI134217741.base = NTI33555172; +NTI134217743.base = NTI134217741; +var NNI134217751 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217751.node = NNI134217751; +NTI134217751.base = NTI33555172; +var NNI134217749 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217749.node = NNI134217749; +NTI134217749.base = NTI33555172; +var NNI134217745 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217745.node = NNI134217745; +NTI134217745.base = NTI33555172; +var NNI922746967 = {kind: 2, len: 2, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "a", len: 0, typ: NTI922746960, name: "a", sons: null}, +{kind: 1, offset: "b", len: 0, typ: NTI33554435, name: "b", sons: null}]}; +NTI922746967.node = NNI922746967; +var NNI687865870 = {kind: 2, len: 2, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "Field0", len: 0, typ: NTI33554435, name: "Field0", sons: null}, +{kind: 1, offset: "Field1", len: 0, typ: NTI33554466, name: "Field1", sons: null}]}; +NTI687865870.node = NNI687865870; + +function mnewString(len_p0) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; i++) {result[i] = 0;} + return result; + + + +} + +function toJSStr(s_p0) { + var result_33556910 = null; + + var res_33556964 = newSeq__system_u2507((s_p0).length); + var i_33556965 = 0; + var j_33556966 = 0; + Label1: { + Label2: while (true) { + if (!(i_33556965 < (s_p0).length)) break Label2; + var c_33556967 = s_p0[i_33556965]; + if ((c_33556967 < 128)) { + res_33556964[j_33556966] = String.fromCharCode(c_33556967); + i_33556965 += 1; + } + else { + var helper_33556993 = newSeq__system_u2507(0); + Label3: { + Label4: while (true) { + if (!true) break Label4; + var code_33556994 = c_33556967.toString(16); + if ((((code_33556994) == null ? 0 : (code_33556994).length) == 1)) { + helper_33556993.push("%0");; + } + else { + helper_33556993.push("%");; + } + + helper_33556993.push(code_33556994);; + i_33556965 += 1; + if ((((s_p0).length <= i_33556965) || (s_p0[i_33556965] < 128))) { + break Label3; + } + + c_33556967 = s_p0[i_33556965]; + } + }; +++excHandler; + try { + res_33556964[j_33556966] = decodeURIComponent(helper_33556993.join("")); +--excHandler; +} catch (EXCEPTION) { + var prevJSError = lastJSError; + lastJSError = EXCEPTION; + --excHandler; + res_33556964[j_33556966] = helper_33556993.join(""); + lastJSError = prevJSError; + } finally { + } + } + + j_33556966 += 1; + } + }; + if (res_33556964.length < j_33556966) { for (var i = res_33556964.length ; i < j_33556966 ; ++i) res_33556964.push(null); } + else { res_33556964.length = j_33556966; }; + result_33556910 = res_33556964.join(""); + + return result_33556910; + +} + +function raiseException(e_p0, ename_p1) { + e_p0.name = ename_p1; + if ((excHandler == 0)) { + unhandledException(e_p0); + } + + throw e_p0; + + +} + +function addInt(a_p0, b_p1) { + var result = a_p0 + b_p1; + checkOverflowInt(result); + return result; + + + +} + +function chckRange(i_p0, a_p1, b_p2) { + var result_33557361 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557361 = i_p0; + break BeforeRet; + } + else { + raiseRangeError(); + } + + }; + + return result_33557361; + +} + +function setConstr() { + var result = {}; + for (var i = 0; i < arguments.length; ++i) { + var x = arguments[i]; + if (typeof(x) == "object") { + for (var j = x[0]; j <= x[1]; ++j) { + result[j] = true; + } + } else { + result[x] = true; + } + } + return result; + + + +} +var ConstSet1 = setConstr(17, 16, 4, 18, 27, 19, 23, 22, 21); + +function nimCopy(dest_p0, src_p1, ti_p2) { + var result_33557321 = null; + + switch (ti_p2.kind) { + case 21: + case 22: + case 23: + case 5: + if (!(isFatPointer__system_u2869(ti_p2))) { + result_33557321 = src_p1; + } + else { + result_33557321 = [src_p1[0], src_p1[1]]; + } + + break; + case 19: + if (dest_p0 === null || dest_p0 === undefined) { + dest_p0 = {}; + } + else { + for (var key in dest_p0) { delete dest_p0[key]; } + } + for (var key in src_p1) { dest_p0[key] = src_p1[key]; } + result_33557321 = dest_p0; + + break; + case 18: + case 17: + if (!((ti_p2.base == null))) { + result_33557321 = nimCopy(dest_p0, src_p1, ti_p2.base); + } + else { + if ((ti_p2.kind == 17)) { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {m_type: ti_p2} : dest_p0; + } + else { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {} : dest_p0; + } + } + nimCopyAux(result_33557321, src_p1, ti_p2.node); + break; + case 4: + case 16: + if(ArrayBuffer.isView(src_p1)) { + if(dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new src_p1.constructor(src_p1); + } else { + dest_p0.set(src_p1, 0); + } + result_33557321 = dest_p0; + } else { + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + } + + break; + case 24: + case 27: + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + + break; + case 28: + if (src_p1 !== null) { + result_33557321 = src_p1.slice(0); + } + + break; + default: + result_33557321 = src_p1; + break; + } + + return result_33557321; + +} + +function chckIndx(i_p0, a_p1, b_p2) { + var result_33557356 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557356 = i_p0; + break BeforeRet; + } + else { + raiseIndexError(i_p0, a_p1, b_p2); + } + + }; + + return result_33557356; + +} + +function makeNimstrLit(c_p0) { + var result = []; + for (var i = 0; i < c_p0.length; ++i) { + result[i] = c_p0.charCodeAt(i); + } + return result; + + + +} + +function subInt(a_p0, b_p1) { + var result = a_p0 - b_p1; + checkOverflowInt(result); + return result; + + + +} + +function cstrToNimstr(c_p0) { + var ln = c_p0.length; + var result = new Array(ln); + var r = 0; + for (var i = 0; i < ln; ++i) { + var ch = c_p0.charCodeAt(i); + + if (ch < 128) { + result[r] = ch; + } + else { + if (ch < 2048) { + result[r] = (ch >> 6) | 192; + } + else { + if (ch < 55296 || ch >= 57344) { + result[r] = (ch >> 12) | 224; + } + else { + ++i; + ch = 65536 + (((ch & 1023) << 10) | (c_p0.charCodeAt(i) & 1023)); + result[r] = (ch >> 18) | 240; + ++r; + result[r] = ((ch >> 12) & 63) | 128; + } + ++r; + result[r] = ((ch >> 6) & 63) | 128; + } + ++r; + result[r] = (ch & 63) | 128; + } + ++r; + } + return result; + + + +} +var ConstSet2 = setConstr([65, 90]); +var ConstSet3 = setConstr(95, 32, 46); +var ConstSet4 = setConstr(95, 32, 46); + +function mulInt(a_p0, b_p1) { + var result = a_p0 * b_p1; + checkOverflowInt(result); + return result; + + + +} +var ConstSet5 = setConstr([97, 122]); +var ConstSet6 = setConstr([65, 90], [97, 122]); +var ConstSet7 = setConstr([97, 122]); +var ConstSet8 = setConstr([65, 90]); +var ConstSet9 = setConstr([65, 90], [97, 122]); + +function nimMax(a_p0, b_p1) { + var Temporary1; + + var result_33557148 = 0; + + BeforeRet: { + if ((b_p1 <= a_p0)) { + Temporary1 = a_p0; + } + else { + Temporary1 = b_p1; + } + + result_33557148 = Temporary1; + break BeforeRet; + }; + + return result_33557148; + +} + +function nimMin(a_p0, b_p1) { + var Temporary1; + + var result_33557144 = 0; + + BeforeRet: { + if ((a_p0 <= b_p1)) { + Temporary1 = a_p0; + } + else { + Temporary1 = b_p1; + } + + result_33557144 = Temporary1; + break BeforeRet; + }; + + return result_33557144; + +} + +function addChar(x_p0, c_p1) { + x_p0.push(c_p1); + + +} +var objectID_1140850866 = [0]; + +function setTheme(theme_p0) { + document.documentElement.setAttribute("data-theme", theme_p0); + window.localStorage.setItem("theme", theme_p0); + + +} + +function add__system_u1942(x_p0, x_p0_Idx, y_p1) { + if (x_p0[x_p0_Idx] === null) { x_p0[x_p0_Idx] = []; } + var off = x_p0[x_p0_Idx].length; + x_p0[x_p0_Idx].length += y_p1.length; + for (var i = 0; i < y_p1.length; ++i) { + x_p0[x_p0_Idx][off+i] = y_p1.charCodeAt(i); + } + + + +} + +function newSeq__system_u2507(len_p0) { + var result_33556943 = []; + + result_33556943 = new Array(len_p0); for (var i = 0 ; i < len_p0 ; ++i) { result_33556943[i] = null; } + return result_33556943; + +} + +function unhandledException(e_p0) { + var buf_33556658 = [[]]; + if (!(((e_p0.message).length == 0))) { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32]);; + buf_33556658[0].push.apply(buf_33556658[0], e_p0.message);; + } + else { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110]);; + } + + buf_33556658[0].push.apply(buf_33556658[0], [32,91]);; + add__system_u1942(buf_33556658, 0, e_p0.name); + buf_33556658[0].push.apply(buf_33556658[0], [93,10]);; + var cbuf_33556659 = toJSStr(buf_33556658[0]); + if (typeof(Error) !== "undefined") { + throw new Error(cbuf_33556659); + } + else { + throw cbuf_33556659; + } + + + +} + +function raiseOverflow() { + raiseException({message: [111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119], parent: null, m_type: NTI134217743, name: null, trace: [], up: null}, "OverflowDefect"); + + +} + +function checkOverflowInt(a_p0) { + if (a_p0 > 2147483647 || a_p0 < -2147483648) raiseOverflow(); + + + +} + +function raiseRangeError() { + raiseException({message: [118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101], parent: null, m_type: NTI134217751, name: null, trace: [], up: null}, "RangeDefect"); + + +} + +function addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, start_p2, n_p3) { + var Temporary1; + + var old_301990096 = (result_p0[result_p0_Idx]).length; + if (result_p0[result_p0_Idx].length < (Temporary1 = chckRange(addInt(old_301990096, n_p3), 0, 2147483647), Temporary1)) { for (var i = result_p0[result_p0_Idx].length; i < Temporary1; ++i) result_p0[result_p0_Idx].push(0); } + else {result_p0[result_p0_Idx].length = Temporary1; }; + Label2: { + var iHEX60gensym4_301990110 = 0; + var i_536872113 = 0; + Label3: { + Label4: while (true) { + if (!(i_536872113 < n_p3)) break Label4; + iHEX60gensym4_301990110 = i_536872113; + result_p0[result_p0_Idx][chckIndx(addInt(old_301990096, iHEX60gensym4_301990110), 0, (result_p0[result_p0_Idx]).length - 1)] = x_p1.charCodeAt(chckIndx(addInt(start_p2, iHEX60gensym4_301990110), 0, (x_p1).length - 1)); + i_536872113 = addInt(i_536872113, 1); + } + }; + }; + + +} + +function addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, x_p1) { + addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, 0, ((x_p1) == null ? 0 : (x_p1).length)); + + +} + +function addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, x_p1) { + addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, ((x_p1) + "")); + + +} + +function addInt__stdZprivateZdigitsutils_u241(result_p0, result_p0_Idx, x_p1) { + addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, BigInt(x_p1)); + + +} + +function HEX24__systemZdollars_u8(x_p0) { + var result_385875978 = [[]]; + + addInt__stdZprivateZdigitsutils_u241(result_385875978, 0, x_p0); + + return result_385875978[0]; + +} + +function isFatPointer__system_u2869(ti_p0) { + var result_33557303 = false; + + BeforeRet: { + result_33557303 = !((ConstSet1[ti_p0.base.kind] != undefined)); + break BeforeRet; + }; + + return result_33557303; + +} + +function nimCopyAux(dest_p0, src_p1, n_p2) { + switch (n_p2.kind) { + case 0: + break; + case 1: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + + break; + case 2: + for (var i = 0; i < n_p2.sons.length; i++) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i]); + } + + break; + case 3: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + for (var i = 0; i < n_p2.sons.length; ++i) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i][1]); + } + + break; + } + + +} + +function raiseIndexError(i_p0, a_p1, b_p2) { + var Temporary1; + + if ((b_p2 < a_p1)) { + Temporary1 = [105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]; + } + else { + Temporary1 = ([105,110,100,101,120,32]).concat(HEX24__systemZdollars_u8(i_p0),[32,110,111,116,32,105,110,32],HEX24__systemZdollars_u8(a_p1),[32,46,46,32],HEX24__systemZdollars_u8(b_p2)); + } + + raiseException({message: nimCopy(null, Temporary1, NTI33554449), parent: null, m_type: NTI134217749, name: null, trace: [], up: null}, "IndexDefect"); + + +} + +function sysFatal__stdZassertions_u44(message_p1) { + raiseException({message: nimCopy(null, message_p1, NTI33554449), m_type: NTI134217745, parent: null, name: null, trace: [], up: null}, "AssertionDefect"); + + +} + +function raiseAssert__stdZassertions_u42(msg_p0) { + sysFatal__stdZassertions_u44(msg_p0); + + +} + +function failedAssertImpl__stdZassertions_u84(msg_p0) { + raiseAssert__stdZassertions_u42(msg_p0); + + +} + +function onDOMLoaded(e_p0) { + var Temporary4; + +function HEX3Aanonymous__dochack_u65(event_p0) { + event_p0.target.parentNode.style.display = "none"; + event_p0.target.parentNode.nextSibling.style.display = "inline"; + + +} + + document.getElementById("theme-select").value = window.localStorage.getItem("theme"); + Label1: { + var pragmaDots_536870976 = null; + var colontmp__536872104 = []; + colontmp__536872104 = document.getElementsByClassName("pragmadots"); + var i_536872106 = 0; + var L_536872107 = (colontmp__536872104).length; + Label2: { + Label3: while (true) { + if (!(i_536872106 < L_536872107)) break Label3; + pragmaDots_536870976 = colontmp__536872104[chckIndx(i_536872106, 0, (colontmp__536872104).length - 1)]; + Temporary4 = HEX3Aanonymous__dochack_u65.bind(null); Temporary4.ClP_0 = HEX3Aanonymous__dochack_u65; Temporary4.ClE_0 = null; + pragmaDots_536870976.onclick = Temporary4; + i_536872106 += 1; + if (!(((colontmp__536872104).length == L_536872107))) { + failedAssertImpl__stdZassertions_u84(makeNimstrLit("iterators.nim(254, 11) `len(a) == L` the length of the seq changed while iterating over it")); + } + + } + }; + }; + + +} + +function isWhitespace__dochack_u408(x_p0) { + var result_536871322 = false; + + result_536871322 = (((x_p0.nodeName == "#text") && !/\S/.test(x_p0.textContent)) || (x_p0.nodeName == "#comment")); + + return result_536871322; + +} + +function toToc__dochack_u411(x_p0, father_p1) { + var Temporary5; + var Temporary6; + var Temporary7; + var Temporary8; + var Temporary15; + + if ((x_p0.nodeName == "UL")) { + var f_536871333 = {heading: null, kids: [], sortId: (father_p1.kids).length, doSort: false}; + var i_536871334 = 0; + Label1: { + Label2: while (true) { + if (!(i_536871334 < x_p0.childNodes.length)) break Label2; + var nxt_536871335 = addInt(i_536871334, 1); + Label3: { + Label4: while (true) { + if (!(nxt_536871335 < x_p0.childNodes.length)) Temporary5 = false; else { Temporary5 = isWhitespace__dochack_u408(x_p0.childNodes[nxt_536871335]); } if (!Temporary5) break Label4; + nxt_536871335 = addInt(nxt_536871335, 1); + } + }; + if (!(nxt_536871335 < x_p0.childNodes.length)) Temporary8 = false; else { Temporary8 = (x_p0.childNodes[i_536871334].nodeName == "LI"); } if (!Temporary8) Temporary7 = false; else { Temporary7 = (x_p0.childNodes[i_536871334].childNodes.length == 1); } if (!Temporary7) Temporary6 = false; else { Temporary6 = (x_p0.childNodes[nxt_536871335].nodeName == "UL"); } if (Temporary6) { + var e_536871348 = {heading: x_p0.childNodes[i_536871334].childNodes[0], kids: [], sortId: (f_536871333.kids).length, doSort: false}; + var it_536871349 = x_p0.childNodes[nxt_536871335]; + Label9: { + var j_536871354 = 0; + var colontmp__536872120 = 0; + colontmp__536872120 = it_536871349.childNodes.length; + var i_536872121 = 0; + Label10: { + Label11: while (true) { + if (!(i_536872121 < colontmp__536872120)) break Label11; + j_536871354 = i_536872121; + toToc__dochack_u411(it_536871349.childNodes[j_536871354], e_536871348); + i_536872121 = addInt(i_536872121, 1); + } + }; + }; + f_536871333.kids.push(e_536871348);; + i_536871334 = addInt(nxt_536871335, 1); + } + else { + toToc__dochack_u411(x_p0.childNodes[i_536871334], f_536871333); + i_536871334 = addInt(i_536871334, 1); + } + + } + }; + father_p1.kids.push(f_536871333);; + } + else { + if (isWhitespace__dochack_u408(x_p0)) { + } + else { + if ((x_p0.nodeName == "LI")) { + var idx_536871372 = []; + Label12: { + var i_536871377 = 0; + var colontmp__536872124 = 0; + colontmp__536872124 = x_p0.childNodes.length; + var i_536872125 = 0; + Label13: { + Label14: while (true) { + if (!(i_536872125 < colontmp__536872124)) break Label14; + i_536871377 = i_536872125; + if (!(isWhitespace__dochack_u408(x_p0.childNodes[i_536871377]))) { + idx_536871372.push(i_536871377);; + } + + i_536872125 = addInt(i_536872125, 1); + } + }; + }; + if (!((idx_536871372).length == 2)) Temporary15 = false; else { Temporary15 = (x_p0.childNodes[idx_536871372[chckIndx(1, 0, (idx_536871372).length - 1)]].nodeName == "UL"); } if (Temporary15) { + var e_536871393 = {heading: x_p0.childNodes[idx_536871372[chckIndx(0, 0, (idx_536871372).length - 1)]], kids: [], sortId: (father_p1.kids).length, doSort: false}; + var it_536871394 = x_p0.childNodes[idx_536871372[chckIndx(1, 0, (idx_536871372).length - 1)]]; + Label16: { + var j_536871399 = 0; + var colontmp__536872128 = 0; + colontmp__536872128 = it_536871394.childNodes.length; + var i_536872129 = 0; + Label17: { + Label18: while (true) { + if (!(i_536872129 < colontmp__536872128)) break Label18; + j_536871399 = i_536872129; + toToc__dochack_u411(it_536871394.childNodes[j_536871399], e_536871393); + i_536872129 = addInt(i_536872129, 1); + } + }; + }; + father_p1.kids.push(e_536871393);; + } + else { + Label19: { + var i_536871408 = 0; + var colontmp__536872132 = 0; + colontmp__536872132 = x_p0.childNodes.length; + var i_536872133 = 0; + Label20: { + Label21: while (true) { + if (!(i_536872133 < colontmp__536872132)) break Label21; + i_536871408 = i_536872133; + toToc__dochack_u411(x_p0.childNodes[i_536871408], father_p1); + i_536872133 = addInt(i_536872133, 1); + } + }; + }; + } + + } + else { + father_p1.kids.push({heading: x_p0, kids: [], sortId: (father_p1.kids).length, doSort: false});; + } + }} + + +} + +function extractItems__dochack_u199(x_p0, heading_p1, items_p2, items_p2_Idx) { + BeforeRet: { + if ((x_p0 == null)) { + break BeforeRet; + } + + if ((!((x_p0.heading == null)) && (x_p0.heading.textContent == heading_p1))) { + Label1: { + var i_536871131 = 0; + var colontmp__536872136 = 0; + colontmp__536872136 = (x_p0.kids).length; + var i_536872137 = 0; + Label2: { + Label3: while (true) { + if (!(i_536872137 < colontmp__536872136)) break Label3; + i_536871131 = i_536872137; + items_p2[items_p2_Idx].push(x_p0.kids[chckIndx(i_536871131, 0, (x_p0.kids).length - 1)].heading);; + i_536872137 = addInt(i_536872137, 1); + } + }; + }; + } + else { + Label4: { + var k_536871157 = null; + var i_536872141 = 0; + var L_536872142 = (x_p0.kids).length; + Label5: { + Label6: while (true) { + if (!(i_536872141 < L_536872142)) break Label6; + k_536871157 = x_p0.kids[chckIndx(i_536872141, 0, (x_p0.kids).length - 1)]; + extractItems__dochack_u199(k_536871157, heading_p1, items_p2, items_p2_Idx); + i_536872141 += 1; + if (!(((x_p0.kids).length == L_536872142))) { + failedAssertImpl__stdZassertions_u84(makeNimstrLit("iterators.nim(254, 11) `len(a) == L` the length of the seq changed while iterating over it")); + } + + } + }; + }; + } + + }; + + +} + +function tree__dochack_u130(tag_p0, kids_p1) { + var result_536871045 = null; + + result_536871045 = document.createElement(tag_p0); + Label1: { + var k_536871059 = null; + var i_536872154 = 0; + Label2: { + Label3: while (true) { + if (!(i_536872154 < (kids_p1).length)) break Label3; + k_536871059 = kids_p1[chckIndx(i_536872154, 0, (kids_p1).length - 1)]; + result_536871045.appendChild(k_536871059); + i_536872154 += 1; + } + }; + }; + + return result_536871045; + +} + +function text__dochack_u155(s_p0) { + var result_536871069 = null; + + result_536871069 = document.createTextNode(s_p0); + + return result_536871069; + +} + +function uncovered__dochack_u600(x_p0) { + var Temporary1; + + var result_536871514 = null; + + BeforeRet: { + if ((((x_p0.kids).length == 0) && !((x_p0.heading == null)))) { + if (!(x_p0.heading.hasOwnProperty('__karaxMarker__'))) { + Temporary1 = x_p0; + } + else { + Temporary1 = null; + } + + result_536871514 = Temporary1; + break BeforeRet; + } + + result_536871514 = {heading: x_p0.heading, kids: [], sortId: x_p0.sortId, doSort: x_p0.doSort}; + Label2: { + var k_536871529 = null; + var i_536872161 = 0; + var L_536872162 = (x_p0.kids).length; + Label3: { + Label4: while (true) { + if (!(i_536872161 < L_536872162)) break Label4; + k_536871529 = x_p0.kids[chckIndx(i_536872161, 0, (x_p0.kids).length - 1)]; + var y_536871530 = uncovered__dochack_u600(k_536871529); + if (!((y_536871530 == null))) { + result_536871514.kids.push(y_536871530);; + } + + i_536872161 += 1; + if (!(((x_p0.kids).length == L_536872162))) { + failedAssertImpl__stdZassertions_u84(makeNimstrLit("iterators.nim(254, 11) `len(a) == L` the length of the seq changed while iterating over it")); + } + + } + }; + }; + if (((result_536871514.kids).length == 0)) { + result_536871514 = null; + } + + }; + + return result_536871514; + +} + +function mergeTocs__dochack_u630(orig_p0, news_p1) { + var result_536871545 = null; + + result_536871545 = uncovered__dochack_u600(orig_p0); + if ((result_536871545 == null)) { + result_536871545 = news_p1; + } + else { + Label1: { + var i_536871557 = 0; + var colontmp__536872157 = 0; + colontmp__536872157 = (news_p1.kids).length; + var i_536872158 = 0; + Label2: { + Label3: while (true) { + if (!(i_536872158 < colontmp__536872157)) break Label3; + i_536871557 = i_536872158; + result_536871545.kids.push(news_p1.kids[chckIndx(i_536871557, 0, (news_p1.kids).length - 1)]);; + i_536872158 = addInt(i_536872158, 1); + } + }; + }; + } + + + return result_536871545; + +} + +function buildToc__dochack_u650(orig_p0, types_p1, procs_p2) { + var result_536871566 = null; + + var newStuff_536871571 = {heading: null, kids: [], doSort: true, sortId: 0}; + Label1: { + var t_536871575 = null; + var i_536872149 = 0; + var L_536872150 = (types_p1).length; + Label2: { + Label3: while (true) { + if (!(i_536872149 < L_536872150)) break Label3; + t_536871575 = types_p1[chckIndx(i_536872149, 0, (types_p1).length - 1)]; + var c_536871580 = {heading: t_536871575.cloneNode(true), kids: [], doSort: true, sortId: 0}; + t_536871575.__karaxMarker__ = true; + Label4: { + var p_536871584 = null; + var i_536872146 = 0; + var L_536872147 = (procs_p2).length; + Label5: { + Label6: while (true) { + if (!(i_536872146 < L_536872147)) break Label6; + p_536871584 = procs_p2[chckIndx(i_536872146, 0, (procs_p2).length - 1)]; + if (!(p_536871584.hasOwnProperty('__karaxMarker__'))) { + var xx_536871585 = p_536871584.parentNode.getElementsByClassName("attachedType"); + if ((((xx_536871585).length == 1) && (xx_536871585[chckIndx(0, 0, (xx_536871585).length - 1)].textContent == t_536871575.textContent))) { + var q_536871590 = tree__dochack_u130("A", [text__dochack_u155(p_536871584.title)]); + q_536871590.setAttribute("href", p_536871584.getAttribute("href")); + c_536871580.kids.push({heading: q_536871590, kids: [], sortId: 0, doSort: false});; + p_536871584.__karaxMarker__ = true; + } + + } + + i_536872146 += 1; + if (!(((procs_p2).length == L_536872147))) { + failedAssertImpl__stdZassertions_u84(makeNimstrLit("iterators.nim(254, 11) `len(a) == L` the length of the seq changed while iterating over it")); + } + + } + }; + }; + newStuff_536871571.kids.push(c_536871580);; + i_536872149 += 1; + if (!(((types_p1).length == L_536872150))) { + failedAssertImpl__stdZassertions_u84(makeNimstrLit("iterators.nim(254, 11) `len(a) == L` the length of the seq changed while iterating over it")); + } + + } + }; + }; + result_536871566 = mergeTocs__dochack_u630(orig_p0, newStuff_536871571); + + return result_536871566; + +} + +function add__dochack_u148(parent_p0, kid_p1) { + if (((parent_p0.nodeName == "TR") && ((kid_p1.nodeName == "TD") || (kid_p1.nodeName == "TH")))) { + var k_536871063 = document.createElement("TD"); + k_536871063.appendChild(kid_p1); + parent_p0.appendChild(k_536871063); + } + else { + parent_p0.appendChild(kid_p1); + } + + + +} + +function setClass__dochack_u152(e_p0, value_p1) { + e_p0.setAttribute("class", value_p1); + + +} + +function toHtml__dochack_u278(x_p0, isRoot_p1) { + var Temporary1; + +function HEX3Aanonymous__dochack_u298(a_p0, b_p1) { + var result_536871213 = 0; + + BeforeRet: { + if ((!((a_p0.heading == null)) && !((b_p1.heading == null)))) { + var x_536871222 = a_p0.heading.textContent; + var y_536871223 = b_p1.heading.textContent; + if ((x_536871222 < y_536871223)) { + result_536871213 = (-1); + break BeforeRet; + } + + if ((y_536871223 < x_536871222)) { + result_536871213 = 1; + break BeforeRet; + } + + result_536871213 = 0; + break BeforeRet; + } + else { + result_536871213 = subInt(a_p0.sortId, b_p1.sortId); + break BeforeRet; + } + + }; + + return result_536871213; + +} + + var result_536871193 = null; + + BeforeRet: { + if ((x_p0 == null)) { + result_536871193 = null; + break BeforeRet; + } + + if (((x_p0.kids).length == 0)) { + if ((x_p0.heading == null)) { + result_536871193 = null; + break BeforeRet; + } + + result_536871193 = x_p0.heading.cloneNode(true); + break BeforeRet; + } + + result_536871193 = tree__dochack_u130("DIV", []); + if ((!((x_p0.heading == null)) && !(x_p0.heading.hasOwnProperty('__karaxMarker__')))) { + add__dochack_u148(result_536871193, x_p0.heading.cloneNode(true)); + } + + var ul_536871209 = tree__dochack_u130("UL", []); + if (isRoot_p1) { + setClass__dochack_u152(ul_536871209, "simple simple-toc"); + } + else { + setClass__dochack_u152(ul_536871209, "simple"); + } + + if (x_p0.doSort) { + Temporary1 = HEX3Aanonymous__dochack_u298.bind(null); Temporary1.ClP_0 = HEX3Aanonymous__dochack_u298; Temporary1.ClE_0 = null; + x_p0.kids.sort(Temporary1); + } + + Label2: { + var k_536871235 = null; + var i_536872165 = 0; + var L_536872166 = (x_p0.kids).length; + Label3: { + Label4: while (true) { + if (!(i_536872165 < L_536872166)) break Label4; + k_536871235 = x_p0.kids[chckIndx(i_536872165, 0, (x_p0.kids).length - 1)]; + var y_536871236 = toHtml__dochack_u278(k_536871235, false); + if (!((y_536871236 == null))) { + add__dochack_u148(ul_536871209, tree__dochack_u130("LI", [y_536871236])); + } + + i_536872165 += 1; + if (!(((x_p0.kids).length == L_536872166))) { + failedAssertImpl__stdZassertions_u84(makeNimstrLit("iterators.nim(254, 11) `len(a) == L` the length of the seq changed while iterating over it")); + } + + } + }; + }; + if (!((ul_536871209.childNodes.length == 0))) { + add__dochack_u148(result_536871193, ul_536871209); + } + + if ((result_536871193.childNodes.length == 0)) { + result_536871193 = null; + } + + }; + + return result_536871193; + +} + +function replaceById__dochack_u158(id_p0, newTree_p1) { + var x_536871073 = document.getElementById(id_p0); + x_536871073.parentNode.replaceChild(newTree_p1, x_536871073); + newTree_p1.id = id_p0; + + +} + +function togglevis__dochack_u708(d_p0) { + if ((d_p0.style.display == "none")) { + d_p0.style.display = "inline"; + } + else { + d_p0.style.display = "none"; + } + + + +} + +function groupBy(value_p0) { + var toc_536871624 = document.getElementById("toc-list"); + if ((alternative_536871619[0] == null)) { + var tt_536871632 = {heading: null, kids: [], sortId: 0, doSort: false}; + toToc__dochack_u411(toc_536871624, tt_536871632); + tt_536871632 = tt_536871632.kids[chckIndx(0, 0, (tt_536871632.kids).length - 1)]; + var types_536871637 = [[]]; + var procs_536871642 = [[]]; + extractItems__dochack_u199(tt_536871632, "Types", types_536871637, 0); + extractItems__dochack_u199(tt_536871632, "Procs", procs_536871642, 0); + extractItems__dochack_u199(tt_536871632, "Converters", procs_536871642, 0); + extractItems__dochack_u199(tt_536871632, "Methods", procs_536871642, 0); + extractItems__dochack_u199(tt_536871632, "Templates", procs_536871642, 0); + extractItems__dochack_u199(tt_536871632, "Macros", procs_536871642, 0); + extractItems__dochack_u199(tt_536871632, "Iterators", procs_536871642, 0); + var ntoc_536871643 = buildToc__dochack_u650(tt_536871632, types_536871637[0], procs_536871642[0]); + var x_536871644 = toHtml__dochack_u278(ntoc_536871643, true); + alternative_536871619[0] = tree__dochack_u130("DIV", [x_536871644]); + } + + if ((value_p0 == "type")) { + replaceById__dochack_u158("tocRoot", alternative_536871619[0]); + } + else { + replaceById__dochack_u158("tocRoot", tree__dochack_u130("DIV", [])); + } + + togglevis__dochack_u708(document.getElementById("toc-list")); + + +} + +function HEX5BHEX5D__pureZstrutils_u1307(s_p0, x_p1) { + var result_704644384 = []; + + var a_704644386 = x_p1.a; + var L_704644388 = addInt(subInt(subInt((s_p0).length, x_p1.b), a_704644386), 1); + result_704644384 = nimCopy(null, mnewString(chckRange(L_704644388, 0, 2147483647)), NTI33554449); + Label1: { + var i_704644393 = 0; + var i_536872175 = 0; + Label2: { + Label3: while (true) { + if (!(i_536872175 < L_704644388)) break Label3; + i_704644393 = i_536872175; + result_704644384[chckIndx(i_704644393, 0, (result_704644384).length - 1)] = s_p0[chckIndx(addInt(i_704644393, a_704644386), 0, (s_p0).length - 1)]; + i_536872175 = addInt(i_536872175, 1); + } + }; + }; + + return result_704644384; + +} + +function HEX2EHEX2E__stdZenumutils_u105(a_p0, b_p1) { + var result_922746992 = ({a: 0, b: 0}); + + result_922746992 = nimCopy(result_922746992, {a: a_p0, b: b_p1}, NTI922746967); + + return result_922746992; + +} +async function loadIndex__dochack_u928() { + var result_536871842 = null; + + BeforeRet: { + var indexURL_536871848 = document.getElementById("indexLink").getAttribute("href"); + var rootURL_536871874 = HEX5BHEX5D__pureZstrutils_u1307(cstrToNimstr(indexURL_536871848), HEX2EHEX2E__stdZenumutils_u105(0, 14)); + var resp_536871886 = (await (await fetch(indexURL_536871848)).text()); + var indexElem_536871887 = document.createElement("div"); + indexElem_536871887.innerHTML = resp_536871886; + Label1: { + var href_536871909 = null; + var colontmp__536872169 = []; + colontmp__536872169 = indexElem_536871887.getElementsByClassName("reference"); + var i_536872171 = 0; + var L_536872172 = (colontmp__536872169).length; + Label2: { + Label3: while (true) { + if (!(i_536872171 < L_536872172)) break Label3; + href_536871909 = colontmp__536872169[chckIndx(i_536872171, 0, (colontmp__536872169).length - 1)]; + href_536871909.setAttribute("href", toJSStr((rootURL_536871874).concat(cstrToNimstr(href_536871909.getAttribute("href"))))); + db_536871661[0].push(href_536871909);; + contents_536871662[0].push(href_536871909.getAttribute("data-doc-search-tag"));; + i_536872171 += 1; + if (!(((colontmp__536872169).length == L_536872172))) { + failedAssertImpl__stdZassertions_u84(makeNimstrLit("iterators.nim(254, 11) `len(a) == L` the length of the seq changed while iterating over it")); + } + + } + }; + }; + result_536871842 = undefined; + break BeforeRet; + }; + + return result_536871842; + +} + +function then__dochack_u1106(future_p0, onSuccess_p1, onReject_p2) { + var result_536872024 = null; + + BeforeRet: { + var ret_536872034 = null; + ret_536872034 = future_p0.then(onSuccess_p1, onReject_p2); + result_536872024 = ret_536872034; + break BeforeRet; + }; + + return result_536872024; + +} + +function nsuToLowerAsciiChar(c_p0) { + var result_704643158 = 0; + + if ((ConstSet2[c_p0] != undefined)) { + result_704643158 = (c_p0 ^ 32); + } + else { + result_704643158 = c_p0; + } + + + return result_704643158; + +} + +function fuzzyMatch__fuzzysearch_u16(pattern_p0, str_p1) { + var Temporary4; + var Temporary5; + var Temporary6; + var Temporary7; + var Temporary8; + + var result_687865877 = {Field0: 0, Field1: false}; + + var scoreState_687865878 = (-100); + var headerMatched_687865879 = false; + var unmatchedLeadingCharCount_687865880 = 0; + var consecutiveMatchCount_687865881 = 0; + var strIndex_687865882 = 0; + var patIndex_687865883 = 0; + var score_687865884 = 0; + Label1: { + Label2: while (true) { + if (!((strIndex_687865882 < ((str_p1) == null ? 0 : (str_p1).length)) && (patIndex_687865883 < ((pattern_p0) == null ? 0 : (pattern_p0).length)))) break Label2; + Label3: { + var patternChar_687865887 = nsuToLowerAsciiChar(pattern_p0.charCodeAt(chckIndx(patIndex_687865883, 0, (pattern_p0).length - 1))); + var strChar_687865888 = nsuToLowerAsciiChar(str_p1.charCodeAt(chckIndx(strIndex_687865882, 0, (str_p1).length - 1))); + if ((ConstSet3[patternChar_687865887] != undefined)) { + patIndex_687865883 = addInt(patIndex_687865883, 1); + break Label3; + } + + if ((ConstSet4[strChar_687865888] != undefined)) { + strIndex_687865882 = addInt(strIndex_687865882, 1); + break Label3; + } + + if ((!(headerMatched_687865879) && (strChar_687865888 == 58))) { + headerMatched_687865879 = true; + scoreState_687865878 = (-100); + score_687865884 = ((Math.floor((0.5 * score_687865884))) | 0); + patIndex_687865883 = 0; + strIndex_687865882 = addInt(strIndex_687865882, 1); + break Label3; + } + + if ((strChar_687865888 == patternChar_687865887)) { + switch (scoreState_687865878) { + case (-100): + case 20: + scoreState_687865878 = 10; + break; + case 0: + scoreState_687865878 = 5; + score_687865884 = addInt(score_687865884, scoreState_687865878); + break; + case 10: + case 5: + consecutiveMatchCount_687865881 = addInt(consecutiveMatchCount_687865881, 1); + scoreState_687865878 = 5; + score_687865884 = addInt(score_687865884, mulInt(5, consecutiveMatchCount_687865881)); + if ((scoreState_687865878 == 10)) { + score_687865884 = addInt(score_687865884, 10); + } + + var onBoundary_687865940 = (patIndex_687865883 == ((pattern_p0) == null ? -1 : (pattern_p0).length - 1)); + if ((!(onBoundary_687865940) && (strIndex_687865882 < ((str_p1) == null ? -1 : (str_p1).length - 1)))) { + var nextPatternChar_687865941 = nsuToLowerAsciiChar(pattern_p0.charCodeAt(chckIndx(addInt(patIndex_687865883, 1), 0, (pattern_p0).length - 1))); + var nextStrChar_687865942 = nsuToLowerAsciiChar(str_p1.charCodeAt(chckIndx(addInt(strIndex_687865882, 1), 0, (str_p1).length - 1))); + if (!!((ConstSet5[nextStrChar_687865942] != undefined))) Temporary4 = false; else { Temporary4 = !((nextStrChar_687865942 == nextPatternChar_687865941)); } onBoundary_687865940 = Temporary4; + } + + if (onBoundary_687865940) { + scoreState_687865878 = 20; + score_687865884 = addInt(score_687865884, scoreState_687865878); + } + + break; + case (-1): + case (-3): + if (!((ConstSet6[str_p1.charCodeAt(chckIndx(subInt(strIndex_687865882, 1), 0, (str_p1).length - 1))] != undefined))) Temporary5 = true; else { if (!(ConstSet7[str_p1.charCodeAt(chckIndx(subInt(strIndex_687865882, 1), 0, (str_p1).length - 1))] != undefined)) Temporary6 = false; else { Temporary6 = (ConstSet8[str_p1.charCodeAt(chckIndx(strIndex_687865882, 0, (str_p1).length - 1))] != undefined); } Temporary5 = Temporary6; } var isLeadingChar_687865966 = Temporary5; + if (isLeadingChar_687865966) { + scoreState_687865878 = 10; + } + else { + scoreState_687865878 = 0; + score_687865884 = addInt(score_687865884, scoreState_687865878); + } + + break; + } + patIndex_687865883 = addInt(patIndex_687865883, 1); + } + else { + switch (scoreState_687865878) { + case (-100): + scoreState_687865878 = (-3); + score_687865884 = addInt(score_687865884, scoreState_687865878); + break; + case 5: + scoreState_687865878 = (-1); + score_687865884 = addInt(score_687865884, scoreState_687865878); + consecutiveMatchCount_687865881 = 0; + break; + case (-3): + if ((unmatchedLeadingCharCount_687865880 < 3)) { + scoreState_687865878 = (-3); + score_687865884 = addInt(score_687865884, scoreState_687865878); + } + + unmatchedLeadingCharCount_687865880 = addInt(unmatchedLeadingCharCount_687865880, 1); + break; + default: + scoreState_687865878 = (-1); + score_687865884 = addInt(score_687865884, scoreState_687865878); + break; + } + } + + strIndex_687865882 = addInt(strIndex_687865882, 1); + }; + } + }; + if (!(patIndex_687865883 == ((pattern_p0) == null ? 0 : (pattern_p0).length))) Temporary7 = false; else { if ((strIndex_687865882 == ((str_p1) == null ? 0 : (str_p1).length))) Temporary8 = true; else { Temporary8 = !((ConstSet9[str_p1.charCodeAt(chckIndx(strIndex_687865882, 0, (str_p1).length - 1))] != undefined)); } Temporary7 = Temporary8; } if (Temporary7) { + score_687865884 = addInt(score_687865884, 10); + } + + var colontmp__536872188 = nimMax(0, score_687865884); + var colontmp__536872189 = (0 < score_687865884); + result_687865877 = nimCopy(result_687865877, {Field0: colontmp__536872188, Field1: colontmp__536872189}, NTI687865870); + + return result_687865877; + +} + +function escapeCString__dochack_u751(x_p0, x_p0_Idx) { + var s_536871665 = []; + Label1: { + var c_536871666 = 0; + var iHEX60gensym13_536872192 = 0; + var nHEX60gensym13_536872193 = ((x_p0[x_p0_Idx]) == null ? 0 : (x_p0[x_p0_Idx]).length); + Label2: { + Label3: while (true) { + if (!(iHEX60gensym13_536872192 < nHEX60gensym13_536872193)) break Label3; + c_536871666 = x_p0[x_p0_Idx].charCodeAt(chckIndx(iHEX60gensym13_536872192, 0, (x_p0[x_p0_Idx]).length - 1)); + switch (c_536871666) { + case 60: + s_536871665.push.apply(s_536871665, [38,108,116,59]);; + break; + case 62: + s_536871665.push.apply(s_536871665, [38,103,116,59]);; + break; + default: + addChar(s_536871665, c_536871666);; + break; + } + iHEX60gensym13_536872192 += 1; + } + }; + }; + x_p0[x_p0_Idx] = toJSStr(s_536871665); + + +} + +function dosearch__dochack_u755(value_p0) { + var Temporary5; + +function HEX3Aanonymous__dochack_u783(a_p0, b_p1) { + var result_536871708 = 0; + + result_536871708 = subInt(b_p1["Field1"], a_p0["Field1"]); + + return result_536871708; + +} + + var result_536871669 = null; + + BeforeRet: { + if (((db_536871661[0]).length == 0)) { + break BeforeRet; + } + + var ul_536871673 = tree__dochack_u130("UL", []); + result_536871669 = tree__dochack_u130("DIV", []); + setClass__dochack_u152(result_536871669, "search_results"); + var matches_536871678 = []; + Label1: { + var i_536871686 = 0; + var colontmp__536872179 = 0; + colontmp__536872179 = (db_536871661[0]).length; + var i_536872180 = 0; + Label2: { + Label3: while (true) { + if (!(i_536872180 < colontmp__536872179)) break Label3; + i_536871686 = i_536872180; + Label4: { + var c_536871687 = contents_536871662[0][chckIndx(i_536871686, 0, (contents_536871662[0]).length - 1)]; + if (((c_536871687 == "Examples") || (c_536871687 == "PEG construction"))) { + break Label4; + } + + var tmpTuple_536871688 = fuzzyMatch__fuzzysearch_u16(value_p0, c_536871687); + var score_536871689 = tmpTuple_536871688["Field0"]; + var matched_536871690 = tmpTuple_536871688["Field1"]; + if (matched_536871690) { + matches_536871678.push({Field0: db_536871661[0][chckIndx(i_536871686, 0, (db_536871661[0]).length - 1)], Field1: score_536871689});; + } + + }; + i_536872180 = addInt(i_536872180, 1); + } + }; + }; + Temporary5 = HEX3Aanonymous__dochack_u783.bind(null); Temporary5.ClP_0 = HEX3Aanonymous__dochack_u783; Temporary5.ClE_0 = null; + matches_536871678.sort(Temporary5); + Label6: { + var i_536871725 = 0; + var colontmp__536872183 = 0; + colontmp__536872183 = nimMin((matches_536871678).length, 29); + var i_536872184 = 0; + Label7: { + Label8: while (true) { + if (!(i_536872184 < colontmp__536872183)) break Label8; + i_536871725 = i_536872184; + matches_536871678[chckIndx(i_536871725, 0, (matches_536871678).length - 1)]["Field0"].innerHTML = matches_536871678[chckIndx(i_536871725, 0, (matches_536871678).length - 1)]["Field0"].getAttribute("data-doc-search-tag"); + escapeCString__dochack_u751(matches_536871678[chckIndx(i_536871725, 0, (matches_536871678).length - 1)]["Field0"], "innerHTML"); + add__dochack_u148(ul_536871673, tree__dochack_u130("LI", [matches_536871678[chckIndx(i_536871725, 0, (matches_536871678).length - 1)]["Field0"]])); + i_536872184 = addInt(i_536872184, 1); + } + }; + }; + if ((ul_536871673.childNodes.length == 0)) { + add__dochack_u148(result_536871669, tree__dochack_u130("B", [text__dochack_u155("no search results")])); + } + else { + add__dochack_u148(result_536871669, tree__dochack_u130("B", [text__dochack_u155("search results")])); + add__dochack_u148(result_536871669, ul_536871673); + } + + }; + + return result_536871669; + +} + +function wrapper__dochack_u1091() { + var elem_536872004 = document.getElementById("searchInput"); + var value_536872005 = elem_536872004.value; + if (!((((value_536872005) == null ? 0 : (value_536872005).length) == 0))) { + if ((oldtoc_536871998[0] == null)) { + oldtoc_536871998[0] = document.getElementById("tocRoot"); + } + + var results_536872009 = dosearch__dochack_u755(value_536872005); + replaceById__dochack_u158("tocRoot", results_536872009); + } + else { + if (!((oldtoc_536871998[0] == null))) { + replaceById__dochack_u158("tocRoot", oldtoc_536871998[0]); + } + } + + +} + +function search() { + var Temporary1; + + if ((loadIndexFut_536872001[0] == null)) { + loadIndexFut_536872001[0] = loadIndex__dochack_u928(); + (then__dochack_u1106(loadIndexFut_536872001[0], wrapper__dochack_u1091, null)); + } + + if (!((timer_536871999[0] == null))) { + clearTimeout(timer_536871999[0]); + } + + Temporary1 = wrapper__dochack_u1091.bind(null); Temporary1.ClP_0 = wrapper__dochack_u1091; Temporary1.ClE_0 = null; + timer_536871999[0] = setTimeout(Temporary1, 400); + + +} + +function copyToClipboard() { + + function updatePreTags() { + + const allPreTags = document.querySelectorAll("pre:not(.line-nums)") + + allPreTags.forEach((e) => { + + const div = document.createElement("div") + div.classList.add("copyToClipBoard") + + const preTag = document.createElement("pre") + preTag.innerHTML = e.innerHTML + + const button = document.createElement("button") + button.value = e.textContent.replace('...', '') + button.classList.add("copyToClipBoardBtn") + button.style.cursor = "pointer" + + div.appendChild(preTag) + div.appendChild(button) + + e.outerHTML = div.outerHTML + + }) + } + + + function copyTextToClipboard(e) { + const clipBoardContent = e.target.value + navigator.clipboard.writeText(clipBoardContent).then(function() { + e.target.style.setProperty("--clipboard-image", "var(--clipboard-image-selected)") + }, function(err) { + console.error("Could not copy text: ", err); + }); + } + + window.addEventListener("click", (e) => { + if (e.target.classList.contains("copyToClipBoardBtn")) { + copyTextToClipboard(e) + } + }) + + window.addEventListener("mouseover", (e) => { + if (e.target.nodeName === "PRE") { + e.target.nextElementSibling.style.setProperty("--clipboard-image", "var(--clipboard-image-normal)") + } + }) + + window.addEventListener("DOMContentLoaded", updatePreTags) + + + + +} +var Temporary1; +var Temporary2; +var t_536870951 = window.localStorage.getItem("theme"); +if ((t_536870951 == null)) { +Temporary1 = "auto"; +} +else { +Temporary1 = t_536870951; +} + +setTheme(Temporary1); +var alternative_536871619 = [null]; +var db_536871661 = [[]]; +var contents_536871662 = [[]]; +var oldtoc_536871998 = [null]; +var timer_536871999 = [null]; +var loadIndexFut_536872001 = [null]; +copyToClipboard(); +Temporary2 = onDOMLoaded.bind(null); Temporary2.ClP_0 = onDOMLoaded; Temporary2.ClE_0 = null; +window.addEventListener("DOMContentLoaded", Temporary2, false); diff --git a/compiler/enumtostr.html b/compiler/enumtostr.html new file mode 100644 index 0000000000000..f50b5aa73ca41 --- /dev/null +++ b/compiler/enumtostr.html @@ -0,0 +1,146 @@ + + + + + + + +enumtostr + + + + + + + + + + + + + + + + +
+
+

enumtostr

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc genCaseObjDiscMapping(t: PType; field: PSym; info: TLineInfo;
+                           g: ModuleGraph; idgen: IdGenerator): PSym {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genEnumToStrProc(t: PType; info: TLineInfo; g: ModuleGraph;
+                      idgen: IdGenerator): PSym {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/enumtostr.idx b/compiler/enumtostr.idx new file mode 100644 index 0000000000000..f6a9a27c57526 --- /dev/null +++ b/compiler/enumtostr.idx @@ -0,0 +1,3 @@ +nimTitle enumtostr enumtostr.html module enumtostr 0 +nim genEnumToStrProc enumtostr.html#genEnumToStrProc,PType,TLineInfo,ModuleGraph,IdGenerator proc genEnumToStrProc(t: PType; info: TLineInfo; g: ModuleGraph; idgen: IdGenerator): PSym 8 +nim genCaseObjDiscMapping enumtostr.html#genCaseObjDiscMapping,PType,PSym,TLineInfo,ModuleGraph,IdGenerator proc genCaseObjDiscMapping(t: PType; field: PSym; info: TLineInfo; g: ModuleGraph;\n idgen: IdGenerator): PSym 70 diff --git a/compiler/errorhandling.html b/compiler/errorhandling.html new file mode 100644 index 0000000000000..65254c2fec227 --- /dev/null +++ b/compiler/errorhandling.html @@ -0,0 +1,197 @@ + + + + + + + +errorhandling + + + + + + + + + + + + + + + + +
+
+

errorhandling

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module contains support code for new-styled error handling via an nkError node kind.

+ +
+

Types

+
+
+
ErrorKind = enum
+  RawTypeMismatchError, ExpressionCannotBeCalled, CustomError,
+  WrongNumberOfArguments, AmbiguousCall
+
+ + expand as you need. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc errorSubNode(n: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc errorToString(config: ConfigRef; n: PNode): string {.
+    ...raises: [ValueError, Exception, KeyError],
+    tags: [RootEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newError(wrongNode: PNode; k: ErrorKind; args: varargs[PNode]): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newError(wrongNode: PNode; msg: string): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/errorhandling.idx b/compiler/errorhandling.idx new file mode 100644 index 0000000000000..a7a6ce8d345b0 --- /dev/null +++ b/compiler/errorhandling.idx @@ -0,0 +1,12 @@ +nimTitle errorhandling errorhandling.html module errorhandling 0 +nim RawTypeMismatchError errorhandling.html#RawTypeMismatchError ErrorKind.RawTypeMismatchError 20 +nim ExpressionCannotBeCalled errorhandling.html#ExpressionCannotBeCalled ErrorKind.ExpressionCannotBeCalled 20 +nim CustomError errorhandling.html#CustomError ErrorKind.CustomError 20 +nim WrongNumberOfArguments errorhandling.html#WrongNumberOfArguments ErrorKind.WrongNumberOfArguments 20 +nim AmbiguousCall errorhandling.html#AmbiguousCall ErrorKind.AmbiguousCall 20 +nim ErrorKind errorhandling.html#ErrorKind enum ErrorKind 20 +nim errorSubNode errorhandling.html#errorSubNode,PNode proc errorSubNode(n: PNode): PNode 27 +nim newError errorhandling.html#newError,PNode,ErrorKind,varargs[PNode] proc newError(wrongNode: PNode; k: ErrorKind; args: varargs[PNode]): PNode 39 +nim newError errorhandling.html#newError,PNode,string proc newError(wrongNode: PNode; msg: string): PNode 50 +nim errorToString errorhandling.html#errorToString,ConfigRef,PNode proc errorToString(config: ConfigRef; n: PNode): string 61 +nimgrp newerror errorhandling.html#newError-procs-all proc 39 diff --git a/compiler/evaltempl.html b/compiler/evaltempl.html new file mode 100644 index 0000000000000..94ff07013d8e4 --- /dev/null +++ b/compiler/evaltempl.html @@ -0,0 +1,169 @@ + + + + + + + +evaltempl + + + + + + + + + + + + + + + + +
+
+

evaltempl

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Template evaluation engine. Now hygienic.

+ +
+

Consts

+
+
+
evalTemplateLimit = 1000
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc evalTemplate(n: PNode; tmpl, genSymOwner: PSym; conf: ConfigRef;
+                  ic: IdentCache; instID: ref int; idgen: IdGenerator;
+                  fromHlo = false): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc wrapInComesFrom(info: TLineInfo; sym: PSym; res: PNode): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/evaltempl.idx b/compiler/evaltempl.idx new file mode 100644 index 0000000000000..788aea7de7aef --- /dev/null +++ b/compiler/evaltempl.idx @@ -0,0 +1,4 @@ +nimTitle evaltempl evaltempl.html module evaltempl 0 +nim evalTemplateLimit evaltempl.html#evalTemplateLimit const evalTemplateLimit 163 +nim wrapInComesFrom evaltempl.html#wrapInComesFrom,TLineInfo,PSym,PNode proc wrapInComesFrom(info: TLineInfo; sym: PSym; res: PNode): PNode 165 +nim evalTemplate evaltempl.html#evalTemplate,PNode,PSym,PSym,ConfigRef,IdentCache,ref.int,IdGenerator proc evalTemplate(n: PNode; tmpl, genSymOwner: PSym; conf: ConfigRef; ic: IdentCache;\n instID: ref int; idgen: IdGenerator; fromHlo = false): PNode 187 diff --git a/compiler/expanddefaults.html b/compiler/expanddefaults.html new file mode 100644 index 0000000000000..b1ee0ad1ea87d --- /dev/null +++ b/compiler/expanddefaults.html @@ -0,0 +1,140 @@ + + + + + + + +expanddefaults + + + + + + + + + + + + + + + + +
+
+

expanddefaults

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ lineinfos, ast, types +
+
+
+

Procs

+
+
+
+
proc caseObjDefaultBranch(obj: PNode; branch: Int128): int {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc expandDefault(t: PType; info: TLineInfo): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/expanddefaults.idx b/compiler/expanddefaults.idx new file mode 100644 index 0000000000000..cff2bf19ad8d4 --- /dev/null +++ b/compiler/expanddefaults.idx @@ -0,0 +1,3 @@ +nimTitle expanddefaults expanddefaults.html module expanddefaults 0 +nim caseObjDefaultBranch expanddefaults.html#caseObjDefaultBranch,PNode,Int128 proc caseObjDefaultBranch(obj: PNode; branch: Int128): int 12 +nim expandDefault expanddefaults.html#expandDefault,PType,TLineInfo proc expandDefault(t: PType; info: TLineInfo): PNode 30 diff --git a/compiler/extccomp.html b/compiler/extccomp.html new file mode 100644 index 0000000000000..5b5fe454994c4 --- /dev/null +++ b/compiler/extccomp.html @@ -0,0 +1,868 @@ + + + + + + + +extccomp + + + + + + + + + + + + + + + + +
+
+

extccomp

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
TInfoCC = tuple[name: string, objExt: string, optSpeed: string, optSize: string,
+                compilerExe: string, cppCompiler: string, compileTmpl: string,
+                buildGui: string, buildDll: string, buildLib: string,
+                linkerExe: string, linkTmpl: string, includeCmd: string,
+                linkDirCmd: string, linkLibCmd: string, debug: string,
+                pic: string, asmStmtFrmt: string, structStmtFmt: string,
+                produceAsm: string, cppXsupport: string, props: TInfoCCProps]
+
+ + + Source   +Edit   + +
+
+
+
TInfoCCProp = enum
+  hasSwitchRange, hasComputedGoto, hasCpp, hasAssume, hasGcGuard, hasGnuAsm,
+  hasDeclspec, hasAttribute, hasBuiltinUnreachable
+
+ + + Source   +Edit   + +
+
+
+
TInfoCCProps = set[TInfoCCProp]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
CC: array[succ(low(TSystemCC)) .. high(TSystemCC), TInfoCC] = [("gcc", "o",
+    " -O3 -fno-ident", " -Os -fno-ident", "gcc", "g++",
+    "-c $options $include -o $objfile $file", " -mwindows", " -shared",
+    "ar rcs $libfile $objfiles", "",
+    "$buildgui $builddll -o $exefile $objfiles $options", " -I", " -L", " -l$1",
+    "", "-fPIC", "__asm__($1);$n", "$1 $3 $2 ",
+    "-Wa,-acdl=$asmfile -g -fverbose-asm -masm=intel",
+    "-std=gnu++17 -funsigned-char", {hasSwitchRange, hasComputedGoto, hasCpp,
+                                     hasGcGuard, hasGnuAsm, hasAttribute,
+                                     hasBuiltinUnreachable}), ("switch_gcc",
+    "o", " -O3 ", " -Os ", "aarch64-none-elf-gcc", "aarch64-none-elf-g++",
+    "-w -MMD -MP -MF $dfile -c $options $include -o $objfile $file",
+    " -mwindows", " -shared", "aarch64-none-elf-gcc-ar rcs $libfile $objfiles",
+    "aarch64-none-elf-gcc",
+    "$buildgui $builddll -Wl,-Map,$mapfile -o $exefile $objfiles $options",
+    " -I", " -L", " -l$1", "", "-fPIE", "asm($1);$n", "$1 $3 $2 ",
+    "-Wa,-acdl=$asmfile -g -fverbose-asm -masm=intel",
+    "-std=gnu++17 -funsigned-char", {hasSwitchRange, hasComputedGoto, hasCpp,
+                                     hasGcGuard, hasGnuAsm, hasAttribute,
+                                     hasBuiltinUnreachable}), ("llvm_gcc", "o",
+    " -O3 -fno-ident", " -Os -fno-ident", "llvm-gcc", "llvm-g++",
+    "-c $options $include -o $objfile $file", " -mwindows", " -shared",
+    "llvm-ar rcs $libfile $objfiles", "",
+    "$buildgui $builddll -o $exefile $objfiles $options", " -I", " -L", " -l$1",
+    "", "-fPIC", "__asm__($1);$n", "$1 $3 $2 ",
+    "-Wa,-acdl=$asmfile -g -fverbose-asm -masm=intel",
+    "-std=gnu++17 -funsigned-char", {hasSwitchRange, hasComputedGoto, hasCpp,
+                                     hasGcGuard, hasGnuAsm, hasAttribute,
+                                     hasBuiltinUnreachable}), ("clang", "o",
+    " -O3 -fno-ident", " -Os -fno-ident", "clang", "clang++",
+    "-c $options $include -o $objfile $file", " -mwindows", " -shared",
+    "llvm-ar rcs $libfile $objfiles", "",
+    "$buildgui $builddll -o $exefile $objfiles $options", " -I", " -L", " -l$1",
+    "", "-fPIC", "__asm__($1);$n", "$1 $3 $2 ",
+    "-Wa,-acdl=$asmfile -g -fverbose-asm -masm=intel",
+    "-std=gnu++17 -funsigned-char", {hasSwitchRange, hasComputedGoto, hasCpp,
+                                     hasGcGuard, hasGnuAsm, hasAttribute,
+                                     hasBuiltinUnreachable}), ("bcc", "obj",
+    " -O3 -6 ", " -O1 -6 ", "bcc32c", "cpp32c",
+    "-c $options $include -o$objfile $file", " -tW", " -tWD", "", "bcc32",
+    "$options $buildgui $builddll -e$exefile $objfiles", " -I", "", "", "", "",
+    "__asm{$n$1$n}$n", "$1 $2", "", "",
+    {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard, hasAttribute}), (
+    "vcc", "obj", " /Ogityb2 ", " /O1 ", "cl", "cl",
+    "/c$vccplatform $options $include /nologo /Fo$objfile $file",
+    " /SUBSYSTEM:WINDOWS user32.lib ", " /LD",
+    "vccexe --command:lib$vccplatform /nologo /OUT:$libfile $objfiles", "cl",
+    "$builddll$vccplatform /Fe$exefile $objfiles $buildgui /nologo $options",
+    " /I", " /link /LIBPATH:", " $1.lib", " /RTC1 /Z7 ", "", "__asm{$n$1$n}$n",
+    "$3$n$1 $2", "/Fa$asmfile", "", {hasCpp, hasAssume, hasDeclspec}), ("tcc",
+    "o", "", "", "tcc", "", "-c $options $include -o $objfile $file",
+    "-Wl,-subsystem=gui", " -shared", "", "tcc",
+    "-o $exefile $options $buildgui $builddll $objfiles", " -I", "", "", " -g ",
+    "", "asm($1);$n", "$1 $2",
+    "-Wa,-acdl=$asmfile -g -fverbose-asm -masm=intel", "",
+    {hasSwitchRange, hasComputedGoto, hasGnuAsm}), ("env", "o", " -O3 ",
+    " -O1 ", "", "", "-c $ccenvflags $options $include -o $objfile $file", "",
+    " -shared ", "", "", "-o $exefile $buildgui $builddll $objfiles $options",
+    " -I", "", "", "", "", "__asm{$n$1$n}$n", "$1 $2", "", "", {hasGnuAsm}), (
+    "icl", "obj", " /Ogityb2 ", " /O1 ", "icl", "cl",
+    "/c$vccplatform $options $include /nologo /Fo$objfile $file",
+    " /SUBSYSTEM:WINDOWS user32.lib ", " /LD",
+    "vccexe --command:lib$vccplatform /nologo /OUT:$libfile $objfiles", "icl",
+    "$builddll$vccplatform /Fe$exefile $objfiles $buildgui /nologo $options",
+    " /I", " /link /LIBPATH:", " $1.lib", " /RTC1 /Z7 ", "", "__asm{$n$1$n}$n",
+    "$3$n$1 $2", "/Fa$asmfile", "", {hasCpp, hasAssume, hasDeclspec}), ("icc",
+    "o", " -O3 -fno-ident", " -Os -fno-ident", "icc", "g++",
+    "-c $options $include -o $objfile $file", " -mwindows", " -shared",
+    "ar rcs $libfile $objfiles", "icc",
+    "$buildgui $builddll -o $exefile $objfiles $options", " -I", " -L", " -l$1",
+    "", "-fPIC", "__asm__($1);$n", "$1 $3 $2 ",
+    "-Wa,-acdl=$asmfile -g -fverbose-asm -masm=intel",
+    "-std=gnu++17 -funsigned-char", {hasSwitchRange, hasComputedGoto, hasCpp,
+                                     hasGcGuard, hasGnuAsm, hasAttribute,
+                                     hasBuiltinUnreachable}), ("clang_cl",
+    "obj", " /Ogityb2 ", " /O1 ", "clang-cl", "clang-cl",
+    "/c$vccplatform $options $include /nologo /Fo$objfile $file",
+    " /SUBSYSTEM:WINDOWS user32.lib ", " /LD",
+    "vccexe --command:lib$vccplatform /nologo /OUT:$libfile $objfiles",
+    "clang-cl", "-fuse-ld=lld $builddll$vccplatform /Fe$exefile $objfiles $buildgui /nologo $options",
+    " /I", " /link /LIBPATH:", " $1.lib", " /RTC1 /Z7 ", "", "__asm{$n$1$n}$n",
+    "$3$n$1 $2", "/Fa$asmfile", "", {hasCpp, hasAssume, hasDeclspec}), ("hipcc",
+    "o", " -O3 -fno-ident", " -Os -fno-ident", "hipcc", "hipcc",
+    "-c $options $include -o $objfile $file", " -mwindows", " -shared",
+    "llvm-ar rcs $libfile $objfiles", "",
+    "$buildgui $builddll -o $exefile $objfiles $options", " -I", " -L", " -l$1",
+    "", "-fPIC", "__asm__($1);$n", "$1 $3 $2 ",
+    "-Wa,-acdl=$asmfile -g -fverbose-asm -masm=intel",
+    "-std=gnu++17 -funsigned-char", {hasSwitchRange, hasComputedGoto, hasCpp,
+                                     hasGcGuard, hasGnuAsm, hasAttribute,
+                                     hasBuiltinUnreachable}), ("nvcc", "o",
+    " -O3 -fno-ident", " -Os -fno-ident", "nvcc", "nvcc",
+    "-c -x cu -Xcompiler=\"$options\" $include -o $objfile $file", " -mwindows",
+    " -shared", "ar rcs $libfile $objfiles", "",
+    "$buildgui $builddll -o $exefile $objfiles -Xcompiler=\"$options\"", " -I",
+    " -L", " -l$1", "", "-fPIC", "__asm__($1);$n", "$1 $3 $2 ",
+    "-Wa,-acdl=$asmfile -g -fverbose-asm -masm=intel",
+    "-std=gnu++17 -funsigned-char", {hasSwitchRange, hasComputedGoto, hasCpp,
+                                     hasGcGuard, hasGnuAsm, hasAttribute,
+                                     hasBuiltinUnreachable})]
+
+ + + Source   +Edit   + +
+
+
+
hExt = ".h"
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc addCompileOption(conf: ConfigRef; option: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addCompileOptionCmd(conf: ConfigRef; option: string) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addExternalFileToCompile(conf: ConfigRef; c: var Cfile) {....raises: [OSError,
+    Exception, IOError, ValueError, KeyError, ERecoverableError, EOFError], tags: [
+    ReadEnvEffect, ReadIOEffect, RootEffect, ReadDirEffect, WriteIOEffect,
+    WriteDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc addExternalFileToCompile(conf: ConfigRef; filename: AbsoluteFile) {....raises: [
+    OSError, IOError, Exception, ValueError, KeyError, ERecoverableError,
+    EOFError], tags: [ReadEnvEffect, ReadIOEffect, WriteDirEffect,
+                      ReadDirEffect, RootEffect, WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
proc addFileToCompile(conf: ConfigRef; cf: Cfile) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addLinkOption(conf: ConfigRef; option: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addLinkOptionCmd(conf: ConfigRef; option: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addLocalCompileOption(conf: ConfigRef; option: string;
+                           nimfile: AbsoluteFile) {.
+    ...raises: [OSError, IOError, Exception], tags: [ReadEnvEffect, ReadIOEffect,
+    WriteDirEffect, ReadDirEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc callCCompiler(conf: ConfigRef) {....raises: [Exception, ValueError, KeyError,
+    IOError, ERecoverableError, OSError], tags: [ReadEnvEffect, RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, WriteDirEffect, ExecIOEffect,
+    TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ccHasSaneOverflow(conf: ConfigRef): bool {....raises: [ValueError],
+    tags: [ExecIOEffect, ReadIOEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc changeDetectedViaJsonBuildInstructions(conf: ConfigRef;
+    jsonFile: AbsoluteFile): bool {....raises: [OSError, IOError, ValueError], tags: [
+    ReadDirEffect, RootEffect, ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc completeCfilePath(conf: ConfigRef; cfile: AbsoluteFile;
+                       createSubDir: bool = true): AbsoluteFile {.
+    ...raises: [OSError, IOError],
+    tags: [ReadEnvEffect, ReadIOEffect, WriteDirEffect, ReadDirEffect],
+    forbids: [].}
+
+ + Generate the absolute file path to the generated modules. + Source   +Edit   + +
+
+ +
+
+
+
proc execExternalProgram(conf: ConfigRef; cmd: string; msg = hintExecuting) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    ExecIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getCompileCFileCmd(conf: ConfigRef; cfile: Cfile; isMainFile = false;
+                        produceOutput = false): string {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    ReadEnvEffect, RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect,
+    WriteDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initVars(conf: ConfigRef) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isVSCompatible(conf: ConfigRef): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc jsonBuildInstructionsFile(conf: ConfigRef): AbsoluteFile {.
+    ...raises: [OSError], tags: [ReadEnvEffect, ReadIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nameToCC(name: string): TSystemCC {....raises: [], tags: [], forbids: [].}
+
+ + Returns the kind of compiler referred to by name, or ccNone if the name doesn't refer to any known compiler. + Source   +Edit   + +
+
+ +
+
+
+
proc resetCompilationLists(conf: ConfigRef) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc runJsonBuildInstructions(conf: ConfigRef; jsonFile: AbsoluteFile) {....raises: [
+    OSError, IOError, Exception, ValueError, KeyError, ERecoverableError], tags: [
+    RootEffect, ReadIOEffect, WriteIOEffect, WriteDirEffect, ReadDirEffect,
+    ReadEnvEffect, ExecIOEffect, TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setCC(conf: ConfigRef; ccname: string; info: TLineInfo) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toObjFile(conf: ConfigRef; filename: AbsoluteFile): AbsoluteFile {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc writeJsonBuildInstructions(conf: ConfigRef; deps: StringTableRef) {....raises: [
+    OSError, Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, ReadEnvEffect, RootEffect, WriteIOEffect, ReadIOEffect,
+    WriteDirEffect, TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc writeMapping(conf: ConfigRef; symbolMapping: Rope) {....raises: [ValueError,
+    OSError, IOError, Exception, KeyError, ERecoverableError], tags: [
+    WriteIOEffect, RootEffect, ReadDirEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/extccomp.idx b/compiler/extccomp.idx new file mode 100644 index 0000000000000..f91ccd25502b6 --- /dev/null +++ b/compiler/extccomp.idx @@ -0,0 +1,41 @@ +nimTitle extccomp extccomp.html module extccomp 0 +nim hasSwitchRange extccomp.html#hasSwitchRange TInfoCCProp.hasSwitchRange 27 +nim hasComputedGoto extccomp.html#hasComputedGoto TInfoCCProp.hasComputedGoto 27 +nim hasCpp extccomp.html#hasCpp TInfoCCProp.hasCpp 27 +nim hasAssume extccomp.html#hasAssume TInfoCCProp.hasAssume 27 +nim hasGcGuard extccomp.html#hasGcGuard TInfoCCProp.hasGcGuard 27 +nim hasGnuAsm extccomp.html#hasGnuAsm TInfoCCProp.hasGnuAsm 27 +nim hasDeclspec extccomp.html#hasDeclspec TInfoCCProp.hasDeclspec 27 +nim hasAttribute extccomp.html#hasAttribute TInfoCCProp.hasAttribute 27 +nim hasBuiltinUnreachable extccomp.html#hasBuiltinUnreachable TInfoCCProp.hasBuiltinUnreachable 27 +nim TInfoCCProp extccomp.html#TInfoCCProp enum TInfoCCProp 27 +nim TInfoCCProps extccomp.html#TInfoCCProps type TInfoCCProps 37 +nim TInfoCC extccomp.html#TInfoCC tuple TInfoCC 38 +nim CC extccomp.html#CC const CC 297 +nim hExt extccomp.html#hExt const hExt 312 +nim nameToCC extccomp.html#nameToCC,string proc nameToCC(name: string): TSystemCC 319 +nim isVSCompatible extccomp.html#isVSCompatible,ConfigRef proc isVSCompatible(conf: ConfigRef): bool 333 +nim setCC extccomp.html#setCC,ConfigRef,string,TLineInfo proc setCC(conf: ConfigRef; ccname: string; info: TLineInfo) 364 +nim addLinkOption extccomp.html#addLinkOption,ConfigRef,string proc addLinkOption(conf: ConfigRef; option: string) 378 +nim addCompileOption extccomp.html#addCompileOption,ConfigRef,string proc addCompileOption(conf: ConfigRef; option: string) 381 +nim addLinkOptionCmd extccomp.html#addLinkOptionCmd,ConfigRef,string proc addLinkOptionCmd(conf: ConfigRef; option: string) 385 +nim addCompileOptionCmd extccomp.html#addCompileOptionCmd,ConfigRef,string proc addCompileOptionCmd(conf: ConfigRef; option: string) 388 +nim initVars extccomp.html#initVars,ConfigRef proc initVars(conf: ConfigRef) 391 +nim completeCfilePath extccomp.html#completeCfilePath,ConfigRef,AbsoluteFile,bool proc completeCfilePath(conf: ConfigRef; cfile: AbsoluteFile;\n createSubDir: bool = true): AbsoluteFile 400 +nim toObjFile extccomp.html#toObjFile,ConfigRef,AbsoluteFile proc toObjFile(conf: ConfigRef; filename: AbsoluteFile): AbsoluteFile 405 +nim addFileToCompile extccomp.html#addFileToCompile,ConfigRef,Cfile proc addFileToCompile(conf: ConfigRef; cf: Cfile) 409 +nim addLocalCompileOption extccomp.html#addLocalCompileOption,ConfigRef,string,AbsoluteFile proc addLocalCompileOption(conf: ConfigRef; option: string; nimfile: AbsoluteFile) 412 +nim resetCompilationLists extccomp.html#resetCompilationLists,ConfigRef proc resetCompilationLists(conf: ConfigRef) 419 +nim addExternalFileToLink extccomp.html#addExternalFileToLink,ConfigRef,AbsoluteFile proc addExternalFileToLink(conf: ConfigRef; filename: AbsoluteFile) 427 +nim execExternalProgram extccomp.html#execExternalProgram,ConfigRef,string proc execExternalProgram(conf: ConfigRef; cmd: string; msg = hintExecuting) 434 +nim ccHasSaneOverflow extccomp.html#ccHasSaneOverflow,ConfigRef proc ccHasSaneOverflow(conf: ConfigRef): bool 556 +nim getCompileCFileCmd extccomp.html#getCompileCFileCmd,ConfigRef,Cfile proc getCompileCFileCmd(conf: ConfigRef; cfile: Cfile; isMainFile = false;\n produceOutput = false): string 574 +nim addExternalFileToCompile extccomp.html#addExternalFileToCompile,ConfigRef,Cfile proc addExternalFileToCompile(conf: ConfigRef; c: var Cfile) 686 +nim addExternalFileToCompile extccomp.html#addExternalFileToCompile,ConfigRef,AbsoluteFile proc addExternalFileToCompile(conf: ConfigRef; filename: AbsoluteFile) 698 +nim callCCompiler extccomp.html#callCCompiler,ConfigRef proc callCCompiler(conf: ConfigRef) 913 +nim jsonBuildInstructionsFile extccomp.html#jsonBuildInstructionsFile,ConfigRef proc jsonBuildInstructionsFile(conf: ConfigRef): AbsoluteFile 1001 +nim writeJsonBuildInstructions extccomp.html#writeJsonBuildInstructions,ConfigRef,StringTableRef proc writeJsonBuildInstructions(conf: ConfigRef; deps: StringTableRef) 1025 +nim changeDetectedViaJsonBuildInstructions extccomp.html#changeDetectedViaJsonBuildInstructions,ConfigRef,AbsoluteFile proc changeDetectedViaJsonBuildInstructions(conf: ConfigRef; jsonFile: AbsoluteFile): bool 1060 +nim runJsonBuildInstructions extccomp.html#runJsonBuildInstructions,ConfigRef,AbsoluteFile proc runJsonBuildInstructions(conf: ConfigRef; jsonFile: AbsoluteFile) 1080 +nim writeMapping extccomp.html#writeMapping,ConfigRef,Rope proc writeMapping(conf: ConfigRef; symbolMapping: Rope) 1109 +nimgrp addexternalfiletocompile extccomp.html#addExternalFileToCompile-procs-all proc 686 diff --git a/compiler/filter_tmpl.html b/compiler/filter_tmpl.html new file mode 100644 index 0000000000000..c6785e23fe1fa --- /dev/null +++ b/compiler/filter_tmpl.html @@ -0,0 +1,125 @@ + + + + + + + +filter_tmpl + + + + + + + + + + + + + + + + +
+
+

filter_tmpl

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc filterTmpl(conf: ConfigRef; stdin: PLLStream; filename: AbsoluteFile;
+                call: PNode): PLLStream {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/filter_tmpl.idx b/compiler/filter_tmpl.idx new file mode 100644 index 0000000000000..de1e158f7f7d9 --- /dev/null +++ b/compiler/filter_tmpl.idx @@ -0,0 +1,2 @@ +nimTitle filter_tmpl filter_tmpl.html module filter_tmpl 0 +nim filterTmpl filter_tmpl.html#filterTmpl,ConfigRef,PLLStream,AbsoluteFile,PNode proc filterTmpl(conf: ConfigRef; stdin: PLLStream; filename: AbsoluteFile;\n call: PNode): PLLStream 204 diff --git a/compiler/filters.html b/compiler/filters.html new file mode 100644 index 0000000000000..2559b39f7a3df --- /dev/null +++ b/compiler/filters.html @@ -0,0 +1,208 @@ + + + + + + + +filters + + + + + + + + + + + + + + + + +
+
+

filters

+
+ +
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc boolArg(conf: ConfigRef; n: PNode; name: string; pos: int; default: bool): bool {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc charArg(conf: ConfigRef; n: PNode; name: string; pos: int; default: char): char {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc filterReplace(conf: ConfigRef; stdin: PLLStream; filename: AbsoluteFile;
+                   call: PNode): PLLStream {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc filterStrip(conf: ConfigRef; stdin: PLLStream; filename: AbsoluteFile;
+                 call: PNode): PLLStream {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc strArg(conf: ConfigRef; n: PNode; name: string; pos: int; default: string): string {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/filters.idx b/compiler/filters.idx new file mode 100644 index 0000000000000..846f7852418f9 --- /dev/null +++ b/compiler/filters.idx @@ -0,0 +1,6 @@ +nimTitle filters filters.html module filters 0 +nim charArg filters.html#charArg,ConfigRef,PNode,string,int,char proc charArg(conf: ConfigRef; n: PNode; name: string; pos: int; default: char): char 33 +nim strArg filters.html#strArg,ConfigRef,PNode,string,int,string proc strArg(conf: ConfigRef; n: PNode; name: string; pos: int; default: string): string 42 +nim boolArg filters.html#boolArg,ConfigRef,PNode,string,int,bool proc boolArg(conf: ConfigRef; n: PNode; name: string; pos: int; default: bool): bool 50 +nim filterStrip filters.html#filterStrip,ConfigRef,PLLStream,AbsoluteFile,PNode proc filterStrip(conf: ConfigRef; stdin: PLLStream; filename: AbsoluteFile;\n call: PNode): PLLStream 59 +nim filterReplace filters.html#filterReplace,ConfigRef,PLLStream,AbsoluteFile,PNode proc filterReplace(conf: ConfigRef; stdin: PLLStream; filename: AbsoluteFile;\n call: PNode): PLLStream 73 diff --git a/compiler/gorgeimpl.html b/compiler/gorgeimpl.html new file mode 100644 index 0000000000000..b63d0b41c67fb --- /dev/null +++ b/compiler/gorgeimpl.html @@ -0,0 +1,124 @@ + + + + + + + +gorgeimpl + + + + + + + + + + + + + + + + +
+
+

gorgeimpl

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Module that implements gorge for the compiler.

+ +
+

Procs

+
+
+
+
proc opGorge(cmd, input, cache: string; info: TLineInfo; conf: ConfigRef): (
+    string, int) {....raises: [OSError, IOError, ValueError, ValueError], tags: [
+    ReadEnvEffect, ReadIOEffect, ExecIOEffect, RootEffect, WriteIOEffect,
+    TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/gorgeimpl.idx b/compiler/gorgeimpl.idx new file mode 100644 index 0000000000000..9556df6e98e78 --- /dev/null +++ b/compiler/gorgeimpl.idx @@ -0,0 +1,2 @@ +nimTitle gorgeimpl gorgeimpl.html module gorgeimpl 0 +nim opGorge gorgeimpl.html#opGorge,string,string,string,TLineInfo,ConfigRef proc opGorge(cmd, input, cache: string; info: TLineInfo; conf: ConfigRef): (string,\n int) 31 diff --git a/compiler/guards.html b/compiler/guards.html new file mode 100644 index 0000000000000..fbbf23edfa3f5 --- /dev/null +++ b/compiler/guards.html @@ -0,0 +1,562 @@ + + + + + + + +guards + + + + + + + + + + + + + + + + +
+
+

guards

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module implements the 'implies' relation for guards.

+ +
+

Types

+
+
+
TModel = object
+  s*: seq[PNode]
+  g*: ModuleGraph
+  beSmart*: bool
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc addAsgnFact(m: var TModel; key, value: PNode) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addCaseBranchFacts(m: var TModel; n: PNode; i: int) {.
+    ...raises: [ERecoverableError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addDiscriminantFact(m: var TModel; n: PNode) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addFact(m: var TModel; nn: PNode) {....raises: [ERecoverableError, KeyError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addFactLe(m: var TModel; a, b: PNode) {....raises: [KeyError], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addFactLt(m: var TModel; a, b: PNode) {....raises: [KeyError], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addFactNeg(m: var TModel; n: PNode) {.
+    ...raises: [ERecoverableError, KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc buildAdd(a: PNode; b: BiggestInt; o: Operators): PNode {.
+    ...raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc buildCall(op: PSym; a, b: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc buildCall(op: PSym; a: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc buildLe(o: Operators; a, b: PNode): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc canon(n: PNode; o: Operators): PNode {....raises: [KeyError], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc checkFieldAccess(m: TModel; n: PNode; conf: ConfigRef; produceError: bool) {.
+    ...raises: [KeyError, ERecoverableError, Exception, ValueError, IOError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc doesImply(facts: TModel; prop: PNode): TImplication {.
+    ...raises: [ERecoverableError, KeyError, Exception, ValueError, IOError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc highBound(conf: ConfigRef; x: PNode; o: Operators): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc impliesNotNil(m: TModel; arg: PNode): TImplication {.
+    ...raises: [ERecoverableError, KeyError, Exception, ValueError, IOError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc interestingCaseExpr(m: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc invalidateFacts(m: var TModel; n: PNode) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc invalidateFacts(s: var seq[PNode]; n: PNode) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lowBound(conf: ConfigRef; x: PNode): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc proveLe(m: TModel; a, b: PNode): TImplication {.
+    ...raises: [KeyError, ERecoverableError, Exception, ValueError, IOError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sameSubexprs(m: TModel; a, b: PNode): bool {.
+    ...raises: [ERecoverableError, KeyError, Exception, ValueError, IOError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sameTree(a, b: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc simpleSlice(a, b: PNode): BiggestInt {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/guards.idx b/compiler/guards.idx new file mode 100644 index 0000000000000..b80441fc4fa85 --- /dev/null +++ b/compiler/guards.idx @@ -0,0 +1,28 @@ +nimTitle guards guards.html module guards 0 +nim interestingCaseExpr guards.html#interestingCaseExpr,PNode proc interestingCaseExpr(m: PNode): bool 93 +nim buildCall guards.html#buildCall,PSym,PNode proc buildCall(op: PSym; a: PNode): PNode 151 +nim buildCall guards.html#buildCall,PSym,PNode,PNode proc buildCall(op: PSym; a, b: PNode): PNode 156 +nim lowBound guards.html#lowBound,ConfigRef,PNode proc lowBound(conf: ConfigRef; x: PNode): PNode 202 +nim highBound guards.html#highBound,ConfigRef,PNode,Operators proc highBound(conf: ConfigRef; x: PNode; o: Operators): PNode 206 +nim buildLe guards.html#buildLe,Operators,PNode,PNode proc buildLe(o: Operators; a, b: PNode): PNode 244 +nim canon guards.html#canon,PNode,Operators proc canon(n: PNode; o: Operators): PNode 247 +nim buildAdd guards.html#buildAdd,PNode,BiggestInt,Operators proc buildAdd(a: PNode; b: BiggestInt; o: Operators): PNode 324 +nim TModel guards.html#TModel object TModel 415 +nim addFact guards.html#addFact,TModel,PNode proc addFact(m: var TModel; nn: PNode) 420 +nim addFactNeg guards.html#addFactNeg,TModel,PNode proc addFactNeg(m: var TModel; n: PNode) 433 +nim sameTree guards.html#sameTree,PNode,PNode proc sameTree(a, b: PNode): bool 449 +nim invalidateFacts guards.html#invalidateFacts,seq[PNode],PNode proc invalidateFacts(s: var seq[PNode]; n: PNode) 484 +nim invalidateFacts guards.html#invalidateFacts,TModel,PNode proc invalidateFacts(m: var TModel; n: PNode) 505 +nim doesImply guards.html#doesImply,TModel,PNode proc doesImply(facts: TModel; prop: PNode): TImplication 842 +nim impliesNotNil guards.html#impliesNotNil,TModel,PNode proc impliesNotNil(m: TModel; arg: PNode): TImplication 851 +nim simpleSlice guards.html#simpleSlice,PNode,PNode proc simpleSlice(a, b: PNode): BiggestInt 854 +nim proveLe guards.html#proveLe,TModel,PNode,PNode proc proveLe(m: TModel; a, b: PNode): TImplication 1084 +nim addFactLe guards.html#addFactLe,TModel,PNode,PNode proc addFactLe(m: var TModel; a, b: PNode) 1093 +nim addFactLt guards.html#addFactLt,TModel,PNode,PNode proc addFactLt(m: var TModel; a, b: PNode) 1096 +nim addDiscriminantFact guards.html#addDiscriminantFact,TModel,PNode proc addDiscriminantFact(m: var TModel; n: PNode) 1127 +nim addAsgnFact guards.html#addAsgnFact,TModel,PNode,PNode proc addAsgnFact(m: var TModel; key, value: PNode) 1134 +nim sameSubexprs guards.html#sameSubexprs,TModel,PNode,PNode proc sameSubexprs(m: TModel; a, b: PNode): bool 1141 +nim addCaseBranchFacts guards.html#addCaseBranchFacts,TModel,PNode,int proc addCaseBranchFacts(m: var TModel; n: PNode; i: int) 1157 +nim checkFieldAccess guards.html#checkFieldAccess,TModel,PNode,ConfigRef,bool proc checkFieldAccess(m: TModel; n: PNode; conf: ConfigRef; produceError: bool) 1182 +nimgrp buildcall guards.html#buildCall-procs-all proc 151 +nimgrp invalidatefacts guards.html#invalidateFacts-procs-all proc 484 diff --git a/compiler/ic/bitabs.html b/compiler/ic/bitabs.html new file mode 100644 index 0000000000000..e7e7a64fc7ce3 --- /dev/null +++ b/compiler/ic/bitabs.html @@ -0,0 +1,398 @@ + + + + + + + +ic/bitabs + + + + + + + + + + + + + + + + +
+
+

ic/bitabs

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

A BiTable is a table that can be seen as an optimized pair of (Table[LitId, Val], Table[Val, LitId]).

+
+

Imports

+
+ rodfiles +
+
+
+

Types

+
+
+
BiTable[T] = object
+
+ + + Source   +Edit   + +
+
+
+
LitId = distinct uint32
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(x: LitId): string {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `<`(x, y: LitId): bool {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `<=`(x, y: LitId): bool {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(x, y: LitId): bool {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `[]`[T](t: BiTable[T]; litId: LitId): lent T {.inline.}
+
+ + + Source   +Edit   + +
+
+
+
proc `[]`[T](t: var BiTable[T]; litId: LitId): var T {.inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getKeyId[T](t: BiTable[T]; v: T): LitId
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getOrIncl[T](t: var BiTable[T]; v: T): LitId
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hash(x: LitId): Hash {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc hash[T](t: BiTable[T]): Hash
+
+ + as the keys are hashes of the values, we simply use them instead + Source   +Edit   + +
+
+ +
+
+
+
proc hasLitId[T](t: BiTable[T]; x: LitId): bool
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initBiTable[T](): BiTable[T]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc len[T](t: BiTable[T]): int
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc load[T](f: var RodFile; t: var BiTable[T])
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sizeOnDisc(t: BiTable[string]): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc store[T](f: var RodFile; t: BiTable[T])
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/ic/bitabs.idx b/compiler/ic/bitabs.idx new file mode 100644 index 0000000000000..2dcdc45c8b54e --- /dev/null +++ b/compiler/ic/bitabs.idx @@ -0,0 +1,21 @@ +nimTitle bitabs ic/bitabs.html module ic/bitabs 0 +nim LitId ic/bitabs.html#LitId type LitId 11 +nim BiTable ic/bitabs.html#BiTable object BiTable 13 +nim initBiTable ic/bitabs.html#initBiTable proc initBiTable[T](): BiTable[T] 17 +nim `$` ic/bitabs.html#$,LitId proc `$`(x: LitId): string 25 +nim `<` ic/bitabs.html#<,LitId,LitId proc `<`(x, y: LitId): bool 26 +nim `<=` ic/bitabs.html#<=,LitId,LitId proc `<=`(x, y: LitId): bool 27 +nim `==` ic/bitabs.html#==,LitId,LitId proc `==`(x, y: LitId): bool 28 +nim hash ic/bitabs.html#hash,LitId proc hash(x: LitId): Hash 29 +nim len ic/bitabs.html#len,BiTable[T] proc len[T](t: BiTable[T]): int 32 +nim hasLitId ic/bitabs.html#hasLitId,BiTable[T],LitId proc hasLitId[T](t: BiTable[T]; x: LitId): bool 43 +nim getKeyId ic/bitabs.html#getKeyId,BiTable[T],T proc getKeyId[T](t: BiTable[T]; v: T): LitId 59 +nim getOrIncl ic/bitabs.html#getOrIncl,BiTable[T],T proc getOrIncl[T](t: var BiTable[T]; v: T): LitId 70 +nim `[]` ic/bitabs.html#[],BiTable[T],LitId proc `[]`[T](t: var BiTable[T]; litId: LitId): var T 97 +nim `[]` ic/bitabs.html#[],BiTable[T],LitId_2 proc `[]`[T](t: BiTable[T]; litId: LitId): lent T 102 +nim hash ic/bitabs.html#hash,BiTable[T] proc hash[T](t: BiTable[T]): Hash 107 +nim store ic/bitabs.html#store,RodFile,BiTable[T] proc store[T](f: var RodFile; t: BiTable[T]) 114 +nim load ic/bitabs.html#load,RodFile,BiTable[T] proc load[T](f: var RodFile; t: var BiTable[T]) 118 +nim sizeOnDisc ic/bitabs.html#sizeOnDisc,BiTable[string] proc sizeOnDisc(t: BiTable[string]): int 122 +nimgrp [] ic/bitabs.html#[]-procs-all proc 97 +nimgrp hash ic/bitabs.html#hash-procs-all proc 29 diff --git a/compiler/ic/cbackend.html b/compiler/ic/cbackend.html new file mode 100644 index 0000000000000..b6b44db76e401 --- /dev/null +++ b/compiler/ic/cbackend.html @@ -0,0 +1,122 @@ + + + + + + + +ic/cbackend + + + + + + + + + + + + + + + + +
+
+

ic/cbackend

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

New entry point into our C/C++ code generator. Ideally somebody would rewrite the old backend (which is 8000 lines of crufty Nim code) to work on packed trees directly and produce the C code as an AST which can then be rendered to text in a very simple manner. Unfortunately nobody wrote this code. So instead we wrap the existing cgen.nim and its friends so that we call directly into the existing code generation logic but avoiding the naive, outdated passes design. Thus you will see some useAliveDataFromDce in flags checks in the old code -- the old code is also doing cross-module dependency tracking and DCE that we don't need anymore. DCE is now done as prepass over the entire packed module graph.

+ +
+

Procs

+
+
+
+
proc generateCode(g: ModuleGraph) {....raises: [KeyError, Exception, OSError,
+    IOError, ValueError, ERecoverableError], tags: [ReadDirEffect, RootEffect,
+    ReadEnvEffect, ReadIOEffect, WriteDirEffect, WriteIOEffect, TimeEffect],
+                                    forbids: [].}
+
+ + The single entry point, generate C(++) code for the entire Nim program aka ModuleGraph. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/ic/cbackend.idx b/compiler/ic/cbackend.idx new file mode 100644 index 0000000000000..519c721e69a7a --- /dev/null +++ b/compiler/ic/cbackend.idx @@ -0,0 +1,2 @@ +nimTitle cbackend ic/cbackend.html module ic/cbackend 0 +nim generateCode ic/cbackend.html#generateCode,ModuleGraph proc generateCode(g: ModuleGraph) 142 diff --git a/compiler/ic/dce.html b/compiler/ic/dce.html new file mode 100644 index 0000000000000..cfd1cd52625ee --- /dev/null +++ b/compiler/ic/dce.html @@ -0,0 +1,183 @@ + + + + + + + +ic/dce + + + + + + + + + + + + + + + + +
+
+

ic/dce

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Dead code elimination (=DCE) for IC.

+ +
+

Types

+
+
+
AliveContext = object
+  ## A stack for marking symbols as alive.
+  ## We need a PackedDecoder for module ID address translations.
+  ## The module we're currently analysing for DCE.
+  ## The final result of our computation.
+
+ + Purpose is to fill the 'alive' field. + Source   +Edit   + +
+
+
+
AliveSyms = seq[IntSet]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc computeAliveSyms(g: PackedModuleGraph; conf: ConfigRef): AliveSyms {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + Entry point for our DCE algorithm. + Source   +Edit   + +
+
+ +
+
+
+
proc isAlive(a: AliveSyms; module: int; item: int32): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ + Backends use this to query if a symbol is alive which means we need to produce (C/C++/etc) code for it. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/ic/dce.idx b/compiler/ic/dce.idx new file mode 100644 index 0000000000000..738a0073b6d69 --- /dev/null +++ b/compiler/ic/dce.idx @@ -0,0 +1,5 @@ +nimTitle dce ic/dce.html module ic/dce 0 +nim AliveSyms ic/dce.html#AliveSyms type AliveSyms 22 +nim AliveContext ic/dce.html#AliveContext object AliveContext 23 +nim computeAliveSyms ic/dce.html#computeAliveSyms,PackedModuleGraph,ConfigRef proc computeAliveSyms(g: PackedModuleGraph; conf: ConfigRef): AliveSyms 151 +nim isAlive ic/dce.html#isAlive,AliveSyms,int,int32 proc isAlive(a: AliveSyms; module: int; item: int32): bool 165 diff --git a/compiler/ic/ic.html b/compiler/ic/ic.html new file mode 100644 index 0000000000000..895e587864cf5 --- /dev/null +++ b/compiler/ic/ic.html @@ -0,0 +1,1307 @@ + + + + + + + +ic/ic + + + + + + + + + + + + + + + + +
+
+

ic/ic

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
LoadedModule = object
+  status*: ModuleStatus
+  fromDisk*: PackedModule
+  module*: PSym
+
+ + + Source   +Edit   + +
+
+
+
ModuleBackendFlag = enum
+  HasDatInitProc, HasModuleInitProc
+
+ + + Source   +Edit   + +
+
+
+
ModuleStatus = enum
+  undefined, storing, loading, loaded, outdated, stored
+
+ + + Source   +Edit   + +
+
+
+
PackedConfig = object
+
+ + + Source   +Edit   + +
+
+
+
PackedDecoder = object
+  config*: ConfigRef
+  cache*: IdentCache
+
+ + + Source   +Edit   + +
+
+
+
PackedEncoder = object
+  thisModule*: int32
+  lastFile*: FileIndex
+  lastLit*: LitId
+  filenames*: Table[FileIndex, LitId]
+  pendingTypes*: seq[PType]
+  pendingSyms*: seq[PSym]
+  typeMarker*: IntSet
+  symMarker*: IntSet
+  config*: ConfigRef
+
+ + + Source   +Edit   + +
+
+
+
PackedModule = object
+  includes*: seq[(LitId, string)]
+  toReplay*: PackedTree
+  topLevel*: PackedTree
+  bodies*: PackedTree
+  exports*: seq[(LitId, int32)]
+  compilerProcs*: seq[(LitId, int32)]
+  converters*, methods*, trmacros*, pureEnums*: seq[int32]
+  typeInstCache*: seq[(PackedItemId, PackedItemId)]
+  procInstCache*: seq[PackedInstantiation]
+  attachedOps*: seq[(PackedItemId, TTypeAttachedOp, PackedItemId)]
+  methodsPerGenericType*: seq[(PackedItemId, int, PackedItemId)]
+  enumToStringProcs*: seq[(PackedItemId, PackedItemId)]
+  methodsPerType*: seq[(PackedItemId, PackedItemId)]
+  dispatchers*: seq[PackedItemId]
+  emittedTypeInfo*: seq[string]
+  backendFlags*: set[ModuleBackendFlag]
+  syms*: OrderedTable[int32, PackedSym]
+  types*: OrderedTable[int32, PackedType]
+  strings*: BiTable[string]
+  numbers*: BiTable[BiggestInt]
+  man*: LineInfoManager
+
+ + the parts of a PackedEncoder that are part of the .rod file + Source   +Edit   + +
+
+
+
PackedModuleGraph = object
+  pm*: seq[LoadedModule]
+  when BenchIC:
+
+ + + Source   +Edit   + +
+
+
+
RodIter = object
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
BenchIC = false
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc addCompilerProc(c: var PackedEncoder; m: var PackedModule; s: PSym) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addConverter(c: var PackedEncoder; m: var PackedModule; s: PSym) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addExported(c: var PackedEncoder; m: var PackedModule; s: PSym) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addHidden(c: var PackedEncoder; m: var PackedModule; s: PSym) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addImportFileDep(c: var PackedEncoder; m: var PackedModule; f: FileIndex) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addIncludeFileDep(c: var PackedEncoder; m: var PackedModule; f: FileIndex) {.
+    ...raises: [IOError], tags: [ReadIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addMethod(c: var PackedEncoder; m: var PackedModule; s: PSym) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addPragmaComputation(c: var PackedEncoder; m: var PackedModule; n: PNode) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addPureEnum(c: var PackedEncoder; m: var PackedModule; s: PSym) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addReexport(c: var PackedEncoder; m: var PackedModule; s: PSym) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addTrmacro(c: var PackedEncoder; m: var PackedModule; s: PSym) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc debug(tree: PackedTree; m: PackedModule) {....raises: [IOError, KeyError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc idgenFromLoadedModule(m: LoadedModule): IdGenerator {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initEncoder(c: var PackedEncoder; m: var PackedModule; moduleSym: PSym;
+                 config: ConfigRef; pc: PackedConfig) {....raises: [IOError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + setup a context for serializing to packed ast + Source   +Edit   + +
+
+ +
+
+
+
proc initPackedDecoder(config: ConfigRef; cache: IdentCache): PackedDecoder {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initRodIter(it: var RodIter; config: ConfigRef; cache: IdentCache;
+                 g: var PackedModuleGraph; module: FileIndex; name: PIdent;
+                 importHidden: bool): PSym {....raises: [KeyError, Exception],
+    tags: [ReadDirEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initRodIterAllSyms(it: var RodIter; config: ConfigRef; cache: IdentCache;
+                        g: var PackedModuleGraph; module: FileIndex;
+                        importHidden: bool): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc interfaceSymbol(config: ConfigRef; cache: IdentCache;
+                     g: var PackedModuleGraph; module: FileIndex; name: PIdent;
+                     importHidden: bool): PSym {....raises: [KeyError, Exception],
+    tags: [ReadDirEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isActive(e: PackedEncoder): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc loadNodes(c: var PackedDecoder; g: var PackedModuleGraph; thisModule: int;
+               tree: PackedTree; n: NodePos): PNode {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc loadProcBody(config: ConfigRef; cache: IdentCache;
+                  g: var PackedModuleGraph; s: PSym): PNode {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc loadRodFile(filename: AbsoluteFile; m: var PackedModule; config: ConfigRef;
+                 ignoreConfig = false): RodFileError {.
+    ...raises: [IOError, KeyError, Exception],
+    tags: [ReadIOEffect, ReadDirEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc loadSymFromId(config: ConfigRef; cache: IdentCache;
+                   g: var PackedModuleGraph; module: int; id: PackedItemId): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc loadTypeFromId(config: ConfigRef; cache: IdentCache;
+                    g: var PackedModuleGraph; module: int; id: PackedItemId): PType {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc moduleFromRodFile(g: var PackedModuleGraph; conf: ConfigRef;
+                       cache: IdentCache; fileIdx: FileIndex;
+                       cachedModules: var seq[FileIndex]): PSym {....raises: [
+    OSError, IOError, Exception, KeyError, ValueError, ERecoverableError], tags: [
+    ReadEnvEffect, ReadIOEffect, WriteDirEffect, ReadDirEffect, RootEffect,
+    WriteIOEffect], forbids: [].}
+
+ + Returns 'nil' if the module needs to be recompiled. + Source   +Edit   + +
+
+ +
+
+
+
proc moduleIndex(c: var PackedDecoder; g: var PackedModuleGraph;
+                 thisModule: int; s: PackedItemId): int32 {.inline,
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nextRodIter(it: var RodIter; g: var PackedModuleGraph): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rememberStartupConfig(dest: var PackedConfig; config: ConfigRef) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rodViewer(rodfile: AbsoluteFile; config: ConfigRef; cache: IdentCache) {.
+    ...raises: [IOError, KeyError, Exception],
+    tags: [ReadIOEffect, ReadDirEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc saveRodFile(filename: AbsoluteFile; encoder: var PackedEncoder;
+                 m: var PackedModule) {....raises: [Exception, IOError, OSError], tags: [
+    RootEffect, WriteIOEffect, WriteDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc searchForCompilerproc(m: LoadedModule; name: string): int32 {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc simulateLoadedModule(g: var PackedModuleGraph; conf: ConfigRef;
+                          cache: IdentCache; moduleSym: PSym; m: PackedModule) {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc storeAttachedProcDef(t: PType; op: TTypeAttachedOp; s: PSym;
+                          encoder: var PackedEncoder; m: var PackedModule) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc storeExpansion(c: var PackedEncoder; m: var PackedModule; info: TLineInfo;
+                    s: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc storeInstantiation(c: var PackedEncoder; m: var PackedModule; s: PSym;
+                        i: PInstantiation) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc storeSym(s: PSym; c: var PackedEncoder; m: var PackedModule): PackedItemId {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc storeTypeInst(c: var PackedEncoder; m: var PackedModule; s: PSym;
+                   inst: PType) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toFileIndex(x: LitId; m: PackedModule; config: ConfigRef): FileIndex {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toFileIndexCached(c: var PackedDecoder; g: PackedModuleGraph;
+                       thisModule: int; f: LitId): FileIndex {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toPackedGeneratedProcDef(s: PSym; encoder: var PackedEncoder;
+                              m: var PackedModule) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Generic procs and generated =hook's need explicit top-level entries so that the code generator can work without having to special case these. These entries will also be useful for other tools and are the cleanest design I can come up with. + Source   +Edit   + +
+
+ +
+
+
+
proc toPackedNode(n: PNode; ir: var PackedTree; c: var PackedEncoder;
+                  m: var PackedModule) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toPackedNodeTopLevel(n: PNode; encoder: var PackedEncoder;
+                          m: var PackedModule) {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toRodFile(conf: ConfigRef; f: AbsoluteFile; ext = RodExt): AbsoluteFile {.
+    ...raises: [OSError, IOError, Exception], tags: [ReadEnvEffect, ReadIOEffect,
+    WriteDirEffect, ReadDirEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toString(tree: PackedTree; n: NodePos; m: PackedModule): string {.
+    ...raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc toString(tree: PackedTree; pos: NodePos; m: PackedModule; nesting: int;
+              result: var string) {....raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc translateId(id: PackedItemId; g: PackedModuleGraph; thisModule: int;
+                 config: ConfigRef): ItemId {....raises: [KeyError, Exception],
+    tags: [ReadDirEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator interfaceSymbols(config: ConfigRef; cache: IdentCache;
+                          g: var PackedModuleGraph; module: FileIndex;
+                          name: PIdent; importHidden: bool): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template `[]`(m: PackedModuleGraph; i: int): LoadedModule
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template len(m: PackedModuleGraph): int
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/ic/ic.idx b/compiler/ic/ic.idx new file mode 100644 index 0000000000000..99fffd8608d35 --- /dev/null +++ b/compiler/ic/ic.idx @@ -0,0 +1,69 @@ +nimTitle ic ic/ic.html module ic/ic 0 +nim PackedConfig ic/ic.html#PackedConfig object PackedConfig 25 +nim HasDatInitProc ic/ic.html#HasDatInitProc ModuleBackendFlag.HasDatInitProc 32 +nim HasModuleInitProc ic/ic.html#HasModuleInitProc ModuleBackendFlag.HasModuleInitProc 32 +nim ModuleBackendFlag ic/ic.html#ModuleBackendFlag enum ModuleBackendFlag 32 +nim PackedModule ic/ic.html#PackedModule object PackedModule 36 +nim PackedEncoder ic/ic.html#PackedEncoder object PackedEncoder 71 +nim toString ic/ic.html#toString,PackedTree,NodePos,PackedModule,int,string proc toString(tree: PackedTree; pos: NodePos; m: PackedModule; nesting: int;\n result: var string) 83 +nim toString ic/ic.html#toString,PackedTree,NodePos,PackedModule proc toString(tree: PackedTree; n: NodePos; m: PackedModule): string 119 +nim debug ic/ic.html#debug,PackedTree,PackedModule proc debug(tree: PackedTree; m: PackedModule) 123 +nim isActive ic/ic.html#isActive,PackedEncoder proc isActive(e: PackedEncoder): bool 126 +nim rememberStartupConfig ic/ic.html#rememberStartupConfig,PackedConfig,ConfigRef proc rememberStartupConfig(dest: var PackedConfig; config: ConfigRef) 173 +nim toFileIndex ic/ic.html#toFileIndex,LitId,PackedModule,ConfigRef proc toFileIndex(x: LitId; m: PackedModule; config: ConfigRef): FileIndex 200 +nim initEncoder ic/ic.html#initEncoder,PackedEncoder,PackedModule,PSym,ConfigRef,PackedConfig proc initEncoder(c: var PackedEncoder; m: var PackedModule; moduleSym: PSym;\n config: ConfigRef; pc: PackedConfig) 209 +nim addIncludeFileDep ic/ic.html#addIncludeFileDep,PackedEncoder,PackedModule,FileIndex proc addIncludeFileDep(c: var PackedEncoder; m: var PackedModule; f: FileIndex) 231 +nim addImportFileDep ic/ic.html#addImportFileDep,PackedEncoder,PackedModule,FileIndex proc addImportFileDep(c: var PackedEncoder; m: var PackedModule; f: FileIndex) 234 +nim addHidden ic/ic.html#addHidden,PackedEncoder,PackedModule,PSym proc addHidden(c: var PackedEncoder; m: var PackedModule; s: PSym) 237 +nim addExported ic/ic.html#addExported,PackedEncoder,PackedModule,PSym proc addExported(c: var PackedEncoder; m: var PackedModule; s: PSym) 243 +nim addConverter ic/ic.html#addConverter,PackedEncoder,PackedModule,PSym proc addConverter(c: var PackedEncoder; m: var PackedModule; s: PSym) 249 +nim addTrmacro ic/ic.html#addTrmacro,PackedEncoder,PackedModule,PSym proc addTrmacro(c: var PackedEncoder; m: var PackedModule; s: PSym) 253 +nim addPureEnum ic/ic.html#addPureEnum,PackedEncoder,PackedModule,PSym proc addPureEnum(c: var PackedEncoder; m: var PackedModule; s: PSym) 256 +nim addMethod ic/ic.html#addMethod,PackedEncoder,PackedModule,PSym proc addMethod(c: var PackedEncoder; m: var PackedModule; s: PSym) 260 +nim addReexport ic/ic.html#addReexport,PackedEncoder,PackedModule,PSym proc addReexport(c: var PackedEncoder; m: var PackedModule; s: PSym) 263 +nim addCompilerProc ic/ic.html#addCompilerProc,PackedEncoder,PackedModule,PSym proc addCompilerProc(c: var PackedEncoder; m: var PackedModule; s: PSym) 270 +nim toPackedNode ic/ic.html#toPackedNode,PNode,PackedTree,PackedEncoder,PackedModule proc toPackedNode(n: PNode; ir: var PackedTree; c: var PackedEncoder;\n m: var PackedModule) 274 +nim storeSym ic/ic.html#storeSym,PSym,PackedEncoder,PackedModule proc storeSym(s: PSym; c: var PackedEncoder; m: var PackedModule): PackedItemId 275 +nim storeTypeInst ic/ic.html#storeTypeInst,PackedEncoder,PackedModule,PSym,PType proc storeTypeInst(c: var PackedEncoder; m: var PackedModule; s: PSym; inst: PType) 494 +nim addPragmaComputation ic/ic.html#addPragmaComputation,PackedEncoder,PackedModule,PNode proc addPragmaComputation(c: var PackedEncoder; m: var PackedModule; n: PNode) 497 +nim toPackedNodeTopLevel ic/ic.html#toPackedNodeTopLevel,PNode,PackedEncoder,PackedModule proc toPackedNodeTopLevel(n: PNode; encoder: var PackedEncoder; m: var PackedModule) 537 +nim toPackedGeneratedProcDef ic/ic.html#toPackedGeneratedProcDef,PSym,PackedEncoder,PackedModule proc toPackedGeneratedProcDef(s: PSym; encoder: var PackedEncoder;\n m: var PackedModule) 541 +nim storeAttachedProcDef ic/ic.html#storeAttachedProcDef,PType,TTypeAttachedOp,PSym,PackedEncoder,PackedModule proc storeAttachedProcDef(t: PType; op: TTypeAttachedOp; s: PSym;\n encoder: var PackedEncoder; m: var PackedModule) 550 +nim storeInstantiation ic/ic.html#storeInstantiation,PackedEncoder,PackedModule,PSym,PInstantiation proc storeInstantiation(c: var PackedEncoder; m: var PackedModule; s: PSym;\n i: PInstantiation) 559 +nim storeExpansion ic/ic.html#storeExpansion,PackedEncoder,PackedModule,TLineInfo,PSym proc storeExpansion(c: var PackedEncoder; m: var PackedModule; info: TLineInfo;\n s: PSym) 568 +nim toRodFile ic/ic.html#toRodFile,ConfigRef,AbsoluteFile proc toRodFile(conf: ConfigRef; f: AbsoluteFile; ext = RodExt): AbsoluteFile 581 +nim BenchIC ic/ic.html#BenchIC const BenchIC 586 +nim loadRodFile ic/ic.html#loadRodFile,AbsoluteFile,PackedModule,ConfigRef proc loadRodFile(filename: AbsoluteFile; m: var PackedModule; config: ConfigRef;\n ignoreConfig = false): RodFileError 599 +nim saveRodFile ic/ic.html#saveRodFile,AbsoluteFile,PackedEncoder,PackedModule proc saveRodFile(filename: AbsoluteFile; encoder: var PackedEncoder;\n m: var PackedModule) 679 +nim PackedDecoder ic/ic.html#PackedDecoder object PackedDecoder 758 +nim undefined ic/ic.html#undefined ModuleStatus.undefined 766 +nim storing ic/ic.html#storing ModuleStatus.storing 766 +nim loading ic/ic.html#loading ModuleStatus.loading 766 +nim loaded ic/ic.html#loaded ModuleStatus.loaded 766 +nim outdated ic/ic.html#outdated ModuleStatus.outdated 766 +nim stored ic/ic.html#stored ModuleStatus.stored 766 +nim ModuleStatus ic/ic.html#ModuleStatus enum ModuleStatus 766 +nim LoadedModule ic/ic.html#LoadedModule object LoadedModule 774 +nim PackedModuleGraph ic/ic.html#PackedModuleGraph object PackedModuleGraph 786 +nim `[]` ic/ic.html#[].t,PackedModuleGraph,int template `[]`(m: PackedModuleGraph; i: int): LoadedModule 798 +nim len ic/ic.html#len.t,PackedModuleGraph template len(m: PackedModuleGraph): int 799 +nim toFileIndexCached ic/ic.html#toFileIndexCached,PackedDecoder,PackedModuleGraph,int,LitId proc toFileIndexCached(c: var PackedDecoder; g: PackedModuleGraph; thisModule: int;\n f: LitId): FileIndex 804 +nim loadNodes ic/ic.html#loadNodes,PackedDecoder,PackedModuleGraph,int,PackedTree,NodePos proc loadNodes(c: var PackedDecoder; g: var PackedModuleGraph; thisModule: int;\n tree: PackedTree; n: NodePos): PNode 822 +nim initPackedDecoder ic/ic.html#initPackedDecoder,ConfigRef,IdentCache proc initPackedDecoder(config: ConfigRef; cache: IdentCache): PackedDecoder 860 +nim moduleIndex ic/ic.html#moduleIndex,PackedDecoder,PackedModuleGraph,int,PackedItemId proc moduleIndex(c: var PackedDecoder; g: var PackedModuleGraph; thisModule: int;\n s: PackedItemId): int32 894 +nim moduleFromRodFile ic/ic.html#moduleFromRodFile,PackedModuleGraph,ConfigRef,IdentCache,FileIndex,seq[FileIndex] proc moduleFromRodFile(g: var PackedModuleGraph; conf: ConfigRef; cache: IdentCache;\n fileIdx: FileIndex; cachedModules: var seq[FileIndex]): PSym 1128 +nim loadProcBody ic/ic.html#loadProcBody,ConfigRef,IdentCache,PackedModuleGraph,PSym proc loadProcBody(config: ConfigRef; cache: IdentCache; g: var PackedModuleGraph;\n s: PSym): PNode 1149 +nim loadTypeFromId ic/ic.html#loadTypeFromId,ConfigRef,IdentCache,PackedModuleGraph,int,PackedItemId proc loadTypeFromId(config: ConfigRef; cache: IdentCache; g: var PackedModuleGraph;\n module: int; id: PackedItemId): PType 1163 +nim loadSymFromId ic/ic.html#loadSymFromId,ConfigRef,IdentCache,PackedModuleGraph,int,PackedItemId proc loadSymFromId(config: ConfigRef; cache: IdentCache; g: var PackedModuleGraph;\n module: int; id: PackedItemId): PSym 1176 +nim translateId ic/ic.html#translateId,PackedItemId,PackedModuleGraph,int,ConfigRef proc translateId(id: PackedItemId; g: PackedModuleGraph; thisModule: int;\n config: ConfigRef): ItemId 1189 +nim simulateLoadedModule ic/ic.html#simulateLoadedModule,PackedModuleGraph,ConfigRef,IdentCache,PSym,PackedModule proc simulateLoadedModule(g: var PackedModuleGraph; conf: ConfigRef;\n cache: IdentCache; moduleSym: PSym; m: PackedModule) 1195 +nim RodIter ic/ic.html#RodIter object RodIter 1209 +nim initRodIter ic/ic.html#initRodIter,RodIter,ConfigRef,IdentCache,PackedModuleGraph,FileIndex,PIdent,bool proc initRodIter(it: var RodIter; config: ConfigRef; cache: IdentCache;\n g: var PackedModuleGraph; module: FileIndex; name: PIdent;\n importHidden: bool): PSym 1219 +nim initRodIterAllSyms ic/ic.html#initRodIterAllSyms,RodIter,ConfigRef,IdentCache,PackedModuleGraph,FileIndex,bool proc initRodIterAllSyms(it: var RodIter; config: ConfigRef; cache: IdentCache;\n g: var PackedModuleGraph; module: FileIndex;\n importHidden: bool): PSym 1237 +nim nextRodIter ic/ic.html#nextRodIter,RodIter,PackedModuleGraph proc nextRodIter(it: var RodIter; g: var PackedModuleGraph): PSym 1256 +nim interfaceSymbols ic/ic.html#interfaceSymbols.i,ConfigRef,IdentCache,PackedModuleGraph,FileIndex,PIdent,bool iterator interfaceSymbols(config: ConfigRef; cache: IdentCache; g: var PackedModuleGraph;\n module: FileIndex; name: PIdent; importHidden: bool): PSym 1263 +nim interfaceSymbol ic/ic.html#interfaceSymbol,ConfigRef,IdentCache,PackedModuleGraph,FileIndex,PIdent,bool proc interfaceSymbol(config: ConfigRef; cache: IdentCache; g: var PackedModuleGraph;\n module: FileIndex; name: PIdent; importHidden: bool): PSym 1273 +nim idgenFromLoadedModule ic/ic.html#idgenFromLoadedModule,LoadedModule proc idgenFromLoadedModule(m: LoadedModule): IdGenerator 1280 +nim searchForCompilerproc ic/ic.html#searchForCompilerproc,LoadedModule,string proc searchForCompilerproc(m: LoadedModule; name: string): int32 1284 +nim rodViewer ic/ic.html#rodViewer,AbsoluteFile,ConfigRef,IdentCache proc rodViewer(rodfile: AbsoluteFile; config: ConfigRef; cache: IdentCache) 1293 +nimgrp tostring ic/ic.html#toString-procs-all proc 83 diff --git a/compiler/ic/iclineinfos.html b/compiler/ic/iclineinfos.html new file mode 100644 index 0000000000000..294b8607a7d56 --- /dev/null +++ b/compiler/ic/iclineinfos.html @@ -0,0 +1,253 @@ + + + + + + + +ic/iclineinfos + + + + + + + + + + + + + + + + +
+
+

ic/iclineinfos

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ bitabs, rodfiles +
+
+
+

Types

+
+
+
LineInfoManager = object
+
+ + + Source   +Edit   + +
+
+
+
PackedLineInfo = distinct uint32
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
NoLineInfo = 0'u
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc getFileId(m: LineInfoManager; i: PackedLineInfo): LitId {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc load(r: var RodFile; m: var LineInfoManager) {....raises: [IOError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pack(m: var LineInfoManager; file: LitId; line, col: int32): PackedLineInfo {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc store(r: var RodFile; m: LineInfoManager) {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc unpack(m: LineInfoManager; i: PackedLineInfo): (LitId, int32, int32) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/ic/iclineinfos.idx b/compiler/ic/iclineinfos.idx new file mode 100644 index 0000000000000..618043c4507e1 --- /dev/null +++ b/compiler/ic/iclineinfos.idx @@ -0,0 +1,9 @@ +nimTitle iclineinfos ic/iclineinfos.html module ic/iclineinfos 0 +nim PackedLineInfo ic/iclineinfos.html#PackedLineInfo type PackedLineInfo 40 +nim LineInfoManager ic/iclineinfos.html#LineInfoManager object LineInfoManager 42 +nim NoLineInfo ic/iclineinfos.html#NoLineInfo const NoLineInfo 46 +nim pack ic/iclineinfos.html#pack,LineInfoManager,LitId,int32,int32 proc pack(m: var LineInfoManager; file: LitId; line, col: int32): PackedLineInfo 48 +nim unpack ic/iclineinfos.html#unpack,LineInfoManager,PackedLineInfo proc unpack(m: LineInfoManager; i: PackedLineInfo): (LitId, int32, int32) 59 +nim getFileId ic/iclineinfos.html#getFileId,LineInfoManager,PackedLineInfo proc getFileId(m: LineInfoManager; i: PackedLineInfo): LitId 69 +nim store ic/iclineinfos.html#store,RodFile,LineInfoManager proc store(r: var RodFile; m: LineInfoManager) 72 +nim load ic/iclineinfos.html#load,RodFile,LineInfoManager proc load(r: var RodFile; m: var LineInfoManager) 73 diff --git a/compiler/ic/integrity.html b/compiler/ic/integrity.html new file mode 100644 index 0000000000000..3f4fa016bdff0 --- /dev/null +++ b/compiler/ic/integrity.html @@ -0,0 +1,121 @@ + + + + + + + +ic/integrity + + + + + + + + + + + + + + + + +
+
+

ic/integrity

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Integrity checking for a set of .rod files. The set must cover a complete Nim project.

+ +
+

Procs

+
+
+
+
proc checkIntegrity(g: ModuleGraph) {....raises: [KeyError, Exception],
+                                      tags: [ReadDirEffect, RootEffect],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/ic/integrity.idx b/compiler/ic/integrity.idx new file mode 100644 index 0000000000000..e77edaf36b114 --- /dev/null +++ b/compiler/ic/integrity.idx @@ -0,0 +1,2 @@ +nimTitle integrity ic/integrity.html module ic/integrity 0 +nim checkIntegrity ic/integrity.html#checkIntegrity,ModuleGraph proc checkIntegrity(g: ModuleGraph) 144 diff --git a/compiler/ic/navigator.html b/compiler/ic/navigator.html new file mode 100644 index 0000000000000..7e7bac693d8df --- /dev/null +++ b/compiler/ic/navigator.html @@ -0,0 +1,181 @@ + + + + + + + +ic/navigator + + + + + + + + + + + + + + + + +
+
+

ic/navigator

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Supports the "nim check --ic:on --defusages:FILE,LINE,COL" IDE-like features. It uses the set of .rod files to accomplish its task. The set must cover a complete Nim project.

+ +
+

Procs

+
+ + + +
+
+
proc writeRodFiles(g: ModuleGraph) {....raises: [Exception, IOError, OSError,
+    KeyError], tags: [RootEffect, WriteIOEffect, WriteDirEffect, ReadEnvEffect,
+                      ReadIOEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/ic/navigator.idx b/compiler/ic/navigator.idx new file mode 100644 index 0000000000000..cb0ee0f2ab685 --- /dev/null +++ b/compiler/ic/navigator.idx @@ -0,0 +1,5 @@ +nimTitle navigator ic/navigator.html module ic/navigator 0 +nim navDefinition ic/navigator.html#navDefinition,ModuleGraph proc navDefinition(g: ModuleGraph) 173 +nim navUsages ic/navigator.html#navUsages,ModuleGraph proc navUsages(g: ModuleGraph) 174 +nim navDefusages ic/navigator.html#navDefusages,ModuleGraph proc navDefusages(g: ModuleGraph) 175 +nim writeRodFiles ic/navigator.html#writeRodFiles,ModuleGraph proc writeRodFiles(g: ModuleGraph) 177 diff --git a/compiler/ic/packed_ast.html b/compiler/ic/packed_ast.html new file mode 100644 index 0000000000000..f48e501f1d310 --- /dev/null +++ b/compiler/ic/packed_ast.html @@ -0,0 +1,1328 @@ + + + + + + + +ic/packed_ast + + + + + + + + + + + + + + + + +
+
+

ic/packed_ast

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Packed AST representation, mostly based on a seq of nodes. For IC support. Far future: Rewrite the compiler passes to use this representation directly in all the transformations, it is superior.

+ +
+

Types

+
+
+
ModuleId = distinct int32
+
+ + + Source   +Edit   + +
+
+
+
NodeId = distinct int32
+
+ + + Source   +Edit   + +
+
+
+
NodePos = distinct int
+
+ + + Source   +Edit   + +
+
+
+
PackedInstantiation = object
+  key*, sym*: PackedItemId
+  concreteTypes*: seq[PackedItemId]
+
+ + + Source   +Edit   + +
+
+
+
PackedItemId = object
+  module*: LitId
+  item*: int32
+
+ + + Source   +Edit   + +
+
+
+
PackedLib = object
+  kind*: TLibKind
+  generated*: bool
+  isOverridden*: bool
+  name*: LitId
+  path*: NodeId
+
+ + + Source   +Edit   + +
+
+
+
PackedNode = object
+  info*: PackedLineInfo
+
+ + + Source   +Edit   + +
+
+
+
PackedSym = object
+  id*: int32
+  kind*: TSymKind
+  name*: LitId
+  typ*: PackedItemId
+  flags*: TSymFlags
+  magic*: TMagic
+  info*: PackedLineInfo
+  ast*: NodeId
+  owner*: PackedItemId
+  guard*: PackedItemId
+  bitsize*: int
+  alignment*: int
+  options*: TOptions
+  position*: int
+  offset*: int32
+  disamb*: int32
+  externalName*: LitId
+  locFlags*: TLocFlags
+  annex*: PackedLib
+  when hasFFI:
+    cname*: LitId
+  constraint*: NodeId
+  instantiatedFrom*: PackedItemId
+
+ + + Source   +Edit   + +
+
+
+
PackedTree = object
+
+ + usually represents a full Nim module + Source   +Edit   + +
+
+
+
PackedType = object
+  id*: int32
+  kind*: TTypeKind
+  callConv*: TCallingConvention
+  flags*: TTypeFlags
+  types*: seq[PackedItemId]
+  n*: NodeId
+  sym*: PackedItemId
+  owner*: PackedItemId
+  size*: BiggestInt
+  align*: int16
+  paddingAtEnd*: int16
+  typeInst*: PackedItemId
+  nonUniqueId*: int32
+
+ + + Source   +Edit   + +
+
+
+
SymId = distinct int32
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
directIntLit = nkNone
+
+ + + Source   +Edit   + +
+
+
+
emptyNodeId = -1'i32
+
+ + + Source   +Edit   + +
+
+
+
externIntLit = {nkCharLit, nkIntLit, nkInt8Lit, nkInt16Lit, nkInt32Lit,
+                nkInt64Lit, nkUIntLit, nkUInt8Lit, nkUInt16Lit, nkUInt32Lit,
+                nkUInt64Lit}
+
+ + + Source   +Edit   + +
+
+
+
externSIntLit = {nkIntLit, nkInt8Lit, nkInt16Lit, nkInt32Lit, nkInt64Lit}
+
+ + + Source   +Edit   + +
+
+
+
externUIntLit = {nkUIntLit, nkUInt8Lit, nkUInt16Lit, nkUInt32Lit, nkUInt64Lit}
+
+ + + Source   +Edit   + +
+
+
+
nilItemId = (module: 0'u, item: 0)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `==`(a, b: NodeId): bool {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(a, b: NodePos): bool {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(a, b: SymId): bool {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `[]`(tree: PackedTree; i: NodePos): lent PackedNode {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addIdent(tree: var PackedTree; s: LitId; info: PackedLineInfo) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addNode(t: var PackedTree; kind: TNodeKind; operand: int32;
+             typeId: PackedItemId = nilItemId; info: PackedLineInfo;
+             flags: TNodeFlags = {}) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addSym(tree: var PackedTree; s: int32; info: PackedLineInfo) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addSymDef(tree: var PackedTree; s: SymId; info: PackedLineInfo) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc findFlags(tree: PackedTree; n: NodePos): TNodeFlags {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc findType(tree: PackedTree; n: NodePos): PackedItemId {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc firstSon(n: NodePos): NodePos {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc firstSon(tree: PackedTree; n: NodePos): NodePos {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getNodeId(tree: PackedTree): NodeId {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasAtLeastXsons(tree: PackedTree; n: NodePos; x: int): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hash(a: SymId): Hash {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasXsons(tree: PackedTree; n: NodePos; x: int): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc info(tree: PackedTree; n: NodePos): PackedLineInfo {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isAtom(tree: PackedTree; pos: int): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ithSon(tree: PackedTree; n: NodePos; i: int): NodePos {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc kind(tree: PackedTree; n: NodePos): TNodeKind {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc len(tree: PackedTree): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc litId(tree: PackedTree; n: NodePos): LitId {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc load(f: var RodFile; t: var PackedTree) {....raises: [IOError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newTreeFrom(old: PackedTree): PackedTree {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc patch(tree: var PackedTree; pos: PatchPos) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc prepare(dest: var PackedTree; source: PackedTree; sourcePos: NodePos): PatchPos {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc prepare(tree: var PackedTree; kind: TNodeKind; flags: TNodeFlags;
+             typeId: PackedItemId; info: PackedLineInfo): PatchPos {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sons2(tree: PackedTree; n: NodePos): (NodePos, NodePos) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sons3(tree: PackedTree; n: NodePos): (NodePos, NodePos, NodePos) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc span(tree: PackedTree; pos: int): int {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc store(f: var RodFile; t: PackedTree) {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toPackedItemId(item: int32): PackedItemId {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator allNodes(tree: PackedTree): NodePos {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator isons(dest: var PackedTree; tree: PackedTree; n: NodePos): (int,
+    NodePos) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator sons(dest: var PackedTree; tree: PackedTree; n: NodePos): NodePos {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator sonsFrom1(tree: PackedTree; n: NodePos): NodePos {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator sonsReadonly(tree: PackedTree; n: NodePos): NodePos {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator sonsWithoutLast2(tree: PackedTree; n: NodePos): NodePos {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template copyInto(dest, n, body)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template copyIntoKind(dest, kind, info, body)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template flags(n: NodePos): TNodeFlags
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template info(n: NodePos): PackedLineInfo
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template kind(n: NodePos): TNodeKind
+
+ + + Source   +Edit   + +
+
+
+
template kind(n: PackedNode): TNodeKind
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template litId(n: NodePos): LitId
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template parent(n: NodePos): NodePos
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template soperand(n: PackedNode): int32
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template symId(n: NodePos): SymId
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template typ(n: NodePos): PackedItemId
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template typeId(n: PackedNode): PackedItemId
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template uoperand(n: NodePos): uint32
+
+ + + Source   +Edit   + +
+
+
+
template uoperand(n: PackedNode): uint32
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/ic/packed_ast.idx b/compiler/ic/packed_ast.idx new file mode 100644 index 0000000000000..dbc352c670b4c --- /dev/null +++ b/compiler/ic/packed_ast.idx @@ -0,0 +1,75 @@ +nimTitle packed_ast ic/packed_ast.html module ic/packed_ast 0 +nim SymId ic/packed_ast.html#SymId type SymId 25 +nim ModuleId ic/packed_ast.html#ModuleId type ModuleId 26 +nim NodePos ic/packed_ast.html#NodePos type NodePos 27 +nim NodeId ic/packed_ast.html#NodeId type NodeId 29 +nim PackedItemId ic/packed_ast.html#PackedItemId object PackedItemId 31 +nim nilItemId ic/packed_ast.html#nilItemId const nilItemId 36 +nim emptyNodeId ic/packed_ast.html#emptyNodeId const emptyNodeId 39 +nim PackedLib ic/packed_ast.html#PackedLib object PackedLib 42 +nim PackedSym ic/packed_ast.html#PackedSym object PackedSym 49 +nim PackedType ic/packed_ast.html#PackedType object PackedType 74 +nim PackedNode ic/packed_ast.html#PackedNode object PackedNode 92 +nim PackedTree ic/packed_ast.html#PackedTree object PackedTree 96 +nim PackedInstantiation ic/packed_ast.html#PackedInstantiation object PackedInstantiation 101 +nim kind ic/packed_ast.html#kind.t,PackedNode template kind(n: PackedNode): TNodeKind 109 +nim uoperand ic/packed_ast.html#uoperand.t,PackedNode template uoperand(n: PackedNode): uint32 110 +nim soperand ic/packed_ast.html#soperand.t,PackedNode template soperand(n: PackedNode): int32 111 +nim typeId ic/packed_ast.html#typeId.t,PackedNode template typeId(n: PackedNode): PackedItemId 119 +nim `==` ic/packed_ast.html#==,SymId,SymId proc `==`(a, b: SymId): bool 121 +nim hash ic/packed_ast.html#hash,SymId proc hash(a: SymId): Hash 122 +nim `==` ic/packed_ast.html#==,NodePos,NodePos proc `==`(a, b: NodePos): bool 124 +nim `==` ic/packed_ast.html#==,NodeId,NodeId proc `==`(a, b: NodeId): bool 126 +nim newTreeFrom ic/packed_ast.html#newTreeFrom,PackedTree proc newTreeFrom(old: PackedTree): PackedTree 128 +nim addIdent ic/packed_ast.html#addIdent,PackedTree,LitId,PackedLineInfo proc addIdent(tree: var PackedTree; s: LitId; info: PackedLineInfo) 132 +nim addSym ic/packed_ast.html#addSym,PackedTree,int32,PackedLineInfo proc addSym(tree: var PackedTree; s: int32; info: PackedLineInfo) 135 +nim addSymDef ic/packed_ast.html#addSymDef,PackedTree,SymId,PackedLineInfo proc addSymDef(tree: var PackedTree; s: SymId; info: PackedLineInfo) 138 +nim isAtom ic/packed_ast.html#isAtom,PackedTree,int proc isAtom(tree: PackedTree; pos: int): bool 141 +nim addNode ic/packed_ast.html#addNode,PackedTree,TNodeKind,int32,PackedItemId,PackedLineInfo,TNodeFlags proc addNode(t: var PackedTree; kind: TNodeKind; operand: int32;\n typeId: PackedItemId = nilItemId; info: PackedLineInfo;\n flags: TNodeFlags = {}) 146 +nim prepare ic/packed_ast.html#prepare,PackedTree,TNodeKind,TNodeFlags,PackedItemId,PackedLineInfo proc prepare(tree: var PackedTree; kind: TNodeKind; flags: TNodeFlags;\n typeId: PackedItemId; info: PackedLineInfo): PatchPos 155 +nim prepare ic/packed_ast.html#prepare,PackedTree,PackedTree,NodePos proc prepare(dest: var PackedTree; source: PackedTree; sourcePos: NodePos): PatchPos 159 +nim patch ic/packed_ast.html#patch,PackedTree,PatchPos proc patch(tree: var PackedTree; pos: PatchPos) 163 +nim len ic/packed_ast.html#len,PackedTree proc len(tree: PackedTree): int 171 +nim `[]` ic/packed_ast.html#[],PackedTree,NodePos proc `[]`(tree: PackedTree; i: NodePos): lent PackedNode 173 +nim sonsReadonly ic/packed_ast.html#sonsReadonly.i,PackedTree,NodePos iterator sonsReadonly(tree: PackedTree; n: NodePos): NodePos 185 +nim sons ic/packed_ast.html#sons.i,PackedTree,PackedTree,NodePos iterator sons(dest: var PackedTree; tree: PackedTree; n: NodePos): NodePos 194 +nim isons ic/packed_ast.html#isons.i,PackedTree,PackedTree,NodePos iterator isons(dest: var PackedTree; tree: PackedTree; n: NodePos): (int, NodePos) 199 +nim sonsFrom1 ic/packed_ast.html#sonsFrom1.i,PackedTree,NodePos iterator sonsFrom1(tree: PackedTree; n: NodePos): NodePos 206 +nim sonsWithoutLast2 ic/packed_ast.html#sonsWithoutLast2.i,PackedTree,NodePos iterator sonsWithoutLast2(tree: PackedTree; n: NodePos): NodePos 217 +nim parent ic/packed_ast.html#parent.t,NodePos template parent(n: NodePos): NodePos 238 +nim hasXsons ic/packed_ast.html#hasXsons,PackedTree,NodePos,int proc hasXsons(tree: PackedTree; n: NodePos; x: int): bool 240 +nim hasAtLeastXsons ic/packed_ast.html#hasAtLeastXsons,PackedTree,NodePos,int proc hasAtLeastXsons(tree: PackedTree; n: NodePos; x: int): bool 246 +nim firstSon ic/packed_ast.html#firstSon,PackedTree,NodePos proc firstSon(tree: PackedTree; n: NodePos): NodePos 254 +nim kind ic/packed_ast.html#kind,PackedTree,NodePos proc kind(tree: PackedTree; n: NodePos): TNodeKind 256 +nim litId ic/packed_ast.html#litId,PackedTree,NodePos proc litId(tree: PackedTree; n: NodePos): LitId 258 +nim info ic/packed_ast.html#info,PackedTree,NodePos proc info(tree: PackedTree; n: NodePos): PackedLineInfo 260 +nim findType ic/packed_ast.html#findType,PackedTree,NodePos proc findType(tree: PackedTree; n: NodePos): PackedItemId 263 +nim findFlags ic/packed_ast.html#findFlags,PackedTree,NodePos proc findFlags(tree: PackedTree; n: NodePos): TNodeFlags 269 +nim typ ic/packed_ast.html#typ.t,NodePos template typ(n: NodePos): PackedItemId 275 +nim flags ic/packed_ast.html#flags.t,NodePos template flags(n: NodePos): TNodeFlags 277 +nim uoperand ic/packed_ast.html#uoperand.t,NodePos template uoperand(n: NodePos): uint32 280 +nim span ic/packed_ast.html#span,PackedTree,int proc span(tree: PackedTree; pos: int): int 283 +nim sons2 ic/packed_ast.html#sons2,PackedTree,NodePos proc sons2(tree: PackedTree; n: NodePos): (NodePos, NodePos) 286 +nim sons3 ic/packed_ast.html#sons3,PackedTree,NodePos proc sons3(tree: PackedTree; n: NodePos): (NodePos, NodePos, NodePos) 292 +nim ithSon ic/packed_ast.html#ithSon,PackedTree,NodePos,int proc ithSon(tree: PackedTree; n: NodePos; i: int): NodePos 299 +nim kind ic/packed_ast.html#kind.t,NodePos template kind(n: NodePos): TNodeKind 312 +nim info ic/packed_ast.html#info.t,NodePos template info(n: NodePos): PackedLineInfo 313 +nim litId ic/packed_ast.html#litId.t,NodePos template litId(n: NodePos): LitId 314 +nim symId ic/packed_ast.html#symId.t,NodePos template symId(n: NodePos): SymId 316 +nim firstSon ic/packed_ast.html#firstSon,NodePos proc firstSon(n: NodePos): NodePos 318 +nim externIntLit ic/packed_ast.html#externIntLit const externIntLit 321 +nim externSIntLit ic/packed_ast.html#externSIntLit const externSIntLit 333 +nim externUIntLit ic/packed_ast.html#externUIntLit const externUIntLit 334 +nim directIntLit ic/packed_ast.html#directIntLit const directIntLit 335 +nim copyInto ic/packed_ast.html#copyInto.t,,, template copyInto(dest, n, body) 337 +nim copyIntoKind ic/packed_ast.html#copyIntoKind.t,,,, template copyIntoKind(dest, kind, info, body) 342 +nim getNodeId ic/packed_ast.html#getNodeId,PackedTree proc getNodeId(tree: PackedTree): NodeId 347 +nim allNodes ic/packed_ast.html#allNodes.i,PackedTree iterator allNodes(tree: PackedTree): NodePos 349 +nim toPackedItemId ic/packed_ast.html#toPackedItemId,int32 proc toPackedItemId(item: int32): PackedItemId 356 +nim load ic/packed_ast.html#load,RodFile,PackedTree proc load(f: var RodFile; t: var PackedTree) 359 +nim store ic/packed_ast.html#store,RodFile,PackedTree proc store(f: var RodFile; t: PackedTree) 364 +nimgrp == ic/packed_ast.html#==-procs-all proc 121 +nimgrp prepare ic/packed_ast.html#prepare-procs-all proc 155 +nimgrp firstson ic/packed_ast.html#firstSon-procs-all proc 254 +nimgrp uoperand ic/packed_ast.html#uoperand-templates-all template 110 +nimgrp kind ic/packed_ast.html#kind-templates-all template 109 diff --git a/compiler/ic/replayer.html b/compiler/ic/replayer.html new file mode 100644 index 0000000000000..62801c0913d5e --- /dev/null +++ b/compiler/ic/replayer.html @@ -0,0 +1,161 @@ + + + + + + + +ic/replayer + + + + + + + + + + + + + + + + +
+
+

ic/replayer

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Module that contains code to replay global VM state changes and pragma state like {.compile: "foo.c".}. For IC (= Incremental compilation) support.

+ +
+

Procs

+
+
+
+
proc replayBackendProcs(g: ModuleGraph; module: int) {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc replayGenericCacheInformation(g: ModuleGraph; module: int) {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + We remember the generic instantiations a module performed in order to to avoid the code bloat that generic code tends to imply. This is cheaper than deduplication of identical generic instantiations. However, deduplication is more powerful and general and I hope to implement it soon too (famous last words). + Source   +Edit   + +
+
+ +
+
+
+
proc replayStateChanges(module: PSym; g: ModuleGraph) {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, OSError, EOFError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    WriteDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/ic/replayer.idx b/compiler/ic/replayer.idx new file mode 100644 index 0000000000000..950fa3ecb26c3 --- /dev/null +++ b/compiler/ic/replayer.idx @@ -0,0 +1,4 @@ +nimTitle replayer ic/replayer.html module ic/replayer 0 +nim replayStateChanges ic/replayer.html#replayStateChanges,PSym,ModuleGraph proc replayStateChanges(module: PSym; g: ModuleGraph) 24 +nim replayBackendProcs ic/replayer.html#replayBackendProcs,ModuleGraph,int proc replayBackendProcs(g: ModuleGraph; module: int) 92 +nim replayGenericCacheInformation ic/replayer.html#replayGenericCacheInformation,ModuleGraph,int proc replayGenericCacheInformation(g: ModuleGraph; module: int) 117 diff --git a/compiler/ic/rodfiles.html b/compiler/ic/rodfiles.html new file mode 100644 index 0000000000000..a947746e87aa9 --- /dev/null +++ b/compiler/ic/rodfiles.html @@ -0,0 +1,450 @@ + + + + + + + +ic/rodfiles + + + + + + + + + + + + + + + + +
+
+

ic/rodfiles

+
+ +
+ Source   +Edit   + +
+ +

Low level binary format used by the compiler to store and load various AST and related data.

+

NB: this is incredibly low level and if you're interested in how the compiler works and less a storage format, you're probably looking for the ic or packed_ast modules to understand the logical format.

+ +

Overview

RodFile represents a Rod File (versioned binary format), and the associated data for common interactions such as IO and error tracking (RodFileError). The file format broken up into sections (RodSection) and preceded by a header (see: cookie). The precise layout, section ordering and data following the section are determined by the user. See ic.loadRodFile.

+ +

A basic but "wrong" example of the lifecycle:

  1. create or open - create a new one or open an existing
  2. +
  3. storeHeader - header info
  4. +
  5. storePrim or storeSeq - save your stuff
  6. +
  7. close - and we're done
  8. +
+

Now read the bits below to understand what's missing.

+ +

Issues with the Example

Missing Sections: This is a low level API, so headers and sections need to be stored and loaded by the user, see storeHeader & loadHeader and storeSection & loadSection, respectively.

+

No Error Handling: The API is centered around IO and prone to error, each operation checks or sets the RodFile.err field. A user of this API needs to handle these appropriately.

+ +

API Notes

+

Valid inputs for Rod files

ASTs, hopes, dreams, and anything as long as it and any children it may have support copyMem. This means anything that is not a pointer and that does not contain a pointer. At a glance these are:

+
  • string
  • +
  • objects & tuples (fields are recursed)
  • +
  • sequences AKA seq[T]
  • +
+ +

Note on error handling style

A flag based approach is used where operations no-op in case of a preexisting error and set the flag if they encounter one.

+ +

Misc

  • 'Prim' is short for 'primitive', as in a non-sequence type
  • +
+

+
+

Types

+
+
+
RodFile = object
+  f*: File
+  currentSection*: RodSection
+  err*: RodFileError
+
+ + + Source   +Edit   + +
+
+
+
RodFileError = enum
+  ok, tooBig, cannotOpen, ioFailure, wrongHeader, wrongSection, configMismatch,
+  includeFileChanged
+
+ + + Source   +Edit   + +
+
+
+
RodSection = enum
+  versionSection, configSection, stringsSection, checkSumsSection, depsSection,
+  numbersSection, exportsSection, hiddenSection, reexportsSection,
+  compilerProcsSection, trmacrosSection, convertersSection, methodsSection,
+  pureEnumsSection, toReplaySection, topLevelSection, bodiesSection,
+  symsSection, typesSection, typeInstCacheSection, procInstCacheSection,
+  attachedOpsSection, methodsPerGenericTypeSection, enumToStringProcsSection,
+  methodsPerTypeSection, dispatchersSection, typeInfoSection,
+  backendFlagsSection, aliveSymsSection, sideChannelSection, namespaceSection,
+  symnamesSection
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc close(f: var RodFile) {....raises: [IOError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc create(filename: string): RodFile {....raises: [], tags: [], forbids: [].}
+
+ + create the file and open it for writing + Source   +Edit   + +
+
+ +
+
+
+
proc loadHeader(f: var RodFile; cookie = defaultCookie) {....raises: [IOError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + Loads the header which is described by cookie. + Source   +Edit   + +
+
+ +
+
+
+
proc loadOrderedTable[K, T](f: var RodFile; s: var OrderedTable[K, T])
+
+ + T must be compatible with copyMem, see loadPrim + Source   +Edit   + +
+
+ +
+
+
+
proc loadPrim(f: var RodFile; s: var string) {....raises: [IOError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + Read a string, the length was stored as a prefix + Source   +Edit   + +
+
+
+
proc loadPrim[T](f: var RodFile; x: var T)
+
+ + Load a non-sequence/string T. + Source   +Edit   + +
+
+ +
+
+
+
proc loadSection(f: var RodFile; expected: RodSection) {....raises: [IOError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + read the bytes value of s, sets and error if the section is incorrect. + Source   +Edit   + +
+
+ +
+
+
+
proc loadSeq[T](f: var RodFile; s: var seq[T])
+
+ + T must be compatible with copyMem, see loadPrim + Source   +Edit   + +
+
+ +
+
+
+
proc open(filename: string): RodFile {....raises: [], tags: [], forbids: [].}
+
+ + open the file for reading + Source   +Edit   + +
+
+ +
+
+
+
proc storeHeader(f: var RodFile; cookie = defaultCookie) {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + stores the header which is described by cookie. + Source   +Edit   + +
+
+ +
+
+
+
proc storeOrderedTable[K, T](f: var RodFile; s: OrderedTable[K, T])
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc storePrim(f: var RodFile; s: string) {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + Stores a string. The len is prefixed to allow for later retreival. + Source   +Edit   + +
+
+
+
proc storePrim[T](f: var RodFile; x: T)
+
+ + Stores a non-sequence/string T. If T doesn't support copyMem and is an object or tuple then the fields are written -- the user from context will need to know which T to load. + Source   +Edit   + +
+
+ +
+
+
+
proc storeSection(f: var RodFile; s: RodSection) {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + update currentSection and writes the bytes value of s. + Source   +Edit   + +
+
+ +
+
+
+
proc storeSeq[T](f: var RodFile; s: seq[T])
+
+ + Stores a sequence of Ts, with the len as a prefix for later retrieval. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/ic/rodfiles.idx b/compiler/ic/rodfiles.idx new file mode 100644 index 0000000000000..013a815318260 --- /dev/null +++ b/compiler/ic/rodfiles.idx @@ -0,0 +1,68 @@ +nimTitle rodfiles ic/rodfiles.html module ic/rodfiles 0 +nim versionSection ic/rodfiles.html#versionSection RodSection.versionSection 74 +nim configSection ic/rodfiles.html#configSection RodSection.configSection 74 +nim stringsSection ic/rodfiles.html#stringsSection RodSection.stringsSection 74 +nim checkSumsSection ic/rodfiles.html#checkSumsSection RodSection.checkSumsSection 74 +nim depsSection ic/rodfiles.html#depsSection RodSection.depsSection 74 +nim numbersSection ic/rodfiles.html#numbersSection RodSection.numbersSection 74 +nim exportsSection ic/rodfiles.html#exportsSection RodSection.exportsSection 74 +nim hiddenSection ic/rodfiles.html#hiddenSection RodSection.hiddenSection 74 +nim reexportsSection ic/rodfiles.html#reexportsSection RodSection.reexportsSection 74 +nim compilerProcsSection ic/rodfiles.html#compilerProcsSection RodSection.compilerProcsSection 74 +nim trmacrosSection ic/rodfiles.html#trmacrosSection RodSection.trmacrosSection 74 +nim convertersSection ic/rodfiles.html#convertersSection RodSection.convertersSection 74 +nim methodsSection ic/rodfiles.html#methodsSection RodSection.methodsSection 74 +nim pureEnumsSection ic/rodfiles.html#pureEnumsSection RodSection.pureEnumsSection 74 +nim toReplaySection ic/rodfiles.html#toReplaySection RodSection.toReplaySection 74 +nim topLevelSection ic/rodfiles.html#topLevelSection RodSection.topLevelSection 74 +nim bodiesSection ic/rodfiles.html#bodiesSection RodSection.bodiesSection 74 +nim symsSection ic/rodfiles.html#symsSection RodSection.symsSection 74 +nim typesSection ic/rodfiles.html#typesSection RodSection.typesSection 74 +nim typeInstCacheSection ic/rodfiles.html#typeInstCacheSection RodSection.typeInstCacheSection 74 +nim procInstCacheSection ic/rodfiles.html#procInstCacheSection RodSection.procInstCacheSection 74 +nim attachedOpsSection ic/rodfiles.html#attachedOpsSection RodSection.attachedOpsSection 74 +nim methodsPerGenericTypeSection ic/rodfiles.html#methodsPerGenericTypeSection RodSection.methodsPerGenericTypeSection 74 +nim enumToStringProcsSection ic/rodfiles.html#enumToStringProcsSection RodSection.enumToStringProcsSection 74 +nim methodsPerTypeSection ic/rodfiles.html#methodsPerTypeSection RodSection.methodsPerTypeSection 74 +nim dispatchersSection ic/rodfiles.html#dispatchersSection RodSection.dispatchersSection 74 +nim typeInfoSection ic/rodfiles.html#typeInfoSection RodSection.typeInfoSection 74 +nim backendFlagsSection ic/rodfiles.html#backendFlagsSection RodSection.backendFlagsSection 74 +nim aliveSymsSection ic/rodfiles.html#aliveSymsSection RodSection.aliveSymsSection 74 +nim sideChannelSection ic/rodfiles.html#sideChannelSection RodSection.sideChannelSection 74 +nim namespaceSection ic/rodfiles.html#namespaceSection RodSection.namespaceSection 74 +nim symnamesSection ic/rodfiles.html#symnamesSection RodSection.symnamesSection 74 +nim RodSection ic/rodfiles.html#RodSection enum RodSection 74 +nim ok ic/rodfiles.html#ok RodFileError.ok 108 +nim tooBig ic/rodfiles.html#tooBig RodFileError.tooBig 108 +nim cannotOpen ic/rodfiles.html#cannotOpen RodFileError.cannotOpen 108 +nim ioFailure ic/rodfiles.html#ioFailure RodFileError.ioFailure 108 +nim wrongHeader ic/rodfiles.html#wrongHeader RodFileError.wrongHeader 108 +nim wrongSection ic/rodfiles.html#wrongSection RodFileError.wrongSection 108 +nim configMismatch ic/rodfiles.html#configMismatch RodFileError.configMismatch 108 +nim includeFileChanged ic/rodfiles.html#includeFileChanged RodFileError.includeFileChanged 108 +nim RodFileError ic/rodfiles.html#RodFileError enum RodFileError 108 +nim RodFile ic/rodfiles.html#RodFile object RodFile 112 +nim storePrim ic/rodfiles.html#storePrim,RodFile,string proc storePrim(f: var RodFile; s: string) 127 +nim storePrim ic/rodfiles.html#storePrim,RodFile,T proc storePrim[T](f: var RodFile; x: T) 142 +nim storeSeq ic/rodfiles.html#storeSeq,RodFile,seq[T] proc storeSeq[T](f: var RodFile; s: seq[T]) 162 +nim storeOrderedTable ic/rodfiles.html#storeOrderedTable,RodFile,OrderedTable[K,T] proc storeOrderedTable[K, T](f: var RodFile; s: OrderedTable[K, T]) 175 +nim loadPrim ic/rodfiles.html#loadPrim,RodFile,string proc loadPrim(f: var RodFile; s: var string) 187 +nim loadPrim ic/rodfiles.html#loadPrim,RodFile,T proc loadPrim[T](f: var RodFile; x: var T) 199 +nim loadSeq ic/rodfiles.html#loadSeq,RodFile,seq[T] proc loadSeq[T](f: var RodFile; s: var seq[T]) 217 +nim loadOrderedTable ic/rodfiles.html#loadOrderedTable,RodFile,OrderedTable[K,T] proc loadOrderedTable[K, T](f: var RodFile; s: var OrderedTable[K, T]) 228 +nim storeHeader ic/rodfiles.html#storeHeader,RodFile proc storeHeader(f: var RodFile; cookie = defaultCookie) 241 +nim loadHeader ic/rodfiles.html#loadHeader,RodFile proc loadHeader(f: var RodFile; cookie = defaultCookie) 247 +nim storeSection ic/rodfiles.html#storeSection,RodFile,RodSection proc storeSection(f: var RodFile; s: RodSection) 256 +nim loadSection ic/rodfiles.html#loadSection,RodFile,RodSection proc loadSection(f: var RodFile; expected: RodSection) 263 +nim create ic/rodfiles.html#create,string proc create(filename: string): RodFile 271 +nim close ic/rodfiles.html#close,RodFile proc close(f: var RodFile) 277 +nim open ic/rodfiles.html#open,string proc open(filename: string): RodFile 279 +nimgrp loadprim ic/rodfiles.html#loadPrim-procs-all proc 187 +nimgrp storeprim ic/rodfiles.html#storePrim-procs-all proc 127 +heading Overview ic/rodfiles.html#overview Overview 0 +heading A basic but "wrong" example of the lifecycle: ic/rodfiles.html#overview-a-basic-but-wrong-example-of-the-lifecyclecolon A basic but "wrong" example of the lifecycle: 0 +heading Issues with the Example ic/rodfiles.html#a-basic-but-wrong-example-of-the-lifecyclecolon-issues-with-the-example Issues with the Example 0 +heading API Notes ic/rodfiles.html#api-notes API Notes 0 +heading Valid inputs for Rod files ic/rodfiles.html#api-notes-valid-inputs-for-rod-files Valid inputs for Rod files 0 +heading Note on error handling style ic/rodfiles.html#api-notes-note-on-error-handling-style Note on error handling style 0 +heading Misc ic/rodfiles.html#api-notes-misc Misc 0 diff --git a/compiler/idents.html b/compiler/idents.html new file mode 100644 index 0000000000000..fd50e505a2eb1 --- /dev/null +++ b/compiler/idents.html @@ -0,0 +1,304 @@ + + + + + + + +idents + + + + + + + + + + + + + + + + +
+
+

idents

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ wordrecg +
+
+
+

Types

+
+
+
IdentCache = ref object
+  idAnon*, idDelegator*, emptyIdent*: PIdent
+
+ + + Source   +Edit   + +
+
+
+
PIdent = ref TIdent
+
+ + + Source   +Edit   + +
+
+
+
TIdent {.acyclic.} = object
+  id*: int
+  s*: string
+  next*: PIdent
+  h*: Hash
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `==`(a, b: PIdent): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cmpIgnoreStyle(a, b: cstring; blen: int): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getIdent(ic: IdentCache; identifier: cstring; length: int; h: Hash): PIdent {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc getIdent(ic: IdentCache; identifier: string): PIdent {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc getIdent(ic: IdentCache; identifier: string; h: Hash): PIdent {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hash(x: PIdent): Hash {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newIdentCache(): IdentCache {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc resetIdentCache() {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc whichKeyword(id: PIdent): TSpecialWord {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/idents.idx b/compiler/idents.idx new file mode 100644 index 0000000000000..f75cac2e5e7e1 --- /dev/null +++ b/compiler/idents.idx @@ -0,0 +1,14 @@ +nimTitle idents idents.html module idents 0 +nim PIdent idents.html#PIdent type PIdent 21 +nim TIdent idents.html#TIdent object TIdent 22 +nim IdentCache idents.html#IdentCache type IdentCache 28 +nim resetIdentCache idents.html#resetIdentCache proc resetIdentCache() 33 +nim cmpIgnoreStyle idents.html#cmpIgnoreStyle,cstring,cstring,int proc cmpIgnoreStyle(a, b: cstring; blen: int): int 35 +nim getIdent idents.html#getIdent,IdentCache,cstring,int,Hash proc getIdent(ic: IdentCache; identifier: cstring; length: int; h: Hash): PIdent 69 +nim getIdent idents.html#getIdent,IdentCache,string proc getIdent(ic: IdentCache; identifier: string): PIdent 99 +nim getIdent idents.html#getIdent,IdentCache,string,Hash proc getIdent(ic: IdentCache; identifier: string; h: Hash): PIdent 103 +nim newIdentCache idents.html#newIdentCache proc newIdentCache(): IdentCache 106 +nim whichKeyword idents.html#whichKeyword,PIdent proc whichKeyword(id: PIdent): TSpecialWord 116 +nim hash idents.html#hash,PIdent proc hash(x: PIdent): Hash 120 +nim `==` idents.html#==,PIdent,PIdent proc `==`(a, b: PIdent): bool 121 +nimgrp getident idents.html#getIdent-procs-all proc 69 diff --git a/compiler/importer.html b/compiler/importer.html new file mode 100644 index 0000000000000..7db50340a6359 --- /dev/null +++ b/compiler/importer.html @@ -0,0 +1,218 @@ + + + + + + + +importer + + + + + + + + + + + + + + + + +
+
+

importer

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module implements the symbol importing mechanism.

+ +
+

Procs

+
+
+
+
proc declarePureEnumField(c: PContext; s: PSym) {....raises: [KeyError, Exception],
+    tags: [ReadDirEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc evalFrom(c: PContext; n: PNode): PNode {....raises: [Exception, ValueError,
+    KeyError, IOError, ERecoverableError, OSError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc evalImport(c: PContext; n: PNode): PNode {....raises: [KeyError, Exception,
+    ValueError, IOError, ERecoverableError, OSError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc evalImportExcept(c: PContext; n: PNode): PNode {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc importAllSymbols(c: PContext; fromMod: PSym) {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc readExceptSet(c: PContext; n: PNode): IntSet {.
+    ...raises: [Exception, KeyError, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/importer.idx b/compiler/importer.idx new file mode 100644 index 0000000000000..cdf8f8c219b7b --- /dev/null +++ b/compiler/importer.idx @@ -0,0 +1,7 @@ +nimTitle importer importer.html module importer 0 +nim readExceptSet importer.html#readExceptSet,PContext,PNode proc readExceptSet(c: PContext; n: PNode): IntSet 23 +nim declarePureEnumField importer.html#declarePureEnumField,PContext,PSym proc declarePureEnumField(c: PContext; s: PSym) 30 +nim importAllSymbols importer.html#importAllSymbols,PContext,PSym proc importAllSymbols(c: PContext; fromMod: PSym) 210 +nim evalImport importer.html#evalImport,PContext,PNode proc evalImport(c: PContext; n: PNode): PNode 343 +nim evalFrom importer.html#evalFrom,PContext,PNode proc evalFrom(c: PContext; n: PNode): PNode 369 +nim evalImportExcept importer.html#evalImportExcept,PContext,PNode proc evalImportExcept(c: PContext; n: PNode): PNode 384 diff --git a/compiler/index.html b/compiler/index.html new file mode 100644 index 0000000000000..a395048f0eba5 --- /dev/null +++ b/compiler/index.html @@ -0,0 +1,94 @@ + + + + + + + +index + + + + + + + + + + + + + + + + +
+
+

index

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module only exists to generate docs for the compiler. +

links

+

+
+

Imports

+
+ nim +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/index.idx b/compiler/index.idx new file mode 100644 index 0000000000000..b86356edc7757 --- /dev/null +++ b/compiler/index.idx @@ -0,0 +1,2 @@ +nimTitle index index.html module index 0 +heading links index.html#links links 0 diff --git a/compiler/injectdestructors.html b/compiler/injectdestructors.html new file mode 100644 index 0000000000000..0f91433abfc7a --- /dev/null +++ b/compiler/injectdestructors.html @@ -0,0 +1,139 @@ + + + + + + + +injectdestructors + + + + + + + + + + + + + + + + +
+
+

injectdestructors

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Injects destructor calls into Nim code as well as an optimizer that optimizes copies to moves. This is implemented as an AST to AST transformation so that every backend benefits from it.See doc/destructors.rst for a spec of the implemented rewrite rules

+ +
+

Procs

+
+
+
+
proc injectDestructorCalls(g: ModuleGraph; idgen: IdGenerator; owner: PSym;
+                           n: PNode): PNode {....raises: [Exception, ValueError,
+    KeyError, IOError, ERecoverableError, OSError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sameLocation(a, b: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/injectdestructors.idx b/compiler/injectdestructors.idx new file mode 100644 index 0000000000000..a7ae9c151eb83 --- /dev/null +++ b/compiler/injectdestructors.idx @@ -0,0 +1,3 @@ +nimTitle injectdestructors injectdestructors.html module injectdestructors 0 +nim sameLocation injectdestructors.html#sameLocation,PNode,PNode proc sameLocation(a, b: PNode): bool 1087 +nim injectDestructorCalls injectdestructors.html#injectDestructorCalls,ModuleGraph,IdGenerator,PSym,PNode proc injectDestructorCalls(g: ModuleGraph; idgen: IdGenerator; owner: PSym; n: PNode): PNode 1255 diff --git a/compiler/int128.html b/compiler/int128.html new file mode 100644 index 0000000000000..e33bf48171f56 --- /dev/null +++ b/compiler/int128.html @@ -0,0 +1,1176 @@ + + + + + + + +int128 + + + + + + + + + + + + + + + + +
+
+

int128

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module is for compiler internal use only. For reliable error messages and range checks, the compiler needs a data type that can hold all from low(BiggestInt) to high(BiggestUInt), This type is for that purpose.

+
+

Types

+
+
+
Int128 = object
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
NegOne = (udata: [4294967295'u, 4294967295'u, 4294967295'u, 4294967295'u])
+
+ + + Source   +Edit   + +
+
+
+
One = (udata: [1'u, 0'u, 0'u, 0'u])
+
+ + + Source   +Edit   + +
+
+
+
Ten = (udata: [10'u, 0'u, 0'u, 0'u])
+
+ + + Source   +Edit   + +
+
+
+
Zero = (udata: [0'u, 0'u, 0'u, 0'u])
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(a: Int128): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `*`(a: Int128; b: int32): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `*`(lhs, rhs: Int128): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `*=`(a: var Int128; b: Int128) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `+`(a, b: Int128): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(a: BiggestInt; b: Int128): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(a: Int128; b: BiggestInt): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `+=`(a: var Int128; b: Int128) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `-`(a, b: Int128): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(a: BiggestInt; b: Int128): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(a: Int128): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(a: Int128; b: BiggestInt): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `-=`(a: var Int128; b: Int128) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `<`(a, b: Int128): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`(a: BiggestInt; b: Int128): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`(a: Int128; b: BiggestInt): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `<=`(a, b: Int128): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`(a: BiggestInt; b: Int128): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`(a: Int128; b: BiggestInt): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(a, b: Int128): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(a: BiggestInt; b: Int128): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(a: Int128; b: BiggestInt): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc abs(a: Int128): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addInt128(result: var string; value: Int128) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addToHex(result: var string; arg: Int128) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bitand(a, b: Int128): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bitnot(a: Int128): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bitor(a, b: Int128): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bitxor(a, b: Int128): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc castToInt64(arg: Int128): int64 {....raises: [], tags: [], forbids: [].}
+
+ + Conversion to int64 without range check. + Source   +Edit   + +
+
+ +
+
+
+
proc castToUInt64(arg: Int128): uint64 {....raises: [], tags: [], forbids: [].}
+
+ + Conversion to uint64 without range check. + Source   +Edit   + +
+
+ +
+
+
+
proc cmp(a, b: Int128): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `div`(a, b: Int128): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc divMod(dividend, divisor: Int128): tuple[quotient, remainder: Int128] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fastLog2(a: Int128): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inc(a: var Int128; y: uint32 = 1) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc maskBytes(arg: Int128; numbytes: int): Int128 {.noinit, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc maskUInt8(arg: Int128): Int128 {.noinit, inline, ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc maskUInt16(arg: Int128): Int128 {.noinit, inline, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc maskUInt32(arg: Int128): Int128 {.noinit, inline, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc maskUInt64(arg: Int128): Int128 {.noinit, inline, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `mod`(a, b: Int128): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc parseDecimalInt128(arg: string; pos: int = 0): Int128 {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `shl`(a: Int128; b: int): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `shr`(a: Int128; b: int): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toFloat64(arg: Int128): float64 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toHex(arg: Int128): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toInt(arg: Int128): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toInt8(arg: Int128): int8 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toInt16(arg: Int128): int16 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toInt32(arg: Int128): int32 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toInt64(arg: Int128): int64 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toInt64Checked(arg: Int128; onError: int64): int64 {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toInt128(arg: float64): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc toInt128[T: SomeInteger | bool](arg: T): Int128
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toUInt(arg: Int128): uint {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toUInt8(arg: Int128): uint8 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toUInt16(arg: Int128): uint16 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toUInt32(arg: Int128): uint32 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toUInt64(arg: Int128): uint64 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template high(t: typedesc[Int128]): Int128
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template low(t: typedesc[Int128]): Int128
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/int128.idx b/compiler/int128.idx new file mode 100644 index 0000000000000..259c217370651 --- /dev/null +++ b/compiler/int128.idx @@ -0,0 +1,75 @@ +nimTitle int128 int128.html module int128 0 +nim Int128 int128.html#Int128 object Int128 12 +nim Zero int128.html#Zero const Zero 23 +nim One int128.html#One const One 24 +nim Ten int128.html#Ten const Ten 25 +nim NegOne int128.html#NegOne const NegOne 28 +nim low int128.html#low.t,typedesc[Int128] template low(t: typedesc[Int128]): Int128 30 +nim high int128.html#high.t,typedesc[Int128] template high(t: typedesc[Int128]): Int128 31 +nim `$` int128.html#$,Int128 proc `$`(a: Int128): string 33 +nim toInt128 int128.html#toInt128,T proc toInt128[T: SomeInteger | bool](arg: T): Int128 35 +nim toInt64 int128.html#toInt64,Int128 proc toInt64(arg: Int128): int64 65 +nim toInt64Checked int128.html#toInt64Checked,Int128,int64 proc toInt64Checked(arg: Int128; onError: int64): int64 75 +nim toInt32 int128.html#toInt32,Int128 proc toInt32(arg: Int128): int32 84 +nim toInt16 int128.html#toInt16,Int128 proc toInt16(arg: Int128): int16 96 +nim toInt8 int128.html#toInt8,Int128 proc toInt8(arg: Int128): int8 108 +nim toInt int128.html#toInt,Int128 proc toInt(arg: Int128): int 120 +nim toUInt64 int128.html#toUInt64,Int128 proc toUInt64(arg: Int128): uint64 126 +nim toUInt32 int128.html#toUInt32,Int128 proc toUInt32(arg: Int128): uint32 131 +nim toUInt16 int128.html#toUInt16,Int128 proc toUInt16(arg: Int128): uint16 137 +nim toUInt8 int128.html#toUInt8,Int128 proc toUInt8(arg: Int128): uint8 143 +nim toUInt int128.html#toUInt,Int128 proc toUInt(arg: Int128): uint 149 +nim castToInt64 int128.html#castToInt64,Int128 proc castToInt64(arg: Int128): int64 155 +nim castToUInt64 int128.html#castToUInt64,Int128 proc castToUInt64(arg: Int128): uint64 159 +nim addToHex int128.html#addToHex,string,Int128 proc addToHex(result: var string; arg: Int128) 168 +nim toHex int128.html#toHex,Int128 proc toHex(arg: Int128): string 174 +nim inc int128.html#inc,Int128,uint32 proc inc(a: var Int128; y: uint32 = 1) 178 +nim cmp int128.html#cmp,Int128,Int128 proc cmp(a, b: Int128): int 188 +nim `<` int128.html#<,Int128,Int128 proc `<`(a, b: Int128): bool 198 +nim `<=` int128.html#<=,Int128,Int128 proc `<=`(a, b: Int128): bool 201 +nim `==` int128.html#==,Int128,Int128 proc `==`(a, b: Int128): bool 204 +nim bitnot int128.html#bitnot,Int128 proc bitnot(a: Int128): Int128 211 +nim bitand int128.html#bitand,Int128,Int128 proc bitand(a, b: Int128): Int128 218 +nim bitor int128.html#bitor,Int128,Int128 proc bitor(a, b: Int128): Int128 225 +nim bitxor int128.html#bitxor,Int128,Int128 proc bitxor(a, b: Int128): Int128 232 +nim `shr` int128.html#shr,Int128,int proc `shr`(a: Int128; b: int): Int128 239 +nim `shl` int128.html#shl,Int128,int proc `shl`(a: Int128; b: int): Int128 266 +nim `+` int128.html#+,Int128,Int128 proc `+`(a, b: Int128): Int128 290 +nim `+=` int128.html#+=,Int128,Int128 proc `+=`(a: var Int128; b: Int128) 301 +nim `-` int128.html#-,Int128 proc `-`(a: Int128): Int128 304 +nim `-` int128.html#-,Int128,Int128 proc `-`(a, b: Int128): Int128 308 +nim `-=` int128.html#-=,Int128,Int128 proc `-=`(a: var Int128; b: Int128) 311 +nim abs int128.html#abs,Int128 proc abs(a: Int128): Int128 314 +nim `*` int128.html#*,Int128,int32 proc `*`(a: Int128; b: int32): Int128 338 +nim `*` int128.html#*,Int128,Int128 proc `*`(lhs, rhs: Int128): Int128 359 +nim `*=` int128.html#*=,Int128,Int128 proc `*=`(a: var Int128; b: Int128) 368 +nim fastLog2 int128.html#fastLog2,Int128 proc fastLog2(a: Int128): int 373 +nim divMod int128.html#divMod,Int128,Int128 proc divMod(dividend, divisor: Int128): tuple[quotient, remainder: Int128] 384 +nim `div` int128.html#div,Int128,Int128 proc `div`(a, b: Int128): Int128 436 +nim `mod` int128.html#mod,Int128,Int128 proc `mod`(a, b: Int128): Int128 440 +nim addInt128 int128.html#addInt128,string,Int128 proc addInt128(result: var string; value: Int128) 444 +nim parseDecimalInt128 int128.html#parseDecimalInt128,string,int proc parseDecimalInt128(arg: string; pos: int = 0): Int128 472 +nim `<` int128.html#<,Int128,BiggestInt proc `<`(a: Int128; b: BiggestInt): bool 493 +nim `<` int128.html#<,BiggestInt,Int128 proc `<`(a: BiggestInt; b: Int128): bool 496 +nim `<=` int128.html#<=,Int128,BiggestInt proc `<=`(a: Int128; b: BiggestInt): bool 499 +nim `<=` int128.html#<=,BiggestInt,Int128 proc `<=`(a: BiggestInt; b: Int128): bool 502 +nim `==` int128.html#==,Int128,BiggestInt proc `==`(a: Int128; b: BiggestInt): bool 505 +nim `==` int128.html#==,BiggestInt,Int128 proc `==`(a: BiggestInt; b: Int128): bool 508 +nim `-` int128.html#-,BiggestInt,Int128 proc `-`(a: BiggestInt; b: Int128): Int128 511 +nim `-` int128.html#-,Int128,BiggestInt proc `-`(a: Int128; b: BiggestInt): Int128 514 +nim `+` int128.html#+,BiggestInt,Int128 proc `+`(a: BiggestInt; b: Int128): Int128 517 +nim `+` int128.html#+,Int128,BiggestInt proc `+`(a: Int128; b: BiggestInt): Int128 520 +nim toFloat64 int128.html#toFloat64,Int128 proc toFloat64(arg: Int128): float64 523 +nim toInt128 int128.html#toInt128,float64 proc toInt128(arg: float64): Int128 538 +nim maskUInt64 int128.html#maskUInt64,Int128 proc maskUInt64(arg: Int128): Int128 553 +nim maskUInt32 int128.html#maskUInt32,Int128 proc maskUInt32(arg: Int128): Int128 560 +nim maskUInt16 int128.html#maskUInt16,Int128 proc maskUInt16(arg: Int128): Int128 567 +nim maskUInt8 int128.html#maskUInt8,Int128 proc maskUInt8(arg: Int128): Int128 574 +nim maskBytes int128.html#maskBytes,Int128,int proc maskBytes(arg: Int128; numbytes: int): Int128 581 +nimgrp - int128.html#--procs-all proc 304 +nimgrp toint128 int128.html#toInt128-procs-all proc 35 +nimgrp <= int128.html#<=-procs-all proc 201 +nimgrp < int128.html#<-procs-all proc 198 +nimgrp == int128.html#==-procs-all proc 204 +nimgrp + int128.html#+-procs-all proc 290 +nimgrp * int128.html#*-procs-all proc 338 diff --git a/compiler/isolation_check.html b/compiler/isolation_check.html new file mode 100644 index 0000000000000..6c737392ecc3b --- /dev/null +++ b/compiler/isolation_check.html @@ -0,0 +1,138 @@ + + + + + + + +isolation_check + + + + + + + + + + + + + + + + +
+
+

isolation_check

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Implementation of the check that recover needs, see https://github.com/nim-lang/RFCs/issues/244 for more details.

+
+

Imports

+
+ ast, types, renderer +
+
+
+

Procs

+
+
+
+
proc canAlias(arg, ret: PType): bool {....raises: [Exception, KeyError, ValueError,
+    ERecoverableError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc checkIsolate(n: PNode): bool {....raises: [Exception, KeyError, ValueError,
+    ERecoverableError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/isolation_check.idx b/compiler/isolation_check.idx new file mode 100644 index 0000000000000..4376e3faf41ab --- /dev/null +++ b/compiler/isolation_check.idx @@ -0,0 +1,3 @@ +nimTitle isolation_check isolation_check.html module isolation_check 0 +nim canAlias isolation_check.html#canAlias,PType,PType proc canAlias(arg, ret: PType): bool 144 +nim checkIsolate isolation_check.html#checkIsolate,PNode proc checkIsolate(n: PNode): bool 166 diff --git a/compiler/jsgen.html b/compiler/jsgen.html new file mode 100644 index 0000000000000..b275200f594bc --- /dev/null +++ b/compiler/jsgen.html @@ -0,0 +1,191 @@ + + + + + + + +jsgen + + + + + + + + + + + + + + + + +
+
+

jsgen

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Type info generation for the JS backend.

+ +
+

Procs

+
+
+
+
proc finalJSCodeGen(graph: ModuleGraph; b: PPassContext; n: PNode): PNode {....raises: [
+    Exception, ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    TimeEffect, WriteDirEffect], forbids: [].}
+
+ + Finalize JS code generation of a Nim module. Param n may contain nodes returned from the last module close call. + Source   +Edit   + +
+
+ +
+
+
+
proc processJSCodeGen(b: PPassContext; n: PNode): PNode {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    TimeEffect], forbids: [].}
+
+ + Generate JS code for a node. + Source   +Edit   + +
+
+ +
+
+
+
proc setupJSgen(graph: ModuleGraph; s: PSym; idgen: IdGenerator): PPassContext {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template config(p: PProc): ConfigRef
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/jsgen.idx b/compiler/jsgen.idx new file mode 100644 index 0000000000000..74607149d47b8 --- /dev/null +++ b/compiler/jsgen.idx @@ -0,0 +1,5 @@ +nimTitle jsgen jsgen.html module jsgen 0 +nim config jsgen.html#config.t,PProc template config(p: PProc): ConfigRef 118 +nim processJSCodeGen jsgen.html#processJSCodeGen,PPassContext,PNode proc processJSCodeGen(b: PPassContext; n: PNode): PNode 3139 +nim finalJSCodeGen jsgen.html#finalJSCodeGen,ModuleGraph,PPassContext,PNode proc finalJSCodeGen(graph: ModuleGraph; b: PPassContext; n: PNode): PNode 3169 +nim setupJSgen jsgen.html#setupJSgen,ModuleGraph,PSym,IdGenerator proc setupJSgen(graph: ModuleGraph; s: PSym; idgen: IdGenerator): PPassContext 3204 diff --git a/compiler/lambdalifting.html b/compiler/lambdalifting.html new file mode 100644 index 0000000000000..248461044d6cf --- /dev/null +++ b/compiler/lambdalifting.html @@ -0,0 +1,395 @@ + + + + + + + +lambdalifting + + + + + + + + + + + + + + + + +
+
+

lambdalifting

+
+ +
+ Source   +Edit   + +
+ +

+ +
+

Consts

+
+
+
envName = ":env"
+
+ + + Source   +Edit   + +
+
+
+
paramName = ":envP"
+
+ + + Source   +Edit   + +
+
+
+
upName = ":up"
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc createClosureIterStateType(g: ModuleGraph; iter: PSym; idgen: IdGenerator): PType {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getClosureIterResult(g: ModuleGraph; iter: PSym; idgen: IdGenerator): PSym {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getEnvParam(routine: PSym): PSym {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getStateField(g: ModuleGraph; owner: PSym): PSym {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc liftForLoop(g: ModuleGraph; body: PNode; idgen: IdGenerator; owner: PSym): PNode {....raises: [
+    Exception, ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc liftIterSym(g: ModuleGraph; n: PNode; idgen: IdGenerator; owner: PSym): PNode {....raises: [
+    Exception, ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc liftIterToProc(g: ModuleGraph; fn: PSym; body: PNode; ptrType: PType;
+                    idgen: IdGenerator): PNode {....raises: [KeyError, Exception,
+    ValueError, IOError, ERecoverableError, OSError], tags: [ReadDirEffect,
+    RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc liftLambdas(g: ModuleGraph; fn: PSym; body: PNode; tooEarly: var bool;
+                 idgen: IdGenerator; flags: TransformFlags): PNode {....raises: [
+    KeyError, Exception, ValueError, IOError, ERecoverableError, OSError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc liftLambdasForTopLevel(module: PSym; body: PNode): PNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeClosure(g: ModuleGraph; idgen: IdGenerator; prc: PSym; env: PNode;
+                 info: TLineInfo): PNode {....raises: [KeyError, Exception,
+    ValueError, IOError, ERecoverableError, OSError], tags: [ReadDirEffect,
+    RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc semCaptureSym(s, owner: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template isIterator(owner: PSym): bool
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/lambdalifting.idx b/compiler/lambdalifting.idx new file mode 100644 index 0000000000000..93d32c638fd8d --- /dev/null +++ b/compiler/lambdalifting.idx @@ -0,0 +1,16 @@ +nimTitle lambdalifting lambdalifting.html module lambdalifting 0 +nim upName lambdalifting.html#upName const upName 125 +nim paramName lambdalifting.html#paramName const paramName 126 +nim envName lambdalifting.html#envName const envName 127 +nim createClosureIterStateType lambdalifting.html#createClosureIterStateType,ModuleGraph,PSym,IdGenerator proc createClosureIterStateType(g: ModuleGraph; iter: PSym; idgen: IdGenerator): PType 134 +nim isIterator lambdalifting.html#isIterator.t,PSym template isIterator(owner: PSym): bool 148 +nim getClosureIterResult lambdalifting.html#getClosureIterResult,ModuleGraph,PSym,IdGenerator proc getClosureIterResult(g: ModuleGraph; iter: PSym; idgen: IdGenerator): PSym 156 +nim getEnvParam lambdalifting.html#getEnvParam,PSym proc getEnvParam(routine: PSym): PSym 177 +nim makeClosure lambdalifting.html#makeClosure,ModuleGraph,IdGenerator,PSym,PNode,TLineInfo proc makeClosure(g: ModuleGraph; idgen: IdGenerator; prc: PSym; env: PNode;\n info: TLineInfo): PNode 218 +nim liftIterSym lambdalifting.html#liftIterSym,ModuleGraph,PNode,IdGenerator,PSym proc liftIterSym(g: ModuleGraph; n: PNode; idgen: IdGenerator; owner: PSym): PNode 251 +nim getStateField lambdalifting.html#getStateField,ModuleGraph,PSym proc getStateField(g: ModuleGraph; owner: PSym): PSym 708 +nim semCaptureSym lambdalifting.html#semCaptureSym,PSym,PSym proc semCaptureSym(s, owner: PSym) 823 +nim liftIterToProc lambdalifting.html#liftIterToProc,ModuleGraph,PSym,PNode,PType,IdGenerator proc liftIterToProc(g: ModuleGraph; fn: PSym; body: PNode; ptrType: PType;\n idgen: IdGenerator): PNode 860 +nim liftLambdas lambdalifting.html#liftLambdas,ModuleGraph,PSym,PNode,bool,IdGenerator,TransformFlags proc liftLambdas(g: ModuleGraph; fn: PSym; body: PNode; tooEarly: var bool;\n idgen: IdGenerator; flags: TransformFlags): PNode 875 +nim liftLambdasForTopLevel lambdalifting.html#liftLambdasForTopLevel,PSym,PNode proc liftLambdasForTopLevel(module: PSym; body: PNode): PNode 908 +nim liftForLoop lambdalifting.html#liftForLoop,ModuleGraph,PNode,IdGenerator,PSym proc liftForLoop(g: ModuleGraph; body: PNode; idgen: IdGenerator; owner: PSym): PNode 914 diff --git a/compiler/layeredtable.html b/compiler/layeredtable.html new file mode 100644 index 0000000000000..a7bd8461b6552 --- /dev/null +++ b/compiler/layeredtable.html @@ -0,0 +1,294 @@ + + + + + + + +layeredtable + + + + + + + + + + + + + + + + +
+
+

layeredtable

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ ast +
+
+
+

Types

+
+
+
LayeredIdTable = LayeredIdTableObj
+
+ + + Source   +Edit   + +
+
+
+
LayeredIdTableObj {.acyclic.} = object
+  topLayer*: TypeMapping     ## the mappings on the current layer
+  nextLayer*: ref LayeredIdTableObj ## the parent type binding context, possibly `nil`
+  previousLen*: int ## total length of the bindings up to the parent layer,
+                    ## used to track if new bindings were added
+
+ + stack of type binding contexts implemented as a linked list + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc currentLen(pt: LayeredIdTable): int {....raises: [], tags: [], forbids: [].}
+
+ + the sum of the cached total binding count of the parents and the current binding count, just used to track if bindings were added + Source   +Edit   + +
+
+ +
+
+
+
proc initLayeredTypeMap(pt: sink TypeMapping = initTypeMapping()): LayeredIdTable {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newTypeMapLayer(pt: LayeredIdTable): LayeredIdTable {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setToPreviousLayer(pt: var LayeredIdTable) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc shallowCopy(pt: LayeredIdTable): LayeredIdTable {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + copies only the type bindings of the current layer, but not any parent layers, useful for write-only bindings + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template lookup(typeMap: LayeredIdTableObj; key: PType): PType
+
+ + + Source   +Edit   + +
+
+
+
template lookup(typeMap: ref LayeredIdTableObj; key: PType): PType
+
+ + recursively looks up binding of key in all parent layers + Source   +Edit   + +
+
+ +
+
+
+
template put(typeMap: var LayeredIdTable; key, value: PType)
+
+ + binds key to value only in current layer + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/layeredtable.idx b/compiler/layeredtable.idx new file mode 100644 index 0000000000000..4f72e8cbc3b8e --- /dev/null +++ b/compiler/layeredtable.idx @@ -0,0 +1,12 @@ +nimTitle layeredtable layeredtable.html module layeredtable 0 +nim LayeredIdTableObj layeredtable.html#LayeredIdTableObj object LayeredIdTableObj 5 +nim LayeredIdTable layeredtable.html#LayeredIdTable type LayeredIdTable 22 +nim initLayeredTypeMap layeredtable.html#initLayeredTypeMap,sinkTypeMapping proc initLayeredTypeMap(pt: sink TypeMapping = initTypeMapping()): LayeredIdTable 24 +nim shallowCopy layeredtable.html#shallowCopy,LayeredIdTableObj proc shallowCopy(pt: LayeredIdTable): LayeredIdTable 27 +nim currentLen layeredtable.html#currentLen,LayeredIdTableObj proc currentLen(pt: LayeredIdTable): int 32 +nim newTypeMapLayer layeredtable.html#newTypeMapLayer,LayeredIdTableObj proc newTypeMapLayer(pt: LayeredIdTable): LayeredIdTable 37 +nim setToPreviousLayer layeredtable.html#setToPreviousLayer,LayeredIdTableObj proc setToPreviousLayer(pt: var LayeredIdTable) 45 +nim lookup layeredtable.html#lookup.t,ref.LayeredIdTableObj,PType template lookup(typeMap: ref LayeredIdTableObj; key: PType): PType 64 +nim lookup layeredtable.html#lookup.t,LayeredIdTableObj,PType template lookup(typeMap: LayeredIdTableObj; key: PType): PType 74 +nim put layeredtable.html#put.t,LayeredIdTableObj,PType,PType template put(typeMap: var LayeredIdTable; key, value: PType) 80 +nimgrp lookup layeredtable.html#lookup-templates-all template 64 diff --git a/compiler/lexer.html b/compiler/lexer.html new file mode 100644 index 0000000000000..c64c6b9ceb929 --- /dev/null +++ b/compiler/lexer.html @@ -0,0 +1,662 @@ + + + + + + + +lexer + + + + + + + + + + + + + + + + +
+
+

lexer

+
+ +
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
ErrorHandler = proc (conf: ConfigRef; info: TLineInfo; msg: TMsgKind;
+                     arg: string)
+
+ + + Source   +Edit   + +
+
+
+
Lexer = object of TBaseLexer
+  fileIdx*: FileIndex
+  indentAhead*: int
+  currLineIndent*: int
+  errorHandler*: ErrorHandler
+  cache*: IdentCache
+  when defined(nimsuggest):
+    tokenEnd*: TLineInfo
+    previousTokenEnd*: TLineInfo
+  config*: ConfigRef
+
+ + + Source   +Edit   + +
+
+
+
NumericalBase = enum
+  base10, base2, base8, base16
+
+ + + Source   +Edit   + +
+
+
+
Token = object
+  tokType*: TokType
+  base*: NumericalBase
+  spacing*: set[TokenSpacing]
+  indent*: int
+  ident*: PIdent
+  iNumber*: BiggestInt
+  fNumber*: BiggestFloat
+  literal*: string
+  line*, col*: int
+  when defined(nimpretty):
+    offsetA*, offsetB*: int
+    commentOffsetA*, commentOffsetB*: int
+
+ + + Source   +Edit   + +
+
+
+
TokenSpacing = enum
+  tsLeading, tsTrailing, tsEof
+
+ + + Source   +Edit   + +
+
+
+
TokType = enum
+  tkInvalid = "tkInvalid", tkEof = "[EOF]", tkSymbol = "tkSymbol",
+  tkAddr = "addr", tkAnd = "and", tkAs = "as", tkAsm = "asm", tkBind = "bind",
+  tkBlock = "block", tkBreak = "break", tkCase = "case", tkCast = "cast",
+  tkConcept = "concept", tkConst = "const", tkContinue = "continue",
+  tkConverter = "converter", tkDefer = "defer", tkDiscard = "discard",
+  tkDistinct = "distinct", tkDiv = "div", tkDo = "do", tkElif = "elif",
+  tkElse = "else", tkEnd = "end", tkEnum = "enum", tkExcept = "except",
+  tkExport = "export", tkFinally = "finally", tkFor = "for", tkFrom = "from",
+  tkFunc = "func", tkIf = "if", tkImport = "import", tkIn = "in",
+  tkInclude = "include", tkInterface = "interface", tkIs = "is",
+  tkIsnot = "isnot", tkIterator = "iterator", tkLet = "let", tkMacro = "macro",
+  tkMethod = "method", tkMixin = "mixin", tkMod = "mod", tkNil = "nil",
+  tkNot = "not", tkNotin = "notin", tkObject = "object", tkOf = "of",
+  tkOr = "or", tkOut = "out", tkProc = "proc", tkPtr = "ptr", tkRaise = "raise",
+  tkRef = "ref", tkReturn = "return", tkShl = "shl", tkShr = "shr",
+  tkStatic = "static", tkTemplate = "template", tkTry = "try",
+  tkTuple = "tuple", tkType = "type", tkUsing = "using", tkVar = "var",
+  tkWhen = "when", tkWhile = "while", tkXor = "xor", tkYield = "yield",
+  tkIntLit = "tkIntLit", tkInt8Lit = "tkInt8Lit", tkInt16Lit = "tkInt16Lit",
+  tkInt32Lit = "tkInt32Lit", tkInt64Lit = "tkInt64Lit", tkUIntLit = "tkUIntLit",
+  tkUInt8Lit = "tkUInt8Lit", tkUInt16Lit = "tkUInt16Lit",
+  tkUInt32Lit = "tkUInt32Lit", tkUInt64Lit = "tkUInt64Lit",
+  tkFloatLit = "tkFloatLit", tkFloat32Lit = "tkFloat32Lit",
+  tkFloat64Lit = "tkFloat64Lit", tkFloat128Lit = "tkFloat128Lit",
+  tkStrLit = "tkStrLit", tkRStrLit = "tkRStrLit",
+  tkTripleStrLit = "tkTripleStrLit", tkGStrLit = "tkGStrLit",
+  tkGTripleStrLit = "tkGTripleStrLit", tkCharLit = "tkCharLit",
+  tkCustomLit = "tkCustomLit", tkParLe = "(", tkParRi = ")", tkBracketLe = "[",
+  tkBracketRi = "]", tkCurlyLe = "{", tkCurlyRi = "}", tkBracketDotLe = "[.",
+  tkBracketDotRi = ".]", tkCurlyDotLe = "{.", tkCurlyDotRi = ".}",
+  tkParDotLe = "(.", tkParDotRi = ".)", tkComma = ",", tkSemiColon = ";",
+  tkColon = ":", tkColonColon = "::", tkEquals = "=", tkDot = ".",
+  tkDotDot = "..", tkBracketLeColon = "[:", tkOpr, tkComment, tkAccent = "`",
+  tkSpaces, tkInfixOpr, tkPrefixOpr, tkPostfixOpr, tkHideableStart,
+  tkHideableEnd
+
+ + + Source   +Edit   + +
+
+
+
TokTypes = set[TokType]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
numChars: set[char] = {'0'..'9', 'a'..'z', 'A'..'Z'}
+
+ + + Source   +Edit   + +
+
+
+
OpChars: set[char] = {'+', '-', '*', '/', '\\', '<', '>', '!', '?', '^', '.',
+                      '|', '=', '%', '&', '$', '@', '~', ':'}
+
+ + + Source   +Edit   + +
+
+
+
SymChars: set[char] = {'a'..'z', 'A'..'Z', '0'..'9', '\x80'..'\xFF'}
+
+ + + Source   +Edit   + +
+
+
+
SymStartChars: set[char] = {'a'..'z', 'A'..'Z', '\x80'..'\xFF'}
+
+ + + Source   +Edit   + +
+
+
+
tokKeywordHigh = tkYield
+
+ + + Source   +Edit   + +
+
+
+
tokKeywordLow = tkAddr
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(tok: Token): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc closeLexer(lex: var Lexer) {....raises: [IOError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getIndentWidth(fileIdx: FileIndex; inputstream: PLLStream;
+                    cache: IdentCache; config: ConfigRef): int {.
+    ...raises: [IOError, Exception, ValueError, KeyError, ERecoverableError], tags: [
+    ReadIOEffect, RootEffect, ReadDirEffect, WriteIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getLineInfo(L: Lexer; tok: Token): TLineInfo {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getPrecedence(ident: PIdent): int {....raises: [], tags: [], forbids: [].}
+
+ + assumes ident is binary operator already + Source   +Edit   + +
+
+
+
proc getPrecedence(tok: Token): int {....raises: [], tags: [], forbids: [].}
+
+ + Calculates the precedence of the given token. + Source   +Edit   + +
+
+ +
+
+
+
proc isKeyword(kind: TokType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isNimIdentifier(s: string): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lexMessage(L: Lexer; msg: TMsgKind; arg = "") {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lexMessageTok(L: Lexer; msg: TMsgKind; tok: Token; arg = "") {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc openLexer(lex: var Lexer; fileIdx: FileIndex; inputstream: PLLStream;
+               cache: IdentCache; config: ConfigRef) {.
+    ...raises: [IOError, Exception], tags: [ReadIOEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc openLexer(lex: var Lexer; filename: AbsoluteFile; inputstream: PLLStream;
+               cache: IdentCache; config: ConfigRef) {.
+    ...raises: [IOError, Exception, KeyError],
+    tags: [ReadIOEffect, RootEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc prettyTok(tok: Token): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc printTok(conf: ConfigRef; tok: Token) {....raises: [Exception, IOError],
+    tags: [RootEffect, WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rawGetTok(L: var Lexer; tok: var Token) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/lexer.idx b/compiler/lexer.idx new file mode 100644 index 0000000000000..b8b04772a1311 --- /dev/null +++ b/compiler/lexer.idx @@ -0,0 +1,157 @@ +nimTitle lexer lexer.html module lexer 0 +nim numChars lexer.html#numChars const numChars 28 +nim SymChars lexer.html#SymChars const SymChars 29 +nim SymStartChars lexer.html#SymStartChars const SymStartChars 30 +nim OpChars lexer.html#OpChars const OpChars 31 +nim tkInvalid lexer.html#tkInvalid TokType.tkInvalid 38 +nim tkEof lexer.html#tkEof TokType.tkEof 38 +nim tkSymbol lexer.html#tkSymbol TokType.tkSymbol 38 +nim tkAddr lexer.html#tkAddr TokType.tkAddr 38 +nim tkAnd lexer.html#tkAnd TokType.tkAnd 38 +nim tkAs lexer.html#tkAs TokType.tkAs 38 +nim tkAsm lexer.html#tkAsm TokType.tkAsm 38 +nim tkBind lexer.html#tkBind TokType.tkBind 38 +nim tkBlock lexer.html#tkBlock TokType.tkBlock 38 +nim tkBreak lexer.html#tkBreak TokType.tkBreak 38 +nim tkCase lexer.html#tkCase TokType.tkCase 38 +nim tkCast lexer.html#tkCast TokType.tkCast 38 +nim tkConcept lexer.html#tkConcept TokType.tkConcept 38 +nim tkConst lexer.html#tkConst TokType.tkConst 38 +nim tkContinue lexer.html#tkContinue TokType.tkContinue 38 +nim tkConverter lexer.html#tkConverter TokType.tkConverter 38 +nim tkDefer lexer.html#tkDefer TokType.tkDefer 38 +nim tkDiscard lexer.html#tkDiscard TokType.tkDiscard 38 +nim tkDistinct lexer.html#tkDistinct TokType.tkDistinct 38 +nim tkDiv lexer.html#tkDiv TokType.tkDiv 38 +nim tkDo lexer.html#tkDo TokType.tkDo 38 +nim tkElif lexer.html#tkElif TokType.tkElif 38 +nim tkElse lexer.html#tkElse TokType.tkElse 38 +nim tkEnd lexer.html#tkEnd TokType.tkEnd 38 +nim tkEnum lexer.html#tkEnum TokType.tkEnum 38 +nim tkExcept lexer.html#tkExcept TokType.tkExcept 38 +nim tkExport lexer.html#tkExport TokType.tkExport 38 +nim tkFinally lexer.html#tkFinally TokType.tkFinally 38 +nim tkFor lexer.html#tkFor TokType.tkFor 38 +nim tkFrom lexer.html#tkFrom TokType.tkFrom 38 +nim tkFunc lexer.html#tkFunc TokType.tkFunc 38 +nim tkIf lexer.html#tkIf TokType.tkIf 38 +nim tkImport lexer.html#tkImport TokType.tkImport 38 +nim tkIn lexer.html#tkIn TokType.tkIn 38 +nim tkInclude lexer.html#tkInclude TokType.tkInclude 38 +nim tkInterface lexer.html#tkInterface TokType.tkInterface 38 +nim tkIs lexer.html#tkIs TokType.tkIs 38 +nim tkIsnot lexer.html#tkIsnot TokType.tkIsnot 38 +nim tkIterator lexer.html#tkIterator TokType.tkIterator 38 +nim tkLet lexer.html#tkLet TokType.tkLet 38 +nim tkMacro lexer.html#tkMacro TokType.tkMacro 38 +nim tkMethod lexer.html#tkMethod TokType.tkMethod 38 +nim tkMixin lexer.html#tkMixin TokType.tkMixin 38 +nim tkMod lexer.html#tkMod TokType.tkMod 38 +nim tkNil lexer.html#tkNil TokType.tkNil 38 +nim tkNot lexer.html#tkNot TokType.tkNot 38 +nim tkNotin lexer.html#tkNotin TokType.tkNotin 38 +nim tkObject lexer.html#tkObject TokType.tkObject 38 +nim tkOf lexer.html#tkOf TokType.tkOf 38 +nim tkOr lexer.html#tkOr TokType.tkOr 38 +nim tkOut lexer.html#tkOut TokType.tkOut 38 +nim tkProc lexer.html#tkProc TokType.tkProc 38 +nim tkPtr lexer.html#tkPtr TokType.tkPtr 38 +nim tkRaise lexer.html#tkRaise TokType.tkRaise 38 +nim tkRef lexer.html#tkRef TokType.tkRef 38 +nim tkReturn lexer.html#tkReturn TokType.tkReturn 38 +nim tkShl lexer.html#tkShl TokType.tkShl 38 +nim tkShr lexer.html#tkShr TokType.tkShr 38 +nim tkStatic lexer.html#tkStatic TokType.tkStatic 38 +nim tkTemplate lexer.html#tkTemplate TokType.tkTemplate 38 +nim tkTry lexer.html#tkTry TokType.tkTry 38 +nim tkTuple lexer.html#tkTuple TokType.tkTuple 38 +nim tkType lexer.html#tkType TokType.tkType 38 +nim tkUsing lexer.html#tkUsing TokType.tkUsing 38 +nim tkVar lexer.html#tkVar TokType.tkVar 38 +nim tkWhen lexer.html#tkWhen TokType.tkWhen 38 +nim tkWhile lexer.html#tkWhile TokType.tkWhile 38 +nim tkXor lexer.html#tkXor TokType.tkXor 38 +nim tkYield lexer.html#tkYield TokType.tkYield 38 +nim tkIntLit lexer.html#tkIntLit TokType.tkIntLit 38 +nim tkInt8Lit lexer.html#tkInt8Lit TokType.tkInt8Lit 38 +nim tkInt16Lit lexer.html#tkInt16Lit TokType.tkInt16Lit 38 +nim tkInt32Lit lexer.html#tkInt32Lit TokType.tkInt32Lit 38 +nim tkInt64Lit lexer.html#tkInt64Lit TokType.tkInt64Lit 38 +nim tkUIntLit lexer.html#tkUIntLit TokType.tkUIntLit 38 +nim tkUInt8Lit lexer.html#tkUInt8Lit TokType.tkUInt8Lit 38 +nim tkUInt16Lit lexer.html#tkUInt16Lit TokType.tkUInt16Lit 38 +nim tkUInt32Lit lexer.html#tkUInt32Lit TokType.tkUInt32Lit 38 +nim tkUInt64Lit lexer.html#tkUInt64Lit TokType.tkUInt64Lit 38 +nim tkFloatLit lexer.html#tkFloatLit TokType.tkFloatLit 38 +nim tkFloat32Lit lexer.html#tkFloat32Lit TokType.tkFloat32Lit 38 +nim tkFloat64Lit lexer.html#tkFloat64Lit TokType.tkFloat64Lit 38 +nim tkFloat128Lit lexer.html#tkFloat128Lit TokType.tkFloat128Lit 38 +nim tkStrLit lexer.html#tkStrLit TokType.tkStrLit 38 +nim tkRStrLit lexer.html#tkRStrLit TokType.tkRStrLit 38 +nim tkTripleStrLit lexer.html#tkTripleStrLit TokType.tkTripleStrLit 38 +nim tkGStrLit lexer.html#tkGStrLit TokType.tkGStrLit 38 +nim tkGTripleStrLit lexer.html#tkGTripleStrLit TokType.tkGTripleStrLit 38 +nim tkCharLit lexer.html#tkCharLit TokType.tkCharLit 38 +nim tkCustomLit lexer.html#tkCustomLit TokType.tkCustomLit 38 +nim tkParLe lexer.html#tkParLe TokType.tkParLe 38 +nim tkParRi lexer.html#tkParRi TokType.tkParRi 38 +nim tkBracketLe lexer.html#tkBracketLe TokType.tkBracketLe 38 +nim tkBracketRi lexer.html#tkBracketRi TokType.tkBracketRi 38 +nim tkCurlyLe lexer.html#tkCurlyLe TokType.tkCurlyLe 38 +nim tkCurlyRi lexer.html#tkCurlyRi TokType.tkCurlyRi 38 +nim tkBracketDotLe lexer.html#tkBracketDotLe TokType.tkBracketDotLe 38 +nim tkBracketDotRi lexer.html#tkBracketDotRi TokType.tkBracketDotRi 38 +nim tkCurlyDotLe lexer.html#tkCurlyDotLe TokType.tkCurlyDotLe 38 +nim tkCurlyDotRi lexer.html#tkCurlyDotRi TokType.tkCurlyDotRi 38 +nim tkParDotLe lexer.html#tkParDotLe TokType.tkParDotLe 38 +nim tkParDotRi lexer.html#tkParDotRi TokType.tkParDotRi 38 +nim tkComma lexer.html#tkComma TokType.tkComma 38 +nim tkSemiColon lexer.html#tkSemiColon TokType.tkSemiColon 38 +nim tkColon lexer.html#tkColon TokType.tkColon 38 +nim tkColonColon lexer.html#tkColonColon TokType.tkColonColon 38 +nim tkEquals lexer.html#tkEquals TokType.tkEquals 38 +nim tkDot lexer.html#tkDot TokType.tkDot 38 +nim tkDotDot lexer.html#tkDotDot TokType.tkDotDot 38 +nim tkBracketLeColon lexer.html#tkBracketLeColon TokType.tkBracketLeColon 38 +nim tkOpr lexer.html#tkOpr TokType.tkOpr 38 +nim tkComment lexer.html#tkComment TokType.tkComment 38 +nim tkAccent lexer.html#tkAccent TokType.tkAccent 38 +nim tkSpaces lexer.html#tkSpaces TokType.tkSpaces 38 +nim tkInfixOpr lexer.html#tkInfixOpr TokType.tkInfixOpr 38 +nim tkPrefixOpr lexer.html#tkPrefixOpr TokType.tkPrefixOpr 38 +nim tkPostfixOpr lexer.html#tkPostfixOpr TokType.tkPostfixOpr 38 +nim tkHideableStart lexer.html#tkHideableStart TokType.tkHideableStart 38 +nim tkHideableEnd lexer.html#tkHideableEnd TokType.tkHideableEnd 38 +nim TokType lexer.html#TokType enum TokType 38 +nim TokTypes lexer.html#TokTypes type TokTypes 81 +nim tokKeywordLow lexer.html#tokKeywordLow const tokKeywordLow 88 +nim tokKeywordHigh lexer.html#tokKeywordHigh const tokKeywordHigh 89 +nim base10 lexer.html#base10 NumericalBase.base10 92 +nim base2 lexer.html#base2 NumericalBase.base2 92 +nim base8 lexer.html#base8 NumericalBase.base8 92 +nim base16 lexer.html#base16 NumericalBase.base16 92 +nim NumericalBase lexer.html#NumericalBase enum NumericalBase 92 +nim tsLeading lexer.html#tsLeading TokenSpacing.tsLeading 97 +nim tsTrailing lexer.html#tsTrailing TokenSpacing.tsTrailing 97 +nim tsEof lexer.html#tsEof TokenSpacing.tsEof 97 +nim TokenSpacing lexer.html#TokenSpacing enum TokenSpacing 97 +nim Token lexer.html#Token object Token 100 +nim ErrorHandler lexer.html#ErrorHandler type ErrorHandler 118 +nim Lexer lexer.html#Lexer object Lexer 119 +nim getLineInfo lexer.html#getLineInfo,Lexer,Token proc getLineInfo(L: Lexer; tok: Token): TLineInfo 133 +nim isKeyword lexer.html#isKeyword,TokType proc isKeyword(kind: TokType): bool 141 +nim isNimIdentifier lexer.html#isNimIdentifier,string proc isNimIdentifier(s: string): bool 146 +nim `$` lexer.html#$,Token proc `$`(tok: Token): string 158 +nim prettyTok lexer.html#prettyTok,Token proc prettyTok(tok: Token): string 170 +nim printTok lexer.html#printTok,ConfigRef,Token proc printTok(conf: ConfigRef; tok: Token) 174 +nim openLexer lexer.html#openLexer,Lexer,FileIndex,PLLStream,IdentCache,ConfigRef proc openLexer(lex: var Lexer; fileIdx: FileIndex; inputstream: PLLStream;\n cache: IdentCache; config: ConfigRef) 178 +nim openLexer lexer.html#openLexer,Lexer,AbsoluteFile,PLLStream,IdentCache,ConfigRef proc openLexer(lex: var Lexer; filename: AbsoluteFile; inputstream: PLLStream;\n cache: IdentCache; config: ConfigRef) 190 +nim closeLexer lexer.html#closeLexer,Lexer proc closeLexer(lex: var Lexer) 194 +nim lexMessage lexer.html#lexMessage,Lexer,TMsgKind,string proc lexMessage(L: Lexer; msg: TMsgKind; arg = "") 208 +nim lexMessageTok lexer.html#lexMessageTok,Lexer,TMsgKind,Token,string proc lexMessageTok(L: Lexer; msg: TMsgKind; tok: Token; arg = "") 211 +nim getPrecedence lexer.html#getPrecedence,Token proc getPrecedence(tok: Token): int 943 +nim rawGetTok lexer.html#rawGetTok,Lexer,Token proc rawGetTok(L: var Lexer; tok: var Token) 1175 +nim getIndentWidth lexer.html#getIndentWidth,FileIndex,PLLStream,IdentCache,ConfigRef proc getIndentWidth(fileIdx: FileIndex; inputstream: PLLStream; cache: IdentCache;\n config: ConfigRef): int 1353 +nim getPrecedence lexer.html#getPrecedence,PIdent proc getPrecedence(ident: PIdent): int 1368 +nimgrp openlexer lexer.html#openLexer-procs-all proc 178 +nimgrp getprecedence lexer.html#getPrecedence-procs-all proc 943 diff --git a/compiler/liftdestructors.html b/compiler/liftdestructors.html new file mode 100644 index 0000000000000..adf3a62b901a3 --- /dev/null +++ b/compiler/liftdestructors.html @@ -0,0 +1,322 @@ + + + + + + + +liftdestructors + + + + + + + + + + + + + + + + +
+
+

liftdestructors

+
+ +
+ Source   +Edit   + +
+ +

This module implements lifting for type-bound operations (=sink, =copy, =destroy, =deepCopy, =wasMoved, =dup).

+ +
+

Procs

+
+
+
+
proc boolLit(g: ModuleGraph; info: TLineInfo; value: bool): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createTypeBoundOps(g: ModuleGraph; c: PContext; orig: PType;
+                        info: TLineInfo; idgen: IdGenerator) {....raises: [OSError,
+    Exception, KeyError, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cyclicType(g: ModuleGraph; t: PType): bool {....raises: [Exception, KeyError],
+    tags: [RootEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genBuiltin(g: ModuleGraph; idgen: IdGenerator; magic: TMagic; name: string;
+                i: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isTrival(s: PSym): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc produceDestructorForDiscriminator(g: ModuleGraph; typ: PType; field: PSym;
+                                       info: TLineInfo; idgen: IdGenerator): PSym {....raises: [
+    Exception, KeyError, ValueError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template asink(t: PType): PSym
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template assignment(t: PType): PSym
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template destructor(t: PType): PSym
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template dup(t: PType): PSym
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template liftTypeBoundOps(c: PContext; typ: PType; info: TLineInfo)
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/liftdestructors.idx b/compiler/liftdestructors.idx new file mode 100644 index 0000000000000..b0b8ce11b517a --- /dev/null +++ b/compiler/liftdestructors.idx @@ -0,0 +1,12 @@ +nimTitle liftdestructors liftdestructors.html module liftdestructors 0 +nim destructor liftdestructors.html#destructor.t,PType template destructor(t: PType): PSym 36 +nim assignment liftdestructors.html#assignment.t,PType template assignment(t: PType): PSym 37 +nim dup liftdestructors.html#dup.t,PType template dup(t: PType): PSym 38 +nim asink liftdestructors.html#asink.t,PType template asink(t: PType): PSym 39 +nim createTypeBoundOps liftdestructors.html#createTypeBoundOps,ModuleGraph,PContext,PType,TLineInfo,IdGenerator proc createTypeBoundOps(g: ModuleGraph; c: PContext; orig: PType; info: TLineInfo;\n idgen: IdGenerator) 45 +nim genBuiltin liftdestructors.html#genBuiltin,ModuleGraph,IdGenerator,TMagic,string,PNode proc genBuiltin(g: ModuleGraph; idgen: IdGenerator; magic: TMagic; name: string;\n i: PNode): PNode 78 +nim boolLit liftdestructors.html#boolLit,ModuleGraph,TLineInfo,bool proc boolLit(g: ModuleGraph; info: TLineInfo; value: bool): PNode 297 +nim cyclicType liftdestructors.html#cyclicType,ModuleGraph,PType proc cyclicType(g: ModuleGraph; t: PType): bool 677 +nim produceDestructorForDiscriminator liftdestructors.html#produceDestructorForDiscriminator,ModuleGraph,PType,PSym,TLineInfo,IdGenerator proc produceDestructorForDiscriminator(g: ModuleGraph; typ: PType; field: PSym;\n info: TLineInfo; idgen: IdGenerator): PSym 1213 +nim liftTypeBoundOps liftdestructors.html#liftTypeBoundOps.t,PContext,PType,TLineInfo template liftTypeBoundOps(c: PContext; typ: PType; info: TLineInfo) 1237 +nim isTrival liftdestructors.html#isTrival,PSym proc isTrival(s: PSym): bool 1269 diff --git a/compiler/liftlocals.html b/compiler/liftlocals.html new file mode 100644 index 0000000000000..497d0c7061879 --- /dev/null +++ b/compiler/liftlocals.html @@ -0,0 +1,125 @@ + + + + + + + +liftlocals + + + + + + + + + + + + + + + + +
+
+

liftlocals

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module implements the '.liftLocals' pragma.

+ +
+

Procs

+
+
+
+
proc liftLocalsIfRequested(prc: PSym; n: PNode; cache: IdentCache;
+                           conf: ConfigRef; idgen: IdGenerator): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/liftlocals.idx b/compiler/liftlocals.idx new file mode 100644 index 0000000000000..23994e0b15f75 --- /dev/null +++ b/compiler/liftlocals.idx @@ -0,0 +1,2 @@ +nimTitle liftlocals liftlocals.html module liftlocals 0 +nim liftLocalsIfRequested liftlocals.html#liftLocalsIfRequested,PSym,PNode,IdentCache,ConfigRef,IdGenerator proc liftLocalsIfRequested(prc: PSym; n: PNode; cache: IdentCache; conf: ConfigRef;\n idgen: IdGenerator): PNode 60 diff --git a/compiler/lineinfos.html b/compiler/lineinfos.html new file mode 100644 index 0000000000000..0d10b86677463 --- /dev/null +++ b/compiler/lineinfos.html @@ -0,0 +1,871 @@ + + + + + + + +lineinfos + + + + + + + + + + + + + + + + +
+
+

lineinfos

+
+ +
+ Source   +Edit   + +
+ +

This module contains the TMsgKind enum as well as the TLineInfo object.

+
+

Imports

+
+ ropes, pathutils +
+
+
+

Types

+
+
+
ERecoverableError = object of ValueError
+
+ + + Source   +Edit   + +
+
+
+
ESuggestDone = object of ValueError
+
+ + + Source   +Edit   + +
+
+
+
FileIndex = distinct int32
+
+ + + Source   +Edit   + +
+
+
+
MsgConfig = object
+  trackPos*: TLineInfo
+  trackPosAttached*: bool    ## whether the tracking position was attached to
+                             ## some close token.
+  errorOutputs*: TErrorOutputs
+  msgContext*: seq[tuple[info: TLineInfo, detail: string]]
+  lastError*: TLineInfo
+  filenameToIndexTbl*: Table[string, FileIndex]
+  fileInfos*: seq[TFileInfo]
+  systemFileIdx*: FileIndex
+
+ + does not need to be stored in the incremental cache + Source   +Edit   + +
+
+
+
Severity {.pure.} = enum
+  Hint, Warning, Error
+
+ + VS Code only supports these three + Source   +Edit   + +
+
+
+
TErrorOutput = enum
+  eStdOut, eStdErr
+
+ + + Source   +Edit   + +
+
+
+
TErrorOutputs = set[TErrorOutput]
+
+ + + Source   +Edit   + +
+
+
+
TFileInfo = object
+  fullPath*: AbsoluteFile
+  projPath*: RelativeFile
+  shortName*: string
+  quotedName*: Rope
+  quotedFullName*: Rope
+  lines*: seq[string]
+  dirtyFile*: AbsoluteFile
+  hash*: string
+  dirty*: bool
+  when defined(nimpretty):
+    fullContent*: string
+
+ + + Source   +Edit   + +
+
+
+
TLineInfo = object
+  line*: uint16
+  col*: int16
+  fileIndex*: FileIndex
+  when defined(nimpretty):
+    offsetA*, offsetB*: int
+    commentOffsetA*, commentOffsetB*: int
+
+ + + Source   +Edit   + +
+
+
+
TMsgKind = enum
+  errUnknown, errFatal, errInternal, errIllFormedAstX, errCannotOpenFile,
+  errXExpected, errRstMissingClosing, errRstGridTableNotImplemented,
+  errRstMarkdownIllformedTable, errRstIllformedTable, errRstNewSectionExpected,
+  errRstGeneralParseError, errRstInvalidDirectiveX, errRstInvalidField,
+  errRstFootnoteMismatch, errRstSandboxedDirective, errProveInit, errGenerated,
+  errFailedMove, errUser, warnCannotOpenFile = "CannotOpenFile",
+  warnOctalEscape = "OctalEscape", warnXIsNeverRead = "XIsNeverRead",
+  warnXmightNotBeenInit = "XmightNotBeenInit", warnDeprecated = "Deprecated",
+  warnConfigDeprecated = "ConfigDeprecated", warnDotLikeOps = "DotLikeOps",
+  warnSmallLshouldNotBeUsed = "SmallLshouldNotBeUsed",
+  warnUnknownMagic = "UnknownMagic",
+  warnRstRedefinitionOfLabel = "RedefinitionOfLabel",
+  warnRstUnknownSubstitutionX = "UnknownSubstitutionX",
+  warnRstAmbiguousLink = "AmbiguousLink", warnRstBrokenLink = "BrokenLink",
+  warnRstLanguageXNotSupported = "LanguageXNotSupported",
+  warnRstFieldXNotSupported = "FieldXNotSupported",
+  warnRstUnusedImportdoc = "UnusedImportdoc", warnRstStyle = "warnRstStyle",
+  warnCommentXIgnored = "CommentXIgnored", warnTypelessParam = "TypelessParam",
+  warnUseBase = "UseBase", warnWriteToForeignHeap = "WriteToForeignHeap",
+  warnUnsafeCode = "UnsafeCode", warnUnusedImportX = "UnusedImport",
+  warnInheritFromException = "InheritFromException",
+  warnEachIdentIsTuple = "EachIdentIsTuple", warnUnsafeSetLen = "UnsafeSetLen",
+  warnUnsafeDefault = "UnsafeDefault", warnProveInit = "ProveInit",
+  warnProveField = "ProveField", warnProveIndex = "ProveIndex",
+  warnUnreachableElse = "UnreachableElse",
+  warnUnreachableCode = "UnreachableCode", warnStaticIndexCheck = "IndexCheck",
+  warnGcUnsafe = "GcUnsafe", warnGcUnsafe2 = "GcUnsafe2", warnUninit = "Uninit",
+  warnGcMem = "GcMem", warnDestructor = "Destructor",
+  warnLockLevel = "LockLevel", warnResultShadowed = "ResultShadowed",
+  warnInconsistentSpacing = "Spacing", warnCaseTransition = "CaseTransition",
+  warnCycleCreated = "CycleCreated", warnObservableStores = "ObservableStores",
+  warnStrictNotNil = "StrictNotNil", warnResultUsed = "ResultUsed",
+  warnCannotOpen = "CannotOpen", warnFileChanged = "FileChanged",
+  warnSuspiciousEnumConv = "EnumConv", warnAnyEnumConv = "AnyEnumConv",
+  warnHoleEnumConv = "HoleEnumConv", warnCstringConv = "CStringConv",
+  warnPtrToCstringConv = "PtrToCstringConv", warnEffect = "Effect",
+  warnCastSizes = "CastSizes", warnAboveMaxSizeSet = "AboveMaxSizeSet",
+  warnImplicitTemplateRedefinition = "ImplicitTemplateRedefinition",
+  warnUnnamedBreak = "UnnamedBreak", warnStmtListLambda = "StmtListLambda",
+  warnBareExcept = "BareExcept",
+  warnImplicitDefaultValue = "ImplicitDefaultValue",
+  warnIgnoredSymbolInjection = "IgnoredSymbolInjection",
+  warnStdPrefix = "StdPrefix", warnUser = "User",
+  warnGlobalVarConstructorTemporary = "GlobalVarConstructorTemporary",
+  hintSuccess = "Success", hintSuccessX = "SuccessX", hintCC = "CC",
+  hintXDeclaredButNotUsed = "XDeclaredButNotUsed",
+  hintDuplicateModuleImport = "DuplicateModuleImport",
+  hintXCannotRaiseY = "XCannotRaiseY",
+  hintConvToBaseNotNeeded = "ConvToBaseNotNeeded",
+  hintConvFromXtoItselfNotNeeded = "ConvFromXtoItselfNotNeeded",
+  hintExprAlwaysX = "ExprAlwaysX", hintQuitCalled = "QuitCalled",
+  hintProcessing = "Processing", hintProcessingStmt = "ProcessingStmt",
+  hintCodeBegin = "CodeBegin", hintCodeEnd = "CodeEnd", hintConf = "Conf",
+  hintPath = "Path", hintConditionAlwaysTrue = "CondTrue",
+  hintConditionAlwaysFalse = "CondFalse", hintName = "Name",
+  hintPattern = "Pattern", hintExecuting = "Exec", hintLinking = "Link",
+  hintDependency = "Dependency", hintSource = "Source",
+  hintPerformance = "Performance", hintStackTrace = "StackTrace",
+  hintGCStats = "GCStats", hintGlobalVar = "GlobalVar",
+  hintExpandMacro = "ExpandMacro", hintUser = "User", hintUserRaw = "UserRaw",
+  hintExtendedContext = "ExtendedContext", hintMsgOrigin = "MsgOrigin",
+  hintDeclaredLoc = "DeclaredLoc", hintUnknownHint = "UnknownHint"
+
+ + + Source   +Edit   + +
+
+
+
TNoteKind = range[warnMin .. hintMax]
+
+ + + Source   +Edit   + +
+
+
+
TNoteKinds = set[TNoteKind]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
commandLineIdx = -3'i32
+
+ + + Source   +Edit   + +
+
+
+
errArgsNeedRunOption = "arguments can only be given if the \'--run\' option is selected"
+
+ + + Source   +Edit   + +
+
+
+
errFloatToString = "cannot convert \'$1\' to \'$2\'"
+
+ + + Source   +Edit   + +
+
+
+
errMax = errUser
+
+ + + Source   +Edit   + +
+
+
+
errMin = errUnknown
+
+ + + Source   +Edit   + +
+
+
+
errXMustBeCompileTime = "\'$1\' can only be used in compile-time context"
+
+ + + Source   +Edit   + +
+
+
+
explanationsBaseUrl = "https://nim-lang.github.io/Nim"
+
+ + + Source   +Edit   + +
+
+
+
fatalMsgs = {errUnknown..errInternal}
+
+ + + Source   +Edit   + +
+
+
+
hintMax = hintUnknownHint
+
+ + + Source   +Edit   + +
+
+
+
hintMin = hintSuccess
+
+ + + Source   +Edit   + +
+
+
+
InvalidFileIdx = -1'i32
+
+ + + Source   +Edit   + +
+
+
+
MsgKindToStr: array[TMsgKind, string] = ["unknown error", "fatal error: $1",
+    "internal error: $1", "illformed AST: $1", "cannot open \'$1\'",
+    "\'$1\' expected", "$1", "grid table is not implemented",
+    "illformed delimiter row of a markdown table", "Illformed table: $1",
+    "new section expected $1", "general parse error",
+    "invalid directive: \'$1\'", "invalid field: $1",
+    "number of footnotes and their references don\'t match: $1",
+    "disabled directive: \'$1\'", "Cannot prove that \'$1\' is initialized.",
+    "$1", "$1", "$1", "cannot open \'$1\'",
+    "octal escape sequences do not exist; leading zero is ignored",
+    "\'$1\' is never read", "\'$1\' might not have been initialized", "$1",
+    "config file \'$1\' is deprecated", "$1",
+    "\'l\' should not be used as an identifier; may look like \'1\' (one)",
+    "unknown magic \'$1\' might crash the compiler",
+    "redefinition of label \'$1\'", "unknown substitution \'$1\'",
+    "ambiguous doc link $1", "broken link \'$1\'",
+    "language \'$1\' not supported", "field \'$1\' not supported",
+    "importdoc for \'$1\' is not used", "RST style: $1",
+    "comment \'$1\' ignored", "",
+    "use {.base.} for base methods; baseless methods are deprecated",
+    "write to foreign heap", "unsafe code: \'$1\'",
+    "imported and not used: \'$1\'", "inherit from a more precise exception type like ValueError, IOError or OSError. If these don\'t suit, inherit from CatchableError or Defect.",
+    "each identifier is a tuple", "setLen can potentially expand the sequence, but the element type \'$1\' doesn\'t have a valid default value",
+    "The \'$1\' type doesn\'t have a valid default value", "Cannot prove that \'$1\' is initialized. This will become a compile time error in the future.",
+    "cannot prove that field \'$1\' is accessible",
+    "cannot prove index \'$1\' is valid",
+    "unreachable else, all cases are already covered",
+    "unreachable code after \'return\' statement or \'{.noReturn.}\' proc",
+    "$1", "not GC-safe: \'$1\'", "$1",
+    "use explicit initialization of \'$1\' for clarity",
+    "\'$1\' uses GC\'ed memory", "usage of a type with a destructor in a non destructible context. This will become a compile time error in the future.",
+    "$1", "Special variable \'result\' is shadowed.",
+    "Number of spaces around \'$#\' is not consistent",
+    "Potential object case transition, instantiate new object instead", "$1",
+    "observable stores to \'$1\'", "$1", "used \'result\' variable",
+    "cannot open: $1", "file changed: $1", "$1", "$1", "$1", "$1", "unsafe conversion to \'cstring\' from \'$1\'; Use a `cast` operation like `cast[cstring](x)`; this will become a compile time error in the future",
+    "$1", "$1", "$1", "template \'$1\' is implicitly redefined; this is deprecated, add an explicit .redefine pragma", "Using an unnamed break in a block is deprecated; Use a named block with a named break instead", "statement list expression assumed to be anonymous proc; this is deprecated, use `do (): ...` or `proc () = ...` instead",
+    "$1", "$1", "$1", "$1 needs the \'std\' prefix", "$1",
+    "global variable \'$1\' initialization requires a temporary variable",
+    "operation successful: $#",
+    "$build\n$loc lines; ${sec}s; $mem; proj: $project; out: $output", "CC: $1",
+    "\'$1\' is declared but not used", "$1", "$1",
+    "conversion to base object is not needed",
+    "conversion from $1 to itself is pointless",
+    "expression evaluates always to \'$1\'", "quit() called", "$1", "$1",
+    "generated code listing:", "end of listing", "used config file \'$1\'",
+    "added path: \'$1\'", "condition is always true: \'$1\'",
+    "condition is always false: \'$1\'", "$1", "$1", "$1", "$1", "$1", "$1",
+    "$1", "$1", "$1", "global variable declared here", "expanded macro: $1",
+    "$1", "$1", "$1", "$1", "$1", "unknown hint: $1"]
+
+ + + Source   +Edit   + +
+
+
+
NotesVerbosity = [{warnCannotOpenFile..warnProveInit,
+                   warnUnreachableElse..warnStaticIndexCheck,
+                   warnGcUnsafe2..warnCycleCreated, warnStrictNotNil,
+                   warnCannotOpen..warnSuspiciousEnumConv,
+                   warnHoleEnumConv..warnStmtListLambda,
+                   warnImplicitDefaultValue..warnIgnoredSymbolInjection,
+                   warnUser..warnGlobalVarConstructorTemporary,
+                   hintXDeclaredButNotUsed..hintQuitCalled,
+                   hintConditionAlwaysTrue..hintName,
+                   hintExpandMacro..hintUserRaw, hintUnknownHint}, {
+    warnCannotOpenFile..warnProveInit,
+    warnUnreachableElse..warnStaticIndexCheck, warnGcUnsafe2..warnCycleCreated,
+    warnStrictNotNil, warnCannotOpen..warnSuspiciousEnumConv,
+    warnHoleEnumConv..warnStmtListLambda,
+    warnImplicitDefaultValue..warnIgnoredSymbolInjection,
+    warnUser..hintProcessing, hintConf, hintConditionAlwaysTrue..hintLinking,
+    hintExpandMacro..hintUserRaw, hintUnknownHint}, {
+    warnCannotOpenFile..warnCycleCreated, warnStrictNotNil,
+    warnCannotOpen..warnSuspiciousEnumConv,
+    warnHoleEnumConv..warnStmtListLambda,
+    warnImplicitDefaultValue..warnIgnoredSymbolInjection,
+    warnUser..hintProcessing, hintCodeBegin..hintPerformance,
+    hintGCStats..hintUserRaw, hintMsgOrigin, hintUnknownHint},
+                  {20..62, warnStrictNotNil, 66..68, 70..78, 80..81, 83..119}]
+
+ + + Source   +Edit   + +
+
+
+
rstWarnings = {warnRstRedefinitionOfLabel..warnRstStyle}
+
+ + + Source   +Edit   + +
+
+
+
trackPosInvalidFileIdx = -2'i32
+
+ + + Source   +Edit   + +
+
+
+
unknownLineInfo = (line: 0'u, col: -1, fileIndex: -1)
+
+ + + Source   +Edit   + +
+
+
+
warnMax = warnGlobalVarConstructorTemporary
+
+ + + Source   +Edit   + +
+
+
+
warnMin = warnCannotOpenFile
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `==`(a, b: FileIndex): bool {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
proc hash(i: TLineInfo): Hash {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initMsgConfig(): MsgConfig {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc raiseRecoverableError(msg: string) {.noinline, noreturn,
+    ...raises: [ERecoverableError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/lineinfos.idx b/compiler/lineinfos.idx new file mode 100644 index 0000000000000..16fece59a581d --- /dev/null +++ b/compiler/lineinfos.idx @@ -0,0 +1,158 @@ +nimTitle lineinfos lineinfos.html module lineinfos 0 +nim explanationsBaseUrl lineinfos.html#explanationsBaseUrl const explanationsBaseUrl 17 +nim createDocLink lineinfos.html#createDocLink,string proc createDocLink(urlSuffix: string): string 21 +nim errUnknown lineinfos.html#errUnknown TMsgKind.errUnknown 30 +nim errFatal lineinfos.html#errFatal TMsgKind.errFatal 30 +nim errInternal lineinfos.html#errInternal TMsgKind.errInternal 30 +nim errIllFormedAstX lineinfos.html#errIllFormedAstX TMsgKind.errIllFormedAstX 30 +nim errCannotOpenFile lineinfos.html#errCannotOpenFile TMsgKind.errCannotOpenFile 30 +nim errXExpected lineinfos.html#errXExpected TMsgKind.errXExpected 30 +nim errRstMissingClosing lineinfos.html#errRstMissingClosing TMsgKind.errRstMissingClosing 30 +nim errRstGridTableNotImplemented lineinfos.html#errRstGridTableNotImplemented TMsgKind.errRstGridTableNotImplemented 30 +nim errRstMarkdownIllformedTable lineinfos.html#errRstMarkdownIllformedTable TMsgKind.errRstMarkdownIllformedTable 30 +nim errRstIllformedTable lineinfos.html#errRstIllformedTable TMsgKind.errRstIllformedTable 30 +nim errRstNewSectionExpected lineinfos.html#errRstNewSectionExpected TMsgKind.errRstNewSectionExpected 30 +nim errRstGeneralParseError lineinfos.html#errRstGeneralParseError TMsgKind.errRstGeneralParseError 30 +nim errRstInvalidDirectiveX lineinfos.html#errRstInvalidDirectiveX TMsgKind.errRstInvalidDirectiveX 30 +nim errRstInvalidField lineinfos.html#errRstInvalidField TMsgKind.errRstInvalidField 30 +nim errRstFootnoteMismatch lineinfos.html#errRstFootnoteMismatch TMsgKind.errRstFootnoteMismatch 30 +nim errRstSandboxedDirective lineinfos.html#errRstSandboxedDirective TMsgKind.errRstSandboxedDirective 30 +nim errProveInit lineinfos.html#errProveInit TMsgKind.errProveInit 30 +nim errGenerated lineinfos.html#errGenerated TMsgKind.errGenerated 30 +nim errFailedMove lineinfos.html#errFailedMove TMsgKind.errFailedMove 30 +nim errUser lineinfos.html#errUser TMsgKind.errUser 30 +nim warnCannotOpenFile lineinfos.html#warnCannotOpenFile TMsgKind.warnCannotOpenFile 30 +nim warnOctalEscape lineinfos.html#warnOctalEscape TMsgKind.warnOctalEscape 30 +nim warnXIsNeverRead lineinfos.html#warnXIsNeverRead TMsgKind.warnXIsNeverRead 30 +nim warnXmightNotBeenInit lineinfos.html#warnXmightNotBeenInit TMsgKind.warnXmightNotBeenInit 30 +nim warnDeprecated lineinfos.html#warnDeprecated TMsgKind.warnDeprecated 30 +nim warnConfigDeprecated lineinfos.html#warnConfigDeprecated TMsgKind.warnConfigDeprecated 30 +nim warnDotLikeOps lineinfos.html#warnDotLikeOps TMsgKind.warnDotLikeOps 30 +nim warnSmallLshouldNotBeUsed lineinfos.html#warnSmallLshouldNotBeUsed TMsgKind.warnSmallLshouldNotBeUsed 30 +nim warnUnknownMagic lineinfos.html#warnUnknownMagic TMsgKind.warnUnknownMagic 30 +nim warnRstRedefinitionOfLabel lineinfos.html#warnRstRedefinitionOfLabel TMsgKind.warnRstRedefinitionOfLabel 30 +nim warnRstUnknownSubstitutionX lineinfos.html#warnRstUnknownSubstitutionX TMsgKind.warnRstUnknownSubstitutionX 30 +nim warnRstAmbiguousLink lineinfos.html#warnRstAmbiguousLink TMsgKind.warnRstAmbiguousLink 30 +nim warnRstBrokenLink lineinfos.html#warnRstBrokenLink TMsgKind.warnRstBrokenLink 30 +nim warnRstLanguageXNotSupported lineinfos.html#warnRstLanguageXNotSupported TMsgKind.warnRstLanguageXNotSupported 30 +nim warnRstFieldXNotSupported lineinfos.html#warnRstFieldXNotSupported TMsgKind.warnRstFieldXNotSupported 30 +nim warnRstUnusedImportdoc lineinfos.html#warnRstUnusedImportdoc TMsgKind.warnRstUnusedImportdoc 30 +nim warnRstStyle lineinfos.html#warnRstStyle TMsgKind.warnRstStyle 30 +nim warnCommentXIgnored lineinfos.html#warnCommentXIgnored TMsgKind.warnCommentXIgnored 30 +nim warnTypelessParam lineinfos.html#warnTypelessParam TMsgKind.warnTypelessParam 30 +nim warnUseBase lineinfos.html#warnUseBase TMsgKind.warnUseBase 30 +nim warnWriteToForeignHeap lineinfos.html#warnWriteToForeignHeap TMsgKind.warnWriteToForeignHeap 30 +nim warnUnsafeCode lineinfos.html#warnUnsafeCode TMsgKind.warnUnsafeCode 30 +nim warnUnusedImportX lineinfos.html#warnUnusedImportX TMsgKind.warnUnusedImportX 30 +nim warnInheritFromException lineinfos.html#warnInheritFromException TMsgKind.warnInheritFromException 30 +nim warnEachIdentIsTuple lineinfos.html#warnEachIdentIsTuple TMsgKind.warnEachIdentIsTuple 30 +nim warnUnsafeSetLen lineinfos.html#warnUnsafeSetLen TMsgKind.warnUnsafeSetLen 30 +nim warnUnsafeDefault lineinfos.html#warnUnsafeDefault TMsgKind.warnUnsafeDefault 30 +nim warnProveInit lineinfos.html#warnProveInit TMsgKind.warnProveInit 30 +nim warnProveField lineinfos.html#warnProveField TMsgKind.warnProveField 30 +nim warnProveIndex lineinfos.html#warnProveIndex TMsgKind.warnProveIndex 30 +nim warnUnreachableElse lineinfos.html#warnUnreachableElse TMsgKind.warnUnreachableElse 30 +nim warnUnreachableCode lineinfos.html#warnUnreachableCode TMsgKind.warnUnreachableCode 30 +nim warnStaticIndexCheck lineinfos.html#warnStaticIndexCheck TMsgKind.warnStaticIndexCheck 30 +nim warnGcUnsafe lineinfos.html#warnGcUnsafe TMsgKind.warnGcUnsafe 30 +nim warnGcUnsafe2 lineinfos.html#warnGcUnsafe2 TMsgKind.warnGcUnsafe2 30 +nim warnUninit lineinfos.html#warnUninit TMsgKind.warnUninit 30 +nim warnGcMem lineinfos.html#warnGcMem TMsgKind.warnGcMem 30 +nim warnDestructor lineinfos.html#warnDestructor TMsgKind.warnDestructor 30 +nim warnLockLevel lineinfos.html#warnLockLevel TMsgKind.warnLockLevel 30 +nim warnResultShadowed lineinfos.html#warnResultShadowed TMsgKind.warnResultShadowed 30 +nim warnInconsistentSpacing lineinfos.html#warnInconsistentSpacing TMsgKind.warnInconsistentSpacing 30 +nim warnCaseTransition lineinfos.html#warnCaseTransition TMsgKind.warnCaseTransition 30 +nim warnCycleCreated lineinfos.html#warnCycleCreated TMsgKind.warnCycleCreated 30 +nim warnObservableStores lineinfos.html#warnObservableStores TMsgKind.warnObservableStores 30 +nim warnStrictNotNil lineinfos.html#warnStrictNotNil TMsgKind.warnStrictNotNil 30 +nim warnResultUsed lineinfos.html#warnResultUsed TMsgKind.warnResultUsed 30 +nim warnCannotOpen lineinfos.html#warnCannotOpen TMsgKind.warnCannotOpen 30 +nim warnFileChanged lineinfos.html#warnFileChanged TMsgKind.warnFileChanged 30 +nim warnSuspiciousEnumConv lineinfos.html#warnSuspiciousEnumConv TMsgKind.warnSuspiciousEnumConv 30 +nim warnAnyEnumConv lineinfos.html#warnAnyEnumConv TMsgKind.warnAnyEnumConv 30 +nim warnHoleEnumConv lineinfos.html#warnHoleEnumConv TMsgKind.warnHoleEnumConv 30 +nim warnCstringConv lineinfos.html#warnCstringConv TMsgKind.warnCstringConv 30 +nim warnPtrToCstringConv lineinfos.html#warnPtrToCstringConv TMsgKind.warnPtrToCstringConv 30 +nim warnEffect lineinfos.html#warnEffect TMsgKind.warnEffect 30 +nim warnCastSizes lineinfos.html#warnCastSizes TMsgKind.warnCastSizes 30 +nim warnAboveMaxSizeSet lineinfos.html#warnAboveMaxSizeSet TMsgKind.warnAboveMaxSizeSet 30 +nim warnImplicitTemplateRedefinition lineinfos.html#warnImplicitTemplateRedefinition TMsgKind.warnImplicitTemplateRedefinition 30 +nim warnUnnamedBreak lineinfos.html#warnUnnamedBreak TMsgKind.warnUnnamedBreak 30 +nim warnStmtListLambda lineinfos.html#warnStmtListLambda TMsgKind.warnStmtListLambda 30 +nim warnBareExcept lineinfos.html#warnBareExcept TMsgKind.warnBareExcept 30 +nim warnImplicitDefaultValue lineinfos.html#warnImplicitDefaultValue TMsgKind.warnImplicitDefaultValue 30 +nim warnIgnoredSymbolInjection lineinfos.html#warnIgnoredSymbolInjection TMsgKind.warnIgnoredSymbolInjection 30 +nim warnStdPrefix lineinfos.html#warnStdPrefix TMsgKind.warnStdPrefix 30 +nim warnUser lineinfos.html#warnUser TMsgKind.warnUser 30 +nim warnGlobalVarConstructorTemporary lineinfos.html#warnGlobalVarConstructorTemporary TMsgKind.warnGlobalVarConstructorTemporary 30 +nim hintSuccess lineinfos.html#hintSuccess TMsgKind.hintSuccess 30 +nim hintSuccessX lineinfos.html#hintSuccessX TMsgKind.hintSuccessX 30 +nim hintCC lineinfos.html#hintCC TMsgKind.hintCC 30 +nim hintXDeclaredButNotUsed lineinfos.html#hintXDeclaredButNotUsed TMsgKind.hintXDeclaredButNotUsed 30 +nim hintDuplicateModuleImport lineinfos.html#hintDuplicateModuleImport TMsgKind.hintDuplicateModuleImport 30 +nim hintXCannotRaiseY lineinfos.html#hintXCannotRaiseY TMsgKind.hintXCannotRaiseY 30 +nim hintConvToBaseNotNeeded lineinfos.html#hintConvToBaseNotNeeded TMsgKind.hintConvToBaseNotNeeded 30 +nim hintConvFromXtoItselfNotNeeded lineinfos.html#hintConvFromXtoItselfNotNeeded TMsgKind.hintConvFromXtoItselfNotNeeded 30 +nim hintExprAlwaysX lineinfos.html#hintExprAlwaysX TMsgKind.hintExprAlwaysX 30 +nim hintQuitCalled lineinfos.html#hintQuitCalled TMsgKind.hintQuitCalled 30 +nim hintProcessing lineinfos.html#hintProcessing TMsgKind.hintProcessing 30 +nim hintProcessingStmt lineinfos.html#hintProcessingStmt TMsgKind.hintProcessingStmt 30 +nim hintCodeBegin lineinfos.html#hintCodeBegin TMsgKind.hintCodeBegin 30 +nim hintCodeEnd lineinfos.html#hintCodeEnd TMsgKind.hintCodeEnd 30 +nim hintConf lineinfos.html#hintConf TMsgKind.hintConf 30 +nim hintPath lineinfos.html#hintPath TMsgKind.hintPath 30 +nim hintConditionAlwaysTrue lineinfos.html#hintConditionAlwaysTrue TMsgKind.hintConditionAlwaysTrue 30 +nim hintConditionAlwaysFalse lineinfos.html#hintConditionAlwaysFalse TMsgKind.hintConditionAlwaysFalse 30 +nim hintName lineinfos.html#hintName TMsgKind.hintName 30 +nim hintPattern lineinfos.html#hintPattern TMsgKind.hintPattern 30 +nim hintExecuting lineinfos.html#hintExecuting TMsgKind.hintExecuting 30 +nim hintLinking lineinfos.html#hintLinking TMsgKind.hintLinking 30 +nim hintDependency lineinfos.html#hintDependency TMsgKind.hintDependency 30 +nim hintSource lineinfos.html#hintSource TMsgKind.hintSource 30 +nim hintPerformance lineinfos.html#hintPerformance TMsgKind.hintPerformance 30 +nim hintStackTrace lineinfos.html#hintStackTrace TMsgKind.hintStackTrace 30 +nim hintGCStats lineinfos.html#hintGCStats TMsgKind.hintGCStats 30 +nim hintGlobalVar lineinfos.html#hintGlobalVar TMsgKind.hintGlobalVar 30 +nim hintExpandMacro lineinfos.html#hintExpandMacro TMsgKind.hintExpandMacro 30 +nim hintUser lineinfos.html#hintUser TMsgKind.hintUser 30 +nim hintUserRaw lineinfos.html#hintUserRaw TMsgKind.hintUserRaw 30 +nim hintExtendedContext lineinfos.html#hintExtendedContext TMsgKind.hintExtendedContext 30 +nim hintMsgOrigin lineinfos.html#hintMsgOrigin TMsgKind.hintMsgOrigin 30 +nim hintDeclaredLoc lineinfos.html#hintDeclaredLoc TMsgKind.hintDeclaredLoc 30 +nim hintUnknownHint lineinfos.html#hintUnknownHint TMsgKind.hintUnknownHint 30 +nim TMsgKind lineinfos.html#TMsgKind enum TMsgKind 30 +nim MsgKindToStr lineinfos.html#MsgKindToStr const MsgKindToStr 117 +nim fatalMsgs lineinfos.html#fatalMsgs const fatalMsgs 244 +nim errMin lineinfos.html#errMin const errMin 245 +nim errMax lineinfos.html#errMax const errMax 246 +nim warnMin lineinfos.html#warnMin const warnMin 247 +nim warnMax lineinfos.html#warnMax const warnMax 248 +nim hintMin lineinfos.html#hintMin const hintMin 249 +nim hintMax lineinfos.html#hintMax const hintMax 250 +nim rstWarnings lineinfos.html#rstWarnings const rstWarnings 251 +nim TNoteKind lineinfos.html#TNoteKind type TNoteKind 254 +nim TNoteKinds lineinfos.html#TNoteKinds type TNoteKinds 255 +nim NotesVerbosity lineinfos.html#NotesVerbosity const NotesVerbosity 268 +nim errXMustBeCompileTime lineinfos.html#errXMustBeCompileTime const errXMustBeCompileTime 269 +nim errArgsNeedRunOption lineinfos.html#errArgsNeedRunOption const errArgsNeedRunOption 270 +nim errFloatToString lineinfos.html#errFloatToString const errFloatToString 271 +nim TFileInfo lineinfos.html#TFileInfo object TFileInfo 274 +nim FileIndex lineinfos.html#FileIndex type FileIndex 294 +nim TLineInfo lineinfos.html#TLineInfo object TLineInfo 295 +nim eStdOut lineinfos.html#eStdOut TErrorOutput.eStdOut 308 +nim eStdErr lineinfos.html#eStdErr TErrorOutput.eStdErr 308 +nim TErrorOutput lineinfos.html#TErrorOutput enum TErrorOutput 308 +nim TErrorOutputs lineinfos.html#TErrorOutputs type TErrorOutputs 312 +nim ERecoverableError lineinfos.html#ERecoverableError object ERecoverableError 314 +nim ESuggestDone lineinfos.html#ESuggestDone object ESuggestDone 315 +nim `==` lineinfos.html#==,FileIndex,FileIndex proc `==`(a, b: FileIndex): bool 317 +nim hash lineinfos.html#hash,TLineInfo proc hash(i: TLineInfo): Hash 319 +nim raiseRecoverableError lineinfos.html#raiseRecoverableError,string proc raiseRecoverableError(msg: string) 322 +nim InvalidFileIdx lineinfos.html#InvalidFileIdx const InvalidFileIdx 326 +nim unknownLineInfo lineinfos.html#unknownLineInfo const unknownLineInfo 327 +nim Severity lineinfos.html#Severity enum Severity 330 +nim trackPosInvalidFileIdx lineinfos.html#trackPosInvalidFileIdx const trackPosInvalidFileIdx 334 +nim commandLineIdx lineinfos.html#commandLineIdx const commandLineIdx 336 +nim MsgConfig lineinfos.html#MsgConfig object MsgConfig 339 +nim initMsgConfig lineinfos.html#initMsgConfig proc initMsgConfig(): MsgConfig 352 diff --git a/compiler/linter.html b/compiler/linter.html new file mode 100644 index 0000000000000..0f771e1e7cd43 --- /dev/null +++ b/compiler/linter.html @@ -0,0 +1,252 @@ + + + + + + + +linter + + + + + + + + + + + + + + + + +
+
+

linter

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module implements the style checker.

+ +
+

Consts

+
+
+
Letters = {'a'..'z', 'A'..'Z', '0'..'9', '\x80'..'\xFF', '_'}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc differ(line: string; a, b: int; x: string): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc identLen(line: string; start: int): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template checkPragmaUse(ctx: PContext; info: TLineInfo; w: TSpecialWord;
+                        pragmaName: string; sym: PSym)
+
+ + Check builtin pragma uses match their definition's style. Note: This only applies to builtin pragmas, not user pragmas. + Source   +Edit   + +
+
+ +
+
+
+
template styleCheckDef(ctx: PContext; info: TLineInfo; s: PSym)
+
+ + Check symbol definitions adhere to NEP1 style rules. + Source   +Edit   + +
+
+
+
template styleCheckDef(ctx: PContext; info: TLineInfo; sym: PSym; k: TSymKind)
+
+ + Check symbol definitions adhere to NEP1 style rules. + Source   +Edit   + +
+
+
+
template styleCheckDef(ctx: PContext; s: PSym)
+
+ + Check symbol definitions adhere to NEP1 style rules. + Source   +Edit   + +
+
+ +
+
+
+
template styleCheckUse(ctx: PContext; info: TLineInfo; sym: PSym)
+
+ + Check symbol uses match their definition's style. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/linter.idx b/compiler/linter.idx new file mode 100644 index 0000000000000..1b403b25644e0 --- /dev/null +++ b/compiler/linter.idx @@ -0,0 +1,10 @@ +nimTitle linter linter.html module linter 0 +nim Letters linter.html#Letters const Letters 19 +nim identLen linter.html#identLen,string,int proc identLen(line: string; start: int): int 21 +nim differ linter.html#differ,string,int,int,string proc differ(line: string; a, b: int; x: string): string 78 +nim styleCheckDef linter.html#styleCheckDef.t,PContext,TLineInfo,PSym,TSymKind template styleCheckDef(ctx: PContext; info: TLineInfo; sym: PSym; k: TSymKind) 95 +nim styleCheckDef linter.html#styleCheckDef.t,PContext,TLineInfo,PSym template styleCheckDef(ctx: PContext; info: TLineInfo; s: PSym) 111 +nim styleCheckDef linter.html#styleCheckDef.t,PContext,PSym template styleCheckDef(ctx: PContext; s: PSym) 115 +nim styleCheckUse linter.html#styleCheckUse.t,PContext,TLineInfo,PSym template styleCheckUse(ctx: PContext; info: TLineInfo; sym: PSym) 137 +nim checkPragmaUse linter.html#checkPragmaUse.t,PContext,TLineInfo,TSpecialWord,string,PSym template checkPragmaUse(ctx: PContext; info: TLineInfo; w: TSpecialWord;\n pragmaName: string; sym: PSym) 152 +nimgrp stylecheckdef linter.html#styleCheckDef-templates-all template 95 diff --git a/compiler/llstream.html b/compiler/llstream.html new file mode 100644 index 0000000000000..691f47b1e51d4 --- /dev/null +++ b/compiler/llstream.html @@ -0,0 +1,422 @@ + + + + + + + +llstream + + + + + + + + + + + + + + + + +
+
+

llstream

+
+ +
+ Source   +Edit   + +
+ +

Low-level streams for high performance.

+
+

Imports

+
+ pathutils +
+
+
+

Types

+
+
+
OnPrompt = proc () {.closure.}
+
+ + + Source   +Edit   + +
+
+
+
PLLStream = ref TLLStream
+
+ + + Source   +Edit   + +
+
+
+
TLLRepl = proc (s: PLLStream; buf: pointer; bufLen: int): int
+
+ + + Source   +Edit   + +
+
+
+
TLLStream = object of RootObj
+  kind*: TLLStreamKind
+  f*: File
+  s*: string
+  rd*, wr*: int
+  lineOffset*: int
+  repl*: TLLRepl
+  onPrompt*: OnPrompt
+
+ + + Source   +Edit   + +
+
+
+
TLLStreamKind = enum
+  llsNone, llsString, llsFile, llsStdIn
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc endsWith(x: string; s: set[char]): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc endsWithOpr(x: string): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc llStreamClose(s: PLLStream) {....raises: [IOError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc llStreamOpen(): PLLStream {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc llStreamOpen(data: sink string): PLLStream {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc llStreamOpen(f: File): PLLStream {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc llStreamOpen(filename: AbsoluteFile; mode: FileMode): PLLStream {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc llStreamOpenStdIn(r: TLLRepl = llReadFromStdin; onPrompt: OnPrompt = nil): PLLStream {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc llStreamRead(s: PLLStream; buf: pointer; bufLen: int): int {.
+    ...raises: [IOError, Exception], tags: [ReadIOEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc llStreamReadAll(s: PLLStream): string {....raises: [IOError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc llStreamReadLine(s: PLLStream; line: var string): bool {....raises: [IOError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc llStreamWrite(s: PLLStream; buf: pointer; buflen: int) {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc llStreamWrite(s: PLLStream; data: char) {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc llStreamWrite(s: PLLStream; data: string) {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc llStreamWriteln(s: PLLStream; data: string) {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/llstream.idx b/compiler/llstream.idx new file mode 100644 index 0000000000000..f9c76a44012e4 --- /dev/null +++ b/compiler/llstream.idx @@ -0,0 +1,27 @@ +nimTitle llstream llstream.html module llstream 0 +nim TLLRepl llstream.html#TLLRepl type TLLRepl 25 +nim OnPrompt llstream.html#OnPrompt type OnPrompt 26 +nim llsNone llstream.html#llsNone TLLStreamKind.llsNone 27 +nim llsString llstream.html#llsString TLLStreamKind.llsString 27 +nim llsFile llstream.html#llsFile TLLStreamKind.llsFile 27 +nim llsStdIn llstream.html#llsStdIn TLLStreamKind.llsStdIn 27 +nim TLLStreamKind llstream.html#TLLStreamKind enum TLLStreamKind 27 +nim TLLStream llstream.html#TLLStream object TLLStream 32 +nim PLLStream llstream.html#PLLStream type PLLStream 41 +nim llStreamOpen llstream.html#llStreamOpen,sinkstring proc llStreamOpen(data: sink string): PLLStream 43 +nim llStreamOpen llstream.html#llStreamOpen,File proc llStreamOpen(f: File): PLLStream 46 +nim llStreamOpen llstream.html#llStreamOpen,AbsoluteFile,FileMode proc llStreamOpen(filename: AbsoluteFile; mode: FileMode): PLLStream 49 +nim llStreamOpen llstream.html#llStreamOpen proc llStreamOpen(): PLLStream 53 +nim llStreamOpenStdIn llstream.html#llStreamOpenStdIn,TLLRepl,OnPrompt proc llStreamOpenStdIn(r: TLLRepl = llReadFromStdin; onPrompt: OnPrompt = nil): PLLStream 57 +nim llStreamClose llstream.html#llStreamClose,PLLStream proc llStreamClose(s: PLLStream) 60 +nim endsWith llstream.html#endsWith,string,set[char] proc endsWith(x: string; s: set[char]): bool 77 +nim endsWithOpr llstream.html#endsWithOpr,string proc endsWithOpr(x: string): bool 90 +nim llStreamRead llstream.html#llStreamRead,PLLStream,pointer,int proc llStreamRead(s: PLLStream; buf: pointer; bufLen: int): int 123 +nim llStreamReadLine llstream.html#llStreamReadLine,PLLStream,string proc llStreamReadLine(s: PLLStream; line: var string): bool 138 +nim llStreamWrite llstream.html#llStreamWrite,PLLStream,string proc llStreamWrite(s: PLLStream; data: string) 162 +nim llStreamWriteln llstream.html#llStreamWriteln,PLLStream,string proc llStreamWriteln(s: PLLStream; data: string) 172 +nim llStreamWrite llstream.html#llStreamWrite,PLLStream,char proc llStreamWrite(s: PLLStream; data: char) 176 +nim llStreamWrite llstream.html#llStreamWrite,PLLStream,pointer,int proc llStreamWrite(s: PLLStream; buf: pointer; buflen: int) 188 +nim llStreamReadAll llstream.html#llStreamReadAll,PLLStream proc llStreamReadAll(s: PLLStream): string 200 +nimgrp llstreamwrite llstream.html#llStreamWrite-procs-all proc 162 +nimgrp llstreamopen llstream.html#llStreamOpen-procs-all proc 43 diff --git a/compiler/lookups.html b/compiler/lookups.html new file mode 100644 index 0000000000000..5b150ad5b791c --- /dev/null +++ b/compiler/lookups.html @@ -0,0 +1,1117 @@ + + + + + + + +lookups + + + + + + + + + + + + + + + + +
+
+

lookups

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
TLookupFlag = enum
+  checkAmbiguity, checkUndeclared, checkModule, checkPureEnumFields
+
+ + + Source   +Edit   + +
+
+
+
TOverloadIter = object
+  it*: TIdentIter
+  mit*: ModuleIter
+  m*: PSym
+  mode*: TOverloadIterMode
+  symChoiceIndex*: int
+
+ + + Source   +Edit   + +
+
+
+
TOverloadIterMode = enum
+  oimDone, oimNoQualifier, oimSelfModule, oimOtherModule, oimSymChoice,
+  oimSymChoiceLocalLookup
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc addDecl(c: PContext; sym: PSym) {.inline, ...raises: [KeyError, Exception,
+    ValueError, IOError, ERecoverableError], tags: [RootEffect, ReadDirEffect,
+    WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc addDecl(c: PContext; sym: PSym; info: TLineInfo) {.inline,
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addDeclAt(c: PContext; scope: PScope; sym: PSym) {.inline,
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc addDeclAt(c: PContext; scope: PScope; sym: PSym; info: TLineInfo) {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addInterfaceDecl(c: PContext; sym: PSym) {.inline,
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + adds a decl and the interface if appropriate + Source   +Edit   + +
+
+ +
+
+
+
proc addInterfaceDeclAt(c: PContext; scope: PScope; sym: PSym) {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + adds a symbol on the scope and the interface if appropriate + Source   +Edit   + +
+
+ +
+
+
+
proc addInterfaceOverloadableSymAt(c: PContext; scope: PScope; sym: PSym) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + adds an overloadable symbol on the scope and the interface if appropriate + Source   +Edit   + +
+
+ +
+
+
+
proc addOverloadableSymAt(c: PContext; scope: PScope; fn: PSym) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + adds an symbol to the given scope, will check for and raise errors if it's a redefinition as opposed to an overload. + Source   +Edit   + +
+
+ +
+
+
+
proc addPrelimDecl(c: PContext; sym: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addUniqueSym(scope: PScope; s: PSym): PSym {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ambiguousIdentifierMsg(candidates: seq[PSym]; prefix = "use one of";
+                            indent = 0): string {.
+    ...raises: [ValueError, Exception, KeyError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc ambiguousIdentifierMsg(choices: PNode; indent = 0): string {.
+    ...raises: [ValueError, Exception, KeyError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc closeScope(c: PContext) {....raises: [Exception], tags: [RootEffect],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc closeShadowScope(c: PContext) {....raises: [], tags: [], forbids: [].}
+
+ + closes the shadow scope, but doesn't merge any of the symbols Does not check for unused symbols or missing forward decls since a macro or template consumes this AST + Source   +Edit   + +
+
+ +
+
+
+
proc cmpScopes(ctx: PContext; s: PSym): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc considerQuotedIdent(c: PContext; n: PNode; origin: PNode = nil): PIdent {.
+    ...raises: [Exception, KeyError, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + Retrieve a PIdent from a PNode, taking into account accent nodes. origin can be nil. If it is not nil, it is used for a better error message. + Source   +Edit   + +
+
+ +
+
+
+
proc debugScopes(c: PContext; limit = 0; max = int.high) {....deprecated,
+    raises: [], tags: [], forbids: [].}
+
+
+ Deprecated +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc errorSym(c: PContext; ident: PIdent; info: TLineInfo): PSym {....raises: [],
+    tags: [], forbids: [].}
+
+ + creates an error symbol to avoid cascading errors (for IDE support) + Source   +Edit   + +
+
+
+
proc errorSym(c: PContext; n: PNode): PSym {.
+    ...raises: [Exception, KeyError, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc errorUndeclaredIdentifier(c: PContext; info: TLineInfo; name: string;
+                               extra = "") {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc errorUndeclaredIdentifierHint(c: PContext; ident: PIdent; info: TLineInfo): PSym {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc errorUseQualifier(c: PContext; info: TLineInfo; candidates: seq[PSym]) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc errorUseQualifier(c: PContext; info: TLineInfo; choices: PNode) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc errorUseQualifier(c: PContext; info: TLineInfo; s: PSym) {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getSymRepr(conf: ConfigRef; s: PSym; getDeclarationPath = true): string {.
+    ...raises: [Exception, KeyError, ValueError],
+    tags: [RootEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initOverloadIter(o: var TOverloadIter; c: PContext; n: PNode): PSym {.
+    ...raises: [Exception, KeyError, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isAmbiguous(c: PContext; s: PIdent; filter: TSymKinds; sym: var PSym): bool {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isShadowScope(s: PScope): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lastOverloadScope(o: TOverloadIter): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc localSearchInScope(c: PContext; s: PIdent): PSym {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lookUp(c: PContext; n: PNode): PSym {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lookUpCandidates(c: PContext; ident: PIdent; filter: set[TSymKind];
+                      includePureEnum = false): seq[PSym] {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mergeShadowScope(c: PContext) {....raises: [Exception, ValueError, KeyError,
+    IOError, ERecoverableError], tags: [RootEffect, ReadDirEffect,
+                                        WriteIOEffect, ReadIOEffect,
+                                        ReadEnvEffect], forbids: [].}
+
+ +

close the existing scope and merge in all defined symbols, this will also trigger any export related code if this is into a non-shadow scope.

+

Merges: shadow -> shadow: add symbols to the parent but check for redefinitions etc shadow -> non-shadow: the above, but also handle exports and all that

+ + Source   +Edit   + +
+
+ +
+
+
+
proc nextOverloadIter(o: var TOverloadIter; c: PContext; n: PNode): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc openScope(c: PContext): PScope {.discardable, ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc openShadowScope(c: PContext) {....raises: [], tags: [], forbids: [].}
+
+ + opens a shadow scope, just like any other scope except the depth is the same as the parent -- see isShadowScope. + Source   +Edit   + +
+
+ +
+
+
+
proc pickSym(c: PContext; n: PNode; kinds: set[TSymKind]; flags: TSymFlags = {}): PSym {.
+    ...raises: [Exception, KeyError, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc qualifiedLookUp(c: PContext; n: PNode; flags: set[TLookupFlag]): PSym {.
+    ...raises: [Exception, KeyError, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rawCloseScope(c: PContext) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc searchInScopes(c: PContext; s: PIdent; ambiguous: var bool): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc searchInScopesAllCandidatesFilterBy(c: PContext; s: PIdent;
+    filter: TSymKinds): seq[PSym] {....raises: [KeyError, Exception],
+                                    tags: [ReadDirEffect, RootEffect],
+                                    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc searchInScopesFilterBy(c: PContext; s: PIdent; filter: TSymKinds): seq[PSym] {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc someSymFromImportTable(c: PContext; name: PIdent; ambiguous: var bool): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc wrongRedefinition(c: PContext; info: TLineInfo; s: string;
+                       conflictsWith: TLineInfo; note = errGenerated) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + Emit a redefinition error if in non-interactive mode + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator allScopes(scope: PScope): PScope {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator allSyms(c: PContext): (PSym, int, bool) {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator importedItems(c: PContext; name: PIdent): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator localScopesFrom(c: PContext; scope: PScope): PScope {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator uniqueSyms(c: PContext): (PSym, int, bool) {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + Like allSyms except only returns unique symbols (Uniqueness determined by line + name) + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template addSym(scope: PScope; s: PSym)
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/lookups.idx b/compiler/lookups.idx new file mode 100644 index 0000000000000..0b0ae1d9a2378 --- /dev/null +++ b/compiler/lookups.idx @@ -0,0 +1,69 @@ +nimTitle lookups lookups.html module lookups 0 +nim considerQuotedIdent lookups.html#considerQuotedIdent,PContext,PNode,PNode proc considerQuotedIdent(c: PContext; n: PNode; origin: PNode = nil): PIdent 31 +nim addSym lookups.html#addSym.t,PScope,PSym template addSym(scope: PScope; s: PSym) 71 +nim addUniqueSym lookups.html#addUniqueSym,PScope,PSym proc addUniqueSym(scope: PScope; s: PSym): PSym 74 +nim openScope lookups.html#openScope,PContext proc openScope(c: PContext): PScope 77 +nim rawCloseScope lookups.html#rawCloseScope,PContext proc rawCloseScope(c: PContext) 83 +nim closeScope lookups.html#closeScope,PContext proc closeScope(c: PContext) 86 +nim allScopes lookups.html#allScopes.i,PScope iterator allScopes(scope: PScope): PScope 90 +nim localScopesFrom lookups.html#localScopesFrom.i,PContext,PScope iterator localScopesFrom(c: PContext; scope: PScope): PScope 96 +nim isShadowScope lookups.html#isShadowScope,PScope proc isShadowScope(s: PScope): bool 101 +nim localSearchInScope lookups.html#localSearchInScope,PContext,PIdent proc localSearchInScope(c: PContext; s: PIdent): PSym 104 +nim importedItems lookups.html#importedItems.i,PContext,PIdent iterator importedItems(c: PContext; name: PIdent): PSym 148 +nim allSyms lookups.html#allSyms.i,PContext iterator allSyms(c: PContext): (PSym, int, bool) 162 +nim uniqueSyms lookups.html#uniqueSyms.i,PContext iterator uniqueSyms(c: PContext): (PSym, int, bool) 181 +nim someSymFromImportTable lookups.html#someSymFromImportTable,PContext,PIdent,bool proc someSymFromImportTable(c: PContext; name: PIdent; ambiguous: var bool): PSym 192 +nim searchInScopes lookups.html#searchInScopes,PContext,PIdent,bool proc searchInScopes(c: PContext; s: PIdent; ambiguous: var bool): PSym 205 +nim debugScopes lookups.html#debugScopes,PContext,int proc debugScopes(c: PContext; limit = 0; max = int.high) 211 +nim searchInScopesAllCandidatesFilterBy lookups.html#searchInScopesAllCandidatesFilterBy,PContext,PIdent,TSymKinds proc searchInScopesAllCandidatesFilterBy(c: PContext; s: PIdent; filter: TSymKinds): seq[\n PSym] 224 +nim searchInScopesFilterBy lookups.html#searchInScopesFilterBy,PContext,PIdent,TSymKinds proc searchInScopesFilterBy(c: PContext; s: PIdent; filter: TSymKinds): seq[PSym] 241 +nim cmpScopes lookups.html#cmpScopes,PContext,PSym proc cmpScopes(ctx: PContext; s: PSym): int 261 +nim isAmbiguous lookups.html#isAmbiguous,PContext,PIdent,TSymKinds,PSym proc isAmbiguous(c: PContext; s: PIdent; filter: TSymKinds; sym: var PSym): bool 273 +nim errorSym lookups.html#errorSym,PContext,PIdent,TLineInfo proc errorSym(c: PContext; ident: PIdent; info: TLineInfo): PSym 308 +nim errorSym lookups.html#errorSym,PContext,PNode proc errorSym(c: PContext; n: PNode): PSym 317 +nim oimDone lookups.html#oimDone TOverloadIterMode.oimDone 328 +nim oimNoQualifier lookups.html#oimNoQualifier TOverloadIterMode.oimNoQualifier 328 +nim oimSelfModule lookups.html#oimSelfModule TOverloadIterMode.oimSelfModule 328 +nim oimOtherModule lookups.html#oimOtherModule TOverloadIterMode.oimOtherModule 328 +nim oimSymChoice lookups.html#oimSymChoice TOverloadIterMode.oimSymChoice 328 +nim oimSymChoiceLocalLookup lookups.html#oimSymChoiceLocalLookup TOverloadIterMode.oimSymChoiceLocalLookup 328 +nim TOverloadIterMode lookups.html#TOverloadIterMode enum TOverloadIterMode 328 +nim TOverloadIter lookups.html#TOverloadIter object TOverloadIter 331 +nim getSymRepr lookups.html#getSymRepr,ConfigRef,PSym proc getSymRepr(conf: ConfigRef; s: PSym; getDeclarationPath = true): string 341 +nim wrongRedefinition lookups.html#wrongRedefinition,PContext,TLineInfo,string,TLineInfo proc wrongRedefinition(c: PContext; info: TLineInfo; s: string;\n conflictsWith: TLineInfo; note = errGenerated) 375 +nim addDeclAt lookups.html#addDeclAt,PContext,PScope,PSym,TLineInfo proc addDeclAt(c: PContext; scope: PScope; sym: PSym; info: TLineInfo) 385 +nim addDeclAt lookups.html#addDeclAt,PContext,PScope,PSym proc addDeclAt(c: PContext; scope: PScope; sym: PSym) 401 +nim addDecl lookups.html#addDecl,PContext,PSym,TLineInfo proc addDecl(c: PContext; sym: PSym; info: TLineInfo) 404 +nim addDecl lookups.html#addDecl,PContext,PSym proc addDecl(c: PContext; sym: PSym) 407 +nim addPrelimDecl lookups.html#addPrelimDecl,PContext,PSym proc addPrelimDecl(c: PContext; sym: PSym) 410 +nim addInterfaceDeclAt lookups.html#addInterfaceDeclAt,PContext,PScope,PSym proc addInterfaceDeclAt(c: PContext; scope: PScope; sym: PSym) 426 +nim addInterfaceDecl lookups.html#addInterfaceDecl,PContext,PSym proc addInterfaceDecl(c: PContext; sym: PSym) 433 +nim addOverloadableSymAt lookups.html#addOverloadableSymAt,PContext,PScope,PSym proc addOverloadableSymAt(c: PContext; scope: PScope; fn: PSym) 437 +nim addInterfaceOverloadableSymAt lookups.html#addInterfaceOverloadableSymAt,PContext,PScope,PSym proc addInterfaceOverloadableSymAt(c: PContext; scope: PScope; sym: PSym) 450 +nim openShadowScope lookups.html#openShadowScope,PContext proc openShadowScope(c: PContext) 457 +nim closeShadowScope lookups.html#closeShadowScope,PContext proc closeShadowScope(c: PContext) 464 +nim mergeShadowScope lookups.html#mergeShadowScope,PContext proc mergeShadowScope(c: PContext) 470 +nim errorUseQualifier lookups.html#errorUseQualifier,PContext,TLineInfo,PSym proc errorUseQualifier(c: PContext; info: TLineInfo; s: PSym) 562 +nim ambiguousIdentifierMsg lookups.html#ambiguousIdentifierMsg,seq[PSym],string,int proc ambiguousIdentifierMsg(candidates: seq[PSym]; prefix = "use one of"; indent = 0): string 566 +nim errorUseQualifier lookups.html#errorUseQualifier,PContext,TLineInfo,seq[PSym] proc errorUseQualifier(c: PContext; info: TLineInfo; candidates: seq[PSym]) 581 +nim ambiguousIdentifierMsg lookups.html#ambiguousIdentifierMsg,PNode,int proc ambiguousIdentifierMsg(choices: PNode; indent = 0): string 584 +nim errorUseQualifier lookups.html#errorUseQualifier,PContext,TLineInfo,PNode proc errorUseQualifier(c: PContext; info: TLineInfo; choices: PNode) 591 +nim errorUndeclaredIdentifier lookups.html#errorUndeclaredIdentifier,PContext,TLineInfo,string,string proc errorUndeclaredIdentifier(c: PContext; info: TLineInfo; name: string; extra = "") 594 +nim errorUndeclaredIdentifierHint lookups.html#errorUndeclaredIdentifierHint,PContext,PIdent,TLineInfo proc errorUndeclaredIdentifierHint(c: PContext; ident: PIdent; info: TLineInfo): PSym 611 +nim lookUp lookups.html#lookUp,PContext,PNode proc lookUp(c: PContext; n: PNode): PSym 617 +nim checkAmbiguity lookups.html#checkAmbiguity TLookupFlag.checkAmbiguity 640 +nim checkUndeclared lookups.html#checkUndeclared TLookupFlag.checkUndeclared 640 +nim checkModule lookups.html#checkModule TLookupFlag.checkModule 640 +nim checkPureEnumFields lookups.html#checkPureEnumFields TLookupFlag.checkPureEnumFields 640 +nim TLookupFlag lookups.html#TLookupFlag enum TLookupFlag 640 +nim lookUpCandidates lookups.html#lookUpCandidates,PContext,PIdent,set[TSymKind] proc lookUpCandidates(c: PContext; ident: PIdent; filter: set[TSymKind];\n includePureEnum = false): seq[PSym] 645 +nim qualifiedLookUp lookups.html#qualifiedLookUp,PContext,PNode,set[TLookupFlag] proc qualifiedLookUp(c: PContext; n: PNode; flags: set[TLookupFlag]): PSym 651 +nim initOverloadIter lookups.html#initOverloadIter,TOverloadIter,PContext,PNode proc initOverloadIter(o: var TOverloadIter; c: PContext; n: PNode): PSym 725 +nim lastOverloadScope lookups.html#lastOverloadScope,TOverloadIter proc lastOverloadScope(o: TOverloadIter): int 792 +nim nextOverloadIter lookups.html#nextOverloadIter,TOverloadIter,PContext,PNode proc nextOverloadIter(o: var TOverloadIter; c: PContext; n: PNode): PSym 827 +nim pickSym lookups.html#pickSym,PContext,PNode,set[TSymKind],TSymFlags proc pickSym(c: PContext; n: PNode; kinds: set[TSymKind]; flags: TSymFlags = {}): PSym 910 +nimgrp adddecl lookups.html#addDecl-procs-all proc 404 +nimgrp ambiguousidentifiermsg lookups.html#ambiguousIdentifierMsg-procs-all proc 566 +nimgrp adddeclat lookups.html#addDeclAt-procs-all proc 385 +nimgrp errorsym lookups.html#errorSym-procs-all proc 308 +nimgrp errorusequalifier lookups.html#errorUseQualifier-procs-all proc 562 diff --git a/compiler/lowerings.html b/compiler/lowerings.html new file mode 100644 index 0000000000000..5ca4cafe27f5e --- /dev/null +++ b/compiler/lowerings.html @@ -0,0 +1,662 @@ + + + + + + + +lowerings + + + + + + + + + + + + + + + + +
+
+

lowerings

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module implements common simple lowerings.

+ +
+

Consts

+
+
+
genPrefix = ":tmp"
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc addField(obj: PType; s: PSym; cache: IdentCache; idgen: IdGenerator): PSym {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addUniqueField(obj: PType; s: PSym; cache: IdentCache; idgen: IdGenerator): PSym {.
+    discardable, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addVar(father, v, value: PNode) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc addVar(father, v: PNode) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc callCodegenProc(g: ModuleGraph; name: string;
+                     info: TLineInfo = unknownLineInfo; arg1: PNode = nil;
+                     arg2: PNode = nil; arg3: PNode = nil;
+                     optionalArgs: PNode = nil): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createObj(g: ModuleGraph; idgen: IdGenerator; owner: PSym; info: TLineInfo;
+               final = true): PType {....raises: [KeyError, Exception],
+                                      tags: [ReadDirEffect, RootEffect],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc evalOnce(g: ModuleGraph; value: PNode; idgen: IdGenerator; owner: PSym): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Turns (value) into (let tmp = value; tmp) so that 'value' can be re-used freely, multiple times. This is frequently required and such a builtin would also be handy to have in macros.nim. The value that can be reused is 'result.lastSon'! + Source   +Edit   + +
+
+ +
+
+
+
proc genAddrOf(n: PNode; idgen: IdGenerator; typeKind = tyPtr): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genDeref(n: PNode; k = nkHiddenDeref): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genHigh(g: ModuleGraph; n: PNode): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genLen(g: ModuleGraph; n: PNode): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getFieldFromObj(t: PType; v: PSym): PSym {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc indirectAccess(a, b: PSym; info: TLineInfo): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc indirectAccess(a: PNode; b: ItemId; info: TLineInfo): PNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc indirectAccess(a: PNode; b: PSym; info: TLineInfo): PNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc indirectAccess(a: PNode; b: string; info: TLineInfo; cache: IdentCache): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lowerSwap(g: ModuleGraph; n: PNode; idgen: IdGenerator; owner: PSym): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lowerTupleUnpacking(g: ModuleGraph; n: PNode; idgen: IdGenerator;
+                         owner: PSym): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newAsgnStmt(le, ri: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newDeref(n: PNode): PNode {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newDotExpr(obj, b: PSym): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newFastAsgnStmt(le, ri: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newFastMoveStmt(g: ModuleGraph; le, ri: PNode): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newIntLit(g: ModuleGraph; info: TLineInfo; value: BiggestInt): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newTryFinally(body, final: PNode): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newTupleAccess(g: ModuleGraph; tup: PNode; i: int): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newTupleAccessRaw(tup: PNode; i: int): PNode {....raises: [KeyError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rawAddField(obj: PType; field: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rawDirectAccess(obj, field: PSym): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rawIndirectAccess(a: PNode; field: PSym; info: TLineInfo): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/lowerings.idx b/compiler/lowerings.idx new file mode 100644 index 0000000000000..49a908d26a546 --- /dev/null +++ b/compiler/lowerings.idx @@ -0,0 +1,34 @@ +nimTitle lowerings lowerings.html module lowerings 0 +nim genPrefix lowerings.html#genPrefix const genPrefix 13 +nim newDeref lowerings.html#newDeref,PNode proc newDeref(n: PNode): PNode 21 +nim newTupleAccess lowerings.html#newTupleAccess,ModuleGraph,PNode,int proc newTupleAccess(g: ModuleGraph; tup: PNode; i: int): PNode 25 +nim addVar lowerings.html#addVar,PNode,PNode proc addVar(father, v: PNode) 41 +nim addVar lowerings.html#addVar,PNode,PNode,PNode proc addVar(father, v, value: PNode) 48 +nim newAsgnStmt lowerings.html#newAsgnStmt,PNode,PNode proc newAsgnStmt(le, ri: PNode): PNode 55 +nim newFastAsgnStmt lowerings.html#newFastAsgnStmt,PNode,PNode proc newFastAsgnStmt(le, ri: PNode): PNode 60 +nim newFastMoveStmt lowerings.html#newFastMoveStmt,ModuleGraph,PNode,PNode proc newFastMoveStmt(g: ModuleGraph; le, ri: PNode): PNode 65 +nim lowerTupleUnpacking lowerings.html#lowerTupleUnpacking,ModuleGraph,PNode,IdGenerator,PSym proc lowerTupleUnpacking(g: ModuleGraph; n: PNode; idgen: IdGenerator; owner: PSym): PNode 72 +nim evalOnce lowerings.html#evalOnce,ModuleGraph,PNode,IdGenerator,PSym proc evalOnce(g: ModuleGraph; value: PNode; idgen: IdGenerator; owner: PSym): PNode 98 +nim newTupleAccessRaw lowerings.html#newTupleAccessRaw,PNode,int proc newTupleAccessRaw(tup: PNode; i: int): PNode 115 +nim newTryFinally lowerings.html#newTryFinally,PNode,PNode proc newTryFinally(body, final: PNode): PNode 122 +nim lowerSwap lowerings.html#lowerSwap,ModuleGraph,PNode,IdGenerator,PSym proc lowerSwap(g: ModuleGraph; n: PNode; idgen: IdGenerator; owner: PSym): PNode 125 +nim createObj lowerings.html#createObj,ModuleGraph,IdGenerator,PSym,TLineInfo proc createObj(g: ModuleGraph; idgen: IdGenerator; owner: PSym; info: TLineInfo;\n final = true): PType 146 +nim rawAddField lowerings.html#rawAddField,PType,PSym proc rawAddField(obj: PType; field: PSym) 166 +nim rawIndirectAccess lowerings.html#rawIndirectAccess,PNode,PSym,TLineInfo proc rawIndirectAccess(a: PNode; field: PSym; info: TLineInfo): PNode 173 +nim rawDirectAccess lowerings.html#rawDirectAccess,PSym,PSym proc rawDirectAccess(obj, field: PSym): PNode 184 +nim addField lowerings.html#addField,PType,PSym,IdentCache,IdGenerator proc addField(obj: PType; s: PSym; cache: IdentCache; idgen: IdGenerator): PSym 213 +nim addUniqueField lowerings.html#addUniqueField,PType,PSym,IdentCache,IdGenerator proc addUniqueField(obj: PType; s: PSym; cache: IdentCache; idgen: IdGenerator): PSym 233 +nim newDotExpr lowerings.html#newDotExpr,PSym,PSym proc newDotExpr(obj, b: PSym): PNode 247 +nim indirectAccess lowerings.html#indirectAccess,PNode,ItemId,TLineInfo proc indirectAccess(a: PNode; b: ItemId; info: TLineInfo): PNode 255 +nim indirectAccess lowerings.html#indirectAccess,PNode,string,TLineInfo,IdentCache proc indirectAccess(a: PNode; b: string; info: TLineInfo; cache: IdentCache): PNode 278 +nim getFieldFromObj lowerings.html#getFieldFromObj,PType,PSym proc getFieldFromObj(t: PType; v: PSym): PSym 302 +nim indirectAccess lowerings.html#indirectAccess,PNode,PSym,TLineInfo proc indirectAccess(a: PNode; b: PSym; info: TLineInfo): PNode 313 +nim indirectAccess lowerings.html#indirectAccess,PSym,PSym,TLineInfo proc indirectAccess(a, b: PSym; info: TLineInfo): PNode 317 +nim genAddrOf lowerings.html#genAddrOf,PNode,IdGenerator proc genAddrOf(n: PNode; idgen: IdGenerator; typeKind = tyPtr): PNode 320 +nim genDeref lowerings.html#genDeref,PNode proc genDeref(n: PNode; k = nkHiddenDeref): PNode 326 +nim callCodegenProc lowerings.html#callCodegenProc,ModuleGraph,string,TLineInfo,PNode,PNode,PNode,PNode proc callCodegenProc(g: ModuleGraph; name: string; info: TLineInfo = unknownLineInfo;\n arg1: PNode = nil; arg2: PNode = nil; arg3: PNode = nil;\n optionalArgs: PNode = nil): PNode 331 +nim newIntLit lowerings.html#newIntLit,ModuleGraph,TLineInfo,BiggestInt proc newIntLit(g: ModuleGraph; info: TLineInfo; value: BiggestInt): PNode 349 +nim genHigh lowerings.html#genHigh,ModuleGraph,PNode proc genHigh(g: ModuleGraph; n: PNode): PNode 353 +nim genLen lowerings.html#genLen,ModuleGraph,PNode proc genLen(g: ModuleGraph; n: PNode): PNode 362 +nimgrp indirectaccess lowerings.html#indirectAccess-procs-all proc 255 +nimgrp addvar lowerings.html#addVar-procs-all proc 41 diff --git a/compiler/macrocacheimpl.html b/compiler/macrocacheimpl.html new file mode 100644 index 0000000000000..4557873bd1f2a --- /dev/null +++ b/compiler/macrocacheimpl.html @@ -0,0 +1,174 @@ + + + + + + + +macrocacheimpl + + + + + + + + + + + + + + + + +
+
+

macrocacheimpl

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module implements helpers for the macro cache.

+
+

Imports

+
+ lineinfos, ast, vmdef +
+
+
+

Procs

+
+
+
+
proc recordAdd(c: PCtx; info: TLineInfo; key: string; val: PNode) {.
+    ...raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc recordInc(c: PCtx; info: TLineInfo; key: string; by: BiggestInt) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc recordIncl(c: PCtx; info: TLineInfo; key: string; val: PNode) {.
+    ...raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc recordPut(c: PCtx; info: TLineInfo; key: string; k: string; val: PNode) {.
+    ...raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/macrocacheimpl.idx b/compiler/macrocacheimpl.idx new file mode 100644 index 0000000000000..f95adc87d7dad --- /dev/null +++ b/compiler/macrocacheimpl.idx @@ -0,0 +1,5 @@ +nimTitle macrocacheimpl macrocacheimpl.html module macrocacheimpl 0 +nim recordInc macrocacheimpl.html#recordInc,PCtx,TLineInfo,string,BiggestInt proc recordInc(c: PCtx; info: TLineInfo; key: string; by: BiggestInt) 17 +nim recordPut macrocacheimpl.html#recordPut,PCtx,TLineInfo,string,string,PNode proc recordPut(c: PCtx; info: TLineInfo; key: string; k: string; val: PNode) 24 +nim recordAdd macrocacheimpl.html#recordAdd,PCtx,TLineInfo,string,PNode proc recordAdd(c: PCtx; info: TLineInfo; key: string; val: PNode) 32 +nim recordIncl macrocacheimpl.html#recordIncl,PCtx,TLineInfo,string,PNode proc recordIncl(c: PCtx; info: TLineInfo; key: string; val: PNode) 39 diff --git a/compiler/magicsys.html b/compiler/magicsys.html new file mode 100644 index 0000000000000..5f9f05c83ee9e --- /dev/null +++ b/compiler/magicsys.html @@ -0,0 +1,436 @@ + + + + + + + +magicsys + + + + + + + + + + + + + + + + +
+
+

magicsys

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc addSonSkipIntLit(father, son: PType; id: IdGenerator) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getCompilerProc(g: ModuleGraph; name: string): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getFloatLitType(g: ModuleGraph; literal: PNode): PType {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getMagicEqSymForType(g: ModuleGraph; t: PType; info: TLineInfo): PSym {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getNimScriptSymbol(g: ModuleGraph; name: string): PSym {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getSysMagic(g: ModuleGraph; info: TLineInfo; name: string; m: TMagic): PSym {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getSysSym(g: ModuleGraph; info: TLineInfo; name: string): PSym {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getSysType(g: ModuleGraph; info: TLineInfo; kind: TTypeKind): PType {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeAddr(n: PNode; idgen: IdGenerator): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makePtrType(baseType: PType; idgen: IdGenerator): PType {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeVarType(owner: PSym; baseType: PType; idgen: IdGenerator; kind = tyVar): PType {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nilOrSysInt(g: ModuleGraph): PType {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc registerCompilerProc(g: ModuleGraph; s: PSym) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc registerNimScriptSymbol(g: ModuleGraph; s: PSym) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc resetNimScriptSymbols(g: ModuleGraph) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc resetSysTypes(g: ModuleGraph) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipIntLit(t: PType; id: IdGenerator): PType {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sysTypeFromName(g: ModuleGraph; info: TLineInfo; name: string): PType {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/magicsys.idx b/compiler/magicsys.idx new file mode 100644 index 0000000000000..c7d9cd33f5d62 --- /dev/null +++ b/compiler/magicsys.idx @@ -0,0 +1,19 @@ +nimTitle magicsys magicsys.html module magicsys 0 +nim nilOrSysInt magicsys.html#nilOrSysInt,ModuleGraph proc nilOrSysInt(g: ModuleGraph): PType 18 +nim getSysSym magicsys.html#getSysSym,ModuleGraph,TLineInfo,string proc getSysSym(g: ModuleGraph; info: TLineInfo; name: string): PSym 25 +nim getSysMagic magicsys.html#getSysMagic,ModuleGraph,TLineInfo,string,TMagic proc getSysMagic(g: ModuleGraph; info: TLineInfo; name: string; m: TMagic): PSym 32 +nim sysTypeFromName magicsys.html#sysTypeFromName,ModuleGraph,TLineInfo,string proc sysTypeFromName(g: ModuleGraph; info: TLineInfo; name: string): PType 45 +nim getSysType magicsys.html#getSysType,ModuleGraph,TLineInfo,TTypeKind proc getSysType(g: ModuleGraph; info: TLineInfo; kind: TTypeKind): PType 48 +nim resetSysTypes magicsys.html#resetSysTypes,ModuleGraph proc resetSysTypes(g: ModuleGraph) 82 +nim getFloatLitType magicsys.html#getFloatLitType,ModuleGraph,PNode proc getFloatLitType(g: ModuleGraph; literal: PNode): PType 89 +nim skipIntLit magicsys.html#skipIntLit,PType,IdGenerator proc skipIntLit(t: PType; id: IdGenerator): PType 94 +nim addSonSkipIntLit magicsys.html#addSonSkipIntLit,PType,PType,IdGenerator proc addSonSkipIntLit(father, son: PType; id: IdGenerator) 101 +nim makeVarType magicsys.html#makeVarType,PSym,PType,IdGenerator proc makeVarType(owner: PSym; baseType: PType; idgen: IdGenerator; kind = tyVar): PType 106 +nim getCompilerProc magicsys.html#getCompilerProc,ModuleGraph,string proc getCompilerProc(g: ModuleGraph; name: string): PSym 113 +nim registerCompilerProc magicsys.html#registerCompilerProc,ModuleGraph,PSym proc registerCompilerProc(g: ModuleGraph; s: PSym) 119 +nim registerNimScriptSymbol magicsys.html#registerNimScriptSymbol,ModuleGraph,PSym proc registerNimScriptSymbol(g: ModuleGraph; s: PSym) 122 +nim getNimScriptSymbol magicsys.html#getNimScriptSymbol,ModuleGraph,string proc getNimScriptSymbol(g: ModuleGraph; name: string): PSym 131 +nim resetNimScriptSymbols magicsys.html#resetNimScriptSymbols,ModuleGraph proc resetNimScriptSymbols(g: ModuleGraph) 134 +nim getMagicEqSymForType magicsys.html#getMagicEqSymForType,ModuleGraph,PType,TLineInfo proc getMagicEqSymForType(g: ModuleGraph; t: PType; info: TLineInfo): PSym 136 +nim makePtrType magicsys.html#makePtrType,PType,IdGenerator proc makePtrType(baseType: PType; idgen: IdGenerator): PType 160 +nim makeAddr magicsys.html#makeAddr,PNode,IdGenerator proc makeAddr(n: PNode; idgen: IdGenerator): PNode 164 diff --git a/compiler/main.html b/compiler/main.html new file mode 100644 index 0000000000000..7f91ffbea1b95 --- /dev/null +++ b/compiler/main.html @@ -0,0 +1,158 @@ + + + + + + + +main + + + + + + + + + + + + + + + + +
+
+

main

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc hashMainCompilationParams(conf: ConfigRef): string {....raises: [],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + doesn't have to be complete; worst case is a cache hit and recompilation. + Source   +Edit   + +
+
+ +
+
+
+
proc mainCommand(graph: ModuleGraph) {....raises: [OSError, Exception, ValueError,
+    KeyError, IOError, ERecoverableError, EOFError, ESuggestDone], tags: [
+    TimeEffect, ReadEnvEffect, ReadIOEffect, RootEffect, ReadDirEffect,
+    WriteIOEffect, ExecIOEffect, WriteDirEffect, WriteEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setOutFile(conf: ConfigRef) {....raises: [ValueError], tags: [ReadIOEffect],
+                                   forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/main.idx b/compiler/main.idx new file mode 100644 index 0000000000000..d3d99201cd06b --- /dev/null +++ b/compiler/main.idx @@ -0,0 +1,4 @@ +nimTitle main main.html module main 0 +nim hashMainCompilationParams main.html#hashMainCompilationParams,ConfigRef proc hashMainCompilationParams(conf: ConfigRef): string 215 +nim setOutFile main.html#setOutFile,ConfigRef proc setOutFile(conf: ConfigRef) 224 +nim mainCommand main.html#mainCommand,ModuleGraph proc mainCommand(graph: ModuleGraph) 240 diff --git a/compiler/mangleutils.html b/compiler/mangleutils.html new file mode 100644 index 0000000000000..d20e01c4bc7ff --- /dev/null +++ b/compiler/mangleutils.html @@ -0,0 +1,154 @@ + + + + + + + +mangleutils + + + + + + + + + + + + + + + + +
+
+

mangleutils

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc mangle(name: string): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mangleParamExt(s: PSym): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mangleProcNameExt(graph: ModuleGraph; s: PSym): string {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/mangleutils.idx b/compiler/mangleutils.idx new file mode 100644 index 0000000000000..ff0cb5821fe8d --- /dev/null +++ b/compiler/mangleutils.idx @@ -0,0 +1,4 @@ +nimTitle mangleutils mangleutils.html module mangleutils 0 +nim mangle mangleutils.html#mangle,string proc mangle(name: string): string 4 +nim mangleParamExt mangleutils.html#mangleParamExt,PSym proc mangleParamExt(s: PSym): string 51 +nim mangleProcNameExt mangleutils.html#mangleProcNameExt,ModuleGraph,PSym proc mangleProcNameExt(graph: ModuleGraph; s: PSym): string 55 diff --git a/compiler/modulegraphs.html b/compiler/modulegraphs.html new file mode 100644 index 0000000000000..0608f90ec220e --- /dev/null +++ b/compiler/modulegraphs.html @@ -0,0 +1,1763 @@ + + + + + + + +modulegraphs + + + + + + + + + + + + + + + + +
+
+

modulegraphs

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module implements the module graph data structure. The module graph represents a complete Nim project. Single modules can either be kept in RAM or stored in a rod-file.

+ +
+

Types

+
+
+
FullId = object
+  module*: int
+  packed*: PackedItemId
+
+ + + Source   +Edit   + +
+
+
+
Iface = object
+  module*: PSym              ## module this "Iface" belongs to
+  converters*: seq[LazySym]
+  patterns*: seq[LazySym]
+  pureEnums*: seq[LazySym]
+  uniqueName*: Rope
+
+ + data we don't want to store directly in the ast.PSym type for s.kind == skModule + Source   +Edit   + +
+
+
+
LazyInstantiation = object
+  module*: int
+  sym*: FullId
+  concreteTypes*: seq[FullId]
+  inst*: PInstantiation
+
+ + + Source   +Edit   + +
+
+
+
LazySym = object
+  id*: FullId
+  sym*: PSym
+
+ + + Source   +Edit   + +
+
+
+
LazyType = object
+  id*: FullId
+  typ*: PType
+
+ + + Source   +Edit   + +
+
+
+
ModuleGraph {.acyclic.} = ref object
+  ifaces*: seq[Iface]        ## indexed by int32 fileIdx
+  packed*: PackedModuleGraph
+  encoders*: seq[PackedEncoder]
+  typeInstCache*: Table[ItemId, seq[LazyType]]
+  procInstCache*: Table[ItemId, seq[LazyInstantiation]]
+  attachedOps*: array[TTypeAttachedOp, Table[ItemId, LazySym]]
+  methodsPerGenericType*: Table[ItemId, seq[(int, LazySym)]]
+  memberProcsPerType*: Table[ItemId, seq[PSym]]
+  initializersPerType*: Table[ItemId, PNode]
+  enumToStringProcs*: Table[ItemId, LazySym]
+  emittedTypeInfo*: Table[string, FileIndex]
+  startupPackedConfig*: PackedConfig
+  packageSyms*: TStrTable
+  deps*: IntSet
+  importDeps*: Table[FileIndex, seq[FileIndex]]
+  suggestMode*: bool
+  interactive*: bool
+  withinSystem*: bool
+  inclToMod*: Table[FileIndex, FileIndex]
+  importStack*: seq[FileIndex]
+  backend*: RootRef
+  config*: ConfigRef
+  cache*: IdentCache
+  vm*: RootRef
+  repl*: RootRef
+  doStopCompile*: proc (): bool {.closure.}
+  usageSym*: PSym
+  owners*: seq[PSym]
+  suggestSymbols*: SuggestSymbolDatabase
+  suggestErrors*: Table[FileIndex, seq[Suggest]]
+  methods*: seq[tuple[methods: seq[PSym], dispatcher: PSym]]
+  bucketTable*: CountTable[ItemId]
+  objectTree*: Table[ItemId, seq[tuple[depth: int, value: PType]]]
+  methodsPerType*: Table[ItemId, seq[LazySym]]
+  dispatchers*: seq[LazySym]
+  systemModule*: PSym
+  sysTypes*: array[TTypeKind, PType]
+  compilerprocs*: TStrTable
+  exposed*: TStrTable
+  packageTypes*: TStrTable
+  emptyNode*: PNode
+  canonTypes*: Table[SigHash, PType]
+  symBodyHashes*: Table[int, SigHash]
+  importModuleCallback*: proc (graph: ModuleGraph; m: PSym; fileIdx: FileIndex): PSym {.
+      nimcall.}
+  includeFileCallback*: proc (graph: ModuleGraph; m: PSym; fileIdx: FileIndex): PNode {.
+      nimcall.}
+  cacheSeqs*: Table[string, PNode]
+  cacheCounters*: Table[string, BiggestInt]
+  cacheTables*: Table[string, BTree[string, PNode]]
+  passes*: seq[TPass]
+  pipelinePass*: PipelinePass
+  onDefinition*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
+  onDefinitionResolveForward*: proc (graph: ModuleGraph; s: PSym;
+                                     info: TLineInfo) {.nimcall.}
+  onUsage*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
+  globalDestructors*: seq[PNode]
+  strongSemCheck*: proc (graph: ModuleGraph; owner: PSym; body: PNode) {.nimcall.}
+  compatibleProps*: proc (graph: ModuleGraph; formal, actual: PType): bool {.
+      nimcall.}
+  idgen*: IdGenerator
+  operators*: Operators
+  cachedFiles*: StringTableRef
+
+ + + Source   +Edit   + +
+
+
+
ModuleIter = object
+
+ + + Source   +Edit   + +
+
+
+
Operators = object
+  opNot*, opContains*, opLe*, opLt*, opAnd*, opOr*, opIsNil*, opEq*: PSym
+  opAdd*, opSub*, opMul*, opDiv*, opLen*: PSym
+
+ + + Source   +Edit   + +
+
+
+
PipelinePass = enum
+  NonePass, SemPass, JSgenPass, CgenPass, EvalPass, InterpreterPass,
+  GenDependPass, Docgen2TexPass, Docgen2JsonPass, Docgen2Pass
+
+ + + Source   +Edit   + +
+
+
+
PPassContext = ref TPassContext
+
+ + + Source   +Edit   + +
+
+
+
SigHash = distinct MD5Digest
+
+ + + Source   +Edit   + +
+
+
+
TPass = tuple[open: TPassOpen, process: TPassProcess, close: TPassClose,
+              isFrontend: bool]
+
+ + + Source   +Edit   + +
+
+
+
TPassClose = proc (graph: ModuleGraph; p: PPassContext; n: PNode): PNode {.
+    nimcall.}
+
+ + + Source   +Edit   + +
+
+
+
TPassContext = object of RootObj
+  idgen*: IdGenerator
+
+ + + Source   +Edit   + +
+
+
+
TPassOpen = proc (graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext {.
+    nimcall.}
+
+ + + Source   +Edit   + +
+
+
+
TPassProcess = proc (p: PPassContext; topLevelStmt: PNode): PNode {.nimcall.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(u: SigHash): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(a, b: SigHash): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addDep(g: ModuleGraph; m: PSym; dep: FileIndex) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addDispatchers(g: ModuleGraph; value: PSym) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addIncludeDep(g: ModuleGraph; module, includeFile: FileIndex) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addMethodToGeneric(g: ModuleGraph; module: int; t: PType; col: int; m: PSym) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func belongsToStdlib(graph: ModuleGraph; sym: PSym): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ + Check if symbol belongs to the 'stdlib' package. + Source   +Edit   + +
+
+ +
+
+
+
proc closeRodFile(g: ModuleGraph; m: PSym) {.
+    ...raises: [Exception, IOError, OSError, KeyError], tags: [RootEffect,
+    WriteIOEffect, WriteDirEffect, ReadEnvEffect, ReadIOEffect, ReadDirEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc completePartialOp(g: ModuleGraph; module: int; t: PType;
+                       op: TTypeAttachedOp; value: PSym) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc configComplete(g: ModuleGraph) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc copyTypeProps(g: ModuleGraph; module: int; dest, src: PType) {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createMagic(g: ModuleGraph; idgen: IdGenerator; name: string; m: TMagic): PSym {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fileSymbols(graph: ModuleGraph; fileIdx: FileIndex): SuggestFileSymbolDatabase {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getAttachedOp(g: ModuleGraph; t: PType; op: TTypeAttachedOp): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + returns the requested attached operation for type t. Can return nil if no such operation exists. + Source   +Edit   + +
+
+ +
+
+
+
proc getBody(g: ModuleGraph; s: PSym): PNode {.inline,
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getModule(g: ModuleGraph; fileIdx: FileIndex): PSym {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getPackage(graph: ModuleGraph; fileIdx: FileIndex): PSym {.
+    ...raises: [KeyError], tags: [ReadDirEffect], forbids: [].}
+
+ + Returns a package symbol for yet to be defined module for fileIdx. The package symbol is added to the graph if it doesn't exist. + Source   +Edit   + +
+
+ +
+
+
+
proc getToStringProc(g: ModuleGraph; t: PType): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasDisabledAsgn(g: ModuleGraph; t: PType): bool {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hash(u: SigHash): Hash {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc hash(x: FileIndex): Hash {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initEncoder(g: ModuleGraph; module: PSym) {....raises: [IOError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initModuleIter(mi: var ModuleIter; g: ModuleGraph; m: PSym; name: PIdent): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initOperators(g: ModuleGraph): Operators {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initStrTables(g: ModuleGraph; m: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isCachedModule(g: ModuleGraph; m: PSym): bool {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isDirty(g: ModuleGraph; m: PSym): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc loadCompilerProc(g: ModuleGraph; name: string): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc loadPackedSym(g: ModuleGraph; s: var LazySym) {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc markClientsDirty(g: ModuleGraph; fileIdx: FileIndex) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc markDirty(g: ModuleGraph; fileIdx: FileIndex) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc moduleFromRodFile(g: ModuleGraph; fileIdx: FileIndex;
+                       cachedModules: var seq[FileIndex]): PSym {....raises: [
+    OSError, IOError, Exception, KeyError, ValueError, ERecoverableError], tags: [
+    ReadEnvEffect, ReadIOEffect, WriteDirEffect, ReadDirEffect, RootEffect,
+    WriteIOEffect], forbids: [].}
+
+ + Returns 'nil' if the module needs to be recompiled. + Source   +Edit   + +
+
+ +
+
+
+
proc moduleOpenForCodegen(g: ModuleGraph; m: FileIndex): bool {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc needsCompilation(g: ModuleGraph): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc needsCompilation(g: ModuleGraph; fileIdx: FileIndex): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newModuleGraph(cache: IdentCache; config: ConfigRef): ModuleGraph {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nextModuleIter(mi: var ModuleIter; g: ModuleGraph): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc onProcessing(graph: ModuleGraph; fileIdx: FileIndex; moduleStatus: string;
+                  fromModule: PSym) {....raises: [Exception, KeyError, ValueError,
+    IOError, ERecoverableError], tags: [RootEffect, ReadDirEffect,
+                                        WriteIOEffect, ReadIOEffect,
+                                        ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc parentModule(g: ModuleGraph; fileIdx: FileIndex): FileIndex {....raises: [],
+    tags: [], forbids: [].}
+
+ + returns 'fileIdx' if the file belonging to this index is directly used as a module or else the module that first references this include file. + Source   +Edit   + +
+
+ +
+
+
+
proc registerModule(g: ModuleGraph; m: PSym) {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc registerModuleById(g: ModuleGraph; m: FileIndex) {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rememberEmittedTypeInfo(g: ModuleGraph; m: FileIndex; ti: string) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rememberFlag(g: ModuleGraph; m: PSym; flag: ModuleBackendFlag) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc resetAllModules(g: ModuleGraph) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc resetForBackend(g: ModuleGraph) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc resolveAttachedOp(g: ModuleGraph; t: var LazySym): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setAttachedOp(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp;
+                   value: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + we also need to record this to the packed module. + Source   +Edit   + +
+
+ +
+
+
+
proc setAttachedOpPartial(g: ModuleGraph; module: int; t: PType;
+                          op: TTypeAttachedOp; value: PSym) {....raises: [],
+    tags: [], forbids: [].}
+
+ + we also need to record this to the packed module. + Source   +Edit   + +
+
+ +
+
+
+
proc setMethodsPerType(g: ModuleGraph; id: ItemId; methods: seq[LazySym]) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setToStringProc(g: ModuleGraph; t: PType; value: PSym) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc someSym(g: ModuleGraph; m: PSym; name: PIdent): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc someSymAmb(g: ModuleGraph; m: PSym; name: PIdent; amb: var bool): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc stopCompile(g: ModuleGraph): bool {.inline, ...raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc strTableAdds(g: ModuleGraph; m: PSym; s: PSym) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc systemModuleSym(g: ModuleGraph; name: PIdent): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc uniqueModuleName(conf: ConfigRef; m: PSym): string {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + The unique module name is guaranteed to only contain {'A'..'Z', 'a'..'z', '0'..'9', '_'} so that it is useful as a C identifier snippet. + Source   +Edit   + +
+
+ +
+
+
+
proc unmarkAllDirty(g: ModuleGraph) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator allSyms(g: ModuleGraph; m: PSym): PSym {....raises: [KeyError, Exception],
+    tags: [ReadDirEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator getDispatchers(g: ModuleGraph): PSym {....raises: [KeyError, Exception],
+    tags: [ReadDirEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator getMethodsPerType(g: ModuleGraph; t: PType): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator methodsForGeneric(g: ModuleGraph; t: PType): (int, PSym) {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator procInstCacheItems(g: ModuleGraph; s: PSym): PInstantiation {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator suggestErrorsIter(g: ModuleGraph): Suggest {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator suggestSymbolsIter(g: ModuleGraph): SymInfoPair {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator systemModuleSyms(g: ModuleGraph; name: PIdent): PSym {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator typeInstCacheItems(g: ModuleGraph; s: PSym): PType {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template onDef(info: TLineInfo; s: PSym)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template onDefResolveForward(info: TLineInfo; s: PSym)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template onUse(info: TLineInfo; s: PSym)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template semtabAll(g: ModuleGraph; m: PSym): TStrTable
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/modulegraphs.idx b/compiler/modulegraphs.idx new file mode 100644 index 0000000000000..8d53b4e0fd35b --- /dev/null +++ b/compiler/modulegraphs.idx @@ -0,0 +1,99 @@ +nimTitle modulegraphs modulegraphs.html module modulegraphs 0 +nim SigHash modulegraphs.html#SigHash type SigHash 24 +nim LazySym modulegraphs.html#LazySym object LazySym 26 +nim Iface modulegraphs.html#Iface object Iface 30 +nim Operators modulegraphs.html#Operators object Operators 40 +nim FullId modulegraphs.html#FullId object FullId 44 +nim LazyType modulegraphs.html#LazyType object LazyType 48 +nim LazyInstantiation modulegraphs.html#LazyInstantiation object LazyInstantiation 52 +nim NonePass modulegraphs.html#NonePass PipelinePass.NonePass 58 +nim SemPass modulegraphs.html#SemPass PipelinePass.SemPass 58 +nim JSgenPass modulegraphs.html#JSgenPass PipelinePass.JSgenPass 58 +nim CgenPass modulegraphs.html#CgenPass PipelinePass.CgenPass 58 +nim EvalPass modulegraphs.html#EvalPass PipelinePass.EvalPass 58 +nim InterpreterPass modulegraphs.html#InterpreterPass PipelinePass.InterpreterPass 58 +nim GenDependPass modulegraphs.html#GenDependPass PipelinePass.GenDependPass 58 +nim Docgen2TexPass modulegraphs.html#Docgen2TexPass PipelinePass.Docgen2TexPass 58 +nim Docgen2JsonPass modulegraphs.html#Docgen2JsonPass PipelinePass.Docgen2JsonPass 58 +nim Docgen2Pass modulegraphs.html#Docgen2Pass PipelinePass.Docgen2Pass 58 +nim PipelinePass modulegraphs.html#PipelinePass enum PipelinePass 58 +nim ModuleGraph modulegraphs.html#ModuleGraph type ModuleGraph 70 +nim TPassContext modulegraphs.html#TPassContext object TPassContext 139 +nim PPassContext modulegraphs.html#PPassContext type PPassContext 141 +nim TPassOpen modulegraphs.html#TPassOpen type TPassOpen 143 +nim TPassClose modulegraphs.html#TPassClose type TPassClose 144 +nim TPassProcess modulegraphs.html#TPassProcess type TPassProcess 145 +nim TPass modulegraphs.html#TPass tuple TPass 147 +nim resetForBackend modulegraphs.html#resetForBackend,ModuleGraph proc resetForBackend(g: ModuleGraph) 152 +nim semtabAll modulegraphs.html#semtabAll.t,ModuleGraph,PSym template semtabAll(g: ModuleGraph; m: PSym): TStrTable 205 +nim initStrTables modulegraphs.html#initStrTables,ModuleGraph,PSym proc initStrTables(g: ModuleGraph; m: PSym) 208 +nim strTableAdds modulegraphs.html#strTableAdds,ModuleGraph,PSym,PSym proc strTableAdds(g: ModuleGraph; m: PSym; s: PSym) 212 +nim isCachedModule modulegraphs.html#isCachedModule,ModuleGraph,PSym proc isCachedModule(g: ModuleGraph; m: PSym): bool 219 +nim initEncoder modulegraphs.html#initEncoder,ModuleGraph,PSym proc initEncoder(g: ModuleGraph; module: PSym) 227 +nim ModuleIter modulegraphs.html#ModuleIter object ModuleIter 235 +nim initModuleIter modulegraphs.html#initModuleIter,ModuleIter,ModuleGraph,PSym,PIdent proc initModuleIter(mi: var ModuleIter; g: ModuleGraph; m: PSym; name: PIdent): PSym 242 +nim nextModuleIter modulegraphs.html#nextModuleIter,ModuleIter,ModuleGraph proc nextModuleIter(mi: var ModuleIter; g: ModuleGraph): PSym 252 +nim allSyms modulegraphs.html#allSyms.i,ModuleGraph,PSym iterator allSyms(g: ModuleGraph; m: PSym): PSym 258 +nim someSym modulegraphs.html#someSym,ModuleGraph,PSym,PIdent proc someSym(g: ModuleGraph; m: PSym; name: PIdent): PSym 271 +nim someSymAmb modulegraphs.html#someSymAmb,ModuleGraph,PSym,PIdent,bool proc someSymAmb(g: ModuleGraph; m: PSym; name: PIdent; amb: var bool): PSym 278 +nim systemModuleSym modulegraphs.html#systemModuleSym,ModuleGraph,PIdent proc systemModuleSym(g: ModuleGraph; name: PIdent): PSym 297 +nim systemModuleSyms modulegraphs.html#systemModuleSyms.i,ModuleGraph,PIdent iterator systemModuleSyms(g: ModuleGraph; name: PIdent): PSym 300 +nim resolveAttachedOp modulegraphs.html#resolveAttachedOp,ModuleGraph,LazySym proc resolveAttachedOp(g: ModuleGraph; t: var LazySym): PSym 332 +nim typeInstCacheItems modulegraphs.html#typeInstCacheItems.i,ModuleGraph,PSym iterator typeInstCacheItems(g: ModuleGraph; s: PSym): PType 339 +nim procInstCacheItems modulegraphs.html#procInstCacheItems.i,ModuleGraph,PSym iterator procInstCacheItems(g: ModuleGraph; s: PSym): PInstantiation 345 +nim getAttachedOp modulegraphs.html#getAttachedOp,ModuleGraph,PType,TTypeAttachedOp proc getAttachedOp(g: ModuleGraph; t: PType; op: TTypeAttachedOp): PSym 352 +nim setAttachedOp modulegraphs.html#setAttachedOp,ModuleGraph,int,PType,TTypeAttachedOp,PSym proc setAttachedOp(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp;\n value: PSym) 360 +nim setAttachedOpPartial modulegraphs.html#setAttachedOpPartial,ModuleGraph,int,PType,TTypeAttachedOp,PSym proc setAttachedOpPartial(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp;\n value: PSym) 364 +nim completePartialOp modulegraphs.html#completePartialOp,ModuleGraph,int,PType,TTypeAttachedOp,PSym proc completePartialOp(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp;\n value: PSym) 368 +nim getDispatchers modulegraphs.html#getDispatchers.i,ModuleGraph iterator getDispatchers(g: ModuleGraph): PSym 375 +nim addDispatchers modulegraphs.html#addDispatchers,ModuleGraph,PSym proc addDispatchers(g: ModuleGraph; value: PSym) 379 +nim setMethodsPerType modulegraphs.html#setMethodsPerType,ModuleGraph,ItemId,seq[LazySym] proc setMethodsPerType(g: ModuleGraph; id: ItemId; methods: seq[LazySym]) 387 +nim getMethodsPerType modulegraphs.html#getMethodsPerType.i,ModuleGraph,PType iterator getMethodsPerType(g: ModuleGraph; t: PType): PSym 391 +nim getToStringProc modulegraphs.html#getToStringProc,ModuleGraph,PType proc getToStringProc(g: ModuleGraph; t: PType): PSym 396 +nim setToStringProc modulegraphs.html#setToStringProc,ModuleGraph,PType,PSym proc setToStringProc(g: ModuleGraph; t: PType; value: PSym) 400 +nim methodsForGeneric modulegraphs.html#methodsForGeneric.i,ModuleGraph,PType iterator methodsForGeneric(g: ModuleGraph; t: PType): (int, PSym) 403 +nim addMethodToGeneric modulegraphs.html#addMethodToGeneric,ModuleGraph,int,PType,int,PSym proc addMethodToGeneric(g: ModuleGraph; module: int; t: PType; col: int; m: PSym) 408 +nim hasDisabledAsgn modulegraphs.html#hasDisabledAsgn,ModuleGraph,PType proc hasDisabledAsgn(g: ModuleGraph; t: PType): bool 411 +nim copyTypeProps modulegraphs.html#copyTypeProps,ModuleGraph,int,PType,PType proc copyTypeProps(g: ModuleGraph; module: int; dest, src: PType) 415 +nim loadCompilerProc modulegraphs.html#loadCompilerProc,ModuleGraph,string proc loadCompilerProc(g: ModuleGraph; name: string): PSym 421 +nim loadPackedSym modulegraphs.html#loadPackedSym,ModuleGraph,LazySym proc loadPackedSym(g: ModuleGraph; s: var LazySym) 435 +nim `$` modulegraphs.html#$,SigHash proc `$`(u: SigHash): string 439 +nim `==` modulegraphs.html#==,SigHash,SigHash proc `==`(a, b: SigHash): bool 442 +nim hash modulegraphs.html#hash,SigHash proc hash(u: SigHash): Hash 445 +nim hash modulegraphs.html#hash,FileIndex proc hash(x: FileIndex): Hash 450 +nim onUse modulegraphs.html#onUse.t,TLineInfo,PSym template onUse(info: TLineInfo; s: PSym) 460 +nim onDef modulegraphs.html#onDef.t,TLineInfo,PSym template onDef(info: TLineInfo; s: PSym) 461 +nim onDefResolveForward modulegraphs.html#onDefResolveForward.t,TLineInfo,PSym template onDefResolveForward(info: TLineInfo; s: PSym) 462 +nim stopCompile modulegraphs.html#stopCompile,ModuleGraph proc stopCompile(g: ModuleGraph): bool 464 +nim createMagic modulegraphs.html#createMagic,ModuleGraph,IdGenerator,string,TMagic proc createMagic(g: ModuleGraph; idgen: IdGenerator; name: string; m: TMagic): PSym 467 +nim uniqueModuleName modulegraphs.html#uniqueModuleName,ConfigRef,PSym proc uniqueModuleName(conf: ConfigRef; m: PSym): string 475 +nim registerModule modulegraphs.html#registerModule,ModuleGraph,PSym proc registerModule(g: ModuleGraph; m: PSym) 518 +nim registerModuleById modulegraphs.html#registerModuleById,ModuleGraph,FileIndex proc registerModuleById(g: ModuleGraph; m: FileIndex) 532 +nim initOperators modulegraphs.html#initOperators,ModuleGraph proc initOperators(g: ModuleGraph): Operators 535 +nim newModuleGraph modulegraphs.html#newModuleGraph,IdentCache,ConfigRef proc newModuleGraph(cache: IdentCache; config: ConfigRef): ModuleGraph 581 +nim resetAllModules modulegraphs.html#resetAllModules,ModuleGraph proc resetAllModules(g: ModuleGraph) 587 +nim getModule modulegraphs.html#getModule,ModuleGraph,FileIndex proc getModule(g: ModuleGraph; fileIdx: FileIndex): PSym 600 +nim moduleOpenForCodegen modulegraphs.html#moduleOpenForCodegen,ModuleGraph,FileIndex proc moduleOpenForCodegen(g: ModuleGraph; m: FileIndex): bool 608 +nim rememberEmittedTypeInfo modulegraphs.html#rememberEmittedTypeInfo,ModuleGraph,FileIndex,string proc rememberEmittedTypeInfo(g: ModuleGraph; m: FileIndex; ti: string) 614 +nim rememberFlag modulegraphs.html#rememberFlag,ModuleGraph,PSym,ModuleBackendFlag proc rememberFlag(g: ModuleGraph; m: PSym; flag: ModuleBackendFlag) 622 +nim closeRodFile modulegraphs.html#closeRodFile,ModuleGraph,PSym proc closeRodFile(g: ModuleGraph; m: PSym) 628 +nim addDep modulegraphs.html#addDep,ModuleGraph,PSym,FileIndex proc addDep(g: ModuleGraph; m: PSym; dep: FileIndex) 647 +nim addIncludeDep modulegraphs.html#addIncludeDep,ModuleGraph,FileIndex,FileIndex proc addIncludeDep(g: ModuleGraph; module, includeFile: FileIndex) 655 +nim parentModule modulegraphs.html#parentModule,ModuleGraph,FileIndex proc parentModule(g: ModuleGraph; fileIdx: FileIndex): FileIndex 658 +nim markDirty modulegraphs.html#markDirty,ModuleGraph,FileIndex proc markDirty(g: ModuleGraph; fileIdx: FileIndex) 676 +nim unmarkAllDirty modulegraphs.html#unmarkAllDirty,ModuleGraph proc unmarkAllDirty(g: ModuleGraph) 683 +nim isDirty modulegraphs.html#isDirty,ModuleGraph,PSym proc isDirty(g: ModuleGraph; m: PSym): bool 689 +nim markClientsDirty modulegraphs.html#markClientsDirty,ModuleGraph,FileIndex proc markClientsDirty(g: ModuleGraph; fileIdx: FileIndex) 692 +nim needsCompilation modulegraphs.html#needsCompilation,ModuleGraph proc needsCompilation(g: ModuleGraph): bool 705 +nim needsCompilation modulegraphs.html#needsCompilation,ModuleGraph,FileIndex proc needsCompilation(g: ModuleGraph; fileIdx: FileIndex): bool 714 +nim getBody modulegraphs.html#getBody,ModuleGraph,PSym proc getBody(g: ModuleGraph; s: PSym): PNode 725 +nim moduleFromRodFile modulegraphs.html#moduleFromRodFile,ModuleGraph,FileIndex,seq[FileIndex] proc moduleFromRodFile(g: ModuleGraph; fileIdx: FileIndex;\n cachedModules: var seq[FileIndex]): PSym 732 +nim configComplete modulegraphs.html#configComplete,ModuleGraph proc configComplete(g: ModuleGraph) 740 +nim onProcessing modulegraphs.html#onProcessing,ModuleGraph,FileIndex,string,PSym proc onProcessing(graph: ModuleGraph; fileIdx: FileIndex; moduleStatus: string;\n fromModule: PSym) 743 +nim getPackage modulegraphs.html#getPackage,ModuleGraph,FileIndex proc getPackage(graph: ModuleGraph; fileIdx: FileIndex): PSym 753 +nim belongsToStdlib modulegraphs.html#belongsToStdlib,ModuleGraph,PSym proc belongsToStdlib(graph: ModuleGraph; sym: PSym): bool 764 +nim fileSymbols modulegraphs.html#fileSymbols,ModuleGraph,FileIndex proc fileSymbols(graph: ModuleGraph; fileIdx: FileIndex): SuggestFileSymbolDatabase 768 +nim suggestSymbolsIter modulegraphs.html#suggestSymbolsIter.i,ModuleGraph iterator suggestSymbolsIter(g: ModuleGraph): SymInfoPair 772 +nim suggestErrorsIter modulegraphs.html#suggestErrorsIter.i,ModuleGraph iterator suggestErrorsIter(g: ModuleGraph): Suggest 777 +nimgrp needscompilation modulegraphs.html#needsCompilation-procs-all proc 705 +nimgrp hash modulegraphs.html#hash-procs-all proc 445 diff --git a/compiler/modulepaths.html b/compiler/modulepaths.html new file mode 100644 index 0000000000000..c68791d14a797 --- /dev/null +++ b/compiler/modulepaths.html @@ -0,0 +1,181 @@ + + + + + + + +modulepaths + + + + + + + + + + + + + + + + +
+
+

modulepaths

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc checkModuleName(conf: ConfigRef; n: PNode; doLocalError = true): FileIndex {....raises: [
+    OSError, Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    ReadEnvEffect, ReadIOEffect, RootEffect, ReadDirEffect, WriteIOEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc demangleModuleName(path: string): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + Demangle a relative module path. + Source   +Edit   + +
+
+ +
+
+
+
proc getModuleName(conf: ConfigRef; n: PNode): string {....raises: [OSError,
+    Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    ReadEnvEffect, ReadIOEffect, RootEffect, ReadDirEffect, WriteIOEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mangleModuleName(conf: ConfigRef; path: AbsoluteFile): string {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ +

Mangle a relative module path to avoid path and symbol collisions.

+

Used by backends that need to generate intermediary files from Nim modules. This is needed because the compiler uses a flat cache file hierarchy.

+

Example: foo-#head/../bar becomes @foo-@hhead@s..@sbar

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/modulepaths.idx b/compiler/modulepaths.idx new file mode 100644 index 0000000000000..c19385615aaf0 --- /dev/null +++ b/compiler/modulepaths.idx @@ -0,0 +1,5 @@ +nimTitle modulepaths modulepaths.html module modulepaths 0 +nim getModuleName modulepaths.html#getModuleName,ConfigRef,PNode proc getModuleName(conf: ConfigRef; n: PNode): string 15 +nim checkModuleName modulepaths.html#checkModuleName,ConfigRef,PNode proc checkModuleName(conf: ConfigRef; n: PNode; doLocalError = true): FileIndex 70 +nim mangleModuleName modulepaths.html#mangleModuleName,ConfigRef,AbsoluteFile proc mangleModuleName(conf: ConfigRef; path: AbsoluteFile): string 82 +nim demangleModuleName modulepaths.html#demangleModuleName,string proc demangleModuleName(path: string): string 93 diff --git a/compiler/modules.html b/compiler/modules.html new file mode 100644 index 0000000000000..754eccc14f3cb --- /dev/null +++ b/compiler/modules.html @@ -0,0 +1,254 @@ + + + + + + + +modules + + + + + + + + + + + + + + + + +
+
+

modules

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Implements the module handling, including the caching of modules.

+ +
+

Procs

+
+
+
+
proc includeModule(graph: ModuleGraph; s: PSym; fileIdx: FileIndex): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeModule(graph: ModuleGraph; filename: AbsoluteFile): PSym {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc makeModule(graph: ModuleGraph; filename: string): PSym {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeStdinModule(graph: ModuleGraph): PSym {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newModule(graph: ModuleGraph; fileIdx: FileIndex): PSym {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc partialInitModule(result: PSym; graph: ModuleGraph; fileIdx: FileIndex;
+                       filename: AbsoluteFile) {....raises: [KeyError],
+    tags: [ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc resetSystemArtifacts(g: ModuleGraph) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc wantMainModule(conf: ConfigRef) {....raises: [Exception, ValueError, KeyError,
+    IOError, ERecoverableError], tags: [RootEffect, ReadDirEffect,
+                                        WriteIOEffect, ReadIOEffect,
+                                        ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/modules.idx b/compiler/modules.idx new file mode 100644 index 0000000000000..7f4c8a20b5446 --- /dev/null +++ b/compiler/modules.idx @@ -0,0 +1,10 @@ +nimTitle modules modules.html module modules 0 +nim resetSystemArtifacts modules.html#resetSystemArtifacts,ModuleGraph proc resetSystemArtifacts(g: ModuleGraph) 20 +nim partialInitModule modules.html#partialInitModule,PSym,ModuleGraph,FileIndex,AbsoluteFile proc partialInitModule(result: PSym; graph: ModuleGraph; fileIdx: FileIndex;\n filename: AbsoluteFile) 26 +nim newModule modules.html#newModule,ModuleGraph,FileIndex proc newModule(graph: ModuleGraph; fileIdx: FileIndex): PSym 31 +nim includeModule modules.html#includeModule,ModuleGraph,PSym,FileIndex proc includeModule(graph: ModuleGraph; s: PSym; fileIdx: FileIndex): PNode 44 +nim wantMainModule modules.html#wantMainModule,ConfigRef proc wantMainModule(conf: ConfigRef) 51 +nim makeModule modules.html#makeModule,ModuleGraph,AbsoluteFile proc makeModule(graph: ModuleGraph; filename: AbsoluteFile): PSym 56 +nim makeModule modules.html#makeModule,ModuleGraph,string proc makeModule(graph: ModuleGraph; filename: string): PSym 60 +nim makeStdinModule modules.html#makeStdinModule,ModuleGraph proc makeStdinModule(graph: ModuleGraph): PSym 63 +nimgrp makemodule modules.html#makeModule-procs-all proc 56 diff --git a/compiler/msgs.html b/compiler/msgs.html new file mode 100644 index 0000000000000..ae3161ecc6c12 --- /dev/null +++ b/compiler/msgs.html @@ -0,0 +1,1377 @@ + + + + + + + +msgs + + + + + + + + + + + + + + + + +
+
+

msgs

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
InstantiationInfo = typeof(instantiationInfo())
+
+ + + Source   +Edit   + +
+
+
+
MsgFlag = enum
+  msgStdout,                ## force writing to stdout, even stderr is default
+  msgSkipHook,              ## skip message hook even if it is present
+  msgNoUnitSep               ## the message is a complete "paragraph".
+
+ + flags altering msgWriteln behavior + Source   +Edit   + +
+
+
+
MsgFlags = set[MsgFlag]
+
+ + + Source   +Edit   + +
+
+
+
TErrorHandling = enum
+  doNothing, doAbort, doRaise
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
ColOffset = 1
+
+ + + Source   +Edit   + +
+
+
+
commandLineDesc = "command line"
+
+ + + Source   +Edit   + +
+
+
+
gCmdLineInfo = (line: 1'u, col: 1, fileIndex: -3)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(conf: ConfigRef; info: TLineInfo): string {.
+    ...raises: [Exception, KeyError], tags: [RootEffect, ReadDirEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `$`(info: TLineInfo): string {.error.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(a, b: TLineInfo): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `??`(conf: ConfigRef; info: TLineInfo; filename: string): bool {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc exactEquals(a, b: TLineInfo): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fileInfoIdx(conf: ConfigRef; filename: AbsoluteFile): FileIndex {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc fileInfoIdx(conf: ConfigRef; filename: AbsoluteFile; isKnownFile: var bool): FileIndex {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc fileInfoIdx(conf: ConfigRef; filename: RelativeFile): FileIndex {.
+    ...raises: [KeyError, Exception, OSError], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc fileInfoIdx(conf: ConfigRef; filename: RelativeFile; isKnownFile: var bool): FileIndex {.
+    ...raises: [KeyError, Exception, OSError], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fileInfoKnown(conf: ConfigRef; filename: AbsoluteFile): bool {....raises: [],
+    tags: [ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc flushDot(conf: ConfigRef) {....raises: [IOError], tags: [WriteIOEffect],
+                                 forbids: [].}
+
+ + safe to call multiple times + Source   +Edit   + +
+
+ +
+
+
+
proc formatMsg(conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg: string): string {.
+    ...raises: [Exception, KeyError, ValueError],
+    tags: [RootEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genSuccessX(conf: ConfigRef) {....raises: [ValueError, OSError, Exception,
+    KeyError, IOError, ERecoverableError], tags: [TimeEffect, ReadDirEffect,
+    RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getHash(conf: ConfigRef; fileIdx: FileIndex): string {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getInfoContext(conf: ConfigRef; index: int): TLineInfo {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getInfoContextLen(conf: ConfigRef): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc liMessage(conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg: string;
+               eh: TErrorHandling; info2: InstantiationInfo; isRaw = false;
+               ignoreError = false) {....gcsafe, noinline, ...raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc listHints(conf: ConfigRef) {....raises: [Exception, IOError, ValueError],
+                                  tags: [RootEffect, WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc listWarnings(conf: ConfigRef) {....raises: [Exception, IOError, ValueError],
+                                     tags: [RootEffect, WriteIOEffect],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc log(s: string) {....raises: [IOError],
+                      tags: [ReadEnvEffect, ReadIOEffect, WriteIOEffect],
+                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeCString(s: string): Rope {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc msgKindToString(kind: TMsgKind): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc msgQuit(x: int8) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc msgQuit(x: string) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc msgWriteln(conf: ConfigRef; s: string; flags: MsgFlags = {}) {.
+    ...raises: [Exception, IOError], tags: [RootEffect, WriteIOEffect], forbids: [].}
+
+ + Writes given message string to stderr by default. If --stdout option is given, writes to stdout instead. If message hook is present, then it is used to output message rather than stderr/stdout. This behavior can be altered by given optional flags. + Source   +Edit   + +
+
+ +
+
+
+
proc newLineInfo(conf: ConfigRef; filename: AbsoluteFile; line, col: int): TLineInfo {.
+    inline, ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newLineInfo(fileInfoIdx: FileIndex; line, col: int): TLineInfo {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc numLines(conf: ConfigRef; fileIdx: FileIndex): int {....raises: [],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + xxx there's an off by 1 error that should be fixed; if a file ends with "foo" or "foon" it will return same number of lines (ie, a trailing empty line is discounted) + Source   +Edit   + +
+
+ +
+
+
+
proc popInfoContext(conf: ConfigRef) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pushInfoContext(conf: ConfigRef; info: TLineInfo; detail: string = "") {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc quotedFilename(conf: ConfigRef; fi: FileIndex): Rope {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc quotedFilename(conf: ConfigRef; i: TLineInfo): Rope {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setDirtyFile(conf: ConfigRef; fileIdx: FileIndex; filename: AbsoluteFile) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setHash(conf: ConfigRef; fileIdx: FileIndex; hash: string) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setInfoContextLen(conf: ConfigRef; L: int) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sourceLine(conf: ConfigRef; i: TLineInfo): string {....raises: [],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + 1-based index (matches editor line numbers); 1st line is for i.line = 1 last valid line is numLines inclusive + Source   +Edit   + +
+
+ +
+
+
+
proc suggestQuit() {....raises: [ESuggestDone], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc suggestWriteln(conf: ConfigRef; s: string) {....raises: [IOError, Exception],
+    tags: [WriteIOEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toCChar(c: char; result: var string) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toColumn(info: TLineInfo): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toFileLineCol(conf: ConfigRef; info: TLineInfo): string {.inline,
+    ...raises: [Exception, KeyError], tags: [RootEffect, ReadDirEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toFilenameOption(conf: ConfigRef; fileIdx: FileIndex; opt: FilenameOption): string {.
+    ...raises: [Exception, KeyError], tags: [RootEffect, ReadDirEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toFullPath(conf: ConfigRef; fileIdx: FileIndex): string {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toFullPathConsiderDirty(conf: ConfigRef; fileIdx: FileIndex): AbsoluteFile {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toLinenumber(info: TLineInfo): int {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toMsgFilename(conf: ConfigRef; fileIdx: FileIndex): string {.
+    ...raises: [Exception, KeyError], tags: [RootEffect, ReadDirEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toProjPath(conf: ConfigRef; fileIdx: FileIndex): string {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc warningDeprecated(conf: ConfigRef; info: TLineInfo = gCmdLineInfo; msg = "") {.
+    inline,
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template fatal(conf: ConfigRef; info: TLineInfo; arg = ""; msg = errFatal)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template globalAssert(conf: ConfigRef; cond: untyped;
+                      info: TLineInfo = unknownLineInfo; arg = "")
+
+ + avoids boilerplate + Source   +Edit   + +
+
+ +
+
+
+
template globalError(conf: ConfigRef; info: TLineInfo; arg: string)
+
+ + + Source   +Edit   + +
+
+
+
template globalError(conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg = "")
+
+ + local means compilation keeps going until errorMax is reached (via doNothing), global means it stops. + Source   +Edit   + +
+
+ +
+
+
+
template instLoc(): InstantiationInfo
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template internalAssert(conf: ConfigRef; e: bool)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template internalError(conf: ConfigRef; errMsg: string)
+
+ + + Source   +Edit   + +
+
+
+
template internalError(conf: ConfigRef; info: TLineInfo; errMsg: string)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template lintReport(conf: ConfigRef; info: TLineInfo; beau, got: string;
+                    extraMsg = "")
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template localError(conf: ConfigRef; info: TLineInfo; arg: string)
+
+ + + Source   +Edit   + +
+
+
+
template localError(conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg = "")
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template message(conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg = "")
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template rawMessage(conf: ConfigRef; msg: TMsgKind; arg: string)
+
+ + + Source   +Edit   + +
+
+
+
template rawMessage(conf: ConfigRef; msg: TMsgKind; args: openArray[string])
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template toFilename(conf: ConfigRef; fileIdx: FileIndex): string
+
+ + + Source   +Edit   + +
+
+
+
template toFilename(conf: ConfigRef; info: TLineInfo): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template toFullPath(conf: ConfigRef; info: TLineInfo): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template toFullPathConsiderDirty(conf: ConfigRef; info: TLineInfo): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template toMsgFilename(conf: ConfigRef; info: TLineInfo): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template toProjPath(conf: ConfigRef; info: TLineInfo): string
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/msgs.idx b/compiler/msgs.idx new file mode 100644 index 0000000000000..da99fafc521af --- /dev/null +++ b/compiler/msgs.idx @@ -0,0 +1,92 @@ +nimTitle msgs msgs.html module msgs 0 +nim InstantiationInfo msgs.html#InstantiationInfo type InstantiationInfo 21 +nim instLoc msgs.html#instLoc.t template instLoc(): InstantiationInfo 22 +nim flushDot msgs.html#flushDot,ConfigRef proc flushDot(conf: ConfigRef) 31 +nim toCChar msgs.html#toCChar,char,string proc toCChar(c: char; result: var string) 40 +nim makeCString msgs.html#makeCString,string proc makeCString(s: string): Rope 51 +nim fileInfoKnown msgs.html#fileInfoKnown,ConfigRef,AbsoluteFile proc fileInfoKnown(conf: ConfigRef; filename: AbsoluteFile): bool 89 +nim fileInfoIdx msgs.html#fileInfoIdx,ConfigRef,AbsoluteFile,bool proc fileInfoIdx(conf: ConfigRef; filename: AbsoluteFile; isKnownFile: var bool): FileIndex 99 +nim fileInfoIdx msgs.html#fileInfoIdx,ConfigRef,AbsoluteFile proc fileInfoIdx(conf: ConfigRef; filename: AbsoluteFile): FileIndex 125 +nim fileInfoIdx msgs.html#fileInfoIdx,ConfigRef,RelativeFile,bool proc fileInfoIdx(conf: ConfigRef; filename: RelativeFile; isKnownFile: var bool): FileIndex 129 +nim fileInfoIdx msgs.html#fileInfoIdx,ConfigRef,RelativeFile proc fileInfoIdx(conf: ConfigRef; filename: RelativeFile): FileIndex 132 +nim newLineInfo msgs.html#newLineInfo,FileIndex,int,int proc newLineInfo(fileInfoIdx: FileIndex; line, col: int): TLineInfo 136 +nim newLineInfo msgs.html#newLineInfo,ConfigRef,AbsoluteFile,int,int proc newLineInfo(conf: ConfigRef; filename: AbsoluteFile; line, col: int): TLineInfo 147 +nim gCmdLineInfo msgs.html#gCmdLineInfo const gCmdLineInfo 150 +nim suggestWriteln msgs.html#suggestWriteln,ConfigRef,string proc suggestWriteln(conf: ConfigRef; s: string) 158 +nim msgQuit msgs.html#msgQuit,int8 proc msgQuit(x: int8) 166 +nim msgQuit msgs.html#msgQuit,string proc msgQuit(x: string) 167 +nim suggestQuit msgs.html#suggestQuit proc suggestQuit() 169 +nim ColOffset msgs.html#ColOffset const ColOffset 186 +nim commandLineDesc msgs.html#commandLineDesc const commandLineDesc 187 +nim getInfoContextLen msgs.html#getInfoContextLen,ConfigRef proc getInfoContextLen(conf: ConfigRef): int 189 +nim setInfoContextLen msgs.html#setInfoContextLen,ConfigRef,int proc setInfoContextLen(conf: ConfigRef; L: int) 190 +nim pushInfoContext msgs.html#pushInfoContext,ConfigRef,TLineInfo,string proc pushInfoContext(conf: ConfigRef; info: TLineInfo; detail: string = "") 192 +nim popInfoContext msgs.html#popInfoContext,ConfigRef proc popInfoContext(conf: ConfigRef) 195 +nim getInfoContext msgs.html#getInfoContext,ConfigRef,int proc getInfoContext(conf: ConfigRef; index: int): TLineInfo 198 +nim toFilename msgs.html#toFilename.t,ConfigRef,FileIndex template toFilename(conf: ConfigRef; fileIdx: FileIndex): string 203 +nim toProjPath msgs.html#toProjPath,ConfigRef,FileIndex proc toProjPath(conf: ConfigRef; fileIdx: FileIndex): string 209 +nim toFullPath msgs.html#toFullPath,ConfigRef,FileIndex proc toFullPath(conf: ConfigRef; fileIdx: FileIndex): string 214 +nim setDirtyFile msgs.html#setDirtyFile,ConfigRef,FileIndex,AbsoluteFile proc setDirtyFile(conf: ConfigRef; fileIdx: FileIndex; filename: AbsoluteFile) 220 +nim setHash msgs.html#setHash,ConfigRef,FileIndex,string proc setHash(conf: ConfigRef; fileIdx: FileIndex; hash: string) 225 +nim getHash msgs.html#getHash,ConfigRef,FileIndex proc getHash(conf: ConfigRef; fileIdx: FileIndex): string 233 +nim toFullPathConsiderDirty msgs.html#toFullPathConsiderDirty,ConfigRef,FileIndex proc toFullPathConsiderDirty(conf: ConfigRef; fileIdx: FileIndex): AbsoluteFile 240 +nim toFilename msgs.html#toFilename.t,ConfigRef,TLineInfo template toFilename(conf: ConfigRef; info: TLineInfo): string 248 +nim toProjPath msgs.html#toProjPath.t,ConfigRef,TLineInfo template toProjPath(conf: ConfigRef; info: TLineInfo): string 251 +nim toFullPath msgs.html#toFullPath.t,ConfigRef,TLineInfo template toFullPath(conf: ConfigRef; info: TLineInfo): string 254 +nim toFullPathConsiderDirty msgs.html#toFullPathConsiderDirty.t,ConfigRef,TLineInfo template toFullPathConsiderDirty(conf: ConfigRef; info: TLineInfo): string 257 +nim toFilenameOption msgs.html#toFilenameOption,ConfigRef,FileIndex,FilenameOption proc toFilenameOption(conf: ConfigRef; fileIdx: FileIndex; opt: FilenameOption): string 260 +nim toMsgFilename msgs.html#toMsgFilename,ConfigRef,FileIndex proc toMsgFilename(conf: ConfigRef; fileIdx: FileIndex): string 282 +nim toMsgFilename msgs.html#toMsgFilename.t,ConfigRef,TLineInfo template toMsgFilename(conf: ConfigRef; info: TLineInfo): string 285 +nim toLinenumber msgs.html#toLinenumber,TLineInfo proc toLinenumber(info: TLineInfo): int 288 +nim toColumn msgs.html#toColumn,TLineInfo proc toColumn(info: TLineInfo): int 291 +nim toFileLineCol msgs.html#toFileLineCol,ConfigRef,TLineInfo proc toFileLineCol(conf: ConfigRef; info: TLineInfo): string 298 +nim `$` msgs.html#$,ConfigRef,TLineInfo proc `$`(conf: ConfigRef; info: TLineInfo): string 302 +nim `$` msgs.html#$,TLineInfo proc `$`(info: TLineInfo): string 304 +nim `??` msgs.html#??,ConfigRef,TLineInfo,string proc `??`(conf: ConfigRef; info: TLineInfo; filename: string): bool 306 +nim msgStdout msgs.html#msgStdout MsgFlag.msgStdout 311 +nim msgSkipHook msgs.html#msgSkipHook MsgFlag.msgSkipHook 311 +nim msgNoUnitSep msgs.html#msgNoUnitSep MsgFlag.msgNoUnitSep 311 +nim MsgFlag msgs.html#MsgFlag enum MsgFlag 311 +nim MsgFlags msgs.html#MsgFlags type MsgFlags 315 +nim msgWriteln msgs.html#msgWriteln,ConfigRef,string,MsgFlags proc msgWriteln(conf: ConfigRef; s: string; flags: MsgFlags = {}) 317 +nim msgKindToString msgs.html#msgKindToString,TMsgKind proc msgKindToString(kind: TMsgKind): string 403 +nim doNothing msgs.html#doNothing TErrorHandling.doNothing 408 +nim doAbort msgs.html#doAbort TErrorHandling.doAbort 408 +nim doRaise msgs.html#doRaise TErrorHandling.doRaise 408 +nim TErrorHandling msgs.html#TErrorHandling enum TErrorHandling 408 +nim log msgs.html#log,string proc log(s: string) 410 +nim `==` msgs.html#==,TLineInfo,TLineInfo proc `==`(a, b: TLineInfo): bool 451 +nim exactEquals msgs.html#exactEquals,TLineInfo,TLineInfo proc exactEquals(a, b: TLineInfo): bool 454 +nim numLines msgs.html#numLines,ConfigRef,FileIndex proc numLines(conf: ConfigRef; fileIdx: FileIndex): int 482 +nim sourceLine msgs.html#sourceLine,ConfigRef,TLineInfo proc sourceLine(conf: ConfigRef; i: TLineInfo): string 494 +nim formatMsg msgs.html#formatMsg,ConfigRef,TLineInfo,TMsgKind,string proc formatMsg(conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg: string): string 513 +nim liMessage msgs.html#liMessage,ConfigRef,TLineInfo,TMsgKind,string,TErrorHandling,InstantiationInfo proc liMessage(conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg: string;\n eh: TErrorHandling; info2: InstantiationInfo; isRaw = false;\n ignoreError = false) 520 +nim rawMessage msgs.html#rawMessage.t,ConfigRef,TMsgKind,openArray[string] template rawMessage(conf: ConfigRef; msg: TMsgKind; args: openArray[string]) 594 +nim rawMessage msgs.html#rawMessage.t,ConfigRef,TMsgKind,string template rawMessage(conf: ConfigRef; msg: TMsgKind; arg: string) 598 +nim fatal msgs.html#fatal.t,ConfigRef,TLineInfo,string template fatal(conf: ConfigRef; info: TLineInfo; arg = ""; msg = errFatal) 601 +nim globalAssert msgs.html#globalAssert.t,ConfigRef,untyped,TLineInfo,string template globalAssert(conf: ConfigRef; cond: untyped; info: TLineInfo = unknownLineInfo;\n arg = "") 604 +nim globalError msgs.html#globalError.t,ConfigRef,TLineInfo,TMsgKind,string template globalError(conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg = "") 611 +nim globalError msgs.html#globalError.t,ConfigRef,TLineInfo,string template globalError(conf: ConfigRef; info: TLineInfo; arg: string) 616 +nim localError msgs.html#localError.t,ConfigRef,TLineInfo,TMsgKind,string template localError(conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg = "") 619 +nim localError msgs.html#localError.t,ConfigRef,TLineInfo,string template localError(conf: ConfigRef; info: TLineInfo; arg: string) 622 +nim message msgs.html#message.t,ConfigRef,TLineInfo,TMsgKind,string template message(conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg = "") 625 +nim warningDeprecated msgs.html#warningDeprecated,ConfigRef,TLineInfo,string proc warningDeprecated(conf: ConfigRef; info: TLineInfo = gCmdLineInfo; msg = "") 628 +nim internalError msgs.html#internalError.t,ConfigRef,TLineInfo,string template internalError(conf: ConfigRef; info: TLineInfo; errMsg: string) 636 +nim internalError msgs.html#internalError.t,ConfigRef,string template internalError(conf: ConfigRef; errMsg: string) 639 +nim internalAssert msgs.html#internalAssert.t,ConfigRef,bool template internalAssert(conf: ConfigRef; e: bool) 642 +nim lintReport msgs.html#lintReport.t,ConfigRef,TLineInfo,string,string,string template lintReport(conf: ConfigRef; info: TLineInfo; beau, got: string; extraMsg = "") 649 +nim quotedFilename msgs.html#quotedFilename,ConfigRef,FileIndex proc quotedFilename(conf: ConfigRef; fi: FileIndex): Rope 654 +nim quotedFilename msgs.html#quotedFilename,ConfigRef,TLineInfo proc quotedFilename(conf: ConfigRef; i: TLineInfo): Rope 662 +nim listWarnings msgs.html#listWarnings,ConfigRef proc listWarnings(conf: ConfigRef) 669 +nim listHints msgs.html#listHints,ConfigRef proc listHints(conf: ConfigRef) 670 +nim genSuccessX msgs.html#genSuccessX,ConfigRef proc genSuccessX(conf: ConfigRef) 672 +nimgrp $ msgs.html#$-procs-all proc 302 +nimgrp newlineinfo msgs.html#newLineInfo-procs-all proc 136 +nimgrp quotedfilename msgs.html#quotedFilename-procs-all proc 654 +nimgrp fileinfoidx msgs.html#fileInfoIdx-procs-all proc 99 +nimgrp msgquit msgs.html#msgQuit-procs-all proc 166 +nimgrp tofilename msgs.html#toFilename-templates-all template 203 +nimgrp internalerror msgs.html#internalError-templates-all template 636 +nimgrp globalerror msgs.html#globalError-templates-all template 611 +nimgrp rawmessage msgs.html#rawMessage-templates-all template 594 +nimgrp localerror msgs.html#localError-templates-all template 619 diff --git a/compiler/nilcheck.html b/compiler/nilcheck.html new file mode 100644 index 0000000000000..216574ba752ed --- /dev/null +++ b/compiler/nilcheck.html @@ -0,0 +1,348 @@ + + + + + + + +nilcheck + + + + + + + + + + + + + + + + +
+
+

nilcheck

+
+ +
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
Nilability = enum
+  Parent, Safe, MaybeNil, Nil, Unreachable
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `$`(a: ExprIndex): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `$`(a: SetIndex): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `+`(a: ExprIndex; b: ExprIndex): ExprIndex {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `+`(a: SetIndex; b: SetIndex): SetIndex {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `-`(a: ExprIndex; b: ExprIndex): ExprIndex {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `-`(a: SetIndex; b: SetIndex): SetIndex {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `<`(a: ExprIndex; b: ExprIndex): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `<=`(a: ExprIndex; b: ExprIndex): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `==`(a: ExprIndex; b: ExprIndex): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `==`(a: SetIndex; b: SetIndex): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `>`(a: ExprIndex; b: ExprIndex): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `>=`(a: ExprIndex; b: ExprIndex): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc add[T, U](a: var SeqOfDistinct[T, U]; value: U)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc checkNil(s: PSym; body: PNode; conf: ConfigRef; idgen: IdGenerator) {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/nilcheck.idx b/compiler/nilcheck.idx new file mode 100644 index 0000000000000..6a6390162fac1 --- /dev/null +++ b/compiler/nilcheck.idx @@ -0,0 +1,25 @@ +nimTitle nilcheck nilcheck.html module nilcheck 0 +nim add nilcheck.html#add,SeqOfDistinct[T,U],U proc add[T, U](a: var SeqOfDistinct[T, U]; value: U) 109 +nim Parent nilcheck.html#Parent Nilability.Parent 166 +nim Safe nilcheck.html#Safe Nilability.Safe 166 +nim MaybeNil nilcheck.html#MaybeNil Nilability.MaybeNil 166 +nim Nil nilcheck.html#Nil Nilability.Nil 166 +nim Unreachable nilcheck.html#Unreachable Nilability.Unreachable 166 +nim Nilability nilcheck.html#Nilability enum Nilability 166 +nim `<` nilcheck.html#<,ExprIndex,ExprIndex proc `<`(a: ExprIndex; b: ExprIndex): bool 180 +nim `<=` nilcheck.html#<=,ExprIndex,ExprIndex proc `<=`(a: ExprIndex; b: ExprIndex): bool 183 +nim `>` nilcheck.html#>,ExprIndex,ExprIndex proc `>`(a: ExprIndex; b: ExprIndex): bool 186 +nim `>=` nilcheck.html#>=,ExprIndex,ExprIndex proc `>=`(a: ExprIndex; b: ExprIndex): bool 189 +nim `==` nilcheck.html#==,ExprIndex,ExprIndex proc `==`(a: ExprIndex; b: ExprIndex): bool 192 +nim `$` nilcheck.html#$,ExprIndex proc `$`(a: ExprIndex): string 195 +nim `+` nilcheck.html#+,ExprIndex,ExprIndex proc `+`(a: ExprIndex; b: ExprIndex): ExprIndex 198 +nim `-` nilcheck.html#-,ExprIndex,ExprIndex proc `-`(a: ExprIndex; b: ExprIndex): ExprIndex 202 +nim `$` nilcheck.html#$,SetIndex proc `$`(a: SetIndex): string 205 +nim `==` nilcheck.html#==,SetIndex,SetIndex proc `==`(a: SetIndex; b: SetIndex): bool 208 +nim `+` nilcheck.html#+,SetIndex,SetIndex proc `+`(a: SetIndex; b: SetIndex): SetIndex 211 +nim `-` nilcheck.html#-,SetIndex,SetIndex proc `-`(a: SetIndex; b: SetIndex): SetIndex 215 +nim checkNil nilcheck.html#checkNil,PSym,PNode,ConfigRef,IdGenerator proc checkNil(s: PSym; body: PNode; conf: ConfigRef; idgen: IdGenerator) 1355 +nimgrp == nilcheck.html#==-procs-all proc 192 +nimgrp + nilcheck.html#+-procs-all proc 198 +nimgrp - nilcheck.html#--procs-all proc 202 +nimgrp $ nilcheck.html#$-procs-all proc 195 diff --git a/compiler/nim.html b/compiler/nim.html new file mode 100644 index 0000000000000..591d2b8a77c44 --- /dev/null +++ b/compiler/nim.html @@ -0,0 +1,88 @@ + + + + + + + +nim + + + + + + + + + + + + + + + + +
+
+

nim

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+ +
+ + +
+
+ + + + diff --git a/compiler/nim.idx b/compiler/nim.idx new file mode 100644 index 0000000000000..ae6a04ba5054e --- /dev/null +++ b/compiler/nim.idx @@ -0,0 +1 @@ +nimTitle nim nim.html module nim 0 diff --git a/compiler/nimblecmd.html b/compiler/nimblecmd.html new file mode 100644 index 0000000000000..036a57eeec847 --- /dev/null +++ b/compiler/nimblecmd.html @@ -0,0 +1,258 @@ + + + + + + + +nimblecmd + + + + + + + + + + + + + + + + +
+
+

nimblecmd

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Implements some helper procs for Nimble (Nim's package manager) support.

+ +
+

Types

+
+
+
Version = distinct string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(ver: Version): string {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `<`(ver: Version; ver2: Version): bool {....raises: [ValueError], tags: [],
+    forbids: [].}
+
+ + This is synced from Nimble's version module. + Source   +Edit   + +
+
+ +
+
+
+
proc addPackage(conf: ConfigRef; packages: var PackageInfo; p: string;
+                info: TLineInfo) {....raises: [ValueError, Exception, KeyError,
+    IOError, ERecoverableError], tags: [RootEffect, ReadDirEffect,
+                                        WriteIOEffect, ReadIOEffect,
+                                        ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addPath(conf: ConfigRef; path: AbsoluteDir; info: TLineInfo) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getPathVersionChecksum(p: string): tuple[name, version, checksum: string] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Splits path p in the format /home/user/.nimble/pkgs/package-0.1-febadeaea2345e777f0f6f8433f7f0a52edd5d1b into ("/home/user/.nimble/pkgs/package", "0.1", "febadeaea2345e777f0f6f8433f7f0a52edd5d1b") + Source   +Edit   + +
+
+ +
+
+
+
proc newVersion(ver: string): Version {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nimblePath(conf: ConfigRef; path: AbsoluteDir; info: TLineInfo) {....raises: [
+    OSError, ValueError, Exception, KeyError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/nimblecmd.idx b/compiler/nimblecmd.idx new file mode 100644 index 0000000000000..b7e3e543dc7b7 --- /dev/null +++ b/compiler/nimblecmd.idx @@ -0,0 +1,9 @@ +nimTitle nimblecmd nimblecmd.html module nimblecmd 0 +nim addPath nimblecmd.html#addPath,ConfigRef,AbsoluteDir,TLineInfo proc addPath(conf: ConfigRef; path: AbsoluteDir; info: TLineInfo) 21 +nim Version nimblecmd.html#Version type Version 26 +nim `$` nimblecmd.html#$,Version proc `$`(ver: Version): string 29 +nim newVersion nimblecmd.html#newVersion,string proc newVersion(ver: string): Version 31 +nim `<` nimblecmd.html#<,Version,Version proc `<`(ver: Version; ver2: Version): bool 48 +nim getPathVersionChecksum nimblecmd.html#getPathVersionChecksum,string proc getPathVersionChecksum(p: string): tuple[name, version, checksum: string] 77 +nim addPackage nimblecmd.html#addPackage,ConfigRef,PackageInfo,string,TLineInfo proc addPackage(conf: ConfigRef; packages: var PackageInfo; p: string;\n info: TLineInfo) 114 +nim nimblePath nimblecmd.html#nimblePath,ConfigRef,AbsoluteDir,TLineInfo proc nimblePath(conf: ConfigRef; path: AbsoluteDir; info: TLineInfo) 165 diff --git a/compiler/nimconf.html b/compiler/nimconf.html new file mode 100644 index 0000000000000..b06eb7cb74ba9 --- /dev/null +++ b/compiler/nimconf.html @@ -0,0 +1,182 @@ + + + + + + + +nimconf + + + + + + + + + + + + + + + + +
+
+

nimconf

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc getSystemConfigPath(conf: ConfigRef; filename: RelativeFile): AbsoluteFile {.
+    ...raises: [OSError], tags: [ReadIOEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getUserConfigPath(filename: RelativeFile): AbsoluteFile {.
+    ...raises: [OSError], tags: [ReadEnvEffect, ReadIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc loadConfigs(cfg: RelativeFile; cache: IdentCache; conf: ConfigRef;
+                 idgen: IdGenerator) {....raises: [OSError, IOError, Exception,
+    KeyError, ValueError, ERecoverableError, EOFError, ESuggestDone], tags: [
+    ReadIOEffect, ReadDirEffect, ReadEnvEffect, RootEffect, WriteIOEffect,
+    WriteEnvEffect, WriteDirEffect, TimeEffect, ExecIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc readConfigFile(filename: AbsoluteFile; cache: IdentCache; config: ConfigRef): bool {....raises: [
+    IOError, Exception, KeyError, ValueError, ERecoverableError, OSError,
+    EOFError], tags: [ReadIOEffect, RootEffect, ReadDirEffect, WriteIOEffect,
+                      ReadEnvEffect, WriteEnvEffect, WriteDirEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/nimconf.idx b/compiler/nimconf.idx new file mode 100644 index 0000000000000..f7825e9d4593a --- /dev/null +++ b/compiler/nimconf.idx @@ -0,0 +1,5 @@ +nimTitle nimconf nimconf.html module nimconf 0 +nim readConfigFile nimconf.html#readConfigFile,AbsoluteFile,IdentCache,ConfigRef proc readConfigFile(filename: AbsoluteFile; cache: IdentCache; config: ConfigRef): bool 217 +nim getUserConfigPath nimconf.html#getUserConfigPath,RelativeFile proc getUserConfigPath(filename: RelativeFile): AbsoluteFile 236 +nim getSystemConfigPath nimconf.html#getSystemConfigPath,ConfigRef,RelativeFile proc getSystemConfigPath(conf: ConfigRef; filename: RelativeFile): AbsoluteFile 239 +nim loadConfigs nimconf.html#loadConfigs,RelativeFile,IdentCache,ConfigRef,IdGenerator proc loadConfigs(cfg: RelativeFile; cache: IdentCache; conf: ConfigRef;\n idgen: IdGenerator) 248 diff --git a/compiler/nimdoc.out.css b/compiler/nimdoc.out.css new file mode 100644 index 0000000000000..0c399e4c19193 --- /dev/null +++ b/compiler/nimdoc.out.css @@ -0,0 +1,1036 @@ +/* +Stylesheet for use with Docutils/rst2html. + +See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to +customize this style sheet. + +Modified from Chad Skeeters' rst2html-style +https://bitbucket.org/cskeeters/rst2html-style/ + +Modified by Boyd Greenfield and narimiran +*/ + +:root { + --primary-background: #fff; + --secondary-background: ghostwhite; + --third-background: #e8e8e8; + --info-background: #50c050; + --warning-background: #c0a000; + --error-background: #e04040; + --border: #dde; + --text: #222; + --anchor: #07b; + --anchor-focus: #607c9f; + --input-focus: #1fa0eb; + --strong: #3c3c3c; + --hint: #9A9A9A; + --nim-sprite-base64: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAN4AAAA9CAYAAADCt9ebAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFFmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxNDggNzkuMTY0MDM2LCAyMDE5LzA4LzEzLTAxOjA2OjU3ICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgeG1sbnM6cGhvdG9zaG9wPSJodHRwOi8vbnMuYWRvYmUuY29tL3Bob3Rvc2hvcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RFdnQ9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZUV2ZW50IyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgMjEuMCAoV2luZG93cykiIHhtcDpDcmVhdGVEYXRlPSIyMDE5LTEyLTAzVDAxOjAzOjQ4KzAxOjAwIiB4bXA6TW9kaWZ5RGF0ZT0iMjAxOS0xMi0wM1QwMjoyODo0MSswMTowMCIgeG1wOk1ldGFkYXRhRGF0ZT0iMjAxOS0xMi0wM1QwMjoyODo0MSswMTowMCIgZGM6Zm9ybWF0PSJpbWFnZS9wbmciIHBob3Rvc2hvcDpDb2xvck1vZGU9IjMiIHBob3Rvc2hvcDpJQ0NQcm9maWxlPSJzUkdCIElFQzYxOTY2LTIuMSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDozMzM0ZjAxYS0yMDExLWE1NGQtOTVjNy1iOTgxMDFlMDFhMmEiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MzMzNGYwMWEtMjAxMS1hNTRkLTk1YzctYjk4MTAxZTAxYTJhIiB4bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ9InhtcC5kaWQ6MzMzNGYwMWEtMjAxMS1hNTRkLTk1YzctYjk4MTAxZTAxYTJhIj4gPHhtcE1NOkhpc3Rvcnk+IDxyZGY6U2VxPiA8cmRmOmxpIHN0RXZ0OmFjdGlvbj0iY3JlYXRlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDozMzM0ZjAxYS0yMDExLWE1NGQtOTVjNy1iOTgxMDFlMDFhMmEiIHN0RXZ0OndoZW49IjIwMTktMTItMDNUMDE6MDM6NDgrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyMS4wIChXaW5kb3dzKSIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4PsixkAAAJ5klEQVR4nO2dfbBUZR3HP3vvxVD0zo0ACXxBuQMoQjJ1DfMl0NIhNcuSZqQhfGt6UWtK06xJexkrmywVRTQlHCIdtclC0zBJvYIvvEUgZpc3XyC7RVbKlQu1/fHdbc+uu2fPOfs85+y55/nMnBl2z+5zfnc5v/M8z+8119XVRYroAG4HfgvMT1YUR4MMAa4HLkhakCRoSVqAELwLeBY4C7gF+D6QS1QiR1ROAJ4Dzk9akKQwoXhtwL4GxvHjU8AKoNPz3leAu4HBFq+bAyZZHD9rDAK+BywDDklYlkQxoXhfAtYAEw2MVckQYBHwU6or99nA08BBFq49GngUeBIYaWH8rNEJdAOXA60Jy5I4jSreSOBKYDzwBPCJhiUqcSjwe2BWnc9NLnxuvMFrnwqsAqYBBwBfNzh2FpmNfs9jkhakWcg1aFxZiH5UL3cDnwf+Xue7BwFjgFHAOwuv24tyob3cO0LIshP4EbCn8Pq/wKvA9sLxMvCvOmPsA1yDZnHv/nEv2mM+F0IeR4m8z7lM7tMbUbzj0CxX7YfbAXwaWFJ4PRrNIu9FS9KJyEIZN68CG4DnkRJtLBw7gHHAYuDdNb77EDAjBhkHIk7xKoiqeK3IwjilzuceQJvoZjdQ/AMZaeoZiWYgBXSEwyleBW0Rv3cR9ZUO4LSI48fN2wN+bi5wJNBvUZaBSCaVy48oxpVhwDdMC5ISxpJRh6/DLGEUrxXt29YBQ+2IkwquR76ofZIWxJFegireNLSnm48skFmmDfmiVgJHJyuKI620ADOpbWEcDPwYOZKD7OmyxCTkXL+wzueOiEEWR8poQb60V4A7kLm/yFjgKeALuM1xLfYDbkX+zEGe98cAX0Oui6viF8vR7OS6urragW2UZr21wK+Aiwlu7XPoN3sYOAd4H6WH1SnA0qSEcjQnRT/e1bgnsw16kGPez4/lyCBF48oNwL+TFGSAsgCndI4qFBVvJ0owdZhjL3CnxfHzBo8+YBMyol0CHBijrKbHS/LoA7Yio9sPgJNr/QHekLGR6MffL+KP4SjnHmQxtoXNmbQP+CHyV75hYDzTIWNpWkU8iR5mq71vVsZqXgtcFqNQ/wG2IOtfD8oi6AX+Ujj+isKz8sBrnu+1okyGdmD/wnEgcDClTIdRyJRvI1cvCMciq7At4rj5eoCPAusbHCfLigda/VyKgi+AtyreMGAzykGzQQ/wO+BxSlkCuy1dq8hw5OieUjimYT+x9bHCdWwS1823Ez1EXmhgjKwrXpHzkduuanbCtzGX+NkPPAj8GincNkPjNkIO5dadUjiOB95m+BonopQpm8R58/0JJbHWy2eshVM8sRvdbyurKV4Hmoka2WA/iwwLP6d+QmzSdKC92GzK/W9R+Q3woQbHCELcN991wJcjftcpXolngKm18vFmoVonYcgDv0Qz5pqGREuOTuA8lPYUZbndh0LJNpkUqgZx33xvomim7RG+6xSvnOm1gqQXoyiMoKxFs8VZpFfpQHvQK4HDUPnAsBa9bxGP0tUjF+IYCkxFew+/G3owdq20pgjzt3uPRscs/o43IaOhH2f4ZaAPRyZQP6vgbuCbyGext87F0sgIZFI/N8BnlwBnolovcWAjq/uzwM0+55cBJ0UYN84ZL+rfbnLMM4FfUDv7Z1XlCe8FetETbleNL7+CZrnvMjCVDuTOOA84Hf+96ga0PC8qXY50FQsuMg+41+d8p885R4n7gdt8zo+qvDkmUF4fZQXwEbS+99KDMhlWkw0eALqQglXyDDCdcovf+4lv5jPNXJ9zWc/FDMMdPudGVCreRlTWwVtWbynwYVQQCFSp61Q042WJLUjB1nneuw8tvXo97x1Lugvg+j1Mo9boySLVHtJFWqsthx5GlbSGeN5bigrHdqPl52Zj4qWLXvTQWY4KOX2ccgPMBLRcuy9+0YzhguXN4GuYq2Zc2R/NZg+hfYt3/9ZCepdQthmB4vIWIYOTbWyWzGt2Y0izG1fqjlltxnsdpbPMRMmd3lqTTumqMw7FZY5G5mSHw5dalreiRWYGWjbZ7gYUlFa0xOtIWA4vk1E6zWEoI+FvyYrjSAO1FG8DCmQGKd+DJFsGogWVVFiP/GWbga9Svg9NgtPQvnd04fUNCcriSBF+vqZ5nn9PQ+Xs4q401oI6EP0R+BkyXoAeAtcgBfwidnvkVaMVFTO6n1JoWTfqiONw1MVP8e6l3GVwOPJZXW5VItGGiuduAu5CZdOrMQJ1CHqpIFccS+LxaD/3Hcr7vF0Xw7UdAwQ/xduLGkJ6aUMhVAuwU006B3wM+ZLmozJ5QRhWkGs9yjKw1fhwDsq8eE/F+y+i1CeHIxD1wppupXrA5xyUOjQHMzU3cyjTeS2aaaN2Fzoc1bhch3xspuqBTkDulQVUz1q4mYEbNuewQD3FexGFS1VjOLoRHwOOinj9HAooXY2CSidHHKeSI5GFcRWNdSxqR7VH1iHHeTV24R+X53C8hSCBvPPqnD8B+AOygn6OYAm0ORSGthLl8B0d4DtRmIKsoMsJF1U/Hi1dt6DusIN8PrsIlUdwOAITpDFlC6q3MTbgmHm011qGepOvQSXPipyOCujW6rxqk0dRWYsVFe8PRSn5JxWOoEvdfOGzfnF5tnCRK+bGi33MoB1hL0U5d1H5J5oVD6A5mp8sQS6KSWh5e0jEcR4BPmhKqJA4xTM3XuxjBlW8DuRacDU3y0myNbNTPHPjxT5m0GTN15A/zVFiI+HKYzgc/ydMlrRfgmQWuYn0F91xJEQYxVuDnMcOrQAWJi2EI72ErQviwqLEQpQ+5XBEIqzi3YWLwF+BMiMcjshEqYR1Gdk1KmxBsaR9SQviSDdRFK8fxVU+YliWZmcbcq7vSFoQR/qJWvuxD0WgLDYoSzPzAqowtjVhORwDhEaKru4GPoliGgcyy4Hj0DLT4TBCo9WO88jQ8Bns97lLghvRTOfqqDiMYqrM+HyUYdBtaLykeRmlK12C9rQOh1FM1vd/HqUIzaT5e+LVoh/VxByHShs6HFaw0VjjHhTxP5d0LT+fRnu5q3HuAodlbHW02Q5cDByM+sw1642cRylCx6PeZiuTFScUFxK+f19QovaRS+t4tsasxhvABbZbSfUCV6CM7qtQl6Fm4E1U22UqcAYqvZ42fgJMxH6vdYc5nkBlSW6Pq4fbS6hb6jg0u9yGug7FyS5U1+UcVBbwbFSuMM1sQ1bXK4A9CcviqM0e9H80HdUxCpwIa4McygA/GfgAcCJqmGKKXUixupEv7nHsLc2agWNQ0d9OzC+PHNHIo1XeLCoe8kkqXiUtwKFoWXoEKqk3BpWLaC8cXsV8HT1J+tFTZKvn+DMqFZi1knvtyKg1O2lBHADcCVxEedNSAP4HJcsr0NNWHVUAAAAASUVORK5CYII="); + + --keyword: #5e8f60; + --identifier: #222; + --comment: #484a86; + --operator: #155da4; + --punctuation: black; + --other: black; + --escapeSequence: #c4891b; + --number: #252dbe; + --literal: #a4255b; + --program: #6060c0; + --option: #508000; + --raw-data: #a4255b; + + --clipboard-image-normal: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='color: black' fill='none' viewBox='0 0 24 24' stroke='currentColor'%3E %3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2' /%3E %3C/svg%3E"); + --clipboard-image-selected: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='color: black' viewBox='0 0 20 20' fill='currentColor'%3E %3Cpath d='M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z' /%3E %3Cpath d='M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z' /%3E %3C/svg%3E"); + --clipboard-image: var(--clipboard-image-normal) +} + +[data-theme="dark"] { + --primary-background: #171921; + --secondary-background: #1e202a; + --third-background: #2b2e3b; + --info-background: #008000; + --warning-background: #807000; + --error-background: #c03000; + --border: #0e1014; + --text: #fff; + --anchor: #8be9fd; + --anchor-focus: #8be9fd; + --input-focus: #8be9fd; + --strong: #bd93f9; + --hint: #7A7C85; + --nim-sprite-base64: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAARMAAABMCAYAAABOBlMuAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFFmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxNDggNzkuMTY0MDM2LCAyMDE5LzA4LzEzLTAxOjA2OjU3ICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgeG1sbnM6cGhvdG9zaG9wPSJodHRwOi8vbnMuYWRvYmUuY29tL3Bob3Rvc2hvcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RFdnQ9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZUV2ZW50IyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgMjEuMCAoV2luZG93cykiIHhtcDpDcmVhdGVEYXRlPSIyMDE5LTEyLTAzVDAxOjE4OjIyKzAxOjAwIiB4bXA6TW9kaWZ5RGF0ZT0iMjAxOS0xMi0wM1QwMToyMDoxMCswMTowMCIgeG1wOk1ldGFkYXRhRGF0ZT0iMjAxOS0xMi0wM1QwMToyMDoxMCswMTowMCIgZGM6Zm9ybWF0PSJpbWFnZS9wbmciIHBob3Rvc2hvcDpDb2xvck1vZGU9IjMiIHBob3Rvc2hvcDpJQ0NQcm9maWxlPSJzUkdCIElFQzYxOTY2LTIuMSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDplZGViMzU3MC1iNmZjLWQyNDQtYTExZi0yMjc5YmY4NDNhYTAiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6ZWRlYjM1NzAtYjZmYy1kMjQ0LWExMWYtMjI3OWJmODQzYWEwIiB4bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ9InhtcC5kaWQ6ZWRlYjM1NzAtYjZmYy1kMjQ0LWExMWYtMjI3OWJmODQzYWEwIj4gPHhtcE1NOkhpc3Rvcnk+IDxyZGY6U2VxPiA8cmRmOmxpIHN0RXZ0OmFjdGlvbj0iY3JlYXRlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDplZGViMzU3MC1iNmZjLWQyNDQtYTExZi0yMjc5YmY4NDNhYTAiIHN0RXZ0OndoZW49IjIwMTktMTItMDNUMDE6MTg6MjIrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyMS4wIChXaW5kb3dzKSIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4JZNR8AAAfG0lEQVR4nO2deViTZ7r/7yxkJaxJ2MK+GCBAMCwS1kgUFQSKK4XWWqsz1jpjp3b0tDP1V+eqU391fqfT/mpPPd20drTFDS0KFEVWJSGAEgLIZpAICBJACIRs549Rj1WILAkBfD/XlevySp68z/0S3+/7vPdzLyidTgcLkU2bd+z39/f/q1gshsrKSoJELFCa2iaEuU9K6kb+8uXxv54/fzE8L/eswNT2zCfQpjbAGKS8lPFKSEjIXiaTCSEhIeDj4xNnapsQ5j6rktZGp6UlfxIdzQVzCplmanvmG1hTG2BIAtlc26CgoDfT0tL2e3l5AQCAjY0NkMnk/a9s2k6rrKw8UV8n1JjYTIQ5RlAw14KzmL3xze1vfJyUuMJaq9UCFovFm9qu+YbBxcSPFUYkk8l2Q0NDsvo6ocrQx5+I8Ih4bz6f/0l8fHyKlZXV4/dRKBQwmcwwMpn8A4FAoPgHhH9bV1sxa488wZxoaycnJ/a9e/duCa5fkc3WvAiTI4Ib77p+XdqHG9anbfLy8gAAgLGxMdBpF+bjvzExqJj4scKI0dHRnwQHB++orq7+AgDeMuTxJ2Jl4rqU9PT0EwEBAUQCgTDuGAaDAampqYepVKpHUHDk325Ulw0a266YuFW+Gzdu/MDPz29jfn7+XgA4aOw5ESZP6kvpCXv3vnM8NiaSamVl+fj9BepGNDoGFRN7e/slcXFxO1xcXMDJyWnH7j//H/fi4uJdgutXmgw5z5O8smn7X9euXbvf29sbMBjMhONQKBRYWVlBbGzsbjMzM3JoOG+/sKKwy1h2rd/4elpGRsYuLy+vaDweD2w2Oy1h5ZrCvEunEaeeiVnMiabyl/F2/+X9P+8JDPQHHA5napMWBAYTk6DgSNuEhIS9DAYDAP7tq1i6dOkqOp3OWbNu0wens44emeoxA9lcWwKBYEMkEm2JRKIdHo+3QKFQWJ1Op8ZgMER3d/dVq1evTnFycpr0MSkUCsTExGzH4/Gk1LTME/39/TI0Go1FoVCg1WrVY2NjipGRkcGRkRH5dPwrEZHLXMPCwjJSUlIy3dzcfB+97+rqGhYSEpIOAIiYmBguN3zL77dt3uPh4W5qUxYUBhMTb2/vjeHh4cvR6P/dILK0tITIyEg7BweHr363/Z3Ampqaf1Zcu/zMKiVsyVJvMplsRyKR7IhEor2FhYUbhUJhJCYm2pFIJB6JRAIymQx4PB7QaDRoNBowMzMDJycnwOOn7icjEokQGxu7icFgbLp///7jFY1WqwWlUgkjIyOgUCgO7Ni5Rz48PCwfHh7uGRkZeaBQKOSjo6ODCoVCXlNVKn/6uCsT13FXrVr1emho6BYKhfLMnP7+/omrU9LPX8g+UThloxEMxqJFXjxESAyPQcSEExrLWLNmzW57e/txP/fw8ABHR8cdDAaDt3xF2ru9vb03sVgs0cbGxs/FxWVZUlISj0aj+dna2oKtrS1M5PcwJCgUCry8vODRrs84vPfoH6OjoyCXy6Gvr+/R6+CWrX9s7evrk/b19bWr1Wqli4sLZ8OGDe95eXmxUSjUuAd0cHDwjoqK2sYKXFIhvnldYYTTQpgU4/8+jyASCYDGoCd+ZkYYF8OICYezl8PhuOkbQyAQIDo62s/NzS2np6cHbGxsgEajAYFAAAwGA1gsFia6CE0NgUAABwcHsLe3B61WC2q1eo9WqwWNRgNKpRLUajUQiUSgUCh6zwGHwwGTydzo5+eXBQBnZu8MEJ5keHhYPqyYWMtHR0ZBpVIhYj9FUDONgOUvT12+du3avMDAQJjssdRqNWCxCyrEZdLodDoQi8Ulx44de628NL/V1Pa8iERE8l2dHB2CJvpcq9Nqbt1qKURWj1Njxld0ZGTkAW9v70kLCQC8sEIC8O/HKx8fn2gmk8kHgCk7pRFmzrWyAikASE1tx0Jj2uH0EZHL/N7YtuvT4OBgzmz4OBYSeDweIiMjt2S++vtMP1YYEmmJsCCY8mNOIJtr6+zsHBcZGXmIw+G4mZubG8m0hU9HRwcUFxe/KxQKTyDRsQjznSmJCS9+dVRERMTfQ0NDo2xtbfUGiSFMjtHRUaitrc3Jzc09kHvxVLmp7UFAmC6oZQkvrZLL5RJhReHtiQb5scKIXC7371FRUX90dnYGIpE4JR8Jgn40Gg20t7fXFxYWfnr9+vWjz8sdYi+Osh4vzgUBwZSgtu94V+fs7Hx7YGCgra6u7khLS0u2RCwYeTQgKmYFh8fj/f/g4OAldnZ2prR1wdPd3Q1CofBQSUnJkdLi3N8E93FCY6k+Pj48FxcXjlar1ZSWlh65VvYr4kREmDNg79+/D3FxcW5OTk5uXl5evNbW1tL0jK3ZXV1d1ykUintycvInoaGhdkj+gvGxs7MDPp+/m0AgWMQvS/lyeHhYTqPRPJycnIJSU1NZ3t7eW2g0Gly/fv2oWq1Gij0hzClQ/gHhpLS0tEM8Hm/7I8Ho7++HlpYWsLa2Bg8PDxOb+OKhUCigqakJ7t+/D25ubuDu7g4oFAp0Oh08ePAAvv7666TTWUdzTG0nAsKTYMU3ryuSU18+4+bmFrZo0SIOAICVlRUsXrx4zkakLnRIJBI8CgJ8MtdJp9NBZ2enqL29XWRC8xAQxgUNAHD+3L8KGhoaCp78ABES04JCoX4jJAAAAwMDUFtbe96YpRMQEKbL41DU5ubmko6Ojj2PSgggzD36+/vrb9y4cX425zzw93/8EBjon2is44+NjSkePBjqGRwc7G5v7xBV19w8U5B/3qgrr9+/uWtXUuKKD/TZ9MXh/066/OuFmunO8dGBQ98HBbGSp/t9U6LRaDXK0dHBoeFhuVzeL22/0yFqamopufjLqRJ933ssJi0tLSXV1dWHGAzGbuObOzs8ubqa71vZKpUKOjo6blwpOF8zm/Mu5cVkLlkSaswprAHAaVihgK7O7oSGxltvfXLon3nXK4RHT2cdN4pfKDCAlZyUuMJan02nTmczAaBmunPw4qI3cbnh0/36XICq0+lgcPABp7OrK629vUP5z8++LLh2XXD05L++yxrvC4/F5EZ12WBS8saLS5Ys2U2lUufUY45SqQSlUgkqlQrUavXj19jYGGg0GtBoNKDT6UCn05VotVq1TqfToFAojFar1eh0Og0Wi8XhcDgeGo1+/PhgZmYGOBwOsFgsmJmZ/eY1F+nt7YXa2trs2Z73wdCQBgCMHp1IJpHA09MdPD3dLRIS+OtKisvWvbP7vf2lZdePVFwzbHTwyMiI3hidkZFRUKvUYzOZ48HQkBIA5nWqBAqFAktLC7C0tADmIh88Pz4uMSyUk7hn776DV4tKPn/6d/lNxp1MJqsRCASf8vn8XdMpOjRTVCoVjI2NgUqlAq1WCyMjI9DX1wf379+Hvr6+/Q8ePOgdGRmRKxSKx0WLFAqFXKlUKnQ6nUar1arHq47mxwrD4/F4Eg6HI2GxWDwej7cgkUjWFAqFam5uTjU3N6eRyeQPLSwswNraGqysrIBAIDwWFywW+zja11Qi29LSclIikeSZZPJZBovBAI8XA8HBQR9kZZ3lR8cmvFZSlGe00p8IkwONRkNERBj4+i7a4+XpHv307/IbMakWlciXJbx0nMPh7Jqo0JGh0el0MDo6Cl1dXSCVSkEmk7177969W319fe1DQ0M9KpVKoVarlWq1WjndNhUPG3ApAWDcOxLTLwSDwWAOotFoDBaLxRMIBAsrKysne3t7Xzqd7k2n0/c4OzsDlUoFHA4364IyMDAATU1NxdWikhcq6tXKyhJezljPJZKI2eERS5cZeoWCMD2srCwhPX0tVzk2djiCG//GtfLLUoBxShB0dHTU3Lx580sLC4vtJBLJKMZoNBqQSqUglUqPdnR01PT09DT19/fLHjx40DM0NNQ72933GiSVGgB4JFQK+LfoSAGgnL04yppEIh2xtLS0t7GxcaFSqR7Ozs4fMRgMcHR0nJX8pJs3b54Ui8UXjT7RHIRMIkFK8irfwcEHPwQELUmqvYHUGJkLmJubw8YNa/i9vfffY/px3myQiDTPiEl9nVDDX576jaenZ7SnpyfLUJNrNBqQyWRw+/bt4x0dHTdkMlltV1dXw/XygjkdEv4wB0YOAK0AUM70C8HQ6fSzdDrdm0qlejg6OrLc3Ny2MBiMadWjfR4PHjyAmzdvZs/1v5MxoVAokJK8iicWS95k+nH+s0EiQhqpzQGoVFtYk5a87ba0XQAA34xbpagg/5zoT7s/OGNnZ8eaaYkBuVwOnZ2d5VKpVNTS0lLS2NhYWFVZ3Dujg5qQh6uY+ocvCAiKIPn4+Jz19PSMdnV15VCpVL6Dg4NBViw6nQ5EItHRpqamqzM+2DzHzo4O69amftLQeKsAZrDLgmBY/PyYsCIhfs+SiKUFE5Y8EwqFx11cXDihoaFTjjFAoVAwPDwMHR0dourq6jNCofDHhZqUVnvjmgIAcgAgJyg40mLRokX8kJCQjT4+PussLS1n1JPl7t27UFxcfHguB6mNjY2B7G4naNRTWyygUCjAYDGAx+PB0sICSCSi3vFYLBbCwjjA8vddBQtATKb7d3saBwc7IJPJBpsHjUGDGRYLJBIJLK0sAfucmyIGg4FFi3y8AwNZtycUk5KiS02vvf7WWQaDkejg4DApQwAeh3xDaWnpPoFAcPxFqnP6sEvgGf+A8Bx3d/cvIyIiNi1evHjT8wpNj8fAwACUlZW9P9dD5+/ckcFbf9gd2dcnn9LNAovF4inmZHtXNxdOdBR3+/JlS33pdP29wolEInA4weuiYxOy5vvuTkeHDHb+8c8xvb33Z3R9/N+Df+uIjYk02DwkEsna2trS1d/fNyGeF7uTyw1/7g3R3t4O2OxA/TVghULhcQqFQk1JSfmYSNR/5wD4d6EfgUBwvLS09IhUKhW9qAV5H9YjKQwJi6uvrKw8ERoamhkSEpKp7w7yJEqlEiQSyZmysrJv53qjdaVSCZdyTk+3qFMrAJRHRPLPN95qeifj5fU7mYt8JhyMRqMhMJDFdnF25gDAvBYTpXIMWlpay2fq/8m5mDcIABYGnEcGAGI/VlhBZWX1yZdSkz55OX0dV5+7w9bGGvz8mPrFpK62QskJjf2GTqd7x8bGbpnID4BCoUAmk0lLSkqOiESik2UleS/MakQflYKrXQDQxY1a3tTe3i6KiIjY5OXlxX7e9+rr6wsuXbr0t4ffn9OgMWjghMZQRcLp+8GulRVI/QPC37Wxtnal0ajJtjY2E451ZjiBra31vE9lR2PQQKFQaAAwo98Yi8Xq9fpPd56HO6rlvKWJv/PwcK+JilyCmajWMw6HAzs7+rMFpQOCIn6zHywSFvXm5eUdFAqFZ9Rq9bgHa2trq79w4cK+zz49cAARkmcpL81v/a/Dhz49d+7c3qqqqjyVSjXuOJ1OBxKJpDw3N/fA5V+zax6978cKw/sHhM/raMrnUVdboSy4fPWQSFSjd5yFBQWIRNKEd2IEw1J4JUd88WL+R51d3XrHWVDMnxUTa2tr1zXrNiUGsrmPf7DS4tymCxcu7Kuurs55+kKQSqVN586d23vs+8NHDXUCC5Wzp3/Iy8rKeruysvLM2Nhvo7VVKhXU1tYWnj17du/T7UOdnZ2D7OzsfGGB09raVi4S1RzXl0eFw+EAj8chYjKLVFffyOrq1C8mJBLpWTFRKBRyDofzC4vFWvXk+1ev/CLOzs7eKxAIslQqFeh0Oujp6enKzs7em/XTd7OayTqfKb56sT4rK+sPAoHg5KO/o0KhAKFQmHXy5MkdF3/5+TeZmctXpIXZ29v7zqVcKWNRX1epuXu3U/y8pEw0GmndOZt0dnXVDw0P6/W5oNHoZ30mQ0NDPb29vfvj4+Pf3rR5B/7od188XnEUXr4gDgmL+0NfX5/U19d3d3l5+YGfTnyDtLmcIhXXLsu4UcvfR6PRGGtra9eysrIjYrE45+kt4Fheou/69es/unnz5vm7d+/Wmsre2WRkZGTQ1DYg/JYGiUiTm1ugBAC9IfHPiEmDpFITE7fqJI/H27lmzZpDq5LWtz55t6wUXO3ihMYerK+vz2tpaUFaM0yT8tL81ujYle+TSCTrvEunBU9/voTLd92wYcPHVCqV39XVdXCu7+oYCp1O90Kc50Jk3I5+xVcv1jc3N5d4enpSMzIyvkpK3sh78nORsKg3++yPBS/q1q+hKCm61DSekERGJ3ikp6d/ERsbm1xVVXWwtbX1hRFtFAqFPMLMUyZsDyoQCI7LZDKIiIjwzczM/GpV0vro2TTsRSUqZoX3+vXrP1u9enXi0NAQiESirIdRtggIc5oJ40zq6uryGhoa8ry8vBJCQ0O9USjU94mrN7yWc+EnvaXb5gJMvxCMp6cnl0Kh2Le1tZVXXLs8L1LXefGrWRkZGZ/x+XyeUqkEkUh0vqenZ14HZyG8OEwoJjdrygd37NxTEBkZmWBtbQ3BwcEeKBTq+/UbX3/355Pfzlmn66qk9dGbN29+k8PhbCSRSNDZ2Snb9ae/HCkpKTksEhbN2QTD5NSX+Vu3bj0cHBzsjcFg4O7du1BWVvbNwxB9BIQ5j94I2Fu3bhXW19cDl8sFLBYLHA7Hg0wmf/e77e84ffXlPz6fLSMnQ2paZkJ4eHjmtm3b+B4eHvZkMhlQKBTY29s72dvbfxgUFJT8x7ffP1NRUfHjXErnZ/qFYKKjo7dt3rz5g8DAQPtH/XHa2tpqGhsbC55/BASEuYFeMblz505NTU3NgfDw8PcwGAygUCjw9fW1IJPJn/1130Hv0tLSI4WXL4hny9inYS+Osvbz80tgMpn8jIwMPovFch2vpoiDgwM4ODhwfH19OYsWLeJv3/Hu+cbGxquzXZz5aZYlvMRJT0/fFhkZue3JZmfd3d0gEolOIr4ShPmEXjFpkFRqXlrzSnFnZ+d7Tk5OjzNfXVxcICMjY6ezszNnVdL6vU8HWhmbgKAIkrOzMyc1NTXz0YU4maAuOp0OK1as4EVFRfGEQqHg1dfePHzr1q2rs71S8WOF4f38/BLS09M/iIyM5DxdxLq5uVlcVVU1bgVwBIS5il4xAQCQyWRigUBwJikpKe3JVGQcDgdLly7l2tranti0ecf7IpEoy9hbxX6sMDydTvdevXr1ltjY2F3u7u6AxT73FJ7B3Nwc4uLiwthsdphQKCzZkL7l0/r6+oKbNeVG90+EhMXZL1++fFtycvKHrq6uz4igUqmE5ubmEiTHCWG+8dwrUXD9imz9xtd/jIuLS7N5KpsTjUZDUFCQE4PB+F4oFGYmJW888Mv5k4UTHGpGxC9LYaenp78VEhKyxdHRESgUyoyOh0KhwNraGuLi4qIDAgKi6+rqyjekb/mHMSN6N6RvSdu+ffseNpsdZm09ftuW+vp6EIvFSB9hhHnHpG7rUqm0orW1tdXS0tLj6TIEaDQaaDQaxMfH811dXTl/3Xfw+JUrVz411J01cfWG6IiIiC07d+5McHNzs7ewMGyOFw6HAwcHB6BSqVx3d/fwz7/4rkAgEBwXCoUnHpZonDGrU9J5MTEx27du3Zrm4uKC0beaqq6u/ry+vj7XEPMiIMwmkxKTimuXZe/u+fCkp6fnexPdUfF4PPj7+1szGIydLi4unF1/+kvenTt3RG1tbRXTqfma8lIG39/fP/HVV19NZrFYHpMpzjQTzMzMwNPTE+Pp6Zng6emZ4Ofnl5CesfV8bW1tznQe3/wDwvFeXl7Rvr6+Ca+88kpaUFCQh74GXzqdDrq7u6GpqankRQmdR1hYTNrhUFVVlcXj8d6ysrKy0OfstLS0hPj4eC6Xy+U2NzeDRCI5/sa2XeX37t1rGhwc7BoYGJBN1P+FFbiE5OzszGaxWImvvvrqpoCAAKfp+ERmCpPJBCaTmcnhcDJLS0u/TE59+YxUKhXoi/lg+oVgrKysGJaWlna2trYeaWlpXDabvTMgIGDSfp2KiorzbW1tL0zoPMLCYtJX6uVfs2u++PKowMPDgz+ZIslEIhECAgKAxWJlajSazJ6eHmhra4PW1tZvtmz9o6Czs7O+r6+vfWxsbFir1WosLCzsV6xYkcnj8d7z9vaelmPV0Hh5eYGnp+f2mJiY7UVFRZ/HL0v5tru7+5ZGo1FisVg8Docj4fF4CxsbG1c+nx/m7e39sYeHB7i4uIC5ufmU6r4ODQ1BZWXlifkSrYuA8DRTumIrKytPent78728vCb9HRQKBVgsFhwcHIBOpwObzd4yNja2RaVSwdDQEHR1dcHo6CjQaDRwdXWdsWPV0KBQKPDw8AA7O7udERERO2tra2FgYACoVCo4OTkBjUYDMpkMeDz+8WuqaLVaaGxsbL19+/YzSX8ICPOFqYrJidDQ0AwvLy/e80c/CwaDARKJBI86BdJoNHB3dwe1Wj0nViL6IJPJwGQywdnZGZRKJRAIBDBUx8OBgQEoLS39BtkORpjPTJg1PB61N64pmpqarvb39xvUiLkuJE9CJpPBxsbGYEICANDZ2SlHgtQQ5jtTEhMAgLq6ulyJRFJvDGNeREZGRkAikRSUFuci2cEI85opi0l+7hmBWCzOeV6dToTJcfv27cHr168jxbgR5j1TFhMAgObm5hKZDNl0MAQtLS3Xzpw6hkS8Isx7piUmUqlUIBAIJuyjgzA5Ojs7QSKRINGuCAuCaYmJsKKw68qVK59KJJIu5HFneiiVSigqKjouEolOmtoWBARDMC0xAQC4+MvPJadOnXq3ra1N8yL0dDEkOp0OSktLy/Pz8w8+3d4CAWG+Mm0xAQA4fuy/jl+8ePGju3fvGsqeBY9Wq4XKysrWU6dOvX31yi8mKyyFgGBoZiQmAAD/79D+fadPn96PCMrz0el0UFVV1frtt9+mj9fiAgFhPjNjMQEAyMvLO3Ds2LE/tLS0INmuerh27Vr9999//xoiJAgLEYOEntbVVigB4PNNm3cMpqSkfMRms50McdyFgkqlgqKiovJTp069nZ97BhEShAWJQePYj373xdF1GzbLFQrFx6Ghob766ne8KNy7dw+KiopO5ubmfmTK4tsICMbG4EkxWT99d35l4rre/v7+D0NCQvh0Ot3QU8wL1Go1SKVSTX5+/sH8/PyDSP8bhIWOUTLsLuVklQcFR65pbGzcvnLlyvfc3NwsCASCMaaac+h0OhgaGoLq6uqaCxcu/OV01tGcTw7uM7VZCAhGx2jpug/vxAd58atzoqKitq1cuXKnvb29saabE+h0Oqiurpbm5eUdrK6uPlspuDrvY0hmO4YIhUIBGq1/X2CmNqFQKL3/79HomZ/z82xEowyy9zFr80zGDqPn/hdeviBmL47ad+fOnRsRERGbQkNDo62srIw97azT2dkJxcXFx0tKSo7Mdh8hY4LD4TDPH2U4MFjMc6tLmZmZzaj+Aw6H0/t9PB4PGCxmRudNJBL0ngeZTAI0Gj3jv+1szfM88Hic8cUEAKCmqlQOAN/ELU2qkEgkySwWK3HRokVcBoMxG9MbDZ1OB83NzdDU1FRQW1t7XiAQHJ+ovu18pbr6Rg6L5ZtoM0EhcUPT0tJW8tWRb0vQqIkvgKqqmhnVfrl2TfANXo+gjKlUio4OWc1M5sjOzjnQUH8rbqLPu3t6moaGhmfc+3q25tGHUqmECoEIUKbIrVkcEkONiIh4jcvlvu7s7OxLo9GmVe7QVCgUCujq6oKGhoaCioqKo9XV1WeM3YDMVPDik1gpyas+XrVyeaKXl8czjyANjbcgI/MNmkg49Q4ECPOH3NyC4RUr+M8IcHt7B1y9WlKRl3/5kElKnD1sfXEoJCzueEBAQGJYWFgGk8nk2djYAIFAgLm4pTw6Ogqjo6Mgl8vhxo0b50tLS4/U19fnLvS2FIWXfxEDQNLmLW9ueW1TxtchHDaQyWRTm4VgYkZHR6G+vhF+/NfP+y5e+vVjiVgwZpKVydOwF0dZW1lZOTGZTD6bzU4LCAiIptPp8HTDL1MwOjoKLS0tUFdXd1IsFudIpdKKgYGB7tloJTrX4MUnsVJTEj9etzY10dHRAQAAGm81wcsZW5CVyQInL69gNCGBjwcAGBx8ANnncypOnTr3H9nn/reD55wovvrQpyIHAHFUzIocGo3mQaPRfBwdHVlubm7bXF1dgcFgABqNNvruglwuh7t374JMJoOOjo7P79y5I+ru7m7q7e1tXQi7MzOh8PIv4pCw2DdaWtte37Au7aPIyCWAxWABjUbPif9HCMbjURtKiaQBfvr5zH9evlJ0uLQ4r/nJMXNiZTIRrMAlJAcHB18HBweWo6Mjy8rKajeJRAJLS0uwtLQECwsLoFAogMfjAYvFgpmZ2XNXMyqVCoaHh2FoaAiGh4cfvwYGBqCvrw+6u7vfvnfvXlNvb29rT09Pq0QsUM7S6c4rNqS/lrZ5U+YPRBKR9M7u9xwqBUUvtNAudH766XSLE8PR49ixE78/8tVnX403Zk7fUR46NUUAIPIPCMdTKJTdNjY2QKPRgE6nA51OB1tbWyCRSIDD4YBAIAAejwcCgfDYUajVakGlUoFarQadTvfY79HX1wf9/f0gl8tBLpfDvXv3HvXw+dxQPYYXMj+d+P7Mmzv+5OHr6/OJWq1GBHeB09TcUiKuq/coKS3/eqIx/wPkiIXC3w6YjAAAAABJRU5ErkJggg=="); + + --keyword: #ff79c6; + --identifier: #f8f8f2; + --comment: #6272a4; + --operator: #ff79c6; + --punctuation: #f8f8f2; + --other: #f8f8f2; + --escapeSequence: #bd93f9; + --number: #bd93f9; + --literal: #f1fa8c; + --program: #9090c0; + --option: #90b010; + --raw-data: #8be9fd; + + --clipboard-image-normal: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='color: lightgray' fill='none' viewBox='0 0 24 24' stroke='currentColor'%3E %3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2' /%3E %3C/svg%3E"); + --clipboard-image-selected: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='color: lightgray' viewBox='0 0 20 20' fill='currentColor'%3E %3Cpath d='M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z' /%3E %3Cpath d='M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z' /%3E %3C/svg%3E"); + --clipboard-image: var(--clipboard-image-normal); +} + +@media (prefers-color-scheme: dark) { + [data-theme="auto"] { + --primary-background: #171921; + --secondary-background: #1e202a; + --third-background: #2b2e3b; + --info-background: #008000; + --warning-background: #807000; + --error-background: #c03000; + --border: #0e1014; + --text: #fff; + --anchor: #8be9fd; + --anchor-focus: #8be9fd; + --input-focus: #8be9fd; + --strong: #bd93f9; + --hint: #7A7C85; + --nim-sprite-base64: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAARMAAABMCAYAAABOBlMuAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFFmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxNDggNzkuMTY0MDM2LCAyMDE5LzA4LzEzLTAxOjA2OjU3ICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgeG1sbnM6cGhvdG9zaG9wPSJodHRwOi8vbnMuYWRvYmUuY29tL3Bob3Rvc2hvcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RFdnQ9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZUV2ZW50IyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgMjEuMCAoV2luZG93cykiIHhtcDpDcmVhdGVEYXRlPSIyMDE5LTEyLTAzVDAxOjE4OjIyKzAxOjAwIiB4bXA6TW9kaWZ5RGF0ZT0iMjAxOS0xMi0wM1QwMToyMDoxMCswMTowMCIgeG1wOk1ldGFkYXRhRGF0ZT0iMjAxOS0xMi0wM1QwMToyMDoxMCswMTowMCIgZGM6Zm9ybWF0PSJpbWFnZS9wbmciIHBob3Rvc2hvcDpDb2xvck1vZGU9IjMiIHBob3Rvc2hvcDpJQ0NQcm9maWxlPSJzUkdCIElFQzYxOTY2LTIuMSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDplZGViMzU3MC1iNmZjLWQyNDQtYTExZi0yMjc5YmY4NDNhYTAiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6ZWRlYjM1NzAtYjZmYy1kMjQ0LWExMWYtMjI3OWJmODQzYWEwIiB4bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ9InhtcC5kaWQ6ZWRlYjM1NzAtYjZmYy1kMjQ0LWExMWYtMjI3OWJmODQzYWEwIj4gPHhtcE1NOkhpc3Rvcnk+IDxyZGY6U2VxPiA8cmRmOmxpIHN0RXZ0OmFjdGlvbj0iY3JlYXRlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDplZGViMzU3MC1iNmZjLWQyNDQtYTExZi0yMjc5YmY4NDNhYTAiIHN0RXZ0OndoZW49IjIwMTktMTItMDNUMDE6MTg6MjIrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyMS4wIChXaW5kb3dzKSIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4JZNR8AAAfG0lEQVR4nO2deViTZ7r/7yxkJaxJ2MK+GCBAMCwS1kgUFQSKK4XWWqsz1jpjp3b0tDP1V+eqU391fqfT/mpPPd20drTFDS0KFEVWJSGAEgLIZpAICBJACIRs549Rj1WILAkBfD/XlevySp68z/0S3+/7vPdzLyidTgcLkU2bd+z39/f/q1gshsrKSoJELFCa2iaEuU9K6kb+8uXxv54/fzE8L/eswNT2zCfQpjbAGKS8lPFKSEjIXiaTCSEhIeDj4xNnapsQ5j6rktZGp6UlfxIdzQVzCplmanvmG1hTG2BIAtlc26CgoDfT0tL2e3l5AQCAjY0NkMnk/a9s2k6rrKw8UV8n1JjYTIQ5RlAw14KzmL3xze1vfJyUuMJaq9UCFovFm9qu+YbBxcSPFUYkk8l2Q0NDsvo6ocrQx5+I8Ih4bz6f/0l8fHyKlZXV4/dRKBQwmcwwMpn8A4FAoPgHhH9bV1sxa488wZxoaycnJ/a9e/duCa5fkc3WvAiTI4Ib77p+XdqHG9anbfLy8gAAgLGxMdBpF+bjvzExqJj4scKI0dHRnwQHB++orq7+AgDeMuTxJ2Jl4rqU9PT0EwEBAUQCgTDuGAaDAampqYepVKpHUHDk325Ulw0a266YuFW+Gzdu/MDPz29jfn7+XgA4aOw5ESZP6kvpCXv3vnM8NiaSamVl+fj9BepGNDoGFRN7e/slcXFxO1xcXMDJyWnH7j//H/fi4uJdgutXmgw5z5O8smn7X9euXbvf29sbMBjMhONQKBRYWVlBbGzsbjMzM3JoOG+/sKKwy1h2rd/4elpGRsYuLy+vaDweD2w2Oy1h5ZrCvEunEaeeiVnMiabyl/F2/+X9P+8JDPQHHA5napMWBAYTk6DgSNuEhIS9DAYDAP7tq1i6dOkqOp3OWbNu0wens44emeoxA9lcWwKBYEMkEm2JRKIdHo+3QKFQWJ1Op8ZgMER3d/dVq1evTnFycpr0MSkUCsTExGzH4/Gk1LTME/39/TI0Go1FoVCg1WrVY2NjipGRkcGRkRH5dPwrEZHLXMPCwjJSUlIy3dzcfB+97+rqGhYSEpIOAIiYmBguN3zL77dt3uPh4W5qUxYUBhMTb2/vjeHh4cvR6P/dILK0tITIyEg7BweHr363/Z3Ampqaf1Zcu/zMKiVsyVJvMplsRyKR7IhEor2FhYUbhUJhJCYm2pFIJB6JRAIymQx4PB7QaDRoNBowMzMDJycnwOOn7icjEokQGxu7icFgbLp///7jFY1WqwWlUgkjIyOgUCgO7Ni5Rz48PCwfHh7uGRkZeaBQKOSjo6ODCoVCXlNVKn/6uCsT13FXrVr1emho6BYKhfLMnP7+/omrU9LPX8g+UThloxEMxqJFXjxESAyPQcSEExrLWLNmzW57e/txP/fw8ABHR8cdDAaDt3xF2ru9vb03sVgs0cbGxs/FxWVZUlISj0aj+dna2oKtrS1M5PcwJCgUCry8vODRrs84vPfoH6OjoyCXy6Gvr+/R6+CWrX9s7evrk/b19bWr1Wqli4sLZ8OGDe95eXmxUSjUuAd0cHDwjoqK2sYKXFIhvnldYYTTQpgU4/8+jyASCYDGoCd+ZkYYF8OICYezl8PhuOkbQyAQIDo62s/NzS2np6cHbGxsgEajAYFAAAwGA1gsFia6CE0NgUAABwcHsLe3B61WC2q1eo9WqwWNRgNKpRLUajUQiUSgUCh6zwGHwwGTydzo5+eXBQBnZu8MEJ5keHhYPqyYWMtHR0ZBpVIhYj9FUDONgOUvT12+du3avMDAQJjssdRqNWCxCyrEZdLodDoQi8Ulx44de628NL/V1Pa8iERE8l2dHB2CJvpcq9Nqbt1qKURWj1Njxld0ZGTkAW9v70kLCQC8sEIC8O/HKx8fn2gmk8kHgCk7pRFmzrWyAikASE1tx0Jj2uH0EZHL/N7YtuvT4OBgzmz4OBYSeDweIiMjt2S++vtMP1YYEmmJsCCY8mNOIJtr6+zsHBcZGXmIw+G4mZubG8m0hU9HRwcUFxe/KxQKTyDRsQjznSmJCS9+dVRERMTfQ0NDo2xtbfUGiSFMjtHRUaitrc3Jzc09kHvxVLmp7UFAmC6oZQkvrZLL5RJhReHtiQb5scKIXC7371FRUX90dnYGIpE4JR8Jgn40Gg20t7fXFxYWfnr9+vWjz8sdYi+Osh4vzgUBwZSgtu94V+fs7Hx7YGCgra6u7khLS0u2RCwYeTQgKmYFh8fj/f/g4OAldnZ2prR1wdPd3Q1CofBQSUnJkdLi3N8E93FCY6k+Pj48FxcXjlar1ZSWlh65VvYr4kREmDNg79+/D3FxcW5OTk5uXl5evNbW1tL0jK3ZXV1d1ykUintycvInoaGhdkj+gvGxs7MDPp+/m0AgWMQvS/lyeHhYTqPRPJycnIJSU1NZ3t7eW2g0Gly/fv2oWq1Gij0hzClQ/gHhpLS0tEM8Hm/7I8Ho7++HlpYWsLa2Bg8PDxOb+OKhUCigqakJ7t+/D25ubuDu7g4oFAp0Oh08ePAAvv7666TTWUdzTG0nAsKTYMU3ryuSU18+4+bmFrZo0SIOAICVlRUsXrx4zkakLnRIJBI8CgJ8MtdJp9NBZ2enqL29XWRC8xAQxgUNAHD+3L8KGhoaCp78ABES04JCoX4jJAAAAwMDUFtbe96YpRMQEKbL41DU5ubmko6Ojj2PSgggzD36+/vrb9y4cX425zzw93/8EBjon2is44+NjSkePBjqGRwc7G5v7xBV19w8U5B/3qgrr9+/uWtXUuKKD/TZ9MXh/066/OuFmunO8dGBQ98HBbGSp/t9U6LRaDXK0dHBoeFhuVzeL22/0yFqamopufjLqRJ933ssJi0tLSXV1dWHGAzGbuObOzs8ubqa71vZKpUKOjo6blwpOF8zm/Mu5cVkLlkSaswprAHAaVihgK7O7oSGxltvfXLon3nXK4RHT2cdN4pfKDCAlZyUuMJan02nTmczAaBmunPw4qI3cbnh0/36XICq0+lgcPABp7OrK629vUP5z8++LLh2XXD05L++yxrvC4/F5EZ12WBS8saLS5Ys2U2lUufUY45SqQSlUgkqlQrUavXj19jYGGg0GtBoNKDT6UCn05VotVq1TqfToFAojFar1eh0Og0Wi8XhcDgeGo1+/PhgZmYGOBwOsFgsmJmZ/eY1F+nt7YXa2trs2Z73wdCQBgCMHp1IJpHA09MdPD3dLRIS+OtKisvWvbP7vf2lZdePVFwzbHTwyMiI3hidkZFRUKvUYzOZ48HQkBIA5nWqBAqFAktLC7C0tADmIh88Pz4uMSyUk7hn776DV4tKPn/6d/lNxp1MJqsRCASf8vn8XdMpOjRTVCoVjI2NgUqlAq1WCyMjI9DX1wf379+Hvr6+/Q8ePOgdGRmRKxSKx0WLFAqFXKlUKnQ6nUar1arHq47mxwrD4/F4Eg6HI2GxWDwej7cgkUjWFAqFam5uTjU3N6eRyeQPLSwswNraGqysrIBAIDwWFywW+zja11Qi29LSclIikeSZZPJZBovBAI8XA8HBQR9kZZ3lR8cmvFZSlGe00p8IkwONRkNERBj4+i7a4+XpHv307/IbMakWlciXJbx0nMPh7Jqo0JGh0el0MDo6Cl1dXSCVSkEmk7177969W319fe1DQ0M9KpVKoVarlWq1WjndNhUPG3ApAWDcOxLTLwSDwWAOotFoDBaLxRMIBAsrKysne3t7Xzqd7k2n0/c4OzsDlUoFHA4364IyMDAATU1NxdWikhcq6tXKyhJezljPJZKI2eERS5cZeoWCMD2srCwhPX0tVzk2djiCG//GtfLLUoBxShB0dHTU3Lx580sLC4vtJBLJKMZoNBqQSqUglUqPdnR01PT09DT19/fLHjx40DM0NNQ72933GiSVGgB4JFQK+LfoSAGgnL04yppEIh2xtLS0t7GxcaFSqR7Ozs4fMRgMcHR0nJX8pJs3b54Ui8UXjT7RHIRMIkFK8irfwcEHPwQELUmqvYHUGJkLmJubw8YNa/i9vfffY/px3myQiDTPiEl9nVDDX576jaenZ7SnpyfLUJNrNBqQyWRw+/bt4x0dHTdkMlltV1dXw/XygjkdEv4wB0YOAK0AUM70C8HQ6fSzdDrdm0qlejg6OrLc3Ny2MBiMadWjfR4PHjyAmzdvZs/1v5MxoVAokJK8iicWS95k+nH+s0EiQhqpzQGoVFtYk5a87ba0XQAA34xbpagg/5zoT7s/OGNnZ8eaaYkBuVwOnZ2d5VKpVNTS0lLS2NhYWFVZ3Dujg5qQh6uY+ocvCAiKIPn4+Jz19PSMdnV15VCpVL6Dg4NBViw6nQ5EItHRpqamqzM+2DzHzo4O69amftLQeKsAZrDLgmBY/PyYsCIhfs+SiKUFE5Y8EwqFx11cXDihoaFTjjFAoVAwPDwMHR0dourq6jNCofDHhZqUVnvjmgIAcgAgJyg40mLRokX8kJCQjT4+PussLS1n1JPl7t27UFxcfHguB6mNjY2B7G4naNRTWyygUCjAYDGAx+PB0sICSCSi3vFYLBbCwjjA8vddBQtATKb7d3saBwc7IJPJBpsHjUGDGRYLJBIJLK0sAfucmyIGg4FFi3y8AwNZtycUk5KiS02vvf7WWQaDkejg4DApQwAeh3xDaWnpPoFAcPxFqnP6sEvgGf+A8Bx3d/cvIyIiNi1evHjT8wpNj8fAwACUlZW9P9dD5+/ckcFbf9gd2dcnn9LNAovF4inmZHtXNxdOdBR3+/JlS33pdP29wolEInA4weuiYxOy5vvuTkeHDHb+8c8xvb33Z3R9/N+Df+uIjYk02DwkEsna2trS1d/fNyGeF7uTyw1/7g3R3t4O2OxA/TVghULhcQqFQk1JSfmYSNR/5wD4d6EfgUBwvLS09IhUKhW9qAV5H9YjKQwJi6uvrKw8ERoamhkSEpKp7w7yJEqlEiQSyZmysrJv53qjdaVSCZdyTk+3qFMrAJRHRPLPN95qeifj5fU7mYt8JhyMRqMhMJDFdnF25gDAvBYTpXIMWlpay2fq/8m5mDcIABYGnEcGAGI/VlhBZWX1yZdSkz55OX0dV5+7w9bGGvz8mPrFpK62QskJjf2GTqd7x8bGbpnID4BCoUAmk0lLSkqOiESik2UleS/MakQflYKrXQDQxY1a3tTe3i6KiIjY5OXlxX7e9+rr6wsuXbr0t4ffn9OgMWjghMZQRcLp+8GulRVI/QPC37Wxtnal0ajJtjY2E451ZjiBra31vE9lR2PQQKFQaAAwo98Yi8Xq9fpPd56HO6rlvKWJv/PwcK+JilyCmajWMw6HAzs7+rMFpQOCIn6zHywSFvXm5eUdFAqFZ9Rq9bgHa2trq79w4cK+zz49cAARkmcpL81v/a/Dhz49d+7c3qqqqjyVSjXuOJ1OBxKJpDw3N/fA5V+zax6978cKw/sHhM/raMrnUVdboSy4fPWQSFSjd5yFBQWIRNKEd2IEw1J4JUd88WL+R51d3XrHWVDMnxUTa2tr1zXrNiUGsrmPf7DS4tymCxcu7Kuurs55+kKQSqVN586d23vs+8NHDXUCC5Wzp3/Iy8rKeruysvLM2Nhvo7VVKhXU1tYWnj17du/T7UOdnZ2D7OzsfGGB09raVi4S1RzXl0eFw+EAj8chYjKLVFffyOrq1C8mJBLpWTFRKBRyDofzC4vFWvXk+1ev/CLOzs7eKxAIslQqFeh0Oujp6enKzs7em/XTd7OayTqfKb56sT4rK+sPAoHg5KO/o0KhAKFQmHXy5MkdF3/5+TeZmctXpIXZ29v7zqVcKWNRX1epuXu3U/y8pEw0GmndOZt0dnXVDw0P6/W5oNHoZ30mQ0NDPb29vfvj4+Pf3rR5B/7od188XnEUXr4gDgmL+0NfX5/U19d3d3l5+YGfTnyDtLmcIhXXLsu4UcvfR6PRGGtra9eysrIjYrE45+kt4Fheou/69es/unnz5vm7d+/Wmsre2WRkZGTQ1DYg/JYGiUiTm1ugBAC9IfHPiEmDpFITE7fqJI/H27lmzZpDq5LWtz55t6wUXO3ihMYerK+vz2tpaUFaM0yT8tL81ujYle+TSCTrvEunBU9/voTLd92wYcPHVCqV39XVdXCu7+oYCp1O90Kc50Jk3I5+xVcv1jc3N5d4enpSMzIyvkpK3sh78nORsKg3++yPBS/q1q+hKCm61DSekERGJ3ikp6d/ERsbm1xVVXWwtbX1hRFtFAqFPMLMUyZsDyoQCI7LZDKIiIjwzczM/GpV0vro2TTsRSUqZoX3+vXrP1u9enXi0NAQiESirIdRtggIc5oJ40zq6uryGhoa8ry8vBJCQ0O9USjU94mrN7yWc+EnvaXb5gJMvxCMp6cnl0Kh2Le1tZVXXLs8L1LXefGrWRkZGZ/x+XyeUqkEkUh0vqenZ14HZyG8OEwoJjdrygd37NxTEBkZmWBtbQ3BwcEeKBTq+/UbX3/355Pfzlmn66qk9dGbN29+k8PhbCSRSNDZ2Snb9ae/HCkpKTksEhbN2QTD5NSX+Vu3bj0cHBzsjcFg4O7du1BWVvbNwxB9BIQ5j94I2Fu3bhXW19cDl8sFLBYLHA7Hg0wmf/e77e84ffXlPz6fLSMnQ2paZkJ4eHjmtm3b+B4eHvZkMhlQKBTY29s72dvbfxgUFJT8x7ffP1NRUfHjXErnZ/qFYKKjo7dt3rz5g8DAQPtH/XHa2tpqGhsbC55/BASEuYFeMblz505NTU3NgfDw8PcwGAygUCjw9fW1IJPJn/1130Hv0tLSI4WXL4hny9inYS+Osvbz80tgMpn8jIwMPovFch2vpoiDgwM4ODhwfH19OYsWLeJv3/Hu+cbGxquzXZz5aZYlvMRJT0/fFhkZue3JZmfd3d0gEolOIr4ShPmEXjFpkFRqXlrzSnFnZ+d7Tk5OjzNfXVxcICMjY6ezszNnVdL6vU8HWhmbgKAIkrOzMyc1NTXz0YU4maAuOp0OK1as4EVFRfGEQqHg1dfePHzr1q2rs71S8WOF4f38/BLS09M/iIyM5DxdxLq5uVlcVVU1bgVwBIS5il4xAQCQyWRigUBwJikpKe3JVGQcDgdLly7l2tranti0ecf7IpEoy9hbxX6sMDydTvdevXr1ltjY2F3u7u6AxT73FJ7B3Nwc4uLiwthsdphQKCzZkL7l0/r6+oKbNeVG90+EhMXZL1++fFtycvKHrq6uz4igUqmE5ubmEiTHCWG+8dwrUXD9imz9xtd/jIuLS7N5KpsTjUZDUFCQE4PB+F4oFGYmJW888Mv5k4UTHGpGxC9LYaenp78VEhKyxdHRESgUyoyOh0KhwNraGuLi4qIDAgKi6+rqyjekb/mHMSN6N6RvSdu+ffseNpsdZm09ftuW+vp6EIvFSB9hhHnHpG7rUqm0orW1tdXS0tLj6TIEaDQaaDQaxMfH811dXTl/3Xfw+JUrVz411J01cfWG6IiIiC07d+5McHNzs7ewMGyOFw6HAwcHB6BSqVx3d/fwz7/4rkAgEBwXCoUnHpZonDGrU9J5MTEx27du3Zrm4uKC0beaqq6u/ry+vj7XEPMiIMwmkxKTimuXZe/u+fCkp6fnexPdUfF4PPj7+1szGIydLi4unF1/+kvenTt3RG1tbRXTqfma8lIG39/fP/HVV19NZrFYHpMpzjQTzMzMwNPTE+Pp6Zng6emZ4Ofnl5CesfV8bW1tznQe3/wDwvFeXl7Rvr6+Ca+88kpaUFCQh74GXzqdDrq7u6GpqankRQmdR1hYTNrhUFVVlcXj8d6ysrKy0OfstLS0hPj4eC6Xy+U2NzeDRCI5/sa2XeX37t1rGhwc7BoYGJBN1P+FFbiE5OzszGaxWImvvvrqpoCAAKfp+ERmCpPJBCaTmcnhcDJLS0u/TE59+YxUKhXoi/lg+oVgrKysGJaWlna2trYeaWlpXDabvTMgIGDSfp2KiorzbW1tL0zoPMLCYtJX6uVfs2u++PKowMPDgz+ZIslEIhECAgKAxWJlajSazJ6eHmhra4PW1tZvtmz9o6Czs7O+r6+vfWxsbFir1WosLCzsV6xYkcnj8d7z9vaelmPV0Hh5eYGnp+f2mJiY7UVFRZ/HL0v5tru7+5ZGo1FisVg8Docj4fF4CxsbG1c+nx/m7e39sYeHB7i4uIC5ufmU6r4ODQ1BZWXlifkSrYuA8DRTumIrKytPent78728vCb9HRQKBVgsFhwcHIBOpwObzd4yNja2RaVSwdDQEHR1dcHo6CjQaDRwdXWdsWPV0KBQKPDw8AA7O7udERERO2tra2FgYACoVCo4OTkBjUYDMpkMeDz+8WuqaLVaaGxsbL19+/YzSX8ICPOFqYrJidDQ0AwvLy/e80c/CwaDARKJBI86BdJoNHB3dwe1Wj0nViL6IJPJwGQywdnZGZRKJRAIBDBUx8OBgQEoLS39BtkORpjPTJg1PB61N64pmpqarvb39xvUiLkuJE9CJpPBxsbGYEICANDZ2SlHgtQQ5jtTEhMAgLq6ulyJRFJvDGNeREZGRkAikRSUFuci2cEI85opi0l+7hmBWCzOeV6dToTJcfv27cHr168jxbgR5j1TFhMAgObm5hKZDNl0MAQtLS3Xzpw6hkS8Isx7piUmUqlUIBAIJuyjgzA5Ojs7QSKRINGuCAuCaYmJsKKw68qVK59KJJIu5HFneiiVSigqKjouEolOmtoWBARDMC0xAQC4+MvPJadOnXq3ra1N8yL0dDEkOp0OSktLy/Pz8w8+3d4CAWG+Mm0xAQA4fuy/jl+8ePGju3fvGsqeBY9Wq4XKysrWU6dOvX31yi8mKyyFgGBoZiQmAAD/79D+fadPn96PCMrz0el0UFVV1frtt9+mj9fiAgFhPjNjMQEAyMvLO3Ds2LE/tLS0INmuerh27Vr9999//xoiJAgLEYOEntbVVigB4PNNm3cMpqSkfMRms50McdyFgkqlgqKiovJTp069nZ97BhEShAWJQePYj373xdF1GzbLFQrFx6Ghob766ne8KNy7dw+KiopO5ubmfmTK4tsICMbG4EkxWT99d35l4rre/v7+D0NCQvh0Ot3QU8wL1Go1SKVSTX5+/sH8/PyDSP8bhIWOUTLsLuVklQcFR65pbGzcvnLlyvfc3NwsCASCMaaac+h0OhgaGoLq6uqaCxcu/OV01tGcTw7uM7VZCAhGx2jpug/vxAd58atzoqKitq1cuXKnvb29saabE+h0Oqiurpbm5eUdrK6uPlspuDrvY0hmO4YIhUIBGq1/X2CmNqFQKL3/79HomZ/z82xEowyy9zFr80zGDqPn/hdeviBmL47ad+fOnRsRERGbQkNDo62srIw97azT2dkJxcXFx0tKSo7Mdh8hY4LD4TDPH2U4MFjMc6tLmZmZzaj+Aw6H0/t9PB4PGCxmRudNJBL0ngeZTAI0Gj3jv+1szfM88Hic8cUEAKCmqlQOAN/ELU2qkEgkySwWK3HRokVcBoMxG9MbDZ1OB83NzdDU1FRQW1t7XiAQHJ+ovu18pbr6Rg6L5ZtoM0EhcUPT0tJW8tWRb0vQqIkvgKqqmhnVfrl2TfANXo+gjKlUio4OWc1M5sjOzjnQUH8rbqLPu3t6moaGhmfc+3q25tGHUqmECoEIUKbIrVkcEkONiIh4jcvlvu7s7OxLo9GmVe7QVCgUCujq6oKGhoaCioqKo9XV1WeM3YDMVPDik1gpyas+XrVyeaKXl8czjyANjbcgI/MNmkg49Q4ECPOH3NyC4RUr+M8IcHt7B1y9WlKRl3/5kElKnD1sfXEoJCzueEBAQGJYWFgGk8nk2djYAIFAgLm4pTw6Ogqjo6Mgl8vhxo0b50tLS4/U19fnLvS2FIWXfxEDQNLmLW9ueW1TxtchHDaQyWRTm4VgYkZHR6G+vhF+/NfP+y5e+vVjiVgwZpKVydOwF0dZW1lZOTGZTD6bzU4LCAiIptPp8HTDL1MwOjoKLS0tUFdXd1IsFudIpdKKgYGB7tloJTrX4MUnsVJTEj9etzY10dHRAQAAGm81wcsZW5CVyQInL69gNCGBjwcAGBx8ANnncypOnTr3H9nn/reD55wovvrQpyIHAHFUzIocGo3mQaPRfBwdHVlubm7bXF1dgcFgABqNNvruglwuh7t374JMJoOOjo7P79y5I+ru7m7q7e1tXQi7MzOh8PIv4pCw2DdaWtte37Au7aPIyCWAxWABjUbPif9HCMbjURtKiaQBfvr5zH9evlJ0uLQ4r/nJMXNiZTIRrMAlJAcHB18HBweWo6Mjy8rKajeJRAJLS0uwtLQECwsLoFAogMfjAYvFgpmZ2XNXMyqVCoaHh2FoaAiGh4cfvwYGBqCvrw+6u7vfvnfvXlNvb29rT09Pq0QsUM7S6c4rNqS/lrZ5U+YPRBKR9M7u9xwqBUUvtNAudH766XSLE8PR49ixE78/8tVnX403Zk7fUR46NUUAIPIPCMdTKJTdNjY2QKPRgE6nA51OB1tbWyCRSIDD4YBAIAAejwcCgfDYUajVakGlUoFarQadTvfY79HX1wf9/f0gl8tBLpfDvXv3HvXw+dxQPYYXMj+d+P7Mmzv+5OHr6/OJWq1GBHeB09TcUiKuq/coKS3/eqIx/wPkiIXC3w6YjAAAAABJRU5ErkJggg=="); + + --keyword: #ff79c6; + --identifier: #f8f8f2; + --comment: #6272a4; + --operator: #ff79c6; + --punctuation: #f8f8f2; + --other: #f8f8f2; + --escapeSequence: #bd93f9; + --number: #bd93f9; + --literal: #f1fa8c; + --program: #9090c0; + --option: #90b010; + --raw-data: #8be9fd; + + --clipboard-image-normal: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='color: lightgray' fill='none' viewBox='0 0 24 24' stroke='currentColor'%3E %3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2' /%3E %3C/svg%3E"); + --clipboard-image-selected: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='color: lightgray' viewBox='0 0 20 20' fill='currentColor'%3E %3Cpath d='M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z' /%3E %3Cpath d='M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z' /%3E %3C/svg%3E"); + --clipboard-image: var(--clipboard-image-normal); + } +} + +.theme-select-wrapper { + display: flex; + align-items: center; +} + +html { + font-size: 100%; + -webkit-text-size-adjust: 100%; + -ms-text-size-adjust: 100%; } + +body { + font-family: "Lato", "Helvetica Neue", "HelveticaNeue", Helvetica, Arial, sans-serif; + font-weight: 400; + font-size: 1.125em; + line-height: 1.5; + color: var(--text); + background-color: var(--primary-background); } + +/* Skeleton grid */ +.container { + position: relative; + width: 100%; + max-width: 1050px; + margin: 0 auto; + padding: 0; + box-sizing: border-box; } + +.column, .columns { + width: 100%; + float: left; + box-sizing: border-box; + margin-left: 1%; } + +@media print { + #global-links, .link-seesrc, .theme-switch-wrapper, #searchInputDiv, .search-groupby { + display:none; + } + .columns { + width:100% !important; + } +} + +.column:first-child, .columns:first-child { + margin-left: 0; } + +.container .row { + display: flex; } + +.three.columns { + width: 25.0%; + height: 100vh; + position: sticky; + top: 0px; + overflow-y: auto; + padding: 2px; +} + +.nine.columns { + width: 75.0%; + padding-left: 1.5em; } + +.twelve.columns { + width: 100%; + margin-left: 0; } + +@media screen and (max-width: 860px) { + .three.columns { + display: none; + } + .nine.columns { + width: 98.0%; + } + body { + font-size: 1em; + line-height: 1.35; + } +} + +cite { + font-style: italic !important; } + + +/* Nim search input */ +div#searchInputDiv { + margin-bottom: 1em; +} +input#searchInput { + width: 80%; +} + +/* + * Some custom formatting for input forms. + * This also fixes input form colors on Firefox with a dark system theme on Linux. + */ +input { + -moz-appearance: none; + background-color: var(--secondary-background); + color: var(--text); + border: 1px solid var(--border); + font-family: "Lato", "Helvetica Neue", "HelveticaNeue", Helvetica, Arial, sans-serif; + font-size: 0.9em; + padding: 6px; +} + +input:focus { + border: 1px solid var(--input-focus); + box-shadow: 0 0 3px var(--input-focus); +} + +select { + -moz-appearance: none; + background-color: var(--secondary-background); + color: var(--text); + border: 1px solid var(--border); + font-family: "Lato", "Helvetica Neue", "HelveticaNeue", Helvetica, Arial, sans-serif; + font-size: 0.9em; + padding: 6px; +} + +select:focus { + border: 1px solid var(--input-focus); + box-shadow: 0 0 3px var(--input-focus); +} + +/* Docgen styles */ + +:target { + border: 2px solid #B5651D; + border-style: dotted; +} + +/* Links */ +a { + color: var(--anchor); + text-decoration: none; +} + +a span.Identifier { + text-decoration: underline; + text-decoration-color: #aab; +} + +a.reference-toplevel { + font-weight: bold; +} + +a.nimdoc { + word-spacing: 0.3em; +} + +a.toc-backref { + text-decoration: none; + color: var(--text); +} + +a.link-seesrc { + color: #607c9f; + font-size: 0.9em; + font-style: italic; +} + +a:hover, a:focus { + color: var(--anchor-focus); + text-decoration: underline; +} + +a:hover span.Identifier { + color: var(--anchor); +} + + +sub, sup { + position: relative; + font-size: 75%; + line-height: 0; + vertical-align: baseline; } + +sup { + top: -0.5em; } + +sub { + bottom: -0.25em; } + +img { + width: auto; + height: auto; + max-width: 100%; + vertical-align: middle; + border: 0; + -ms-interpolation-mode: bicubic; } + +@media print { + * { + color: black !important; + text-shadow: none !important; + background: transparent !important; + box-shadow: none !important; } + + a, a:visited { + text-decoration: underline; } + + a[href]:after { + content: " (" attr(href) ")"; } + + abbr[title]:after { + content: " (" attr(title) ")"; } + + .ir a:after, + a[href^="javascript:"]:after, + a[href^="#"]:after { + content: ""; } + + pre, blockquote { + border: 1px solid #999; + page-break-inside: avoid; } + + thead { + display: table-header-group; } + + tr, img { + page-break-inside: avoid; } + + img { + max-width: 100% !important; } + + @page { + margin: 0.5cm; } + + h1 { + page-break-before: always; } + + h1.title { + page-break-before: avoid; } + + p, h2, h3 { + orphans: 3; + widows: 3; } + + h2, h3 { + page-break-after: avoid; } +} + + +p { + margin-top: 0.5em; + margin-bottom: 0.5em; } + +small { + font-size: 85%; } + +strong { + font-weight: 600; + font-size: 0.95em; + color: var(--strong); } + +em { + font-style: italic; } + +h1 { + font-size: 1.8em; + font-weight: 400; + padding-bottom: .25em; + border-bottom: 6px solid var(--third-background); + margin-top: 2.5em; + margin-bottom: 1em; + line-height: 1.2em; } + +h1.title { + padding-bottom: 1em; + border-bottom: 0px; + font-size: 2.5em; + text-align: center; + font-weight: 900; + margin-top: 0.75em; + margin-bottom: 0em; } + +h2 { + font-size: 1.3em; + margin-top: 2em; } + +h2.subtitle { + margin-top: 0em; + text-align: center; } + +h3 { + font-size: 1.125em; + font-style: italic; + margin-top: 1.5em; } + +h4 { + font-size: 1.125em; + margin-top: 1em; } + +h5 { + font-size: 1.125em; + margin-top: 0.75em; } + +h6 { + font-size: 1.1em; } + + +ul, ol { + padding: 0; + margin-top: 0.5em; + margin-left: 0.75em; } + +ul ul, ul ol, ol ol, ol ul { + margin-bottom: 0; + margin-left: 1.25em; } + +ul.simple > li { + list-style-type: circle; } + +ul.simple-boot li { + list-style-type: none; + margin-left: 0em; + margin-bottom: 0.5em; } + +ol.simple > li, ul.simple > li { + margin-bottom: 0.2em; + margin-left: 0.4em } + +ul.simple.simple-toc > li { + margin-top: 1em; } + +ul.simple-toc { + list-style: none; + font-size: 0.9em; + margin-left: -0.3em; + margin-top: 1em; } + +ul.simple-toc > li { + list-style-type: none; } + +ul.simple-toc-section { + list-style-type: circle; + margin-left: 0.8em; + color: #6c9aae; } + +ul.nested-toc-section { + list-style-type: circle; + margin-left: -0.75em; + color: var(--text); } + +ul.nested-toc-section > li { + margin-left: 1.25em; } + + +ol.arabic { + list-style: decimal; } + +ol.loweralpha { + list-style: lower-alpha; } + +ol.upperalpha { + list-style: upper-alpha; } + +ol.lowerroman { + list-style: lower-roman; } + +ol.upperroman { + list-style: upper-roman; } + +ul.auto-toc { + list-style-type: none; } + + +dl { + margin-bottom: 1.5em; } + +dt { + margin-bottom: -0.5em; + margin-left: 0.0em; } + +dd { + margin-left: 2.0em; + margin-bottom: 3.0em; + margin-top: 0.5em; } + + +hr { + margin: 2em 0; + border: 0; + border-top: 1px solid #aaa; } + +hr.footnote { + width: 25%; + border-top: 0.15em solid #999; + margin-bottom: 0.15em; + margin-top: 0.15em; +} +div.footnote-group { + margin-left: 1em; +} +div.footnote-label { + display: inline-block; + min-width: 1.7em; +} + +div.option-list { + border: 0.1em solid var(--border); +} +div.option-list-item { + padding-left: 12em; + padding-right: 0; + padding-bottom: 0.3em; + padding-top: 0.3em; +} +div.odd { + background-color: var(--secondary-background); +} +div.option-list-label { + margin-left: -11.5em; + margin-right: 0em; + min-width: 11.5em; + display: inline-block; + vertical-align: top; +} +div.option-list-description { + width: calc(100% - 1em); + padding-left: 1em; + padding-right: 0; + display: inline-block; +} + +blockquote { + font-size: 0.9em; + font-style: italic; + padding-left: 0.5em; + margin-left: 0; + border-left: 5px solid #bbc; +} + +blockquote.markdown-quote { + font-size: 0.9rem; /* use rem to avoid recursion */ + font-style: normal; +} + +.pre, span.tok { + font-family: "Source Code Pro", Monaco, Menlo, Consolas, "Courier New", monospace; + font-weight: 500; + font-size: 0.85em; + color: var(--text); + background-color: var(--third-background); + padding-left: 3px; + padding-right: 3px; + border-radius: 4px; +} + +span.tok { + border: 1px solid #808080; + padding-bottom: 0.1em; + margin-right: 0.2em; +} + +.copyToClipBoard { + position: relative; +} + +pre { + font-family: "Source Code Pro", Monaco, Menlo, Consolas, "Courier New", monospace; + color: var(--text); + font-weight: 500; + display: inline-block; + box-sizing: border-box; + min-width: 100%; + padding: 0.5em; + margin-top: 0.5em; + margin-bottom: 0.5em; + font-size: 0.85em; + white-space: pre !important; + overflow-y: hidden; + overflow-x: visible; + background-color: var(--secondary-background); + border: 1px solid var(--border); + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} + +.copyToClipBoardBtn { + visibility: hidden; + position: absolute; + width: 24px; + border-radius: 4px; + background-image: var(--clipboard-image); + right: 5px; + top: 13px; + background-color: var(--secondary-background); + padding: 11px; + border: 0; +} + +.copyToClipBoard:hover .copyToClipBoardBtn { + visibility: visible; +} + +.pre-scrollable { + max-height: 340px; + overflow-y: scroll; } + + +/* Nim line-numbered tables */ +.line-nums-table { + width: 100%; + table-layout: fixed; } + +table.line-nums-table { + border-radius: 4px; + border: 1px solid var(--border); + background-color: var(--secondary-background); + border-collapse: separate; + margin-top: 15px; + margin-bottom: 25px; } + +.line-nums-table tbody { + border: none; } + +.line-nums-table td pre { + border: none; + background-color: transparent; } + +.line-nums-table td.blob-line-nums { + width: 28px; } + +.line-nums-table td.blob-line-nums pre { + color: #b0b0b0; + -webkit-filter: opacity(75%); + filter: opacity(75%); + text-align: right; + border-color: transparent; + background-color: transparent; + padding-left: 0px; + margin-left: 0px; + padding-right: 0px; + margin-right: 0px; } + + +table { + max-width: 100%; + background-color: transparent; + margin-top: 0.5em; + margin-bottom: 1.5em; + border-collapse: collapse; + border-color: var(--third-background); + border-spacing: 0; +} + +table:not(.line-nums-table) { + font-size: 0.9em; +} + +table th, table td { + padding: 0px 0.5em 0px; + border-color: var(--third-background); +} + +table th { + background-color: var(--third-background); + border-color: var(--third-background); + font-weight: bold; } + +table th.docinfo-name { + background-color: transparent; + text-align: right; +} + +table:not(.line-nums-table) tr:hover { + background-color: var(--third-background); } + + +/* rst2html default used to remove borders from tables and images */ +.borderless, table.borderless td, table.borderless th { + border: 0; } + +table.borderless td, table.borderless th { + /* Override padding for "table.docutils td" with "! important". + The right padding separates the table cells. */ + padding: 0 0.5em 0 0 !important; } + +.admonition { + padding: 0.3em; + background-color: var(--secondary-background); + border-left: 0.4em solid #7f7f84; + margin-bottom: 0.5em; + -webkit-box-shadow: 0 5px 8px -6px rgba(0,0,0,.2); + -moz-box-shadow: 0 5px 8px -6px rgba(0,0,0,.2); + box-shadow: 0 5px 8px -6px rgba(0,0,0,.2); +} +.admonition-info { + border-color: var(--info-background); +} +.admonition-info-text { + color: var(--info-background); +} +.admonition-warning { + border-color: var(--warning-background); +} +.admonition-warning-text { + color: var(--warning-background); +} +.admonition-error { + border-color: var(--error-background); +} +.admonition-error-text { + color: var(--error-background); +} + +.first { + /* Override more specific margin styles with "! important". */ + margin-top: 0 !important; } + +.last, .with-subtitle { + margin-bottom: 0 !important; } + +.hidden { + display: none; } + +blockquote.epigraph { + margin: 2em 5em; } + +dl.docutils dd { + margin-bottom: 0.5em; } + +object[type="image/svg+xml"], object[type="application/x-shockwave-flash"] { + overflow: hidden; } + + +div.figure { + margin-left: 2em; + margin-right: 2em; } + +div.footer, div.header { + clear: both; + text-align: center; + color: #666; + font-size: smaller; } + +div.footer { + padding-top: 5em; } + +div.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; } + +div.line-block div.line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; } + +div.topic { + margin: 2em; } + +div.search_results { + background-color: var(--third-background); + margin: 3vh 5vw; + padding: 1em; + border: 1px solid #4d4d4d; + position: fixed; + top: 10px; + isolation: isolate; + max-width: calc(100vw - 6em); + z-index: 1; + max-height: calc(100vh - 6em); + overflow-y: scroll;} + +div#global-links ul { + margin-left: 0; + list-style-type: none; } + +div#global-links > simple-boot { + margin-left: 3em; } + +hr.docutils { + width: 75%; } + +img.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; } + +img.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; } + +img.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; } + +.align-left { + text-align: left; } + +.align-center { + clear: both; + text-align: center; } + +.align-right { + text-align: right; } + +/* reset inner alignment in figures */ +div.align-right { + text-align: inherit; } + +p.attribution { + text-align: right; + margin-left: 50%; } + +p.caption { + font-style: italic; } + +p.credits { + font-style: italic; + font-size: smaller; } + +p.label { + white-space: nowrap; } + +p.rubric { + font-weight: bold; + font-size: larger; + color: maroon; + text-align: center; } + +p.topic-title { + font-weight: bold; } + +pre.address { + margin-bottom: 0; + margin-top: 0; + font: inherit; } + +pre.literal-block, pre.doctest-block, pre.math, pre.code { + margin-left: 2em; + margin-right: 2em; } + +pre.code .ln { + color: grey; } + +/* line numbers */ +pre.code, code { + background-color: #eeeeee; } + +pre.code .comment, code .comment { + color: #5c6576; } + +pre.code .keyword, code .keyword { + color: #3B0D06; + font-weight: bold; } + +pre.code .literal.string, code .literal.string { + color: #0c5404; } + +pre.code .name.builtin, code .name.builtin { + color: #352b84; } + +pre.code .deleted, code .deleted { + background-color: #DEB0A1; } + +pre.code .inserted, code .inserted { + background-color: #A3D289; } + +span.classifier { + font-style: oblique; } + +span.classifier-delimiter { + font-weight: bold; } + +span.problematic { + color: #b30000; } + +span.section-subtitle { + /* font-size relative to parent (h1..h6 element) */ + font-size: 80%; } + +span.DecNumber { + color: var(--number); } + +span.BinNumber { + color: var(--number); } + +span.HexNumber { + color: var(--number); } + +span.OctNumber { + color: var(--number); } + +span.FloatNumber { + color: var(--number); } + +span.Identifier { + color: var(--identifier); } + +span.Keyword { + font-weight: 600; + color: var(--keyword); } + +span.StringLit { + color: var(--literal); } + +span.LongStringLit { + color: var(--literal); } + +span.CharLit { + color: var(--literal); } + +span.EscapeSequence { + color: var(--escapeSequence); } + +span.Operator { + color: var(--operator); } + +span.Punctuation { + color: var(--punctuation); } + +span.Comment, span.LongComment { + font-style: italic; + font-weight: 400; + color: var(--comment); } + +span.RegularExpression { + color: darkviolet; } + +span.TagStart { + color: darkviolet; } + +span.TagEnd { + color: darkviolet; } + +span.Key { + color: #252dbe; } + +span.Value { + color: #252dbe; } + +span.RawData { + color: var(--raw-data); } + +span.Assembler { + color: #252dbe; } + +span.Preprocessor { + color: #252dbe; } + +span.Directive { + color: #252dbe; } + +span.option { + font-weight: bold; + font-family: "Source Code Pro", Monaco, Menlo, Consolas, "Courier New", monospace; + color: var(--option); } + +span.Prompt { + font-weight: bold; + color: red; } + +span.ProgramOutput { + font-weight: bold; + color: #808080; } + +span.program { + font-weight: bold; + color: var(--program); + text-decoration: underline; + text-decoration-color: var(--hint); + text-decoration-thickness: 0.05em; + text-underline-offset: 0.15em; } + +span.Command, span.Rule, span.Hyperlink, +span.Label, span.Reference, span.Other { + color: var(--other); } + +/* Pop type, const, proc, and iterator defs in nim def blocks */ +dt pre > span.Identifier, dt pre > span.Operator { + color: var(--identifier); + font-weight: 700; } + +dt pre > span.Keyword ~ span.Identifier, dt pre > span.Identifier ~ span.Identifier, +dt pre > span.Operator ~ span.Identifier, dt pre > span.Other ~ span.Identifier { + color: var(--identifier); + font-weight: inherit; } + +/* Nim sprite for the footer (taken from main page favicon) */ +.nim-sprite { + display: inline-block; + width: 51px; + height: 14px; + background-position: 0 0; + background-size: 51px 14px; + -webkit-filter: opacity(50%); + filter: opacity(50%); + background-repeat: no-repeat; + background-image: var(--nim-sprite-base64); + margin-bottom: 5px; } + +span.pragmadots { + /* Position: relative frees us up to make the dots + look really nice without fucking up the layout and + causing bulging in the parent container */ + position: relative; + /* 1px down looks slightly nicer */ + top: 1px; + padding: 2px; + background-color: var(--third-background); + border-radius: 4px; + margin: 0 2px; + cursor: pointer; + font-size: 0.8em; } + +span.pragmadots:hover { + background-color: var(--hint); } + +span.pragmawrap { + display: none; } + +span.attachedType { + display: none; + visibility: hidden; } diff --git a/compiler/nimlexbase.html b/compiler/nimlexbase.html new file mode 100644 index 0000000000000..2223d4dada9db --- /dev/null +++ b/compiler/nimlexbase.html @@ -0,0 +1,395 @@ + + + + + + + +nimlexbase + + + + + + + + + + + + + + + + +
+
+

nimlexbase

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ llstream +
+
+
+

Types

+
+
+
TBaseLexer = object of RootObj
+  bufpos*: int
+  buf*: cstring
+  stream*: PLLStream
+  lineNumber*: int
+  sentinel*: int
+  lineStart*: int
+  offsetBase*: int
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
Apo = '\''
+
+ + + Source   +Edit   + +
+
+
+
BACKSPACE = '\b'
+
+ + + Source   +Edit   + +
+
+
+
BEL = '\a'
+
+ + + Source   +Edit   + +
+
+
+
CR = '\r'
+
+ + + Source   +Edit   + +
+
+
+
EndOfFile = '\x00'
+
+ + + Source   +Edit   + +
+
+
+
ESC = '\e'
+
+ + + Source   +Edit   + +
+
+
+
FF = '\f'
+
+ + + Source   +Edit   + +
+
+
+
LF = '\n'
+
+ + + Source   +Edit   + +
+
+
+
Lrz = ' '
+
+ + + Source   +Edit   + +
+
+
+
NewLines = {'\r', '\n'}
+
+ + + Source   +Edit   + +
+
+
+
Tabulator = '\t'
+
+ + + Source   +Edit   + +
+
+
+
VT = '\v'
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc closeBaseLexer(L: var TBaseLexer) {....raises: [IOError], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getColNumber(L: TBaseLexer; pos: int): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getCurrentLine(L: TBaseLexer; marker: bool = true): string {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc handleCR(L: var TBaseLexer; pos: int): int {....raises: [IOError, Exception],
+    tags: [ReadIOEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc handleLF(L: var TBaseLexer; pos: int): int {....raises: [IOError, Exception],
+    tags: [ReadIOEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc openBaseLexer(L: var TBaseLexer; inputstream: PLLStream; bufLen: int = 8192) {.
+    ...raises: [IOError, Exception], tags: [ReadIOEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/nimlexbase.idx b/compiler/nimlexbase.idx new file mode 100644 index 0000000000000..82d070de8018f --- /dev/null +++ b/compiler/nimlexbase.idx @@ -0,0 +1,20 @@ +nimTitle nimlexbase nimlexbase.html module nimlexbase 0 +nim Lrz nimlexbase.html#Lrz const Lrz 23 +nim Apo nimlexbase.html#Apo const Apo 24 +nim Tabulator nimlexbase.html#Tabulator const Tabulator 25 +nim ESC nimlexbase.html#ESC const ESC 26 +nim CR nimlexbase.html#CR const CR 27 +nim FF nimlexbase.html#FF const FF 28 +nim LF nimlexbase.html#LF const LF 29 +nim BEL nimlexbase.html#BEL const BEL 30 +nim BACKSPACE nimlexbase.html#BACKSPACE const BACKSPACE 31 +nim VT nimlexbase.html#VT const VT 32 +nim EndOfFile nimlexbase.html#EndOfFile const EndOfFile 35 +nim NewLines nimlexbase.html#NewLines const NewLines 41 +nim TBaseLexer nimlexbase.html#TBaseLexer object TBaseLexer 44 +nim openBaseLexer nimlexbase.html#openBaseLexer,TBaseLexer,PLLStream,int proc openBaseLexer(L: var TBaseLexer; inputstream: PLLStream; bufLen: int = 8192) 57 +nim closeBaseLexer nimlexbase.html#closeBaseLexer,TBaseLexer proc closeBaseLexer(L: var TBaseLexer) 60 +nim getCurrentLine nimlexbase.html#getCurrentLine,TBaseLexer,bool proc getCurrentLine(L: TBaseLexer; marker: bool = true): string 61 +nim getColNumber nimlexbase.html#getColNumber,TBaseLexer,int proc getColNumber(L: TBaseLexer; pos: int): int 62 +nim handleCR nimlexbase.html#handleCR,TBaseLexer,int proc handleCR(L: var TBaseLexer; pos: int): int 63 +nim handleLF nimlexbase.html#handleLF,TBaseLexer,int proc handleLF(L: var TBaseLexer; pos: int): int 67 diff --git a/compiler/nimpaths.html b/compiler/nimpaths.html new file mode 100644 index 0000000000000..deeedf52e5bf1 --- /dev/null +++ b/compiler/nimpaths.html @@ -0,0 +1,262 @@ + + + + + + + +nimpaths + + + + + + + + + + + + + + + + +
+
+

nimpaths

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Represents absolute paths, but using a symbolic variables (eg $nimr) which can be resolved at runtime; this avoids hardcoding at compile time absolute paths so that the project root can be relocated.

+

xxx factor pending https://github.com/timotheecour/Nim/issues/616, see also $nim/testament/lib/stdtest/specialpaths.nim specialpaths is simpler because it doesn't need variables to be relocatable at runtime (eg for use in testament)

+
interpolation variables:
+
$nimr: such that $nimr/lib/system.nim exists (avoids confusion with $nim binary) in compiler, it's obtainable via getPrefixDir(); for other tools (eg koch),
+
+
this could be getCurrentDir() or getAppFilename().parentDir.parentDir,
+depending on use case
+

Unstable API

+

+
+

Consts

+
+
+
docCls = "$nimr/doc/nimdoc.cls"
+
+ + + Source   +Edit   + +
+
+
+
docCss = "$nimr/doc/nimdoc.css"
+
+ + + Source   +Edit   + +
+
+
+
docHackJs = "$nimr/tools/dochack/dochack.js"
+
+ + + Source   +Edit   + +
+
+
+
docHackJsFname = "dochack.js"
+
+ + + Source   +Edit   + +
+
+
+
docHackNim = "$nimr/tools/dochack/dochack.nim"
+
+ + + Source   +Edit   + +
+
+
+
dotdotMangle = "_._"
+
+ + refs #13223 + Source   +Edit   + +
+
+
+
htmldocsDirname = "htmldocs"
+
+ + + Source   +Edit   + +
+
+
+
nimdocOutCls = "nimdoc.cls"
+
+ + + Source   +Edit   + +
+
+
+
nimdocOutCss = "nimdoc.out.css"
+
+ + + Source   +Edit   + +
+
+
+
theindexFname = "theindex.html"
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc getDocHacksJs(nimr: string; nim = getCurrentCompilerExe();
+                   forceRebuild = false): string {....raises: [ValueError],
+    tags: [ReadDirEffect, ExecIOEffect], forbids: [].}
+
+ + return absolute path to dochack.js, rebuilding if it doesn't exist or if forceRebuild. + Source   +Edit   + +
+
+ +
+
+
+
proc interp(path: string; nimr: string): string {....raises: [ValueError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/nimpaths.idx b/compiler/nimpaths.idx new file mode 100644 index 0000000000000..6c77a53c3a26a --- /dev/null +++ b/compiler/nimpaths.idx @@ -0,0 +1,13 @@ +nimTitle nimpaths nimpaths.html module nimpaths 0 +nim docCss nimpaths.html#docCss const docCss 27 +nim docCls nimpaths.html#docCls const docCls 28 +nim docHackNim nimpaths.html#docHackNim const docHackNim 29 +nim docHackJs nimpaths.html#docHackJs const docHackJs 30 +nim docHackJsFname nimpaths.html#docHackJsFname const docHackJsFname 31 +nim theindexFname nimpaths.html#theindexFname const theindexFname 32 +nim nimdocOutCss nimpaths.html#nimdocOutCss const nimdocOutCss 33 +nim nimdocOutCls nimpaths.html#nimdocOutCls const nimdocOutCls 34 +nim htmldocsDirname nimpaths.html#htmldocsDirname const htmldocsDirname 36 +nim dotdotMangle nimpaths.html#dotdotMangle const dotdotMangle 37 +nim interp nimpaths.html#interp,string,string proc interp(path: string; nimr: string): string 41 +nim getDocHacksJs nimpaths.html#getDocHacksJs,string proc getDocHacksJs(nimr: string; nim = getCurrentCompilerExe(); forceRebuild = false): string 45 diff --git a/compiler/nimsets.html b/compiler/nimsets.html new file mode 100644 index 0000000000000..c6c891be9c102 --- /dev/null +++ b/compiler/nimsets.html @@ -0,0 +1,411 @@ + + + + + + + +nimsets + + + + + + + + + + + + + + + + +
+
+

nimsets

+
+ +
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc cardSet(conf: ConfigRef; a: PNode): BiggestInt {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc complement(conf: ConfigRef; a: PNode): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc containsSets(conf: ConfigRef; a, b: PNode): bool {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc deduplicate(conf: ConfigRef; a: PNode): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc diffSets(conf: ConfigRef; a, b: PNode): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc emptyRange(a, b: PNode): bool {....raises: [ERecoverableError], tags: [],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc equalSets(conf: ConfigRef; a, b: PNode): bool {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inSet(s: PNode; elem: PNode): bool {....raises: [ERecoverableError], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc intersectSets(conf: ConfigRef; a, b: PNode): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc overlap(a, b: PNode): bool {....raises: [ERecoverableError], tags: [],
+                                  forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setHasRange(s: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc someInSet(s: PNode; a, b: PNode): bool {....raises: [ERecoverableError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc symdiffSets(conf: ConfigRef; a, b: PNode): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toBitSet(conf: ConfigRef; s: PNode): TBitSet {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toTreeSet(conf: ConfigRef; s: TBitSet; settype: PType; info: TLineInfo): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc unionSets(conf: ConfigRef; a, b: PNode): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/nimsets.idx b/compiler/nimsets.idx new file mode 100644 index 0000000000000..4dfd55b027cd1 --- /dev/null +++ b/compiler/nimsets.idx @@ -0,0 +1,17 @@ +nimTitle nimsets nimsets.html module nimsets 0 +nim inSet nimsets.html#inSet,PNode,PNode proc inSet(s: PNode; elem: PNode): bool 18 +nim overlap nimsets.html#overlap,PNode,PNode proc overlap(a, b: PNode): bool 33 +nim someInSet nimsets.html#someInSet,PNode,PNode,PNode proc someInSet(s: PNode; a, b: PNode): bool 47 +nim toBitSet nimsets.html#toBitSet,ConfigRef,PNode proc toBitSet(conf: ConfigRef; s: PNode): TBitSet 64 +nim toTreeSet nimsets.html#toTreeSet,ConfigRef,TBitSet,PType,TLineInfo proc toTreeSet(conf: ConfigRef; s: TBitSet; settype: PType; info: TLineInfo): PNode 79 +nim unionSets nimsets.html#unionSets,ConfigRef,PNode,PNode proc unionSets(conf: ConfigRef; a, b: PNode): PNode 119 +nim diffSets nimsets.html#diffSets,ConfigRef,PNode,PNode proc diffSets(conf: ConfigRef; a, b: PNode): PNode 120 +nim intersectSets nimsets.html#intersectSets,ConfigRef,PNode,PNode proc intersectSets(conf: ConfigRef; a, b: PNode): PNode 121 +nim symdiffSets nimsets.html#symdiffSets,ConfigRef,PNode,PNode proc symdiffSets(conf: ConfigRef; a, b: PNode): PNode 122 +nim containsSets nimsets.html#containsSets,ConfigRef,PNode,PNode proc containsSets(conf: ConfigRef; a, b: PNode): bool 124 +nim equalSets nimsets.html#equalSets,ConfigRef,PNode,PNode proc equalSets(conf: ConfigRef; a, b: PNode): bool 129 +nim complement nimsets.html#complement,ConfigRef,PNode proc complement(conf: ConfigRef; a: PNode): PNode 134 +nim deduplicate nimsets.html#deduplicate,ConfigRef,PNode proc deduplicate(conf: ConfigRef; a: PNode): PNode 139 +nim cardSet nimsets.html#cardSet,ConfigRef,PNode proc cardSet(conf: ConfigRef; a: PNode): BiggestInt 143 +nim setHasRange nimsets.html#setHasRange,PNode proc setHasRange(s: PNode): bool 147 +nim emptyRange nimsets.html#emptyRange,PNode,PNode proc emptyRange(a, b: PNode): bool 156 diff --git a/compiler/nodejs.html b/compiler/nodejs.html new file mode 100644 index 0000000000000..819190987fb11 --- /dev/null +++ b/compiler/nodejs.html @@ -0,0 +1,112 @@ + + + + + + + +nodejs + + + + + + + + + + + + + + + + +
+
+

nodejs

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Procs

+
+
+
+
proc findNodeJs(): string {.inline, ...raises: [OSError, IOError],
+                            tags: [ReadDirEffect, ReadEnvEffect, ReadIOEffect],
+                            forbids: [].}
+
+ + Find NodeJS executable and return it as a string. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/nodejs.idx b/compiler/nodejs.idx new file mode 100644 index 0000000000000..0a9cac88ce24e --- /dev/null +++ b/compiler/nodejs.idx @@ -0,0 +1,2 @@ +nimTitle nodejs nodejs.html module nodejs 0 +nim findNodeJs nodejs.html#findNodeJs proc findNodeJs(): string 3 diff --git a/compiler/nodekinds.html b/compiler/nodekinds.html new file mode 100644 index 0000000000000..e29ef90d734b8 --- /dev/null +++ b/compiler/nodekinds.html @@ -0,0 +1,189 @@ + + + + + + + +nodekinds + + + + + + + + + + + + + + + + +
+
+

nodekinds

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

NodeKind enum.

+
+

Types

+
+
+
TNodeKind = enum
+  nkNone, nkEmpty, nkIdent, nkSym, nkType, nkCharLit, nkIntLit, nkInt8Lit,
+  nkInt16Lit, nkInt32Lit, nkInt64Lit, nkUIntLit, nkUInt8Lit, nkUInt16Lit,
+  nkUInt32Lit, nkUInt64Lit, nkFloatLit, nkFloat32Lit, nkFloat64Lit,
+  nkFloat128Lit, nkStrLit, nkRStrLit, nkTripleStrLit, nkNilLit, nkComesFrom,
+  nkDotCall, nkCommand, nkCall, nkCallStrLit, nkInfix, nkPrefix, nkPostfix,
+  nkHiddenCallConv, nkExprEqExpr, nkExprColonExpr, nkIdentDefs, nkVarTuple,
+  nkPar, nkObjConstr, nkCurly, nkCurlyExpr, nkBracket, nkBracketExpr,
+  nkPragmaExpr, nkRange, nkDotExpr, nkCheckedFieldExpr, nkDerefExpr, nkIfExpr,
+  nkElifExpr, nkElseExpr, nkLambda, nkDo, nkAccQuoted, nkTableConstr, nkBind,
+  nkClosedSymChoice, nkOpenSymChoice, nkHiddenStdConv, nkHiddenSubConv, nkConv,
+  nkCast, nkStaticExpr, nkAddr, nkHiddenAddr, nkHiddenDeref, nkObjDownConv,
+  nkObjUpConv, nkChckRangeF, nkChckRange64, nkChckRange, nkStringToCString,
+  nkCStringToString, nkAsgn, nkFastAsgn, nkGenericParams, nkFormalParams,
+  nkOfInherit, nkImportAs, nkProcDef, nkMethodDef, nkConverterDef, nkMacroDef,
+  nkTemplateDef, nkIteratorDef, nkOfBranch, nkElifBranch, nkExceptBranch,
+  nkElse, nkAsmStmt, nkPragma, nkPragmaBlock, nkIfStmt, nkWhenStmt, nkForStmt,
+  nkParForStmt, nkWhileStmt, nkCaseStmt, nkTypeSection, nkVarSection,
+  nkLetSection, nkConstSection, nkConstDef, nkTypeDef, nkYieldStmt, nkDefer,
+  nkTryStmt, nkFinally, nkRaiseStmt, nkReturnStmt, nkBreakStmt, nkContinueStmt,
+  nkBlockStmt, nkStaticStmt, nkDiscardStmt, nkStmtList, nkImportStmt,
+  nkImportExceptStmt, nkExportStmt, nkExportExceptStmt, nkFromStmt,
+  nkIncludeStmt, nkBindStmt, nkMixinStmt, nkUsingStmt, nkCommentStmt,
+  nkStmtListExpr, nkBlockExpr, nkStmtListType, nkBlockType, nkWith, nkWithout,
+  nkTypeOfExpr, nkObjectTy, nkTupleTy, nkTupleClassTy, nkTypeClassTy,
+  nkStaticTy, nkRecList, nkRecCase, nkRecWhen, nkRefTy, nkPtrTy, nkVarTy,
+  nkConstTy, nkOutTy, nkDistinctTy, nkProcTy, nkIteratorTy, nkSinkAsgn,
+  nkEnumTy, nkEnumFieldDef, nkArgList, nkPattern, nkHiddenTryStmt, nkClosure,
+  nkGotoState, nkState, nkBreakState, nkFuncDef, nkTupleConstr, nkError,
+  nkModuleRef, nkReplayAction, nkNilRodNode, nkOpenSym
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
nkCallKinds = {nkCall, nkInfix, nkPrefix, nkPostfix, nkCommand, nkCallStrLit,
+               nkHiddenCallConv}
+
+ + + Source   +Edit   + +
+
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/nodekinds.idx b/compiler/nodekinds.idx new file mode 100644 index 0000000000000..fb666ab4f5b78 --- /dev/null +++ b/compiler/nodekinds.idx @@ -0,0 +1,169 @@ +nimTitle nodekinds nodekinds.html module nodekinds 0 +nim nkNone nodekinds.html#nkNone TNodeKind.nkNone 13 +nim nkEmpty nodekinds.html#nkEmpty TNodeKind.nkEmpty 13 +nim nkIdent nodekinds.html#nkIdent TNodeKind.nkIdent 13 +nim nkSym nodekinds.html#nkSym TNodeKind.nkSym 13 +nim nkType nodekinds.html#nkType TNodeKind.nkType 13 +nim nkCharLit nodekinds.html#nkCharLit TNodeKind.nkCharLit 13 +nim nkIntLit nodekinds.html#nkIntLit TNodeKind.nkIntLit 13 +nim nkInt8Lit nodekinds.html#nkInt8Lit TNodeKind.nkInt8Lit 13 +nim nkInt16Lit nodekinds.html#nkInt16Lit TNodeKind.nkInt16Lit 13 +nim nkInt32Lit nodekinds.html#nkInt32Lit TNodeKind.nkInt32Lit 13 +nim nkInt64Lit nodekinds.html#nkInt64Lit TNodeKind.nkInt64Lit 13 +nim nkUIntLit nodekinds.html#nkUIntLit TNodeKind.nkUIntLit 13 +nim nkUInt8Lit nodekinds.html#nkUInt8Lit TNodeKind.nkUInt8Lit 13 +nim nkUInt16Lit nodekinds.html#nkUInt16Lit TNodeKind.nkUInt16Lit 13 +nim nkUInt32Lit nodekinds.html#nkUInt32Lit TNodeKind.nkUInt32Lit 13 +nim nkUInt64Lit nodekinds.html#nkUInt64Lit TNodeKind.nkUInt64Lit 13 +nim nkFloatLit nodekinds.html#nkFloatLit TNodeKind.nkFloatLit 13 +nim nkFloat32Lit nodekinds.html#nkFloat32Lit TNodeKind.nkFloat32Lit 13 +nim nkFloat64Lit nodekinds.html#nkFloat64Lit TNodeKind.nkFloat64Lit 13 +nim nkFloat128Lit nodekinds.html#nkFloat128Lit TNodeKind.nkFloat128Lit 13 +nim nkStrLit nodekinds.html#nkStrLit TNodeKind.nkStrLit 13 +nim nkRStrLit nodekinds.html#nkRStrLit TNodeKind.nkRStrLit 13 +nim nkTripleStrLit nodekinds.html#nkTripleStrLit TNodeKind.nkTripleStrLit 13 +nim nkNilLit nodekinds.html#nkNilLit TNodeKind.nkNilLit 13 +nim nkComesFrom nodekinds.html#nkComesFrom TNodeKind.nkComesFrom 13 +nim nkDotCall nodekinds.html#nkDotCall TNodeKind.nkDotCall 13 +nim nkCommand nodekinds.html#nkCommand TNodeKind.nkCommand 13 +nim nkCall nodekinds.html#nkCall TNodeKind.nkCall 13 +nim nkCallStrLit nodekinds.html#nkCallStrLit TNodeKind.nkCallStrLit 13 +nim nkInfix nodekinds.html#nkInfix TNodeKind.nkInfix 13 +nim nkPrefix nodekinds.html#nkPrefix TNodeKind.nkPrefix 13 +nim nkPostfix nodekinds.html#nkPostfix TNodeKind.nkPostfix 13 +nim nkHiddenCallConv nodekinds.html#nkHiddenCallConv TNodeKind.nkHiddenCallConv 13 +nim nkExprEqExpr nodekinds.html#nkExprEqExpr TNodeKind.nkExprEqExpr 13 +nim nkExprColonExpr nodekinds.html#nkExprColonExpr TNodeKind.nkExprColonExpr 13 +nim nkIdentDefs nodekinds.html#nkIdentDefs TNodeKind.nkIdentDefs 13 +nim nkVarTuple nodekinds.html#nkVarTuple TNodeKind.nkVarTuple 13 +nim nkPar nodekinds.html#nkPar TNodeKind.nkPar 13 +nim nkObjConstr nodekinds.html#nkObjConstr TNodeKind.nkObjConstr 13 +nim nkCurly nodekinds.html#nkCurly TNodeKind.nkCurly 13 +nim nkCurlyExpr nodekinds.html#nkCurlyExpr TNodeKind.nkCurlyExpr 13 +nim nkBracket nodekinds.html#nkBracket TNodeKind.nkBracket 13 +nim nkBracketExpr nodekinds.html#nkBracketExpr TNodeKind.nkBracketExpr 13 +nim nkPragmaExpr nodekinds.html#nkPragmaExpr TNodeKind.nkPragmaExpr 13 +nim nkRange nodekinds.html#nkRange TNodeKind.nkRange 13 +nim nkDotExpr nodekinds.html#nkDotExpr TNodeKind.nkDotExpr 13 +nim nkCheckedFieldExpr nodekinds.html#nkCheckedFieldExpr TNodeKind.nkCheckedFieldExpr 13 +nim nkDerefExpr nodekinds.html#nkDerefExpr TNodeKind.nkDerefExpr 13 +nim nkIfExpr nodekinds.html#nkIfExpr TNodeKind.nkIfExpr 13 +nim nkElifExpr nodekinds.html#nkElifExpr TNodeKind.nkElifExpr 13 +nim nkElseExpr nodekinds.html#nkElseExpr TNodeKind.nkElseExpr 13 +nim nkLambda nodekinds.html#nkLambda TNodeKind.nkLambda 13 +nim nkDo nodekinds.html#nkDo TNodeKind.nkDo 13 +nim nkAccQuoted nodekinds.html#nkAccQuoted TNodeKind.nkAccQuoted 13 +nim nkTableConstr nodekinds.html#nkTableConstr TNodeKind.nkTableConstr 13 +nim nkBind nodekinds.html#nkBind TNodeKind.nkBind 13 +nim nkClosedSymChoice nodekinds.html#nkClosedSymChoice TNodeKind.nkClosedSymChoice 13 +nim nkOpenSymChoice nodekinds.html#nkOpenSymChoice TNodeKind.nkOpenSymChoice 13 +nim nkHiddenStdConv nodekinds.html#nkHiddenStdConv TNodeKind.nkHiddenStdConv 13 +nim nkHiddenSubConv nodekinds.html#nkHiddenSubConv TNodeKind.nkHiddenSubConv 13 +nim nkConv nodekinds.html#nkConv TNodeKind.nkConv 13 +nim nkCast nodekinds.html#nkCast TNodeKind.nkCast 13 +nim nkStaticExpr nodekinds.html#nkStaticExpr TNodeKind.nkStaticExpr 13 +nim nkAddr nodekinds.html#nkAddr TNodeKind.nkAddr 13 +nim nkHiddenAddr nodekinds.html#nkHiddenAddr TNodeKind.nkHiddenAddr 13 +nim nkHiddenDeref nodekinds.html#nkHiddenDeref TNodeKind.nkHiddenDeref 13 +nim nkObjDownConv nodekinds.html#nkObjDownConv TNodeKind.nkObjDownConv 13 +nim nkObjUpConv nodekinds.html#nkObjUpConv TNodeKind.nkObjUpConv 13 +nim nkChckRangeF nodekinds.html#nkChckRangeF TNodeKind.nkChckRangeF 13 +nim nkChckRange64 nodekinds.html#nkChckRange64 TNodeKind.nkChckRange64 13 +nim nkChckRange nodekinds.html#nkChckRange TNodeKind.nkChckRange 13 +nim nkStringToCString nodekinds.html#nkStringToCString TNodeKind.nkStringToCString 13 +nim nkCStringToString nodekinds.html#nkCStringToString TNodeKind.nkCStringToString 13 +nim nkAsgn nodekinds.html#nkAsgn TNodeKind.nkAsgn 13 +nim nkFastAsgn nodekinds.html#nkFastAsgn TNodeKind.nkFastAsgn 13 +nim nkGenericParams nodekinds.html#nkGenericParams TNodeKind.nkGenericParams 13 +nim nkFormalParams nodekinds.html#nkFormalParams TNodeKind.nkFormalParams 13 +nim nkOfInherit nodekinds.html#nkOfInherit TNodeKind.nkOfInherit 13 +nim nkImportAs nodekinds.html#nkImportAs TNodeKind.nkImportAs 13 +nim nkProcDef nodekinds.html#nkProcDef TNodeKind.nkProcDef 13 +nim nkMethodDef nodekinds.html#nkMethodDef TNodeKind.nkMethodDef 13 +nim nkConverterDef nodekinds.html#nkConverterDef TNodeKind.nkConverterDef 13 +nim nkMacroDef nodekinds.html#nkMacroDef TNodeKind.nkMacroDef 13 +nim nkTemplateDef nodekinds.html#nkTemplateDef TNodeKind.nkTemplateDef 13 +nim nkIteratorDef nodekinds.html#nkIteratorDef TNodeKind.nkIteratorDef 13 +nim nkOfBranch nodekinds.html#nkOfBranch TNodeKind.nkOfBranch 13 +nim nkElifBranch nodekinds.html#nkElifBranch TNodeKind.nkElifBranch 13 +nim nkExceptBranch nodekinds.html#nkExceptBranch TNodeKind.nkExceptBranch 13 +nim nkElse nodekinds.html#nkElse TNodeKind.nkElse 13 +nim nkAsmStmt nodekinds.html#nkAsmStmt TNodeKind.nkAsmStmt 13 +nim nkPragma nodekinds.html#nkPragma TNodeKind.nkPragma 13 +nim nkPragmaBlock nodekinds.html#nkPragmaBlock TNodeKind.nkPragmaBlock 13 +nim nkIfStmt nodekinds.html#nkIfStmt TNodeKind.nkIfStmt 13 +nim nkWhenStmt nodekinds.html#nkWhenStmt TNodeKind.nkWhenStmt 13 +nim nkForStmt nodekinds.html#nkForStmt TNodeKind.nkForStmt 13 +nim nkParForStmt nodekinds.html#nkParForStmt TNodeKind.nkParForStmt 13 +nim nkWhileStmt nodekinds.html#nkWhileStmt TNodeKind.nkWhileStmt 13 +nim nkCaseStmt nodekinds.html#nkCaseStmt TNodeKind.nkCaseStmt 13 +nim nkTypeSection nodekinds.html#nkTypeSection TNodeKind.nkTypeSection 13 +nim nkVarSection nodekinds.html#nkVarSection TNodeKind.nkVarSection 13 +nim nkLetSection nodekinds.html#nkLetSection TNodeKind.nkLetSection 13 +nim nkConstSection nodekinds.html#nkConstSection TNodeKind.nkConstSection 13 +nim nkConstDef nodekinds.html#nkConstDef TNodeKind.nkConstDef 13 +nim nkTypeDef nodekinds.html#nkTypeDef TNodeKind.nkTypeDef 13 +nim nkYieldStmt nodekinds.html#nkYieldStmt TNodeKind.nkYieldStmt 13 +nim nkDefer nodekinds.html#nkDefer TNodeKind.nkDefer 13 +nim nkTryStmt nodekinds.html#nkTryStmt TNodeKind.nkTryStmt 13 +nim nkFinally nodekinds.html#nkFinally TNodeKind.nkFinally 13 +nim nkRaiseStmt nodekinds.html#nkRaiseStmt TNodeKind.nkRaiseStmt 13 +nim nkReturnStmt nodekinds.html#nkReturnStmt TNodeKind.nkReturnStmt 13 +nim nkBreakStmt nodekinds.html#nkBreakStmt TNodeKind.nkBreakStmt 13 +nim nkContinueStmt nodekinds.html#nkContinueStmt TNodeKind.nkContinueStmt 13 +nim nkBlockStmt nodekinds.html#nkBlockStmt TNodeKind.nkBlockStmt 13 +nim nkStaticStmt nodekinds.html#nkStaticStmt TNodeKind.nkStaticStmt 13 +nim nkDiscardStmt nodekinds.html#nkDiscardStmt TNodeKind.nkDiscardStmt 13 +nim nkStmtList nodekinds.html#nkStmtList TNodeKind.nkStmtList 13 +nim nkImportStmt nodekinds.html#nkImportStmt TNodeKind.nkImportStmt 13 +nim nkImportExceptStmt nodekinds.html#nkImportExceptStmt TNodeKind.nkImportExceptStmt 13 +nim nkExportStmt nodekinds.html#nkExportStmt TNodeKind.nkExportStmt 13 +nim nkExportExceptStmt nodekinds.html#nkExportExceptStmt TNodeKind.nkExportExceptStmt 13 +nim nkFromStmt nodekinds.html#nkFromStmt TNodeKind.nkFromStmt 13 +nim nkIncludeStmt nodekinds.html#nkIncludeStmt TNodeKind.nkIncludeStmt 13 +nim nkBindStmt nodekinds.html#nkBindStmt TNodeKind.nkBindStmt 13 +nim nkMixinStmt nodekinds.html#nkMixinStmt TNodeKind.nkMixinStmt 13 +nim nkUsingStmt nodekinds.html#nkUsingStmt TNodeKind.nkUsingStmt 13 +nim nkCommentStmt nodekinds.html#nkCommentStmt TNodeKind.nkCommentStmt 13 +nim nkStmtListExpr nodekinds.html#nkStmtListExpr TNodeKind.nkStmtListExpr 13 +nim nkBlockExpr nodekinds.html#nkBlockExpr TNodeKind.nkBlockExpr 13 +nim nkStmtListType nodekinds.html#nkStmtListType TNodeKind.nkStmtListType 13 +nim nkBlockType nodekinds.html#nkBlockType TNodeKind.nkBlockType 13 +nim nkWith nodekinds.html#nkWith TNodeKind.nkWith 13 +nim nkWithout nodekinds.html#nkWithout TNodeKind.nkWithout 13 +nim nkTypeOfExpr nodekinds.html#nkTypeOfExpr TNodeKind.nkTypeOfExpr 13 +nim nkObjectTy nodekinds.html#nkObjectTy TNodeKind.nkObjectTy 13 +nim nkTupleTy nodekinds.html#nkTupleTy TNodeKind.nkTupleTy 13 +nim nkTupleClassTy nodekinds.html#nkTupleClassTy TNodeKind.nkTupleClassTy 13 +nim nkTypeClassTy nodekinds.html#nkTypeClassTy TNodeKind.nkTypeClassTy 13 +nim nkStaticTy nodekinds.html#nkStaticTy TNodeKind.nkStaticTy 13 +nim nkRecList nodekinds.html#nkRecList TNodeKind.nkRecList 13 +nim nkRecCase nodekinds.html#nkRecCase TNodeKind.nkRecCase 13 +nim nkRecWhen nodekinds.html#nkRecWhen TNodeKind.nkRecWhen 13 +nim nkRefTy nodekinds.html#nkRefTy TNodeKind.nkRefTy 13 +nim nkPtrTy nodekinds.html#nkPtrTy TNodeKind.nkPtrTy 13 +nim nkVarTy nodekinds.html#nkVarTy TNodeKind.nkVarTy 13 +nim nkConstTy nodekinds.html#nkConstTy TNodeKind.nkConstTy 13 +nim nkOutTy nodekinds.html#nkOutTy TNodeKind.nkOutTy 13 +nim nkDistinctTy nodekinds.html#nkDistinctTy TNodeKind.nkDistinctTy 13 +nim nkProcTy nodekinds.html#nkProcTy TNodeKind.nkProcTy 13 +nim nkIteratorTy nodekinds.html#nkIteratorTy TNodeKind.nkIteratorTy 13 +nim nkSinkAsgn nodekinds.html#nkSinkAsgn TNodeKind.nkSinkAsgn 13 +nim nkEnumTy nodekinds.html#nkEnumTy TNodeKind.nkEnumTy 13 +nim nkEnumFieldDef nodekinds.html#nkEnumFieldDef TNodeKind.nkEnumFieldDef 13 +nim nkArgList nodekinds.html#nkArgList TNodeKind.nkArgList 13 +nim nkPattern nodekinds.html#nkPattern TNodeKind.nkPattern 13 +nim nkHiddenTryStmt nodekinds.html#nkHiddenTryStmt TNodeKind.nkHiddenTryStmt 13 +nim nkClosure nodekinds.html#nkClosure TNodeKind.nkClosure 13 +nim nkGotoState nodekinds.html#nkGotoState TNodeKind.nkGotoState 13 +nim nkState nodekinds.html#nkState TNodeKind.nkState 13 +nim nkBreakState nodekinds.html#nkBreakState TNodeKind.nkBreakState 13 +nim nkFuncDef nodekinds.html#nkFuncDef TNodeKind.nkFuncDef 13 +nim nkTupleConstr nodekinds.html#nkTupleConstr TNodeKind.nkTupleConstr 13 +nim nkError nodekinds.html#nkError TNodeKind.nkError 13 +nim nkModuleRef nodekinds.html#nkModuleRef TNodeKind.nkModuleRef 13 +nim nkReplayAction nodekinds.html#nkReplayAction TNodeKind.nkReplayAction 13 +nim nkNilRodNode nodekinds.html#nkNilRodNode TNodeKind.nkNilRodNode 13 +nim nkOpenSym nodekinds.html#nkOpenSym TNodeKind.nkOpenSym 13 +nim TNodeKind nodekinds.html#TNodeKind enum TNodeKind 13 +nim nkCallKinds nodekinds.html#nkCallKinds const nkCallKinds 210 diff --git a/compiler/nversion.html b/compiler/nversion.html new file mode 100644 index 0000000000000..f4bed69206c88 --- /dev/null +++ b/compiler/nversion.html @@ -0,0 +1,148 @@ + + + + + + + +nversion + + + + + + + + + + + + + + + + +
+
+

nversion

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Consts

+
+
+
DefaultSetElements = 256
+
+ + assumed set element count when using int literals + Source   +Edit   + +
+
+
+
MaxSetElements = 65536
+
+ + + Source   +Edit   + +
+
+
+
NimCompilerApiVersion = 3
+
+ + Check for the existence of this before accessing it as older versions of the compiler API do not declare this. + Source   +Edit   + +
+
+
+
RodFileVersion = "1223"
+
+ + + Source   +Edit   + +
+
+
+
VersionAsString = "2.2.1"
+
+ + + Source   +Edit   + +
+
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/nversion.idx b/compiler/nversion.idx new file mode 100644 index 0000000000000..3fafa7a2e7c7d --- /dev/null +++ b/compiler/nversion.idx @@ -0,0 +1,6 @@ +nimTitle nversion nversion.html module nversion 0 +nim MaxSetElements nversion.html#MaxSetElements const MaxSetElements 14 +nim DefaultSetElements nversion.html#DefaultSetElements const DefaultSetElements 15 +nim VersionAsString nversion.html#VersionAsString const VersionAsString 17 +nim RodFileVersion nversion.html#RodFileVersion const RodFileVersion 18 +nim NimCompilerApiVersion nversion.html#NimCompilerApiVersion const NimCompilerApiVersion 20 diff --git a/compiler/optimizer.html b/compiler/optimizer.html new file mode 100644 index 0000000000000..6a4afd37c5e3e --- /dev/null +++ b/compiler/optimizer.html @@ -0,0 +1,122 @@ + + + + + + + +optimizer + + + + + + + + + + + + + + + + +
+
+

optimizer

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Optimizer:

  • elide 'wasMoved(x); destroy(x)' pairs
  • +
  • recognize "all paths lead to 'wasMoved(x)'"
  • +
+

+ +
+

Procs

+
+
+
+
proc optimize(n: PNode): PNode {....raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/optimizer.idx b/compiler/optimizer.idx new file mode 100644 index 0000000000000..65e68c864bc5f --- /dev/null +++ b/compiler/optimizer.idx @@ -0,0 +1,2 @@ +nimTitle optimizer optimizer.html module optimizer 0 +nim optimize optimizer.html#optimize,PNode proc optimize(n: PNode): PNode 264 diff --git a/compiler/options.html b/compiler/options.html new file mode 100644 index 0000000000000..350487eb4f084 --- /dev/null +++ b/compiler/options.html @@ -0,0 +1,2162 @@ + + + + + + + +options + + + + + + + + + + + + + + + + +
+
+

options

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
Cfile = object
+  nimname*: string
+  cname*, obj*: AbsoluteFile
+  flags*: set[CfileFlag]
+  customArgs*: string
+
+ + + Source   +Edit   + +
+
+
+
CfileFlag {.pure.} = enum
+  Cached,                   ## no need to recompile this time
+  External                   ## file was introduced via .compile pragma
+
+ + + Source   +Edit   + +
+
+
+
CfileList = seq[Cfile]
+
+ + + Source   +Edit   + +
+
+
+
Command = enum
+  cmdNone, cmdUnknown, cmdCompileToC, cmdCompileToCpp, cmdCompileToOC,
+  cmdCompileToJS, cmdCrun, cmdTcc, cmdCheck, cmdM, cmdParse, cmdRod,
+  cmdIdeTools, cmdNimscript, cmdDoc0, cmdDoc, cmdDoc2tex, cmdRst2html,
+  cmdRst2tex, cmdMd2html, cmdMd2tex, cmdJsondoc0, cmdJsondoc, cmdCtags,
+  cmdBuildindex, cmdGendepend, cmdDump, cmdInteractive, cmdNop, cmdJsonscript
+
+ + Nim's commands + Source   +Edit   + +
+
+
+
ConfigRef {.acyclic.} = ref object
+  backend*: TBackend
+  target*: Target
+  linesCompiled*: int
+  options*: TOptions
+  globalOptions*: TGlobalOptions
+  macrosToExpand*: StringTableRef
+  arcToExpand*: StringTableRef
+  m*: MsgConfig
+  filenameOption*: FilenameOption
+  unitSep*: string
+  evalTemplateCounter*: int
+  evalMacroCounter*: int
+  exitcode*: int8
+  cmd*: Command
+  cmdInput*: string
+  projectIsCmd*: bool
+  implicitCmd*: bool
+  selectedGC*: TGCMode
+  exc*: ExceptionSystem
+  hintProcessingDots*: bool
+  verbosity*: int
+  numberOfProcessors*: int
+  lastCmdTime*: float
+  symbolFiles*: SymbolFilesOption
+  spellSuggestMax*: int
+  cppDefines*: HashSet[string]
+  headerFile*: string
+  nimbasePattern*: string
+  features*: set[Feature]
+  legacyFeatures*: set[LegacyFeature]
+  arguments*: string         ## the arguments to be passed to the program that
+                             ## should be run
+  ideCmd*: IdeCmd
+  cCompiler*: TSystemCC
+  modifiedyNotes*: TNoteKinds
+  cmdlineNotes*: TNoteKinds
+  foreignPackageNotes*: TNoteKinds
+  notes*: TNoteKinds
+  warningAsErrors*: TNoteKinds
+  mainPackageNotes*: TNoteKinds
+  mainPackageId*: int
+  errorCounter*: int
+  hintCounter*: int
+  warnCounter*: int
+  errorMax*: int
+  maxLoopIterationsVM*: int  ## VM: max iterations of all loops
+  isVmTrace*: bool
+  configVars*: StringTableRef
+  symbols*: StringTableRef   ## We need to use a StringTableRef here as defined
+                             ## symbols are always guaranteed to be style
+                             ## insensitive. Otherwise hell would break lose.
+  packageCache*: StringTableRef
+  nimblePaths*: seq[AbsoluteDir]
+  searchPaths*: seq[AbsoluteDir]
+  lazyPaths*: seq[AbsoluteDir]
+  outFile*: RelativeFile
+  outDir*: AbsoluteDir
+  jsonBuildFile*: AbsoluteFile
+  prefixDir*, libpath*, nimcacheDir*: AbsoluteDir
+  dllOverrides*, moduleOverrides*, cfileSpecificOptions*: StringTableRef
+  projectName*: string
+  projectPath*: AbsoluteDir
+  projectFull*: AbsoluteFile
+  projectIsStdin*: bool
+  lastMsgWasDot*: set[StdOrrKind]
+  projectMainIdx*: FileIndex
+  projectMainIdx2*: FileIndex
+  command*: string
+  commandArgs*: seq[string]
+  commandLine*: string
+  extraCmds*: seq[string]
+  implicitImports*: seq[string]
+  implicitIncludes*: seq[string]
+  docSeeSrcUrl*: string
+  docRoot*: string           ## see nim --fullhelp for --docRoot
+  docCmd*: string            ## see nim --fullhelp for --docCmd
+  configFiles*: seq[AbsoluteFile]
+  cIncludes*: seq[AbsoluteDir]
+  cLibs*: seq[AbsoluteDir]
+  cLinkedLibs*: seq[string]
+  externalToLink*: seq[string]
+  linkOptionsCmd*: string
+  compileOptionsCmd*: seq[string]
+  linkOptions*: string
+  compileOptions*: string
+  cCompilerPath*: string
+  toCompile*: CfileList
+  suggestionResultHook*: proc (result: Suggest) {.closure.}
+  suggestVersion*: int
+  suggestMaxResults*: int
+  lastLineInfo*: TLineInfo
+  writelnHook*: proc (output: string) {.closure, ...gcsafe.}
+  structuredErrorHook*: proc (config: ConfigRef; info: TLineInfo; msg: string;
+                              severity: Severity) {.closure, ...gcsafe.}
+  cppCustomNamespace*: string
+  nimMainPrefix*: string
+  vmProfileData*: ProfileData
+  expandProgress*: bool
+  expandLevels*: int
+  expandNodeResult*: string
+  expandPosition*: TLineInfo
+  currentConfigDir*: string
+  clientProcessId*: int
+
+ + every global configuration fields marked with '*' are subject to the incremental compilation mechanisms (+) means "part of the dependency" + Source   +Edit   + +
+
+
+
ExceptionSystem = enum
+  excNone, excSetjmp, excCpp, excGoto, excQuirky
+
+ + + Source   +Edit   + +
+
+
+
Feature = enum
+  dotOperators, callOperator, parallel, destructor, notnil, dynamicBindSym,
+  forLoopMacros, caseStmtMacros, codeReordering, compiletimeFFI, ## This requires building nim with `-d:nimHasLibFFI`
+                                                                  ## which itself requires `koch installdeps libffi`, see #10150
+                                                                  ## Note: this feature can't be localized with {.push.}
+  vmopsDanger, strictFuncs, views, strictNotNil, overloadableEnums,
+  strictEffects, unicodeOperators, flexibleOptionalParams, strictDefs,
+  strictCaseObjects, inferGenericTypes, openSym, genericsOpenSym, vtables,
+  typeBoundOps
+
+ + experimental features; DO NOT RENAME THESE! + Source   +Edit   + +
+
+
+
FilenameOption = enum
+  foAbs, foRelProject, foCanonical, foLegacyRelProj, foName, foStacktrace
+
+ + + Source   +Edit   + +
+
+
+
IdeCmd = enum
+  ideNone, ideSug, ideCon, ideDef, ideUse, ideDus, ideChk, ideChkFile, ideMod,
+  ideHighlight, ideOutline, ideKnown, ideMsg, ideProject, ideGlobalSymbols,
+  ideRecompile, ideChanged, ideType, ideDeclaration, ideExpand, ideInlayHints
+
+ + + Source   +Edit   + +
+
+
+
LegacyFeature = enum
+  allowSemcheckedAstModification, ## Allows to modify a NimNode where the type has already been
+                                   ## flagged with nfSem. If you actually do this, it will cause
+                                   ## bugs.
+  checkUnsignedConversions, ## Historically and especially in version 1.0.0 of the language
+                             ## conversions to unsigned numbers were checked. In 1.0.4 they
+                             ## are not anymore.
+  laxEffects,               ## Lax effects system prior to Nim 2.0.
+  verboseTypeMismatch, emitGenerics, ## generics are emitted in the module that contains them.
+                                      ## Useful for libraries that rely on local passC
+  jsNoLambdaLifting,        ## Old transformation for closures in JS backend
+  noStrictDefs               ## disable "strictdefs"
+
+ + + Source   +Edit   + +
+
+
+
ProfileData = ref object
+  data*: TableRef[TLineInfo, ProfileInfo]
+
+ + + Source   +Edit   + +
+
+
+
ProfileInfo = object
+  time*: float
+  count*: int
+
+ + + Source   +Edit   + +
+
+
+
StdOrrKind = enum
+  stdOrrStdout, stdOrrStderr
+
+ + + Source   +Edit   + +
+
+
+
Suggest = ref object
+  section*: IdeCmd
+  qualifiedPath*: seq[string]
+  name*: ptr string
+  filePath*: string
+  line*: int
+  column*: int
+  doc*: string
+  forth*: string
+  quality*: range[0 .. 100] = 0
+  isGlobal*: bool
+  contextFits*: bool
+  prefix*: PrefixMatch
+  symkind*: byte
+  scope*, localUsages*, globalUsages*: int
+  tokenLen*: int
+  version*: int
+  endLine*: uint16
+  endCol*: int
+  inlayHintInfo*: SuggestInlayHint
+
+ + + Source   +Edit   + +
+
+
+
SuggestInlayHint = ref object
+  kind*: SuggestInlayHintKind
+  line*: int
+  column*: int
+  label*: string
+  paddingLeft*: bool
+  paddingRight*: bool
+  allowInsert*: bool
+  tooltip*: string
+
+ + + Source   +Edit   + +
+
+
+
SuggestInlayHintKind = enum
+  sihkType = "Type", sihkParameter = "Parameter", sihkException = "Exception"
+
+ + + Source   +Edit   + +
+
+
+
Suggestions = seq[Suggest]
+
+ + + Source   +Edit   + +
+
+
+
SymbolFilesOption = enum
+  disabledSf, writeOnlySf, readOnlySf, v2Sf, stressTest
+
+ + + Source   +Edit   + +
+
+
+
TBackend = enum
+  backendInvalid = "", backendC = "c", backendCpp = "cpp", backendJs = "js",
+  backendObjc = "objc"
+
+ + + Source   +Edit   + +
+
+
+
TGCMode = enum
+  gcUnselected = "unselected", gcNone = "none", gcBoehm = "boehm",
+  gcRegions = "regions", gcArc = "arc", gcOrc = "orc",
+  gcAtomicArc = "atomicArc", gcMarkAndSweep = "markAndSweep", gcHooks = "hooks",
+  gcRefc = "refc", gcGo = "go"
+
+ + + Source   +Edit   + +
+
+
+
TGlobalOption = enum
+  gloptNone, optForceFullMake, optWasNimscript, optListCmd, optCompileOnly,
+  optNoLinking, optCDebug, optGenDynLib, optGenStaticLib, optGenGuiApp,
+  optGenScript, optGenCDeps, optGenMapping, optRun, optUseNimcache,
+  optStyleHint, optStyleError, optStyleUsages, optSkipSystemConfigFile,
+  optSkipProjConfigFile, optSkipUserConfigFile, optSkipParentConfigFiles,
+  optNoMain, optUseColors, optThreads, optStdout, optThreadAnalysis,
+  optTlsEmulation, optGenIndex, optGenIndexOnly, optNoImportdoc,
+  optEmbedOrigSrc, optIdeDebug, optIdeTerse, optIdeExceptionInlayHints,
+  optExcessiveStackTrace, optShowAllMismatches, optWholeProject, optDocInternal,
+  optMixedMode, optDeclaredLocs, optNoNimblePath, optHotCodeReloading,
+  optDynlibOverrideAll, optSeqDestructors, optTinyRtti, optOwnedRefs,
+  optMultiMethods, optBenchmarkVM, optProduceAsm, optPanics, optSourcemap,
+  optProfileVM, optEnableDeepCopy, optShowNonExportedFields, optJsBigInt64
+
+ + + Source   +Edit   + +
+
+
+
TGlobalOptions = set[TGlobalOption]
+
+ + + Source   +Edit   + +
+
+
+
TOption = enum
+  optNone, optObjCheck, optFieldCheck, optRangeCheck, optBoundsCheck,
+  optOverflowCheck, optRefCheck, optNaNCheck, optInfCheck, optStaticBoundsCheck,
+  optStyleCheck, optAssert, optLineDir, optWarns, optHints, optOptimizeSpeed,
+  optOptimizeSize, optStackTrace, optStackTraceMsgs, optLineTrace, optByRef,
+  optProfiler, optImplicitStatic, optTrMacros, optMemTracker, optSinkInference,
+  optCursorInference, optImportHidden, optQuirky
+
+ + + Source   +Edit   + +
+
+
+
TOptions = set[TOption]
+
+ + + Source   +Edit   + +
+
+
+
TStringSeq = seq[string]
+
+ + + Source   +Edit   + +
+
+
+
TSystemCC = enum
+  ccNone, ccGcc, ccNintendoSwitch, ccLLVM_Gcc, ccCLang, ccBcc, ccVcc, ccTcc,
+  ccEnv, ccIcl, ccIcc, ccClangCl, ccHipcc, ccNvcc
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
ChecksOptions = {optObjCheck, optFieldCheck, optRangeCheck, optOverflowCheck,
+                 optBoundsCheck, optAssert, optNaNCheck, optInfCheck,
+                 optStyleCheck}
+
+ + + Source   +Edit   + +
+
+
+
cmdBackends = {cmdCompileToC, cmdCompileToCpp, cmdCompileToOC, cmdCompileToJS,
+               cmdCrun}
+
+ + + Source   +Edit   + +
+
+
+
cmdDocLike = {cmdDoc0, cmdDoc, cmdDoc2tex, cmdJsondoc0, cmdJsondoc, cmdCtags,
+              cmdBuildindex}
+
+ + + Source   +Edit   + +
+
+
+
copyrightYear = "2024"
+
+ + + Source   +Edit   + +
+
+
+
DefaultConfig = r"nim.cfg"
+
+ + + Source   +Edit   + +
+
+
+
DefaultConfigNims = r"config.nims"
+
+ + + Source   +Edit   + +
+
+
+
DefaultGlobalOptions = {optThreadAnalysis, optExcessiveStackTrace, optJsBigInt64}
+
+ + + Source   +Edit   + +
+
+
+
DefaultOptions = {optObjCheck, optFieldCheck, optRangeCheck, optBoundsCheck,
+                  optOverflowCheck, optAssert, optWarns, optRefCheck, optHints,
+                  optStackTrace, optLineTrace, optTrMacros, optStyleCheck,
+                  optCursorInference}
+
+ + + Source   +Edit   + +
+
+
+
DocConfig = r"nimdoc.cfg"
+
+ + + Source   +Edit   + +
+
+
+
docRootDefault = "@default"
+
+ + + Source   +Edit   + +
+
+
+
DocTexConfig = r"nimdoc.tex.cfg"
+
+ + + Source   +Edit   + +
+
+
+
foreignPackageNotesDefault = {hintProcessing, warnUnknownMagic, hintQuitCalled,
+                              hintExecuting, hintUser, warnUser}
+
+ + + Source   +Edit   + +
+
+
+
genSubDir = r"nimcache"
+
+ + + Source   +Edit   + +
+
+
+
harmlessOptions = {optForceFullMake, optNoLinking, optRun, optUseColors,
+                   optStdout}
+
+ + + Source   +Edit   + +
+
+
+
hasFFI = false
+
+ + + Source   +Edit   + +
+
+
+
hasTinyCBackend = false
+
+ + + Source   +Edit   + +
+
+
+
htmldocsDir = "htmldocs"
+
+ + + Source   +Edit   + +
+
+
+
HtmlExt = "html"
+
+ + + Source   +Edit   + +
+
+
+
IniExt = "ini"
+
+ + + Source   +Edit   + +
+
+
+
JsonExt = "json"
+
+ + + Source   +Edit   + +
+
+
+
nimEnableCovariance = false
+
+ + + Source   +Edit   + +
+
+
+
NimExt = "nim"
+
+ + + Source   +Edit   + +
+
+
+
oKeepVariableNames = true
+
+ + + Source   +Edit   + +
+
+
+
oldExperimentalFeatures = {dotOperators, callOperator, parallel}
+
+ + + Source   +Edit   + +
+
+
+
RodExt = "rod"
+
+ + + Source   +Edit   + +
+
+
+
spellSuggestSecretSauce = -1
+
+ + + Source   +Edit   + +
+
+
+
stdlibDirs = ["pure", "core", "arch", "pure/collections", "pure/concurrency",
+              "pure/unidecode", "impure", "wrappers", "wrappers/linenoise",
+              "windows", "posix", "js", "deprecated/pure"]
+
+ + + Source   +Edit   + +
+
+
+
stdPrefix = "std/"
+
+ + + Source   +Edit   + +
+
+
+
TagsExt = "tags"
+
+ + + Source   +Edit   + +
+
+
+
TexExt = "tex"
+
+ + + Source   +Edit   + +
+
+
+
useEffectSystem = true
+
+ + + Source   +Edit   + +
+
+
+
useWriteTracking = false
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(c: IdeCmd): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc absOutFile(conf: ConfigRef): AbsoluteFile {....raises: [OSError],
+    tags: [ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc assignIfDefault[T](result: var T; val: T; def = default(T))
+
+ + if result was already assigned to a value (that wasn't def), this is a noop. + Source   +Edit   + +
+
+ +
+
+
+
proc canonicalImport(conf: ConfigRef; file: AbsoluteFile): string {.
+    ...raises: [Exception, KeyError], tags: [RootEffect, ReadDirEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc canonicalImportAux(conf: ConfigRef; file: AbsoluteFile): string {.
+    ...raises: [Exception, KeyError], tags: [RootEffect, ReadDirEffect],
+    forbids: [].}
+
+ + Shows the canonical module import, e.g.: system, std/tables, fusion/pointers, system/assertions, std/private/asciitables + Source   +Edit   + +
+
+ +
+
+
+
proc canonicalizePath(conf: ConfigRef; path: AbsoluteFile): AbsoluteFile {.
+    ...raises: [OSError], tags: [ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clearNimblePath(conf: ConfigRef) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc completeGeneratedFilePath(conf: ConfigRef; f: AbsoluteFile;
+                               createSubDir: bool = true): AbsoluteFile {.
+    ...raises: [OSError, IOError],
+    tags: [ReadEnvEffect, ReadIOEffect, WriteDirEffect, ReadDirEffect],
+    forbids: [].}
+
+ + Return an absolute path of a generated intermediary file. Optionally creates the cache directory if createSubDir is true. + Source   +Edit   + +
+
+ +
+
+
+
proc cppDefine(c: ConfigRef; define: string) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc disableNimblePath(conf: ConfigRef) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc existsConfigVar(conf: ConfigRef; key: string): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc expandDone(conf: ConfigRef): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc findFile(conf: ConfigRef; f: string; suppressStdlib = false): AbsoluteFile {.
+    ...raises: [OSError, KeyError], tags: [ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc findModule(conf: ConfigRef; modulename, currentModule: string): AbsoluteFile {.
+    ...raises: [OSError, KeyError], tags: [ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc findProjectNimFile(conf: ConfigRef; pkg: string): string {.
+    ...raises: [OSError], tags: [ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc floatInt64Align(conf: ConfigRef): int16 {....raises: [], tags: [], forbids: [].}
+
+ + Returns either 4 or 8 depending on reasons. + Source   +Edit   + +
+
+ +
+
+
+
proc getClockStr(): string {....raises: [], tags: [ReadEnvEffect, TimeEffect],
+                             forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getConfigVar(conf: ConfigRef; key: string; default = ""): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getDateStr(): string {....raises: [], tags: [ReadEnvEffect, TimeEffect],
+                            forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getNimbleFile(conf: ConfigRef; path: string): string {....raises: [KeyError],
+    tags: [ReadDirEffect], forbids: [].}
+
+ + returns absolute path to nimble file, e.g.: /pathto/cligen.nimble + Source   +Edit   + +
+
+ +
+
+
+
proc getNimcacheDir(conf: ConfigRef): AbsoluteDir {....raises: [OSError],
+    tags: [ReadEnvEffect, ReadIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getOutFile(conf: ConfigRef; filename: RelativeFile; ext: string): AbsoluteFile {.
+    ...raises: [OSError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getPackageName(conf: ConfigRef; path: string): string {....raises: [KeyError],
+    tags: [ReadDirEffect], forbids: [].}
+
+ + returns nimble package name, e.g.: cligen + Source   +Edit   + +
+
+ +
+
+
+
proc getPrefixDir(conf: ConfigRef): AbsoluteDir {....raises: [],
+    tags: [ReadIOEffect], forbids: [].}
+
+ +

Gets the prefix dir, usually the parent directory where the binary resides.

+

This is overridden by some tools (namely nimsuggest) via the conf.prefixDir field. This should resolve to root of nim sources, whether running nim from a local clone or using installed nim, so that these exist: result/doc/advopt.txt and result/lib/system.nim

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getRelativePathFromConfigPath(conf: ConfigRef; f: AbsoluteFile;
+                                   isTitle = false): RelativeFile {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasHint(conf: ConfigRef; note: TNoteKind): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasWarn(conf: ConfigRef; note: TNoteKind): bool {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hcrOn(conf: ConfigRef): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc importantComments(conf: ConfigRef): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inclDynlibOverride(conf: ConfigRef; lib: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isDefined(conf: ConfigRef; symbol: string): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isDynlibOverride(conf: ConfigRef; lib: string): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mainCommandArg(conf: ConfigRef): string {....raises: [], tags: [], forbids: [].}
+
+ + This is intended for commands like check or parse which will work on the main project file unless explicitly given a specific file argument + Source   +Edit   + +
+
+ +
+
+
+
proc newConfigRef(): ConfigRef {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newPartialConfigRef(): ConfigRef {....raises: [], tags: [], forbids: [].}
+
+ + create a new ConfigRef that is only good enough for error reporting. + Source   +Edit   + +
+
+ +
+
+
+
proc parseIdeCmd(s: string): IdeCmd {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pathSubs(conf: ConfigRef; p, config: string): string {.
+    ...raises: [ValueError, OSError], tags: [ReadEnvEffect, ReadIOEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc prepareToWriteOutput(conf: ConfigRef): AbsoluteFile {.
+    ...raises: [OSError, IOError], tags: [ReadDirEffect, WriteDirEffect],
+    forbids: [].}
+
+ + Create the output directory and returns a full path to the output file + Source   +Edit   + +
+
+ +
+
+
+
proc removeTrailingDirSep(path: string): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setConfigVar(conf: ConfigRef; key, val: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setDefaultLibpath(conf: ConfigRef) {....raises: [OSError],
+    tags: [ReadIOEffect, ReadDirEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setFromProjectName(conf: ConfigRef; projectName: string) {.
+    ...raises: [OSError], tags: [ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setNote(conf: ConfigRef; note: TNoteKind; enabled = true) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setNoteDefaults(conf: ConfigRef; note: TNoteKind; enabled = true) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc showNonExportedFields(conf: ConfigRef) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toGeneratedFile(conf: ConfigRef; path: AbsoluteFile; ext: string): AbsoluteFile {.
+    ...raises: [OSError], tags: [ReadEnvEffect, ReadIOEffect], forbids: [].}
+
+ + converts "/home/a/mymodule.nim", "rod" to "/home/a/nimcache/mymodule.rod" + Source   +Edit   + +
+
+ +
+
+
+
proc usesWriteBarrier(conf: ConfigRef): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator nimbleSubs(conf: ConfigRef; p: string): string {....raises: [ValueError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template compilationCachePresent(conf: ConfigRef): untyped
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template newPackageCache(): untyped
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template optPreserveOrigSource(conf: ConfigRef): untyped
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template quitOrRaise(conf: ConfigRef; msg = "")
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template setErrorMaxHighMaybe(conf: ConfigRef)
+
+ + do not stop after first error (but honor --errorMax if provided) + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/options.idx b/compiler/options.idx new file mode 100644 index 0000000000000..c33911da1ba96 --- /dev/null +++ b/compiler/options.idx @@ -0,0 +1,331 @@ +nimTitle options options.html module options 0 +nim hasTinyCBackend options.html#hasTinyCBackend const hasTinyCBackend 24 +nim useEffectSystem options.html#useEffectSystem const useEffectSystem 25 +nim useWriteTracking options.html#useWriteTracking const useWriteTracking 26 +nim hasFFI options.html#hasFFI const hasFFI 27 +nim copyrightYear options.html#copyrightYear const copyrightYear 28 +nim nimEnableCovariance options.html#nimEnableCovariance const nimEnableCovariance 30 +nim optNone options.html#optNone TOption.optNone 34 +nim optObjCheck options.html#optObjCheck TOption.optObjCheck 34 +nim optFieldCheck options.html#optFieldCheck TOption.optFieldCheck 34 +nim optRangeCheck options.html#optRangeCheck TOption.optRangeCheck 34 +nim optBoundsCheck options.html#optBoundsCheck TOption.optBoundsCheck 34 +nim optOverflowCheck options.html#optOverflowCheck TOption.optOverflowCheck 34 +nim optRefCheck options.html#optRefCheck TOption.optRefCheck 34 +nim optNaNCheck options.html#optNaNCheck TOption.optNaNCheck 34 +nim optInfCheck options.html#optInfCheck TOption.optInfCheck 34 +nim optStaticBoundsCheck options.html#optStaticBoundsCheck TOption.optStaticBoundsCheck 34 +nim optStyleCheck options.html#optStyleCheck TOption.optStyleCheck 34 +nim optAssert options.html#optAssert TOption.optAssert 34 +nim optLineDir options.html#optLineDir TOption.optLineDir 34 +nim optWarns options.html#optWarns TOption.optWarns 34 +nim optHints options.html#optHints TOption.optHints 34 +nim optOptimizeSpeed options.html#optOptimizeSpeed TOption.optOptimizeSpeed 34 +nim optOptimizeSize options.html#optOptimizeSize TOption.optOptimizeSize 34 +nim optStackTrace options.html#optStackTrace TOption.optStackTrace 34 +nim optStackTraceMsgs options.html#optStackTraceMsgs TOption.optStackTraceMsgs 34 +nim optLineTrace options.html#optLineTrace TOption.optLineTrace 34 +nim optByRef options.html#optByRef TOption.optByRef 34 +nim optProfiler options.html#optProfiler TOption.optProfiler 34 +nim optImplicitStatic options.html#optImplicitStatic TOption.optImplicitStatic 34 +nim optTrMacros options.html#optTrMacros TOption.optTrMacros 34 +nim optMemTracker options.html#optMemTracker TOption.optMemTracker 34 +nim optSinkInference options.html#optSinkInference TOption.optSinkInference 34 +nim optCursorInference options.html#optCursorInference TOption.optCursorInference 34 +nim optImportHidden options.html#optImportHidden TOption.optImportHidden 34 +nim optQuirky options.html#optQuirky TOption.optQuirky 34 +nim TOption options.html#TOption enum TOption 34 +nim TOptions options.html#TOptions type TOptions 55 +nim gloptNone options.html#gloptNone TGlobalOption.gloptNone 56 +nim optForceFullMake options.html#optForceFullMake TGlobalOption.optForceFullMake 56 +nim optWasNimscript options.html#optWasNimscript TGlobalOption.optWasNimscript 56 +nim optListCmd options.html#optListCmd TGlobalOption.optListCmd 56 +nim optCompileOnly options.html#optCompileOnly TGlobalOption.optCompileOnly 56 +nim optNoLinking options.html#optNoLinking TGlobalOption.optNoLinking 56 +nim optCDebug options.html#optCDebug TGlobalOption.optCDebug 56 +nim optGenDynLib options.html#optGenDynLib TGlobalOption.optGenDynLib 56 +nim optGenStaticLib options.html#optGenStaticLib TGlobalOption.optGenStaticLib 56 +nim optGenGuiApp options.html#optGenGuiApp TGlobalOption.optGenGuiApp 56 +nim optGenScript options.html#optGenScript TGlobalOption.optGenScript 56 +nim optGenCDeps options.html#optGenCDeps TGlobalOption.optGenCDeps 56 +nim optGenMapping options.html#optGenMapping TGlobalOption.optGenMapping 56 +nim optRun options.html#optRun TGlobalOption.optRun 56 +nim optUseNimcache options.html#optUseNimcache TGlobalOption.optUseNimcache 56 +nim optStyleHint options.html#optStyleHint TGlobalOption.optStyleHint 56 +nim optStyleError options.html#optStyleError TGlobalOption.optStyleError 56 +nim optStyleUsages options.html#optStyleUsages TGlobalOption.optStyleUsages 56 +nim optSkipSystemConfigFile options.html#optSkipSystemConfigFile TGlobalOption.optSkipSystemConfigFile 56 +nim optSkipProjConfigFile options.html#optSkipProjConfigFile TGlobalOption.optSkipProjConfigFile 56 +nim optSkipUserConfigFile options.html#optSkipUserConfigFile TGlobalOption.optSkipUserConfigFile 56 +nim optSkipParentConfigFiles options.html#optSkipParentConfigFiles TGlobalOption.optSkipParentConfigFiles 56 +nim optNoMain options.html#optNoMain TGlobalOption.optNoMain 56 +nim optUseColors options.html#optUseColors TGlobalOption.optUseColors 56 +nim optThreads options.html#optThreads TGlobalOption.optThreads 56 +nim optStdout options.html#optStdout TGlobalOption.optStdout 56 +nim optThreadAnalysis options.html#optThreadAnalysis TGlobalOption.optThreadAnalysis 56 +nim optTlsEmulation options.html#optTlsEmulation TGlobalOption.optTlsEmulation 56 +nim optGenIndex options.html#optGenIndex TGlobalOption.optGenIndex 56 +nim optGenIndexOnly options.html#optGenIndexOnly TGlobalOption.optGenIndexOnly 56 +nim optNoImportdoc options.html#optNoImportdoc TGlobalOption.optNoImportdoc 56 +nim optEmbedOrigSrc options.html#optEmbedOrigSrc TGlobalOption.optEmbedOrigSrc 56 +nim optIdeDebug options.html#optIdeDebug TGlobalOption.optIdeDebug 56 +nim optIdeTerse options.html#optIdeTerse TGlobalOption.optIdeTerse 56 +nim optIdeExceptionInlayHints options.html#optIdeExceptionInlayHints TGlobalOption.optIdeExceptionInlayHints 56 +nim optExcessiveStackTrace options.html#optExcessiveStackTrace TGlobalOption.optExcessiveStackTrace 56 +nim optShowAllMismatches options.html#optShowAllMismatches TGlobalOption.optShowAllMismatches 56 +nim optWholeProject options.html#optWholeProject TGlobalOption.optWholeProject 56 +nim optDocInternal options.html#optDocInternal TGlobalOption.optDocInternal 56 +nim optMixedMode options.html#optMixedMode TGlobalOption.optMixedMode 56 +nim optDeclaredLocs options.html#optDeclaredLocs TGlobalOption.optDeclaredLocs 56 +nim optNoNimblePath options.html#optNoNimblePath TGlobalOption.optNoNimblePath 56 +nim optHotCodeReloading options.html#optHotCodeReloading TGlobalOption.optHotCodeReloading 56 +nim optDynlibOverrideAll options.html#optDynlibOverrideAll TGlobalOption.optDynlibOverrideAll 56 +nim optSeqDestructors options.html#optSeqDestructors TGlobalOption.optSeqDestructors 56 +nim optTinyRtti options.html#optTinyRtti TGlobalOption.optTinyRtti 56 +nim optOwnedRefs options.html#optOwnedRefs TGlobalOption.optOwnedRefs 56 +nim optMultiMethods options.html#optMultiMethods TGlobalOption.optMultiMethods 56 +nim optBenchmarkVM options.html#optBenchmarkVM TGlobalOption.optBenchmarkVM 56 +nim optProduceAsm options.html#optProduceAsm TGlobalOption.optProduceAsm 56 +nim optPanics options.html#optPanics TGlobalOption.optPanics 56 +nim optSourcemap options.html#optSourcemap TGlobalOption.optSourcemap 56 +nim optProfileVM options.html#optProfileVM TGlobalOption.optProfileVM 56 +nim optEnableDeepCopy options.html#optEnableDeepCopy TGlobalOption.optEnableDeepCopy 56 +nim optShowNonExportedFields options.html#optShowNonExportedFields TGlobalOption.optShowNonExportedFields 56 +nim optJsBigInt64 options.html#optJsBigInt64 TGlobalOption.optJsBigInt64 56 +nim TGlobalOption options.html#TGlobalOption enum TGlobalOption 56 +nim TGlobalOptions options.html#TGlobalOptions type TGlobalOptions 114 +nim harmlessOptions options.html#harmlessOptions const harmlessOptions 117 +nim genSubDir options.html#genSubDir const genSubDir 118 +nim NimExt options.html#NimExt const NimExt 119 +nim RodExt options.html#RodExt const RodExt 120 +nim HtmlExt options.html#HtmlExt const HtmlExt 121 +nim JsonExt options.html#JsonExt const JsonExt 122 +nim TagsExt options.html#TagsExt const TagsExt 123 +nim TexExt options.html#TexExt const TexExt 124 +nim IniExt options.html#IniExt const IniExt 125 +nim DefaultConfig options.html#DefaultConfig const DefaultConfig 126 +nim DefaultConfigNims options.html#DefaultConfigNims const DefaultConfigNims 127 +nim DocConfig options.html#DocConfig const DocConfig 128 +nim DocTexConfig options.html#DocTexConfig const DocTexConfig 129 +nim htmldocsDir options.html#htmldocsDir const htmldocsDir 130 +nim docRootDefault options.html#docRootDefault const docRootDefault 131 +nim oKeepVariableNames options.html#oKeepVariableNames const oKeepVariableNames 132 +nim spellSuggestSecretSauce options.html#spellSuggestSecretSauce const spellSuggestSecretSauce 133 +nim backendInvalid options.html#backendInvalid TBackend.backendInvalid 136 +nim backendC options.html#backendC TBackend.backendC 136 +nim backendCpp options.html#backendCpp TBackend.backendCpp 136 +nim backendJs options.html#backendJs TBackend.backendJs 136 +nim backendObjc options.html#backendObjc TBackend.backendObjc 136 +nim TBackend options.html#TBackend enum TBackend 136 +nim cmdNone options.html#cmdNone Command.cmdNone 145 +nim cmdUnknown options.html#cmdUnknown Command.cmdUnknown 145 +nim cmdCompileToC options.html#cmdCompileToC Command.cmdCompileToC 145 +nim cmdCompileToCpp options.html#cmdCompileToCpp Command.cmdCompileToCpp 145 +nim cmdCompileToOC options.html#cmdCompileToOC Command.cmdCompileToOC 145 +nim cmdCompileToJS options.html#cmdCompileToJS Command.cmdCompileToJS 145 +nim cmdCrun options.html#cmdCrun Command.cmdCrun 145 +nim cmdTcc options.html#cmdTcc Command.cmdTcc 145 +nim cmdCheck options.html#cmdCheck Command.cmdCheck 145 +nim cmdM options.html#cmdM Command.cmdM 145 +nim cmdParse options.html#cmdParse Command.cmdParse 145 +nim cmdRod options.html#cmdRod Command.cmdRod 145 +nim cmdIdeTools options.html#cmdIdeTools Command.cmdIdeTools 145 +nim cmdNimscript options.html#cmdNimscript Command.cmdNimscript 145 +nim cmdDoc0 options.html#cmdDoc0 Command.cmdDoc0 145 +nim cmdDoc options.html#cmdDoc Command.cmdDoc 145 +nim cmdDoc2tex options.html#cmdDoc2tex Command.cmdDoc2tex 145 +nim cmdRst2html options.html#cmdRst2html Command.cmdRst2html 145 +nim cmdRst2tex options.html#cmdRst2tex Command.cmdRst2tex 145 +nim cmdMd2html options.html#cmdMd2html Command.cmdMd2html 145 +nim cmdMd2tex options.html#cmdMd2tex Command.cmdMd2tex 145 +nim cmdJsondoc0 options.html#cmdJsondoc0 Command.cmdJsondoc0 145 +nim cmdJsondoc options.html#cmdJsondoc Command.cmdJsondoc 145 +nim cmdCtags options.html#cmdCtags Command.cmdCtags 145 +nim cmdBuildindex options.html#cmdBuildindex Command.cmdBuildindex 145 +nim cmdGendepend options.html#cmdGendepend Command.cmdGendepend 145 +nim cmdDump options.html#cmdDump Command.cmdDump 145 +nim cmdInteractive options.html#cmdInteractive Command.cmdInteractive 145 +nim cmdNop options.html#cmdNop Command.cmdNop 145 +nim cmdJsonscript options.html#cmdJsonscript Command.cmdJsonscript 145 +nim Command options.html#Command enum Command 145 +nim cmdBackends options.html#cmdBackends const cmdBackends 176 +nim cmdDocLike options.html#cmdDocLike const cmdDocLike 178 +nim TStringSeq options.html#TStringSeq type TStringSeq 182 +nim gcUnselected options.html#gcUnselected TGCMode.gcUnselected 183 +nim gcNone options.html#gcNone TGCMode.gcNone 183 +nim gcBoehm options.html#gcBoehm TGCMode.gcBoehm 183 +nim gcRegions options.html#gcRegions TGCMode.gcRegions 183 +nim gcArc options.html#gcArc TGCMode.gcArc 183 +nim gcOrc options.html#gcOrc TGCMode.gcOrc 183 +nim gcAtomicArc options.html#gcAtomicArc TGCMode.gcAtomicArc 183 +nim gcMarkAndSweep options.html#gcMarkAndSweep TGCMode.gcMarkAndSweep 183 +nim gcHooks options.html#gcHooks TGCMode.gcHooks 183 +nim gcRefc options.html#gcRefc TGCMode.gcRefc 183 +nim gcGo options.html#gcGo TGCMode.gcGo 183 +nim TGCMode options.html#TGCMode enum TGCMode 183 +nim ideNone options.html#ideNone IdeCmd.ideNone 198 +nim ideSug options.html#ideSug IdeCmd.ideSug 198 +nim ideCon options.html#ideCon IdeCmd.ideCon 198 +nim ideDef options.html#ideDef IdeCmd.ideDef 198 +nim ideUse options.html#ideUse IdeCmd.ideUse 198 +nim ideDus options.html#ideDus IdeCmd.ideDus 198 +nim ideChk options.html#ideChk IdeCmd.ideChk 198 +nim ideChkFile options.html#ideChkFile IdeCmd.ideChkFile 198 +nim ideMod options.html#ideMod IdeCmd.ideMod 198 +nim ideHighlight options.html#ideHighlight IdeCmd.ideHighlight 198 +nim ideOutline options.html#ideOutline IdeCmd.ideOutline 198 +nim ideKnown options.html#ideKnown IdeCmd.ideKnown 198 +nim ideMsg options.html#ideMsg IdeCmd.ideMsg 198 +nim ideProject options.html#ideProject IdeCmd.ideProject 198 +nim ideGlobalSymbols options.html#ideGlobalSymbols IdeCmd.ideGlobalSymbols 198 +nim ideRecompile options.html#ideRecompile IdeCmd.ideRecompile 198 +nim ideChanged options.html#ideChanged IdeCmd.ideChanged 198 +nim ideType options.html#ideType IdeCmd.ideType 198 +nim ideDeclaration options.html#ideDeclaration IdeCmd.ideDeclaration 198 +nim ideExpand options.html#ideExpand IdeCmd.ideExpand 198 +nim ideInlayHints options.html#ideInlayHints IdeCmd.ideInlayHints 198 +nim IdeCmd options.html#IdeCmd enum IdeCmd 198 +nim dotOperators options.html#dotOperators Feature.dotOperators 203 +nim callOperator options.html#callOperator Feature.callOperator 203 +nim parallel options.html#parallel Feature.parallel 203 +nim destructor options.html#destructor Feature.destructor 203 +nim notnil options.html#notnil Feature.notnil 203 +nim dynamicBindSym options.html#dynamicBindSym Feature.dynamicBindSym 203 +nim forLoopMacros options.html#forLoopMacros Feature.forLoopMacros 203 +nim caseStmtMacros options.html#caseStmtMacros Feature.caseStmtMacros 203 +nim codeReordering options.html#codeReordering Feature.codeReordering 203 +nim compiletimeFFI options.html#compiletimeFFI Feature.compiletimeFFI 203 +nim vmopsDanger options.html#vmopsDanger Feature.vmopsDanger 203 +nim strictFuncs options.html#strictFuncs Feature.strictFuncs 203 +nim views options.html#views Feature.views 203 +nim strictNotNil options.html#strictNotNil Feature.strictNotNil 203 +nim overloadableEnums options.html#overloadableEnums Feature.overloadableEnums 203 +nim strictEffects options.html#strictEffects Feature.strictEffects 203 +nim unicodeOperators options.html#unicodeOperators Feature.unicodeOperators 203 +nim flexibleOptionalParams options.html#flexibleOptionalParams Feature.flexibleOptionalParams 203 +nim strictDefs options.html#strictDefs Feature.strictDefs 203 +nim strictCaseObjects options.html#strictCaseObjects Feature.strictCaseObjects 203 +nim inferGenericTypes options.html#inferGenericTypes Feature.inferGenericTypes 203 +nim openSym options.html#openSym Feature.openSym 203 +nim genericsOpenSym options.html#genericsOpenSym Feature.genericsOpenSym 203 +nim vtables options.html#vtables Feature.vtables 203 +nim typeBoundOps options.html#typeBoundOps Feature.typeBoundOps 203 +nim Feature options.html#Feature enum Feature 203 +nim allowSemcheckedAstModification options.html#allowSemcheckedAstModification LegacyFeature.allowSemcheckedAstModification 234 +nim checkUnsignedConversions options.html#checkUnsignedConversions LegacyFeature.checkUnsignedConversions 234 +nim laxEffects options.html#laxEffects LegacyFeature.laxEffects 234 +nim verboseTypeMismatch options.html#verboseTypeMismatch LegacyFeature.verboseTypeMismatch 234 +nim emitGenerics options.html#emitGenerics LegacyFeature.emitGenerics 234 +nim jsNoLambdaLifting options.html#jsNoLambdaLifting LegacyFeature.jsNoLambdaLifting 234 +nim noStrictDefs options.html#noStrictDefs LegacyFeature.noStrictDefs 234 +nim LegacyFeature options.html#LegacyFeature enum LegacyFeature 234 +nim disabledSf options.html#disabledSf SymbolFilesOption.disabledSf 254 +nim writeOnlySf options.html#writeOnlySf SymbolFilesOption.writeOnlySf 254 +nim readOnlySf options.html#readOnlySf SymbolFilesOption.readOnlySf 254 +nim v2Sf options.html#v2Sf SymbolFilesOption.v2Sf 254 +nim stressTest options.html#stressTest SymbolFilesOption.stressTest 254 +nim SymbolFilesOption options.html#SymbolFilesOption enum SymbolFilesOption 254 +nim ccNone options.html#ccNone TSystemCC.ccNone 257 +nim ccGcc options.html#ccGcc TSystemCC.ccGcc 257 +nim ccNintendoSwitch options.html#ccNintendoSwitch TSystemCC.ccNintendoSwitch 257 +nim ccLLVM_Gcc options.html#ccLLVM_Gcc TSystemCC.ccLLVM_Gcc 257 +nim ccCLang options.html#ccCLang TSystemCC.ccCLang 257 +nim ccBcc options.html#ccBcc TSystemCC.ccBcc 257 +nim ccVcc options.html#ccVcc TSystemCC.ccVcc 257 +nim ccTcc options.html#ccTcc TSystemCC.ccTcc 257 +nim ccEnv options.html#ccEnv TSystemCC.ccEnv 257 +nim ccIcl options.html#ccIcl TSystemCC.ccIcl 257 +nim ccIcc options.html#ccIcc TSystemCC.ccIcc 257 +nim ccClangCl options.html#ccClangCl TSystemCC.ccClangCl 257 +nim ccHipcc options.html#ccHipcc TSystemCC.ccHipcc 257 +nim ccNvcc options.html#ccNvcc TSystemCC.ccNvcc 257 +nim TSystemCC options.html#TSystemCC enum TSystemCC 257 +nim excNone options.html#excNone ExceptionSystem.excNone 261 +nim excSetjmp options.html#excSetjmp ExceptionSystem.excSetjmp 261 +nim excCpp options.html#excCpp ExceptionSystem.excCpp 261 +nim excGoto options.html#excGoto ExceptionSystem.excGoto 261 +nim excQuirky options.html#excQuirky ExceptionSystem.excQuirky 261 +nim ExceptionSystem options.html#ExceptionSystem enum ExceptionSystem 261 +nim CfileFlag options.html#CfileFlag enum CfileFlag 268 +nim Cfile options.html#Cfile object Cfile 272 +nim CfileList options.html#CfileList type CfileList 277 +nim Suggest options.html#Suggest type Suggest 279 +nim Suggestions options.html#Suggestions type Suggestions 301 +nim sihkType options.html#sihkType SuggestInlayHintKind.sihkType 303 +nim sihkParameter options.html#sihkParameter SuggestInlayHintKind.sihkParameter 303 +nim sihkException options.html#sihkException SuggestInlayHintKind.sihkException 303 +nim SuggestInlayHintKind options.html#SuggestInlayHintKind enum SuggestInlayHintKind 303 +nim SuggestInlayHint options.html#SuggestInlayHint type SuggestInlayHint 308 +nim ProfileInfo options.html#ProfileInfo object ProfileInfo 318 +nim ProfileData options.html#ProfileData type ProfileData 322 +nim stdOrrStdout options.html#stdOrrStdout StdOrrKind.stdOrrStdout 325 +nim stdOrrStderr options.html#stdOrrStderr StdOrrKind.stdOrrStderr 325 +nim StdOrrKind options.html#StdOrrKind enum StdOrrKind 325 +nim foAbs options.html#foAbs FilenameOption.foAbs 329 +nim foRelProject options.html#foRelProject FilenameOption.foRelProject 329 +nim foCanonical options.html#foCanonical FilenameOption.foCanonical 329 +nim foLegacyRelProj options.html#foLegacyRelProj FilenameOption.foLegacyRelProj 329 +nim foName options.html#foName FilenameOption.foName 329 +nim foStacktrace options.html#foStacktrace FilenameOption.foStacktrace 329 +nim FilenameOption options.html#FilenameOption enum FilenameOption 329 +nim ConfigRef options.html#ConfigRef type ConfigRef 337 +nim assignIfDefault options.html#assignIfDefault,T,T,typeof(default(T)) proc assignIfDefault[T](result: var T; val: T; def = default(T)) 454 +nim setErrorMaxHighMaybe options.html#setErrorMaxHighMaybe.t,ConfigRef template setErrorMaxHighMaybe(conf: ConfigRef) 458 +nim setNoteDefaults options.html#setNoteDefaults,ConfigRef,TNoteKind proc setNoteDefaults(conf: ConfigRef; note: TNoteKind; enabled = true) 462 +nim setNote options.html#setNote,ConfigRef,TNoteKind proc setNote(conf: ConfigRef; note: TNoteKind; enabled = true) 469 +nim hasHint options.html#hasHint,ConfigRef,TNoteKind proc hasHint(conf: ConfigRef; note: TNoteKind): bool 474 +nim hasWarn options.html#hasWarn,ConfigRef,TNoteKind proc hasWarn(conf: ConfigRef; note: TNoteKind): bool 483 +nim hcrOn options.html#hcrOn,ConfigRef proc hcrOn(conf: ConfigRef): bool 486 +nim oldExperimentalFeatures options.html#oldExperimentalFeatures const oldExperimentalFeatures 495 +nim ChecksOptions options.html#ChecksOptions const ChecksOptions 498 +nim DefaultOptions options.html#DefaultOptions const DefaultOptions 502 +nim DefaultGlobalOptions options.html#DefaultGlobalOptions const DefaultGlobalOptions 506 +nim getDateStr options.html#getDateStr proc getDateStr(): string 521 +nim getClockStr options.html#getClockStr proc getClockStr(): string 524 +nim newPackageCache options.html#newPackageCache.t template newPackageCache(): untyped 527 +nim foreignPackageNotesDefault options.html#foreignPackageNotesDefault const foreignPackageNotesDefault 536 +nim isDefined options.html#isDefined,ConfigRef,string proc isDefined(conf: ConfigRef; symbol: string): bool 539 +nim newConfigRef options.html#newConfigRef proc newConfigRef(): ConfigRef 558 +nim newPartialConfigRef options.html#newPartialConfigRef proc newPartialConfigRef(): ConfigRef 615 +nim cppDefine options.html#cppDefine,ConfigRef,string proc cppDefine(c: ConfigRef; define: string) 623 +nim quitOrRaise options.html#quitOrRaise.t,ConfigRef,string template quitOrRaise(conf: ConfigRef; msg = "") 678 +nim importantComments options.html#importantComments,ConfigRef proc importantComments(conf: ConfigRef): bool 685 +nim usesWriteBarrier options.html#usesWriteBarrier,ConfigRef proc usesWriteBarrier(conf: ConfigRef): bool 686 +nim compilationCachePresent options.html#compilationCachePresent.t,ConfigRef template compilationCachePresent(conf: ConfigRef): untyped 688 +nim optPreserveOrigSource options.html#optPreserveOrigSource.t,ConfigRef template optPreserveOrigSource(conf: ConfigRef): untyped 692 +nim mainCommandArg options.html#mainCommandArg,ConfigRef proc mainCommandArg(conf: ConfigRef): string 695 +nim existsConfigVar options.html#existsConfigVar,ConfigRef,string proc existsConfigVar(conf: ConfigRef; key: string): bool 704 +nim getConfigVar options.html#getConfigVar,ConfigRef,string,string proc getConfigVar(conf: ConfigRef; key: string; default = ""): string 707 +nim setConfigVar options.html#setConfigVar,ConfigRef,string,string proc setConfigVar(conf: ConfigRef; key, val: string) 710 +nim getOutFile options.html#getOutFile,ConfigRef,RelativeFile,string proc getOutFile(conf: ConfigRef; filename: RelativeFile; ext: string): AbsoluteFile 713 +nim absOutFile options.html#absOutFile,ConfigRef proc absOutFile(conf: ConfigRef): AbsoluteFile 720 +nim prepareToWriteOutput options.html#prepareToWriteOutput,ConfigRef proc prepareToWriteOutput(conf: ConfigRef): AbsoluteFile 727 +nim getPrefixDir options.html#getPrefixDir,ConfigRef proc getPrefixDir(conf: ConfigRef): AbsoluteDir 732 +nim setDefaultLibpath options.html#setDefaultLibpath,ConfigRef proc setDefaultLibpath(conf: ConfigRef) 753 +nim canonicalizePath options.html#canonicalizePath,ConfigRef,AbsoluteFile proc canonicalizePath(conf: ConfigRef; path: AbsoluteFile): AbsoluteFile 769 +nim setFromProjectName options.html#setFromProjectName,ConfigRef,string proc setFromProjectName(conf: ConfigRef; projectName: string) 772 +nim removeTrailingDirSep options.html#removeTrailingDirSep,string proc removeTrailingDirSep(path: string): string 785 +nim disableNimblePath options.html#disableNimblePath,ConfigRef proc disableNimblePath(conf: ConfigRef) 791 +nim clearNimblePath options.html#clearNimblePath,ConfigRef proc clearNimblePath(conf: ConfigRef) 796 +nim getNimbleFile options.html#getNimbleFile,ConfigRef,string proc getNimbleFile(conf: ConfigRef; path: string): string 18 +nim getPackageName options.html#getPackageName,ConfigRef,string proc getPackageName(conf: ConfigRef; path: string): string 38 +nim getNimcacheDir options.html#getNimcacheDir,ConfigRef proc getNimcacheDir(conf: ConfigRef): AbsoluteDir 808 +nim pathSubs options.html#pathSubs,ConfigRef,string,string proc pathSubs(conf: ConfigRef; p, config: string): string 827 +nim nimbleSubs options.html#nimbleSubs.i,ConfigRef,string iterator nimbleSubs(conf: ConfigRef; p: string): string 839 +nim toGeneratedFile options.html#toGeneratedFile,ConfigRef,AbsoluteFile,string proc toGeneratedFile(conf: ConfigRef; path: AbsoluteFile; ext: string): AbsoluteFile 848 +nim completeGeneratedFilePath options.html#completeGeneratedFilePath,ConfigRef,AbsoluteFile,bool proc completeGeneratedFilePath(conf: ConfigRef; f: AbsoluteFile;\n createSubDir: bool = true): AbsoluteFile 853 +nim stdlibDirs options.html#stdlibDirs const stdlibDirs 892 +nim stdPrefix options.html#stdPrefix const stdPrefix 903 +nim getRelativePathFromConfigPath options.html#getRelativePathFromConfigPath,ConfigRef,AbsoluteFile proc getRelativePathFromConfigPath(conf: ConfigRef; f: AbsoluteFile; isTitle = false): RelativeFile 905 +nim findFile options.html#findFile,ConfigRef,string proc findFile(conf: ConfigRef; f: string; suppressStdlib = false): AbsoluteFile 921 +nim findModule options.html#findModule,ConfigRef,string,string proc findModule(conf: ConfigRef; modulename, currentModule: string): AbsoluteFile 934 +nim findProjectNimFile options.html#findProjectNimFile,ConfigRef,string proc findProjectNimFile(conf: ConfigRef; pkg: string): string 960 +nim canonicalImportAux options.html#canonicalImportAux,ConfigRef,AbsoluteFile proc canonicalImportAux(conf: ConfigRef; file: AbsoluteFile): string 1000 +nim canonicalImport options.html#canonicalImport,ConfigRef,AbsoluteFile proc canonicalImport(conf: ConfigRef; file: AbsoluteFile): string 1015 +nim inclDynlibOverride options.html#inclDynlibOverride,ConfigRef,string proc inclDynlibOverride(conf: ConfigRef; lib: string) 1027 +nim isDynlibOverride options.html#isDynlibOverride,ConfigRef,string proc isDynlibOverride(conf: ConfigRef; lib: string): bool 1030 +nim showNonExportedFields options.html#showNonExportedFields,ConfigRef proc showNonExportedFields(conf: ConfigRef) 1034 +nim expandDone options.html#expandDone,ConfigRef proc expandDone(conf: ConfigRef): bool 1037 +nim parseIdeCmd options.html#parseIdeCmd,string proc parseIdeCmd(s: string): IdeCmd 1040 +nim `$` options.html#$,IdeCmd proc `$`(c: IdeCmd): string 1061 +nim floatInt64Align options.html#floatInt64Align,ConfigRef proc floatInt64Align(conf: ConfigRef): int16 1085 diff --git a/compiler/packages.html b/compiler/packages.html new file mode 100644 index 0000000000000..760b7855449bf --- /dev/null +++ b/compiler/packages.html @@ -0,0 +1,208 @@ + + + + + + + +packages + + + + + + + + + + + + + + + + +
+
+

packages

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Package related procs.

+

See Also:

+
  • packagehandling for package path handling
  • +
  • modulegraphs.getPackage
  • +
  • modulegraphs.belongsToStdlib
  • +
+

+ +
+

Procs

+
+
+
+
func belongsToProjectPackage(conf: ConfigRef; sym: PSym): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Return whether the symbol belongs to the project's package.

+

See Also:

+
  • modulegraphs.belongsToStdlib
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
func belongsToProjectPackageMaybeNil(conf: ConfigRef; sym: PSym): bool {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Return whether the symbol belongs to the project's package. Returns false if sym is nil.

+

See Also:

+
  • modulegraphs.belongsToStdlib
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
proc getPackage(conf: ConfigRef; cache: IdentCache; fileIdx: FileIndex): PSym {.
+    ...raises: [KeyError], tags: [ReadDirEffect], forbids: [].}
+
+ +

Return a new package symbol.

+

See Also:

+
  • modulegraphs.getPackage
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
func getPackageId(sym: PSym): int {....raises: [], tags: [], forbids: [].}
+
+ + Return the owning package ID. + Source   +Edit   + +
+
+ +
+
+
+
func getPackageSymbol(sym: PSym): PSym {....raises: [], tags: [], forbids: [].}
+
+ + Return the owning package symbol. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/packages.idx b/compiler/packages.idx new file mode 100644 index 0000000000000..9610d0ae51ac7 --- /dev/null +++ b/compiler/packages.idx @@ -0,0 +1,6 @@ +nimTitle packages packages.html module packages 0 +nim getPackage packages.html#getPackage,ConfigRef,IdentCache,FileIndex proc getPackage(conf: ConfigRef; cache: IdentCache; fileIdx: FileIndex): PSym 23 +nim getPackageSymbol packages.html#getPackageSymbol,PSym proc getPackageSymbol(sym: PSym): PSym 36 +nim getPackageId packages.html#getPackageId,PSym proc getPackageId(sym: PSym): int 44 +nim belongsToProjectPackage packages.html#belongsToProjectPackage,ConfigRef,PSym proc belongsToProjectPackage(conf: ConfigRef; sym: PSym): bool 48 +nim belongsToProjectPackageMaybeNil packages.html#belongsToProjectPackageMaybeNil,ConfigRef,PSym proc belongsToProjectPackageMaybeNil(conf: ConfigRef; sym: PSym): bool 55 diff --git a/compiler/parampatterns.html b/compiler/parampatterns.html new file mode 100644 index 0000000000000..cd60ad8c583f5 --- /dev/null +++ b/compiler/parampatterns.html @@ -0,0 +1,311 @@ + + + + + + + +parampatterns + + + + + + + + + + + + + + + + +
+
+

parampatterns

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module implements the pattern matching features for term rewriting macro support.

+ +
+

Types

+
+
+
TAliasRequest = enum
+  aqNone = 1, aqShouldAlias, aqNoAlias
+
+ + + Source   +Edit   + +
+
+
+
TAssignableResult = enum
+  arNone, arLValue, arLocalLValue, arDiscriminant, arAddressableConst,
+  arLentValue, arStrange
+
+ + + Source   +Edit   + +
+
+
+
TSideEffectAnalysis = enum
+  seUnknown, seSideEffect, seNoSideEffect
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
MaxStackSize = 64
+
+ + max required stack size by the VM + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc checkForSideEffects(n: PNode): TSideEffectAnalysis {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc exprRoot(n: PNode; allowCalls = true): PSym {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isAssignable(owner: PSym; n: PNode): TAssignableResult {.
+    ...raises: [KeyError, Exception, ValueError, ERecoverableError],
+    tags: [RootEffect], forbids: [].}
+
+ + 'owner' can be nil! + Source   +Edit   + +
+
+ +
+
+
+
proc isLValue(n: PNode): bool {....raises: [KeyError, Exception, ValueError,
+    ERecoverableError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc matchNodeKinds(p, n: PNode): bool {.
+    ...raises: [KeyError, Exception, ValueError, ERecoverableError],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc semNodeKindConstraints(n: PNode; conf: ConfigRef; start: Natural): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + does semantic checking for a node kind pattern and compiles it into an efficient internal format. + Source   +Edit   + +
+
+ +
+
+
+
proc whichAlias(p: PSym): TAliasRequest {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/parampatterns.idx b/compiler/parampatterns.idx new file mode 100644 index 0000000000000..04d4737bdb050 --- /dev/null +++ b/compiler/parampatterns.idx @@ -0,0 +1,25 @@ +nimTitle parampatterns parampatterns.html module parampatterns 0 +nim aqNone parampatterns.html#aqNone TAliasRequest.aqNone 22 +nim aqShouldAlias parampatterns.html#aqShouldAlias TAliasRequest.aqShouldAlias 22 +nim aqNoAlias parampatterns.html#aqNoAlias TAliasRequest.aqNoAlias 22 +nim TAliasRequest parampatterns.html#TAliasRequest enum TAliasRequest 22 +nim MaxStackSize parampatterns.html#MaxStackSize const MaxStackSize 45 +nim whichAlias parampatterns.html#whichAlias,PSym proc whichAlias(p: PSym): TAliasRequest 53 +nim semNodeKindConstraints parampatterns.html#semNodeKindConstraints,PNode,ConfigRef,Natural proc semNodeKindConstraints(n: PNode; conf: ConfigRef; start: Natural): PNode 120 +nim seUnknown parampatterns.html#seUnknown TSideEffectAnalysis.seUnknown 136 +nim seSideEffect parampatterns.html#seSideEffect TSideEffectAnalysis.seSideEffect 136 +nim seNoSideEffect parampatterns.html#seNoSideEffect TSideEffectAnalysis.seNoSideEffect 136 +nim TSideEffectAnalysis parampatterns.html#TSideEffectAnalysis enum TSideEffectAnalysis 136 +nim checkForSideEffects parampatterns.html#checkForSideEffects,PNode proc checkForSideEffects(n: PNode): TSideEffectAnalysis 139 +nim arNone parampatterns.html#arNone TAssignableResult.arNone 178 +nim arLValue parampatterns.html#arLValue TAssignableResult.arLValue 178 +nim arLocalLValue parampatterns.html#arLocalLValue TAssignableResult.arLocalLValue 178 +nim arDiscriminant parampatterns.html#arDiscriminant TAssignableResult.arDiscriminant 178 +nim arAddressableConst parampatterns.html#arAddressableConst TAssignableResult.arAddressableConst 178 +nim arLentValue parampatterns.html#arLentValue TAssignableResult.arLentValue 178 +nim arStrange parampatterns.html#arStrange TAssignableResult.arStrange 178 +nim TAssignableResult parampatterns.html#TAssignableResult enum TAssignableResult 178 +nim exprRoot parampatterns.html#exprRoot,PNode proc exprRoot(n: PNode; allowCalls = true): PSym 188 +nim isAssignable parampatterns.html#isAssignable,PSym,PNode proc isAssignable(owner: PSym; n: PNode): TAssignableResult 219 +nim isLValue parampatterns.html#isLValue,PNode proc isLValue(n: PNode): bool 314 +nim matchNodeKinds parampatterns.html#matchNodeKinds,PNode,PNode proc matchNodeKinds(p, n: PNode): bool 317 diff --git a/compiler/parser.html b/compiler/parser.html new file mode 100644 index 0000000000000..2058e714b53fb --- /dev/null +++ b/compiler/parser.html @@ -0,0 +1,648 @@ + + + + + + + +parser + + + + + + + + + + + + + + + + +
+
+

parser

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
Parser = object
+  lex*: Lexer
+  tok*: Token
+  lineStartPrevious*: int
+  lineNumberPrevious*: int
+  bufposPrevious*: int
+  inPragma*: int
+  inSemiStmtList*: int
+  when not defined(nimCustomAst):
+  when defined(nimpretty):
+    em*: Emitter
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc checkFirstLineIndentation(p: var Parser) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc closeParser(p: var Parser) {....raises: [IOError], tags: [], forbids: [].}
+
+ + Close a parser, freeing up its resources. + Source   +Edit   + +
+
+ +
+
+
+
proc eat(p: var Parser; tokType: TokType) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc expectIdent(p: Parser) {....raises: [Exception, ValueError, KeyError, IOError,
+                                       ERecoverableError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc expectIdentOrKeyw(p: Parser) {....raises: [Exception, ValueError, KeyError,
+    IOError, ERecoverableError], tags: [RootEffect, ReadDirEffect,
+                                        WriteIOEffect, ReadIOEffect,
+                                        ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getTok(p: var Parser) {....raises: [Exception, ValueError, KeyError, IOError,
+                                      ERecoverableError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc indAndComment(p: var Parser; n: PNode; maybeMissEquals = false) {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isOperator(tok: Token): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newFloatNodeP(kind: TNodeKind; floatVal: BiggestFloat; p: Parser): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newIdentNodeP(ident: PIdent; p: Parser): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newIntNodeP(kind: TNodeKind; intVal: BiggestInt; p: Parser): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newNodeP(kind: TNodeKind; p: Parser): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newStrNodeP(kind: TNodeKind; strVal: sink string; p: Parser): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc openParser(p: var Parser; fileIdx: FileIndex; inputStream: PLLStream;
+                cache: IdentCache; config: ConfigRef) {.
+    ...raises: [IOError, Exception, ValueError, KeyError, ERecoverableError], tags: [
+    ReadIOEffect, RootEffect, ReadDirEffect, WriteIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + Open a parser, using the given arguments to set up its internal state. + Source   +Edit   + +
+
+
+
proc openParser(p: var Parser; filename: AbsoluteFile; inputStream: PLLStream;
+                cache: IdentCache; config: ConfigRef) {.
+    ...raises: [IOError, Exception, ValueError, KeyError, ERecoverableError], tags: [
+    ReadIOEffect, RootEffect, ReadDirEffect, WriteIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc optInd(p: var Parser; n: PNode) {....raises: [KeyError, Exception, ValueError,
+    IOError, ERecoverableError], tags: [RootEffect, ReadDirEffect,
+                                        WriteIOEffect, ReadIOEffect,
+                                        ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc optPar(p: var Parser) {....raises: [Exception, ValueError, KeyError, IOError,
+                                      ERecoverableError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc parLineInfo(p: Parser): TLineInfo {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc parMessage(p: Parser; msg: TMsgKind; arg: string = "") {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc parseAll(p: var Parser): PNode {....raises: [Exception, ValueError, KeyError,
+    IOError, ERecoverableError], tags: [RootEffect, ReadDirEffect,
+                                        WriteIOEffect, ReadIOEffect,
+                                        ReadEnvEffect], forbids: [].}
+
+ + Parses the rest of the input stream held by the parser into a PNode. + Source   +Edit   + +
+
+ +
+
+
+
proc parseString(s: string; cache: IdentCache; config: ConfigRef;
+                 filename: string = ""; line: int = 0;
+                 errorHandler: ErrorHandler = nil): PNode {.
+    ...raises: [IOError, Exception, ValueError, KeyError, ERecoverableError], tags: [
+    ReadIOEffect, RootEffect, ReadDirEffect, WriteIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + Parses a string into an AST, returning the top node. filename and line, although optional, provide info so that the compiler can generate correct error messages referring to the original source. + Source   +Edit   + +
+
+ +
+
+
+
proc parseSymbol(p: var Parser; mode = smNormal): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc parseTopLevelStmt(p: var Parser): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + Implements an iterator which, when called repeatedly, returns the next top-level statement or emptyNode if end of stream. + Source   +Edit   + +
+
+ +
+
+
+
proc setBaseFlags(n: PNode; base: NumericalBase) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipComment(p: var Parser; node: PNode) {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipInd(p: var Parser) {....raises: [Exception, ValueError, KeyError, IOError,
+                                       ERecoverableError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/parser.idx b/compiler/parser.idx new file mode 100644 index 0000000000000..3a2fee7978a9b --- /dev/null +++ b/compiler/parser.idx @@ -0,0 +1,29 @@ +nimTitle parser parser.html module parser 0 +nim Parser parser.html#Parser object Parser 69 +nim isOperator parser.html#isOperator,Token proc isOperator(tok: Token): bool 97 +nim getTok parser.html#getTok,Parser proc getTok(p: var Parser) 98 +nim parMessage parser.html#parMessage,Parser,TMsgKind,string proc parMessage(p: Parser; msg: TMsgKind; arg: string = "") 99 +nim skipComment parser.html#skipComment,Parser,PNode proc skipComment(p: var Parser; node: PNode) 100 +nim newNodeP parser.html#newNodeP,TNodeKind,Parser proc newNodeP(kind: TNodeKind; p: Parser): PNode 101 +nim newIntNodeP parser.html#newIntNodeP,TNodeKind,BiggestInt,Parser proc newIntNodeP(kind: TNodeKind; intVal: BiggestInt; p: Parser): PNode 102 +nim newFloatNodeP parser.html#newFloatNodeP,TNodeKind,BiggestFloat,Parser proc newFloatNodeP(kind: TNodeKind; floatVal: BiggestFloat; p: Parser): PNode 103 +nim newStrNodeP parser.html#newStrNodeP,TNodeKind,sinkstring,Parser proc newStrNodeP(kind: TNodeKind; strVal: sink string; p: Parser): PNode 104 +nim newIdentNodeP parser.html#newIdentNodeP,PIdent,Parser proc newIdentNodeP(ident: PIdent; p: Parser): PNode 105 +nim expectIdentOrKeyw parser.html#expectIdentOrKeyw,Parser proc expectIdentOrKeyw(p: Parser) 106 +nim expectIdent parser.html#expectIdent,Parser proc expectIdent(p: Parser) 107 +nim parLineInfo parser.html#parLineInfo,Parser proc parLineInfo(p: Parser): TLineInfo 108 +nim eat parser.html#eat,Parser,TokType proc eat(p: var Parser; tokType: TokType) 109 +nim skipInd parser.html#skipInd,Parser proc skipInd(p: var Parser) 110 +nim optPar parser.html#optPar,Parser proc optPar(p: var Parser) 111 +nim optInd parser.html#optInd,Parser,PNode proc optInd(p: var Parser; n: PNode) 112 +nim indAndComment parser.html#indAndComment,Parser,PNode proc indAndComment(p: var Parser; n: PNode; maybeMissEquals = false) 113 +nim setBaseFlags parser.html#setBaseFlags,PNode,NumericalBase proc setBaseFlags(n: PNode; base: NumericalBase) 114 +nim parseSymbol parser.html#parseSymbol,Parser proc parseSymbol(p: var Parser; mode = smNormal): PNode 115 +nim openParser parser.html#openParser,Parser,FileIndex,PLLStream,IdentCache,ConfigRef proc openParser(p: var Parser; fileIdx: FileIndex; inputStream: PLLStream;\n cache: IdentCache; config: ConfigRef) 149 +nim openParser parser.html#openParser,Parser,AbsoluteFile,PLLStream,IdentCache,ConfigRef proc openParser(p: var Parser; filename: AbsoluteFile; inputStream: PLLStream;\n cache: IdentCache; config: ConfigRef) 162 +nim closeParser parser.html#closeParser,Parser proc closeParser(p: var Parser) 166 +nim checkFirstLineIndentation parser.html#checkFirstLineIndentation,Parser proc checkFirstLineIndentation(p: var Parser) 2530 +nim parseTopLevelStmt parser.html#parseTopLevelStmt,Parser proc parseTopLevelStmt(p: var Parser): PNode 2534 +nim parseAll parser.html#parseAll,Parser proc parseAll(p: var Parser): PNode 2564 +nim parseString parser.html#parseString,string,IdentCache,ConfigRef,string,int,ErrorHandler proc parseString(s: string; cache: IdentCache; config: ConfigRef;\n filename: string = ""; line: int = 0;\n errorHandler: ErrorHandler = nil): PNode 2574 +nimgrp openparser parser.html#openParser-procs-all proc 149 diff --git a/compiler/pathutils.html b/compiler/pathutils.html new file mode 100644 index 0000000000000..243e67732eb20 --- /dev/null +++ b/compiler/pathutils.html @@ -0,0 +1,567 @@ + + + + + + + +pathutils + + + + + + + + + + + + + + + + +
+
+

pathutils

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Path handling utilities for Nim. Strictly typed code in order to avoid the never ending time sink in getting path handling right.

+
+

Types

+
+
+
AbsoluteDir = distinct string
+
+ + + Source   +Edit   + +
+
+
+
AbsoluteFile = distinct string
+
+ + + Source   +Edit   + +
+
+ +
+
RelativeDir = distinct string
+
+ + + Source   +Edit   + +
+
+
+
RelativeFile = distinct string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(x: AnyPath): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `/`(base: AbsoluteDir; f: RelativeDir): AbsoluteDir {....raises: [OSError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `/`(base: AbsoluteDir; f: RelativeFile): AbsoluteFile {....raises: [OSError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `==`[T: AnyPath](x, y: T): bool
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addFileExt(x: AbsoluteFile; ext: string): AbsoluteFile {.borrow,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc addFileExt(x: RelativeFile; ext: string): RelativeFile {.borrow,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc changeFileExt(x: AbsoluteFile; ext: string): AbsoluteFile {.borrow,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc changeFileExt(x: RelativeFile; ext: string): RelativeFile {.borrow,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cmpPaths(x, y: AbsoluteDir): int {.borrow, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc copyFile(source, dest: AbsoluteFile) {....raises: [OSError, IOError],
+    tags: [ReadDirEffect, ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createDir(x: AbsoluteDir) {.borrow, ...raises: [OSError, IOError],
+                                 tags: [WriteDirEffect, ReadDirEffect],
+                                 forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc customPath(x: string): string {....raises: [OSError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc dirExists(x: AbsoluteDir): bool {.borrow, ...raises: [],
+                                       tags: [ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc extractFilename(x: AbsoluteFile): string {.borrow, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fileExists(x: AbsoluteFile): bool {.borrow, ...raises: [],
+    tags: [ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isEmpty(x: AnyPath): bool {.inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc quoteShell(x: AbsoluteDir): string {.borrow, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc quoteShell(x: AbsoluteFile): string {.borrow, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc relativeTo(fullPath: AbsoluteFile; baseFilename: AbsoluteDir; sep = DirSep): RelativeFile {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc removeFile(x: AbsoluteFile) {.borrow, ...raises: [OSError],
+                                   tags: [WriteDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc splitFile(x: AbsoluteFile): tuple[dir: AbsoluteDir, name, ext: string] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toAbsolute(file: string; base: AbsoluteDir): AbsoluteFile {.
+    ...raises: [OSError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toAbsoluteDir(path: string): AbsoluteDir {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc writeFile(x: AbsoluteFile; content: string) {.borrow, ...raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/pathutils.idx b/compiler/pathutils.idx new file mode 100644 index 0000000000000..e8fe853356121 --- /dev/null +++ b/compiler/pathutils.idx @@ -0,0 +1,34 @@ +nimTitle pathutils pathutils.html module pathutils 0 +nim AbsoluteFile pathutils.html#AbsoluteFile type AbsoluteFile 19 +nim AbsoluteDir pathutils.html#AbsoluteDir type AbsoluteDir 20 +nim RelativeFile pathutils.html#RelativeFile type RelativeFile 21 +nim RelativeDir pathutils.html#RelativeDir type RelativeDir 22 +nim AnyPath pathutils.html#AnyPath type AnyPath 23 +nim isEmpty pathutils.html#isEmpty,AnyPath proc isEmpty(x: AnyPath): bool 25 +nim copyFile pathutils.html#copyFile,AbsoluteFile,AbsoluteFile proc copyFile(source, dest: AbsoluteFile) 27 +nim removeFile pathutils.html#removeFile,AbsoluteFile proc removeFile(x: AbsoluteFile) 30 +nim splitFile pathutils.html#splitFile,AbsoluteFile proc splitFile(x: AbsoluteFile): tuple[dir: AbsoluteDir, name, ext: string] 32 +nim extractFilename pathutils.html#extractFilename,AbsoluteFile proc extractFilename(x: AbsoluteFile): string 36 +nim fileExists pathutils.html#fileExists,AbsoluteFile proc fileExists(x: AbsoluteFile): bool 38 +nim dirExists pathutils.html#dirExists,AbsoluteDir proc dirExists(x: AbsoluteDir): bool 39 +nim quoteShell pathutils.html#quoteShell,AbsoluteFile proc quoteShell(x: AbsoluteFile): string 41 +nim quoteShell pathutils.html#quoteShell,AbsoluteDir proc quoteShell(x: AbsoluteDir): string 42 +nim cmpPaths pathutils.html#cmpPaths,AbsoluteDir,AbsoluteDir proc cmpPaths(x, y: AbsoluteDir): int 44 +nim createDir pathutils.html#createDir,AbsoluteDir proc createDir(x: AbsoluteDir) 46 +nim toAbsoluteDir pathutils.html#toAbsoluteDir,string proc toAbsoluteDir(path: string): AbsoluteDir 48 +nim `$` pathutils.html#$,AnyPath proc `$`(x: AnyPath): string 52 +nim `==` pathutils.html#==,T,T proc `==`[T: AnyPath](x, y: T): bool 58 +nim `/` pathutils.html#/,AbsoluteDir,RelativeFile proc `/`(base: AbsoluteDir; f: RelativeFile): AbsoluteFile 71 +nim `/` pathutils.html#/,AbsoluteDir,RelativeDir proc `/`(base: AbsoluteDir; f: RelativeDir): AbsoluteDir 79 +nim relativeTo pathutils.html#relativeTo,AbsoluteFile,AbsoluteDir proc relativeTo(fullPath: AbsoluteFile; baseFilename: AbsoluteDir; sep = DirSep): RelativeFile 87 +nim toAbsolute pathutils.html#toAbsolute,string,AbsoluteDir proc toAbsolute(file: string; base: AbsoluteDir): AbsoluteFile 94 +nim changeFileExt pathutils.html#changeFileExt,AbsoluteFile,string proc changeFileExt(x: AbsoluteFile; ext: string): AbsoluteFile 98 +nim changeFileExt pathutils.html#changeFileExt,RelativeFile,string proc changeFileExt(x: RelativeFile; ext: string): RelativeFile 99 +nim addFileExt pathutils.html#addFileExt,AbsoluteFile,string proc addFileExt(x: AbsoluteFile; ext: string): AbsoluteFile 101 +nim addFileExt pathutils.html#addFileExt,RelativeFile,string proc addFileExt(x: RelativeFile; ext: string): RelativeFile 102 +nim writeFile pathutils.html#writeFile,AbsoluteFile,string proc writeFile(x: AbsoluteFile; content: string) 104 +nim customPath pathutils.html#customPath,string proc customPath(x: string): string 152 +nimgrp quoteshell pathutils.html#quoteShell-procs-all proc 41 +nimgrp / pathutils.html#/-procs-all proc 71 +nimgrp changefileext pathutils.html#changeFileExt-procs-all proc 98 +nimgrp addfileext pathutils.html#addFileExt-procs-all proc 101 diff --git a/compiler/patterns.html b/compiler/patterns.html new file mode 100644 index 0000000000000..5475b6caf8207 --- /dev/null +++ b/compiler/patterns.html @@ -0,0 +1,140 @@ + + + + + + + +patterns + + + + + + + + + + + + + + + + +
+
+

patterns

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module implements the pattern matching features for term rewriting macro support.

+ +
+

Procs

+
+
+
+
proc applyRule(c: PContext; s: PSym; n: PNode): PNode {.
+    ...raises: [Exception, KeyError, ValueError, ERecoverableError, IOError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + returns a tree to semcheck if the rule triggered; nil otherwise + Source   +Edit   + +
+
+ +
+
+
+
proc sameTrees(a, b: PNode): bool {....raises: [Exception], tags: [RootEffect],
+                                    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/patterns.idx b/compiler/patterns.idx new file mode 100644 index 0000000000000..9bb8ebc9fea47 --- /dev/null +++ b/compiler/patterns.idx @@ -0,0 +1,3 @@ +nimTitle patterns patterns.html module patterns 0 +nim sameTrees patterns.html#sameTrees,PNode,PNode proc sameTrees(a, b: PNode): bool 55 +nim applyRule patterns.html#applyRule,PContext,PSym,PNode proc applyRule(c: PContext; s: PSym; n: PNode): PNode 277 diff --git a/compiler/pipelines.html b/compiler/pipelines.html new file mode 100644 index 0000000000000..c93b6a3350243 --- /dev/null +++ b/compiler/pipelines.html @@ -0,0 +1,275 @@ + + + + + + + +pipelines + + + + + + + + + + + + + + + + +
+
+

pipelines

+
+ +
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc compilePipelineModule(graph: ModuleGraph; fileIdx: FileIndex;
+                           flags: TSymFlags; fromModule: PSym = nil): PSym {....raises: [
+    OSError, IOError, Exception, KeyError, ValueError, ERecoverableError,
+    EOFError, ESuggestDone], tags: [ReadEnvEffect, ReadIOEffect, WriteDirEffect,
+                                    ReadDirEffect, RootEffect, WriteIOEffect,
+                                    TimeEffect, ExecIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc compilePipelineProject(graph: ModuleGraph; projectFileIdx = InvalidFileIdx) {....raises: [
+    Exception, ValueError, KeyError, IOError, ERecoverableError, OSError,
+    EOFError, ESuggestDone], tags: [RootEffect, ReadDirEffect, WriteIOEffect,
+                                    ReadIOEffect, ReadEnvEffect, WriteDirEffect,
+                                    TimeEffect, ExecIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc compilePipelineSystemModule(graph: ModuleGraph) {....raises: [KeyError,
+    Exception, OSError, IOError, ValueError, ERecoverableError, EOFError,
+    ESuggestDone], tags: [ReadDirEffect, RootEffect, ReadEnvEffect,
+                          ReadIOEffect, WriteDirEffect, WriteIOEffect,
+                          TimeEffect, ExecIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc connectPipelineCallbacks(graph: ModuleGraph) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc prePass(c: PContext; n: PNode) {....raises: [Exception, KeyError, ValueError,
+    IOError, ERecoverableError], tags: [RootEffect, ReadDirEffect,
+                                        WriteIOEffect, ReadIOEffect,
+                                        ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc processImplicitImports(graph: ModuleGraph; implicits: seq[string];
+                            nodeKind: TNodeKind; m: PSym; ctx: PContext;
+                            bModule: PPassContext; idgen: IdGenerator) {....raises: [
+    OSError, KeyError, Exception, ValueError, IOError, ERecoverableError,
+    EOFError, ESuggestDone], tags: [ReadDirEffect, RootEffect, WriteIOEffect,
+                                    ReadIOEffect, ReadEnvEffect, WriteDirEffect,
+                                    TimeEffect, ExecIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc processPipelineModule(graph: ModuleGraph; module: PSym; idgen: IdGenerator;
+                           stream: PLLStream): bool {....raises: [Exception,
+    IOError, ValueError, KeyError, ERecoverableError, OSError, EOFError,
+    ESuggestDone], tags: [RootEffect, ReadIOEffect, ReadDirEffect,
+                          WriteIOEffect, ReadEnvEffect, WriteDirEffect,
+                          TimeEffect, ExecIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setPipeLinePass(graph: ModuleGraph; pass: PipelinePass) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/pipelines.idx b/compiler/pipelines.idx new file mode 100644 index 0000000000000..81c8060906ea6 --- /dev/null +++ b/compiler/pipelines.idx @@ -0,0 +1,9 @@ +nimTitle pipelines pipelines.html module pipelines 0 +nim setPipeLinePass pipelines.html#setPipeLinePass,ModuleGraph,PipelinePass proc setPipeLinePass(graph: ModuleGraph; pass: PipelinePass) 17 +nim processImplicitImports pipelines.html#processImplicitImports,ModuleGraph,seq[string],TNodeKind,PSym,PContext,PPassContext,IdGenerator proc processImplicitImports(graph: ModuleGraph; implicits: seq[string];\n nodeKind: TNodeKind; m: PSym; ctx: PContext;\n bModule: PPassContext; idgen: IdGenerator) 50 +nim prePass pipelines.html#prePass,PContext,PNode proc prePass(c: PContext; n: PNode) 66 +nim processPipelineModule pipelines.html#processPipelineModule,ModuleGraph,PSym,IdGenerator,PLLStream proc processPipelineModule(graph: ModuleGraph; module: PSym; idgen: IdGenerator;\n stream: PLLStream): bool 94 +nim compilePipelineModule pipelines.html#compilePipelineModule,ModuleGraph,FileIndex,TSymFlags,PSym proc compilePipelineModule(graph: ModuleGraph; fileIdx: FileIndex; flags: TSymFlags;\n fromModule: PSym = nil): PSym 220 +nim connectPipelineCallbacks pipelines.html#connectPipelineCallbacks,ModuleGraph proc connectPipelineCallbacks(graph: ModuleGraph) 282 +nim compilePipelineSystemModule pipelines.html#compilePipelineSystemModule,ModuleGraph proc compilePipelineSystemModule(graph: ModuleGraph) 286 +nim compilePipelineProject pipelines.html#compilePipelineProject,ModuleGraph proc compilePipelineProject(graph: ModuleGraph; projectFileIdx = InvalidFileIdx) 293 diff --git a/compiler/pipelineutils.html b/compiler/pipelineutils.html new file mode 100644 index 0000000000000..8c1560ad1455e --- /dev/null +++ b/compiler/pipelineutils.html @@ -0,0 +1,175 @@ + + + + + + + +pipelineutils + + + + + + + + + + + + + + + + +
+
+

pipelineutils

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc moduleHasChanged(graph: ModuleGraph; module: PSym): bool {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc prepareConfigNotes(graph: ModuleGraph; module: PSym) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc resolveMod(conf: ConfigRef; module, relativeTo: string): FileIndex {.
+    ...raises: [OSError, KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipCodegen(config: ConfigRef; n: PNode): bool {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/pipelineutils.idx b/compiler/pipelineutils.idx new file mode 100644 index 0000000000000..8bab7db25ca75 --- /dev/null +++ b/compiler/pipelineutils.idx @@ -0,0 +1,5 @@ +nimTitle pipelineutils pipelineutils.html module pipelineutils 0 +nim skipCodegen pipelineutils.html#skipCodegen,ConfigRef,PNode proc skipCodegen(config: ConfigRef; n: PNode): bool 3 +nim resolveMod pipelineutils.html#resolveMod,ConfigRef,string,string proc resolveMod(conf: ConfigRef; module, relativeTo: string): FileIndex 9 +nim prepareConfigNotes pipelineutils.html#prepareConfigNotes,ModuleGraph,PSym proc prepareConfigNotes(graph: ModuleGraph; module: PSym) 16 +nim moduleHasChanged pipelineutils.html#moduleHasChanged,ModuleGraph,PSym proc moduleHasChanged(graph: ModuleGraph; module: PSym): bool 24 diff --git a/compiler/platform.html b/compiler/platform.html new file mode 100644 index 0000000000000..42f74ddea24e6 --- /dev/null +++ b/compiler/platform.html @@ -0,0 +1,650 @@ + + + + + + + +platform + + + + + + + + + + + + + + + + +
+
+

platform

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Types

+
+
+
Target = object
+  targetCPU*, hostCPU*: TSystemCPU
+  targetOS*, hostOS*: TSystemOS
+  intSize*: int
+  floatSize*: int
+  ptrSize*: int
+  tnl*: string
+
+ + + Source   +Edit   + +
+
+
+
TInfoCPU = tuple[name: string, intSize: int, endian: Endianness,
+                 floatSize, bit: int]
+
+ + + Source   +Edit   + +
+
+
+
TInfoOS = tuple[name: string, parDir: string, dllFrmt: string,
+                altDirSep: string, objExt: string, newLine: string,
+                pathSep: string, dirSep: string, scriptExt: string,
+                curDir: string, exeExt: string, extSep: string,
+                props: TInfoOSProps]
+
+ + + Source   +Edit   + +
+
+
+
TInfoOSProp = enum
+  ospNeedsPIC, ospCaseInsensitive, ospPosix, ospLacksThreadVars
+
+ + + Source   +Edit   + +
+
+
+
TInfoOSProps = set[TInfoOSProp]
+
+ + + Source   +Edit   + +
+
+
+
TSystemCPU = enum
+  cpuNone, cpuI386, cpuM68k, cpuAlpha, cpuPowerpc, cpuPowerpc64, cpuPowerpc64el,
+  cpuSparc, cpuVm, cpuHppa, cpuIa64, cpuAmd64, cpuMips, cpuMipsel, cpuArm,
+  cpuArm64, cpuJS, cpuNimVM, cpuAVR, cpuMSP430, cpuSparc64, cpuMips64,
+  cpuMips64el, cpuRiscV32, cpuRiscV64, cpuEsp, cpuWasm32, cpuE2k, cpuLoongArch64
+
+ + + Source   +Edit   + +
+
+
+
TSystemOS = enum
+  osNone, osDos, osWindows, osOs2, osLinux, osMorphos, osSkyos, osSolaris,
+  osIrix, osNetbsd, osFreebsd, osOpenbsd, osDragonfly, osCrossos, osAix,
+  osPalmos, osQnx, osAmiga, osAtari, osNetware, osMacos, osMacosx, osIos,
+  osHaiku, osAndroid, osVxWorks, osGenode, osJS, osNimVM, osStandalone,
+  osNintendoSwitch, osFreeRTOS, osZephyr, osNuttX, osAny
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
CPU: array[succ(low(TSystemCPU)) .. high(TSystemCPU), TInfoCPU] = [
+    (name: "i386", intSize: 32, endian: littleEndian, floatSize: 64, bit: 32),
+    (name: "m68k", intSize: 32, endian: bigEndian, floatSize: 64, bit: 32), (
+    name: "alpha", intSize: 64, endian: littleEndian, floatSize: 64, bit: 64),
+    (name: "powerpc", intSize: 32, endian: bigEndian, floatSize: 64, bit: 32), (
+    name: "powerpc64", intSize: 64, endian: bigEndian, floatSize: 64, bit: 64), (
+    name: "powerpc64el", intSize: 64, endian: littleEndian, floatSize: 64,
+    bit: 64),
+    (name: "sparc", intSize: 32, endian: bigEndian, floatSize: 64, bit: 32),
+    (name: "vm", intSize: 32, endian: littleEndian, floatSize: 64, bit: 32),
+    (name: "hppa", intSize: 32, endian: bigEndian, floatSize: 64, bit: 32),
+    (name: "ia64", intSize: 64, endian: littleEndian, floatSize: 64, bit: 64), (
+    name: "amd64", intSize: 64, endian: littleEndian, floatSize: 64, bit: 64),
+    (name: "mips", intSize: 32, endian: bigEndian, floatSize: 64, bit: 32), (
+    name: "mipsel", intSize: 32, endian: littleEndian, floatSize: 64, bit: 32),
+    (name: "arm", intSize: 32, endian: littleEndian, floatSize: 64, bit: 32), (
+    name: "arm64", intSize: 64, endian: littleEndian, floatSize: 64, bit: 64),
+    (name: "js", intSize: 32, endian: littleEndian, floatSize: 64, bit: 32),
+    (name: "nimvm", intSize: 32, endian: bigEndian, floatSize: 64, bit: 32),
+    (name: "avr", intSize: 16, endian: littleEndian, floatSize: 32, bit: 16), (
+    name: "msp430", intSize: 16, endian: littleEndian, floatSize: 32, bit: 16),
+    (name: "sparc64", intSize: 64, endian: bigEndian, floatSize: 64, bit: 64),
+    (name: "mips64", intSize: 64, endian: bigEndian, floatSize: 64, bit: 64), (
+    name: "mips64el", intSize: 64, endian: littleEndian, floatSize: 64, bit: 64), (
+    name: "riscv32", intSize: 32, endian: littleEndian, floatSize: 64, bit: 32), (
+    name: "riscv64", intSize: 64, endian: littleEndian, floatSize: 64, bit: 64),
+    (name: "esp", intSize: 32, endian: littleEndian, floatSize: 64, bit: 32), (
+    name: "wasm32", intSize: 32, endian: littleEndian, floatSize: 64, bit: 32),
+    (name: "e2k", intSize: 64, endian: littleEndian, floatSize: 64, bit: 64), (
+    name: "loongarch64", intSize: 64, endian: littleEndian, floatSize: 64,
+    bit: 64)]
+
+ + + Source   +Edit   + +
+
+
+
EndianToStr: array[Endianness, string] = ["littleEndian", "bigEndian"]
+
+ + + Source   +Edit   + +
+
+
+
OS: array[succ(low(TSystemOS)) .. high(TSystemOS), TInfoOS] = [(name: "DOS",
+    parDir: "..", dllFrmt: "$1.dll", altDirSep: "/", objExt: ".obj",
+    newLine: "\r\n", pathSep: ";", dirSep: "\\", scriptExt: ".bat", curDir: ".",
+    exeExt: ".exe", extSep: ".", props: {ospCaseInsensitive}), (name: "Windows",
+    parDir: "..", dllFrmt: "$1.dll", altDirSep: "/", objExt: ".obj",
+    newLine: "\r\n", pathSep: ";", dirSep: "\\", scriptExt: ".bat", curDir: ".",
+    exeExt: ".exe", extSep: ".", props: {ospCaseInsensitive}), (name: "OS2",
+    parDir: "..", dllFrmt: "$1.dll", altDirSep: "/", objExt: ".obj",
+    newLine: "\r\n", pathSep: ";", dirSep: "\\", scriptExt: ".bat", curDir: ".",
+    exeExt: ".exe", extSep: ".", props: {ospCaseInsensitive}), (name: "Linux",
+    parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".",
+    exeExt: "", extSep: ".", props: {ospNeedsPIC, ospPosix}), (name: "MorphOS",
+    parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".",
+    exeExt: "", extSep: ".", props: {ospNeedsPIC, ospPosix}), (name: "SkyOS",
+    parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".",
+    exeExt: "", extSep: ".", props: {ospNeedsPIC, ospPosix}), (name: "Solaris",
+    parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".",
+    exeExt: "", extSep: ".", props: {ospNeedsPIC, ospPosix}), (name: "Irix",
+    parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".",
+    exeExt: "", extSep: ".", props: {ospNeedsPIC, ospPosix}), (name: "NetBSD",
+    parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".",
+    exeExt: "", extSep: ".", props: {ospNeedsPIC, ospPosix}), (name: "FreeBSD",
+    parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".",
+    exeExt: "", extSep: ".", props: {ospNeedsPIC, ospPosix}), (name: "OpenBSD",
+    parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".",
+    exeExt: "", extSep: ".", props: {ospNeedsPIC, ospPosix}), (
+    name: "DragonFly", parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/",
+    objExt: ".o", newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh",
+    curDir: ".", exeExt: "", extSep: ".", props: {ospNeedsPIC, ospPosix}), (
+    name: "CROSSOS", parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/",
+    objExt: ".o", newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh",
+    curDir: ".", exeExt: "", extSep: ".", props: {ospNeedsPIC, ospPosix}), (
+    name: "AIX", parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/",
+    objExt: ".o", newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh",
+    curDir: ".", exeExt: "", extSep: ".", props: {ospNeedsPIC, ospPosix}), (
+    name: "PalmOS", parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/",
+    objExt: ".o", newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh",
+    curDir: ".", exeExt: "", extSep: ".", props: {ospNeedsPIC}), (name: "QNX",
+    parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".",
+    exeExt: "", extSep: ".", props: {ospNeedsPIC, ospPosix}), (name: "Amiga",
+    parDir: "..", dllFrmt: "$1.library", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".",
+    exeExt: "", extSep: ".", props: {ospNeedsPIC}), (name: "Atari",
+    parDir: "..", dllFrmt: "$1.dll", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: "", curDir: ".",
+    exeExt: ".tpp", extSep: ".", props: {ospNeedsPIC}), (name: "Netware",
+    parDir: "..", dllFrmt: "$1.nlm", altDirSep: "/", objExt: "",
+    newLine: "\r\n", pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".",
+    exeExt: ".nlm", extSep: ".", props: {ospCaseInsensitive}), (name: "MacOS",
+    parDir: "::", dllFrmt: "$1Lib", altDirSep: ":", objExt: ".o", newLine: "\r",
+    pathSep: ",", dirSep: ":", scriptExt: "", curDir: ":", exeExt: "",
+    extSep: ".", props: {ospCaseInsensitive}), (name: "MacOSX", parDir: "..",
+    dllFrmt: "lib$1.dylib", altDirSep: ":", objExt: ".o", newLine: "\n",
+    pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".", exeExt: "",
+    extSep: ".", props: {ospNeedsPIC, ospPosix, ospLacksThreadVars}), (
+    name: "iOS", parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/",
+    objExt: ".o", newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh",
+    curDir: ".", exeExt: "", extSep: ".", props: {ospNeedsPIC, ospPosix}), (
+    name: "Haiku", parDir: "..", dllFrmt: "lib$1.so", altDirSep: ":",
+    objExt: ".o", newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh",
+    curDir: ".", exeExt: "", extSep: ".",
+    props: {ospNeedsPIC, ospPosix, ospLacksThreadVars}), (name: "Android",
+    parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".",
+    exeExt: "", extSep: ".", props: {ospNeedsPIC, ospPosix}), (name: "VxWorks",
+    parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ";", dirSep: "\\", scriptExt: ".sh", curDir: ".",
+    exeExt: ".vxe", extSep: ".",
+    props: {ospNeedsPIC, ospPosix, ospLacksThreadVars}), (name: "Genode",
+    pardir: "..", dllFrmt: "$1.lib.so", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: "", curDir: "/",
+    exeExt: "", extSep: ".", props: {ospNeedsPIC, ospLacksThreadVars}), (
+    name: "JS", parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".",
+    exeExt: "", extSep: ".", props: {}), (name: "NimVM", parDir: "..",
+    dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o", newLine: "\n",
+    pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".", exeExt: "",
+    extSep: ".", props: {}), (name: "Standalone", parDir: "..",
+                              dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o",
+                              newLine: "\n", pathSep: ":", dirSep: "/",
+                              scriptExt: ".sh", curDir: ".", exeExt: "",
+                              extSep: ".", props: {}), (name: "NintendoSwitch",
+    parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".",
+    exeExt: ".elf", extSep: ".", props: {ospNeedsPIC, ospPosix}), (
+    name: "FreeRTOS", parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/",
+    objExt: ".o", newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh",
+    curDir: ".", exeExt: "", extSep: ".", props: {ospPosix}), (name: "Zephyr",
+    parDir: "..", dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o",
+    newLine: "\n", pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".",
+    exeExt: "", extSep: ".", props: {ospPosix}), (name: "NuttX", parDir: "..",
+    dllFrmt: "lib$1.so", altDirSep: "/", objExt: ".o", newLine: "\n",
+    pathSep: ":", dirSep: "/", scriptExt: ".sh", curDir: ".", exeExt: "",
+    extSep: ".", props: {ospPosix}), (name: "Any", parDir: "..",
+                                      dllFrmt: "lib$1.so", altDirSep: "/",
+                                      objExt: ".o", newLine: "\n", pathSep: ":",
+                                      dirSep: "/", scriptExt: ".sh",
+                                      curDir: ".", exeExt: "", extSep: ".",
+                                      props: {})]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc listCPUnames(): seq[string] {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc listOSnames(): seq[string] {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nameToCPU(name: string): TSystemCPU {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nameToOS(name: string): TSystemOS {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setTarget(t: var Target; o: TSystemOS; c: TSystemCPU) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setTargetFromSystem(t: var Target) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/platform.idx b/compiler/platform.idx new file mode 100644 index 0000000000000..f6b68c6ccbefd --- /dev/null +++ b/compiler/platform.idx @@ -0,0 +1,85 @@ +nimTitle platform platform.html module platform 0 +nim osNone platform.html#osNone TSystemOS.osNone 24 +nim osDos platform.html#osDos TSystemOS.osDos 24 +nim osWindows platform.html#osWindows TSystemOS.osWindows 24 +nim osOs2 platform.html#osOs2 TSystemOS.osOs2 24 +nim osLinux platform.html#osLinux TSystemOS.osLinux 24 +nim osMorphos platform.html#osMorphos TSystemOS.osMorphos 24 +nim osSkyos platform.html#osSkyos TSystemOS.osSkyos 24 +nim osSolaris platform.html#osSolaris TSystemOS.osSolaris 24 +nim osIrix platform.html#osIrix TSystemOS.osIrix 24 +nim osNetbsd platform.html#osNetbsd TSystemOS.osNetbsd 24 +nim osFreebsd platform.html#osFreebsd TSystemOS.osFreebsd 24 +nim osOpenbsd platform.html#osOpenbsd TSystemOS.osOpenbsd 24 +nim osDragonfly platform.html#osDragonfly TSystemOS.osDragonfly 24 +nim osCrossos platform.html#osCrossos TSystemOS.osCrossos 24 +nim osAix platform.html#osAix TSystemOS.osAix 24 +nim osPalmos platform.html#osPalmos TSystemOS.osPalmos 24 +nim osQnx platform.html#osQnx TSystemOS.osQnx 24 +nim osAmiga platform.html#osAmiga TSystemOS.osAmiga 24 +nim osAtari platform.html#osAtari TSystemOS.osAtari 24 +nim osNetware platform.html#osNetware TSystemOS.osNetware 24 +nim osMacos platform.html#osMacos TSystemOS.osMacos 24 +nim osMacosx platform.html#osMacosx TSystemOS.osMacosx 24 +nim osIos platform.html#osIos TSystemOS.osIos 24 +nim osHaiku platform.html#osHaiku TSystemOS.osHaiku 24 +nim osAndroid platform.html#osAndroid TSystemOS.osAndroid 24 +nim osVxWorks platform.html#osVxWorks TSystemOS.osVxWorks 24 +nim osGenode platform.html#osGenode TSystemOS.osGenode 24 +nim osJS platform.html#osJS TSystemOS.osJS 24 +nim osNimVM platform.html#osNimVM TSystemOS.osNimVM 24 +nim osStandalone platform.html#osStandalone TSystemOS.osStandalone 24 +nim osNintendoSwitch platform.html#osNintendoSwitch TSystemOS.osNintendoSwitch 24 +nim osFreeRTOS platform.html#osFreeRTOS TSystemOS.osFreeRTOS 24 +nim osZephyr platform.html#osZephyr TSystemOS.osZephyr 24 +nim osNuttX platform.html#osNuttX TSystemOS.osNuttX 24 +nim osAny platform.html#osAny TSystemOS.osAny 24 +nim TSystemOS platform.html#TSystemOS enum TSystemOS 24 +nim ospNeedsPIC platform.html#ospNeedsPIC TInfoOSProp.ospNeedsPIC 33 +nim ospCaseInsensitive platform.html#ospCaseInsensitive TInfoOSProp.ospCaseInsensitive 33 +nim ospPosix platform.html#ospPosix TInfoOSProp.ospPosix 33 +nim ospLacksThreadVars platform.html#ospLacksThreadVars TInfoOSProp.ospLacksThreadVars 33 +nim TInfoOSProp platform.html#TInfoOSProp enum TInfoOSProp 33 +nim TInfoOSProps platform.html#TInfoOSProps type TInfoOSProps 38 +nim TInfoOS platform.html#TInfoOS tuple TInfoOS 39 +nim OS platform.html#OS const OS 46 +nim cpuNone platform.html#cpuNone TSystemCPU.cpuNone 208 +nim cpuI386 platform.html#cpuI386 TSystemCPU.cpuI386 208 +nim cpuM68k platform.html#cpuM68k TSystemCPU.cpuM68k 208 +nim cpuAlpha platform.html#cpuAlpha TSystemCPU.cpuAlpha 208 +nim cpuPowerpc platform.html#cpuPowerpc TSystemCPU.cpuPowerpc 208 +nim cpuPowerpc64 platform.html#cpuPowerpc64 TSystemCPU.cpuPowerpc64 208 +nim cpuPowerpc64el platform.html#cpuPowerpc64el TSystemCPU.cpuPowerpc64el 208 +nim cpuSparc platform.html#cpuSparc TSystemCPU.cpuSparc 208 +nim cpuVm platform.html#cpuVm TSystemCPU.cpuVm 208 +nim cpuHppa platform.html#cpuHppa TSystemCPU.cpuHppa 208 +nim cpuIa64 platform.html#cpuIa64 TSystemCPU.cpuIa64 208 +nim cpuAmd64 platform.html#cpuAmd64 TSystemCPU.cpuAmd64 208 +nim cpuMips platform.html#cpuMips TSystemCPU.cpuMips 208 +nim cpuMipsel platform.html#cpuMipsel TSystemCPU.cpuMipsel 208 +nim cpuArm platform.html#cpuArm TSystemCPU.cpuArm 208 +nim cpuArm64 platform.html#cpuArm64 TSystemCPU.cpuArm64 208 +nim cpuJS platform.html#cpuJS TSystemCPU.cpuJS 208 +nim cpuNimVM platform.html#cpuNimVM TSystemCPU.cpuNimVM 208 +nim cpuAVR platform.html#cpuAVR TSystemCPU.cpuAVR 208 +nim cpuMSP430 platform.html#cpuMSP430 TSystemCPU.cpuMSP430 208 +nim cpuSparc64 platform.html#cpuSparc64 TSystemCPU.cpuSparc64 208 +nim cpuMips64 platform.html#cpuMips64 TSystemCPU.cpuMips64 208 +nim cpuMips64el platform.html#cpuMips64el TSystemCPU.cpuMips64el 208 +nim cpuRiscV32 platform.html#cpuRiscV32 TSystemCPU.cpuRiscV32 208 +nim cpuRiscV64 platform.html#cpuRiscV64 TSystemCPU.cpuRiscV64 208 +nim cpuEsp platform.html#cpuEsp TSystemCPU.cpuEsp 208 +nim cpuWasm32 platform.html#cpuWasm32 TSystemCPU.cpuWasm32 208 +nim cpuE2k platform.html#cpuE2k TSystemCPU.cpuE2k 208 +nim cpuLoongArch64 platform.html#cpuLoongArch64 TSystemCPU.cpuLoongArch64 208 +nim TSystemCPU platform.html#TSystemCPU enum TSystemCPU 208 +nim TInfoCPU platform.html#TInfoCPU tuple TInfoCPU 217 +nim EndianToStr platform.html#EndianToStr const EndianToStr 221 +nim CPU platform.html#CPU const CPU 222 +nim Target platform.html#Target object Target 254 +nim setTarget platform.html#setTarget,Target,TSystemOS,TSystemCPU proc setTarget(t: var Target; o: TSystemOS; c: TSystemCPU) 262 +nim nameToOS platform.html#nameToOS,string proc nameToOS(name: string): TSystemOS 273 +nim listOSnames platform.html#listOSnames proc listOSnames(): seq[string] 279 +nim nameToCPU platform.html#nameToCPU,string proc nameToCPU(name: string): TSystemCPU 284 +nim listCPUnames platform.html#listCPUnames proc listCPUnames(): seq[string] 290 +nim setTargetFromSystem platform.html#setTargetFromSystem,Target proc setTargetFromSystem(t: var Target) 295 diff --git a/compiler/pluginsupport.html b/compiler/pluginsupport.html new file mode 100644 index 0000000000000..5c07482a8fe71 --- /dev/null +++ b/compiler/pluginsupport.html @@ -0,0 +1,156 @@ + + + + + + + +pluginsupport + + + + + + + + + + + + + + + + +
+
+

pluginsupport

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Plugin support for the Nim compiler. Right now plugins need to be built with the compiler only: plugins using DLLs or the FFI will not work.

+
+

Imports

+
+ ast, semdata, idents +
+
+
+

Types

+
+
+
Plugin = tuple[package, module, fn: string, t: Transformation]
+
+ + + Source   +Edit   + +
+
+
+
Transformation = proc (c: PContext; n: PNode): PNode {.nimcall.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc pluginMatches(ic: IdentCache; p: Plugin; s: PSym): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/pluginsupport.idx b/compiler/pluginsupport.idx new file mode 100644 index 0000000000000..96c76cfcbebcd --- /dev/null +++ b/compiler/pluginsupport.idx @@ -0,0 +1,4 @@ +nimTitle pluginsupport pluginsupport.html module pluginsupport 0 +nim Transformation pluginsupport.html#Transformation type Transformation 17 +nim Plugin pluginsupport.html#Plugin tuple Plugin 18 +nim pluginMatches pluginsupport.html#pluginMatches,IdentCache,Plugin,PSym proc pluginMatches(ic: IdentCache; p: Plugin; s: PSym): bool 22 diff --git a/compiler/pragmas.html b/compiler/pragmas.html new file mode 100644 index 0000000000000..5c275e773dd39 --- /dev/null +++ b/compiler/pragmas.html @@ -0,0 +1,725 @@ + + + + + + + +pragmas + + + + + + + + + + + + + + + + +
+
+

pragmas

+
+ +
+ Source   +Edit   + +
+ +

+ +
+

Consts

+
+
+
allRoutinePragmas = {wMagic..wThread, wEffectsOf, wConstructor, wDelegator,
+                     wImportCpp, wImportObjC..wExportNims, wNodecl,
+                     wSideEffect..wNosinks, wDynlib..wUsed, wError,
+                     wStackTrace..wLineTrace, wDeprecated..wVarargs,
+                     wNimcall..wNoconv, wNonReloadable, wRaises,
+                     wTags..wEnsures, wNoDestroy, wCompileTime..wNoInit,
+                     wBorrow..wDiscardable, wGensym..wInject, wAsmNoStackFrame,
+                     wCodegenDecl, wLocks, wLiftLocals..wSystemRaisesDefect,
+                     wQuirky..wExtern, wVirtual, wMember}
+
+ + + Source   +Edit   + +
+
+
+
constPragmas = {wMagic, wIntDefine..wBoolDefine, wImportCpp, wImportObjC,
+                wImportc..wExportNims, wNodecl, wHeader, wCompilerProc..wCore,
+                wUsed, wError, wDefine, wDeprecated, wGensym..wInject, wExtern}
+
+ + + Source   +Edit   + +
+
+
+
converterPragmas = {wMagic..wThread, wEffectsOf, wConstructor, wDelegator,
+                    wImportCpp, wImportObjC..wExportNims, wNodecl,
+                    wSideEffect..wNosinks, wDynlib..wProcVar, wUsed, wError,
+                    wStackTrace..wLineTrace, wDeprecated..wVarargs,
+                    wNimcall..wNoconv, wNonReloadable, wRaises, wTags..wEnsures,
+                    wNoDestroy, wCompileTime..wNoInit, wBorrow..wDiscardable,
+                    wGensym..wInject, wAsmNoStackFrame, wCodegenDecl, wLocks,
+                    wLiftLocals..wSystemRaisesDefect, wQuirky..wExtern,
+                    wVirtual, wMember}
+
+ + + Source   +Edit   + +
+
+
+
enumFieldPragmas = {wDeprecated}
+
+ + + Source   +Edit   + +
+
+
+
exprPragmas = {wLine, wLocks, wNoRewrite, wGcSafe, wNoSideEffect}
+
+ + + Source   +Edit   + +
+
+
+
fieldPragmas = {wCursor..wNoalias, wImportCpp, wImportObjC,
+                wImportc..wExportCpp, wRequiresInit..wAlign, wUsed, wError,
+                wDeprecated, wNoInit, wGuard, wExtern, wBitsize}
+
+ + + Source   +Edit   + +
+
+
+
FirstCallConv = wNimcall
+
+ + + Source   +Edit   + +
+
+
+
forVarPragmas = {wInject, wGensym}
+
+ + + Source   +Edit   + +
+
+
+
iteratorPragmas = {wMagic, wEffectsOf, wImportCpp, wImportObjC,
+                   wImportc..wExportNims, wNodecl, wSideEffect,
+                   wNoSideEffect..wGcSafe, wUsed, wError, wDeprecated,
+                   wNimcall..wNoconv, wRaises, wTags..wEnsures,
+                   wBorrow..wDiscardable, wGensym..wInject, wLocks, wExtern}
+
+ + + Source   +Edit   + +
+
+
+
lambdaPragmas = {wNimcall..wNoconv, wNoSideEffect, wSideEffect, wNoreturn,
+                 wNosinks, wDynlib, wHeader, wThread, wAsmNoStackFrame, wRaises,
+                 wLocks, wTags, wForbids, wRequires, wEnsures, wEffectsOf,
+                 wGcSafe, wCodegenDecl, wNoInit, wCompileTime}
+
+ + + Source   +Edit   + +
+
+
+
LastCallConv = wNoconv
+
+ + + Source   +Edit   + +
+
+
+
letPragmas = {wMagic, wCursor..wNoalias, wImportCpp, wImportObjC,
+              wImportc..wExportNims, wAlign..wNodecl, wHeader, wDynlib..wCore,
+              wUsed, wError, wDeprecated, wCompileTime..wNoInit,
+              wGensym..wInject, wThreadVar, wGlobal..wCodegenDecl, wGuard,
+              wLiftLocals, wExtern..wRegister, wVolatile}
+
+ + + Source   +Edit   + +
+
+
+
macroPragmas = {wMagic, wDelegator, wImportCpp, wImportObjC,
+                wImportc..wExportNims, wNodecl, wNoSideEffect,
+                wCompilerProc..wCore, wUsed, wError, wDeprecated,
+                wNimcall..wNoconv, wNonReloadable, wDiscardable,
+                wGensym..wInject, wExtern}
+
+ + + Source   +Edit   + +
+
+
+
methodPragmas = {wMagic..wThread, wEffectsOf, wConstructor, wDelegator,
+                 wImportObjC..wExportNims, wNodecl, wSideEffect..wNosinks,
+                 wDynlib..wUsed, wError, wStackTrace..wLineTrace,
+                 wDeprecated..wVarargs, wNimcall..wNoconv, wNonReloadable,
+                 wRaises, wTags..wEnsures, wNoDestroy, wCompileTime..wNoInit,
+                 wBorrow..wDiscardable, wGensym..wInject, wAsmNoStackFrame,
+                 wCodegenDecl, wLocks, wLiftLocals..wSystemRaisesDefect,
+                 wQuirky..wExtern, wVirtual, wMember}
+
+ + + Source   +Edit   + +
+
+
+
paramPragmas = {wNoalias, wInject, wGensym, wByRef, wByCopy, wCodegenDecl,
+                wExportc, wExportCpp}
+
+ + + Source   +Edit   + +
+
+
+
procPragmas = {wMagic..wThread, wEffectsOf, wConstructor, wDelegator,
+               wImportCpp, wImportObjC..wExportNims, wNodecl,
+               wSideEffect..wNosinks, wDynlib..wProcVar, wUsed, wError,
+               wStackTrace..wLineTrace, wDeprecated..wVarargs,
+               wNimcall..wNoconv, wNonReloadable, wRaises, wTags..wEnsures,
+               wNoDestroy, wCompileTime..wNoInit, wBorrow..wDiscardable,
+               wGensym..wInject, wAsmNoStackFrame, wCodegenDecl, wLocks,
+               wLiftLocals..wSystemRaisesDefect, wQuirky..wExtern, wVirtual,
+               wMember}
+
+ + + Source   +Edit   + +
+
+
+
procTypePragmas = {wNimcall..wNoconv, wVarargs, wNoSideEffect, wThread, wRaises,
+                   wEffectsOf, wLocks, wTags, wForbids, wGcSafe, wRequires,
+                   wEnsures}
+
+ + + Source   +Edit   + +
+
+
+
stmtPragmas = {wHint, wWarning, wError, wFatal, wDefine, wUndef, wCompile,
+               wLink, wLinksys, wPure, wPush, wPop, wPassl, wPassc, wLocalPassc,
+               wDeadCodeElimUnused, wDeprecated, wPragma, wEmit, wUnroll,
+               wLinearScanEnd, wPatterns, wTrMacros, wEffects, wNoForward,
+               wReorder, wComputedGoto, wExperimental, wDoctype, wThis, wUsed,
+               wInvariant, wAssume, wAssert}
+
+ + + Source   +Edit   + +
+
+
+
stmtPragmasTopLevel = {wChecks, wObjChecks, wFieldChecks, wRangeChecks,
+                       wBoundChecks, wOverflowChecks, wNilChecks,
+                       wStaticBoundchecks, wStyleChecks, wAssertions, wWarnings,
+                       wHints, wLineDir, wStackTrace, wLineTrace, wOptimization,
+                       wFloatChecks, wInfChecks, wNanChecks}
+
+ + + Source   +Edit   + +
+
+
+
templatePragmas = {wDeprecated, wError, wGensym, wInject, wDirty, wDelegator,
+                   wExportNims, wUsed, wPragma, wRedefine, wCallsite}
+
+ + + Source   +Edit   + +
+
+
+
typePragmas = {wMagic, wFinal, wImportCpp..wImportObjC, wImportc..wRequiresInit,
+               wNodecl..wPure, wHeader, wGcSafe, wCompilerProc..wCore, wUsed,
+               wError, wDeprecated, wSize, wPackage, wNoInit, wBorrow,
+               wAcyclic..wShallow, wGensym..wInject, wInheritable,
+               wCodegenDecl..wUnchecked, wPartial..wExplain, wExtern,
+               wUnion..wPacked, wByCopy..wByRef, wSendable}
+
+ + + Source   +Edit   + +
+
+
+
varPragmas = {wMagic, wCursor..wNoalias, wImportCpp, wImportObjC,
+              wImportc..wExportNims, wAlign..wNodecl, wHeader, wDynlib..wCore,
+              wUsed, wError, wDeprecated, wCompileTime..wNoInit,
+              wGensym..wInject, wThreadVar, wGlobal..wCodegenDecl, wGuard,
+              wLiftLocals, wExtern..wRegister, wVolatile}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc getPragmaVal(procAst: PNode; name: TSpecialWord): PNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasPragma(n: PNode; pragma: TSpecialWord): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc illegalCustomPragma(c: PContext; n: PNode; s: PSym) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc implicitPragmas(c: PContext; sym: PSym; info: TLineInfo;
+                     validPragmas: TSpecialWords) {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, OSError, EOFError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    WriteDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc invalidPragma(c: PContext; n: PNode) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pragma(c: PContext; sym: PSym; n: PNode; validPragmas: TSpecialWords;
+            isStatement: bool = false) {....raises: [Exception, ValueError,
+    KeyError, IOError, ERecoverableError, OSError, EOFError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect, WriteDirEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pragmaAsm(c: PContext; n: PNode): char {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + Checks asm pragmas and get's the asm subschar (default: '`'). + Source   +Edit   + +
+
+ +
+
+
+
proc pragmaCallable(c: PContext; sym: PSym; n: PNode;
+                    validPragmas: TSpecialWords; isStatement: bool = false) {....raises: [
+    Exception, ValueError, KeyError, IOError, ERecoverableError, OSError,
+    EOFError], tags: [RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect,
+                      ReadEnvEffect, WriteDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pragmaNoForward(c: PContext; n: PNode; flag = sfNoForward) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pragmaToOptions(w: TSpecialWord): TOptions {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc semAsmOrEmit(con: PContext; n: PNode; marker: char): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/pragmas.idx b/compiler/pragmas.idx new file mode 100644 index 0000000000000..90cc83b11b86f --- /dev/null +++ b/compiler/pragmas.idx @@ -0,0 +1,34 @@ +nimTitle pragmas pragmas.html module pragmas 0 +nim FirstCallConv pragmas.html#FirstCallConv const FirstCallConv 27 +nim LastCallConv pragmas.html#LastCallConv const LastCallConv 28 +nim procPragmas pragmas.html#procPragmas const procPragmas 34 +nim converterPragmas pragmas.html#converterPragmas const converterPragmas 42 +nim methodPragmas pragmas.html#methodPragmas const methodPragmas 43 +nim templatePragmas pragmas.html#templatePragmas const templatePragmas 44 +nim macroPragmas pragmas.html#macroPragmas const macroPragmas 46 +nim iteratorPragmas pragmas.html#iteratorPragmas const iteratorPragmas 49 +nim exprPragmas pragmas.html#exprPragmas const exprPragmas 53 +nim stmtPragmas pragmas.html#stmtPragmas const stmtPragmas 54 +nim stmtPragmasTopLevel pragmas.html#stmtPragmasTopLevel const stmtPragmasTopLevel 63 +nim lambdaPragmas pragmas.html#lambdaPragmas const lambdaPragmas 69 +nim typePragmas pragmas.html#typePragmas const typePragmas 74 +nim fieldPragmas pragmas.html#fieldPragmas const fieldPragmas 80 +nim varPragmas pragmas.html#varPragmas const varPragmas 82 +nim constPragmas pragmas.html#constPragmas const constPragmas 87 +nim paramPragmas pragmas.html#paramPragmas const paramPragmas 91 +nim letPragmas pragmas.html#letPragmas const letPragmas 92 +nim procTypePragmas pragmas.html#procTypePragmas const procTypePragmas 93 +nim forVarPragmas pragmas.html#forVarPragmas const forVarPragmas 96 +nim allRoutinePragmas pragmas.html#allRoutinePragmas const allRoutinePragmas 97 +nim enumFieldPragmas pragmas.html#enumFieldPragmas const enumFieldPragmas 98 +nim getPragmaVal pragmas.html#getPragmaVal,PNode,TSpecialWord proc getPragmaVal(procAst: PNode; name: TSpecialWord): PNode 100 +nim pragma pragmas.html#pragma,PContext,PSym,PNode,TSpecialWords,bool proc pragma(c: PContext; sym: PSym; n: PNode; validPragmas: TSpecialWords;\n isStatement: bool = false) 109 +nim invalidPragma pragmas.html#invalidPragma,PContext,PNode proc invalidPragma(c: PContext; n: PNode) 122 +nim illegalCustomPragma pragmas.html#illegalCustomPragma,PContext,PNode,PSym proc illegalCustomPragma(c: PContext; n: PNode; s: PSym) 125 +nim pragmaNoForward pragmas.html#pragmaNoForward,PContext,PNode proc pragmaNoForward(c: PContext; n: PNode; flag = sfNoForward) 283 +nim pragmaAsm pragmas.html#pragmaAsm,PContext,PNode proc pragmaAsm(c: PContext; n: PNode): char 296 +nim pragmaToOptions pragmas.html#pragmaToOptions,TSpecialWord proc pragmaToOptions(w: TSpecialWord): TOptions 395 +nim semAsmOrEmit pragmas.html#semAsmOrEmit,PContext,PNode,char proc semAsmOrEmit(con: PContext; n: PNode; marker: char): PNode 615 +nim implicitPragmas pragmas.html#implicitPragmas,PContext,PSym,TLineInfo,TSpecialWords proc implicitPragmas(c: PContext; sym: PSym; info: TLineInfo;\n validPragmas: TSpecialWords) 1357 +nim hasPragma pragmas.html#hasPragma,PNode,TSpecialWord proc hasPragma(n: PNode; pragma: TSpecialWord): bool 1382 +nim pragmaCallable pragmas.html#pragmaCallable,PContext,PSym,PNode,TSpecialWords,bool proc pragmaCallable(c: PContext; sym: PSym; n: PNode; validPragmas: TSpecialWords;\n isStatement: bool = false) 1407 diff --git a/compiler/prefixmatches.html b/compiler/prefixmatches.html new file mode 100644 index 0000000000000..e87153ca1bffd --- /dev/null +++ b/compiler/prefixmatches.html @@ -0,0 +1,143 @@ + + + + + + + +prefixmatches + + + + + + + + + + + + + + + + +
+
+

prefixmatches

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Types

+
+
+
PrefixMatch {.pure.} = enum
+  None,                     ## no prefix detected
+  Abbrev,                   ## prefix is an abbreviation of the symbol
+  Substr,                   ## prefix is a substring of the symbol
+  Prefix                     ## prefix does match the symbol
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc prefixMatch(p, s: string): PrefixMatch {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/prefixmatches.idx b/compiler/prefixmatches.idx new file mode 100644 index 0000000000000..4e598cc1ef4e6 --- /dev/null +++ b/compiler/prefixmatches.idx @@ -0,0 +1,3 @@ +nimTitle prefixmatches prefixmatches.html module prefixmatches 0 +nim PrefixMatch prefixmatches.html#PrefixMatch enum PrefixMatch 13 +nim prefixMatch prefixmatches.html#prefixMatch,string,string proc prefixMatch(p, s: string): PrefixMatch 19 diff --git a/compiler/procfind.html b/compiler/procfind.html new file mode 100644 index 0000000000000..a446d0d6592ad --- /dev/null +++ b/compiler/procfind.html @@ -0,0 +1,125 @@ + + + + + + + +procfind + + + + + + + + + + + + + + + + +
+
+

procfind

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc searchForProc(c: PContext; scope: PScope; fn: PSym): tuple[proto: PSym,
+    comesFromShadowScope: bool] {....raises: [Exception, KeyError, ValueError,
+    IOError, ERecoverableError], tags: [RootEffect, ReadDirEffect,
+                                        WriteIOEffect, ReadIOEffect,
+                                        ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/procfind.idx b/compiler/procfind.idx new file mode 100644 index 0000000000000..d21233fb9fe91 --- /dev/null +++ b/compiler/procfind.idx @@ -0,0 +1,2 @@ +nimTitle procfind procfind.html module procfind 0 +nim searchForProc procfind.html#searchForProc,PContext,PScope,PSym proc searchForProc(c: PContext; scope: PScope; fn: PSym): tuple[proto: PSym,\n comesFromShadowScope: bool] 55 diff --git a/compiler/pushpoppragmas.html b/compiler/pushpoppragmas.html new file mode 100644 index 0000000000000..a84efe67cfee8 --- /dev/null +++ b/compiler/pushpoppragmas.html @@ -0,0 +1,162 @@ + + + + + + + +pushpoppragmas + + + + + + + + + + + + + + + + +
+
+

pushpoppragmas

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc processPushBackendOption(config: ConfigRef;
+                              optionsStack: var seq[(TOptions, TNoteKinds)];
+                              options: var TOptions; n: PNode; start: int) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template processPopBackendOption(config: ConfigRef; optionsStack: var seq[
+    (TOptions, TNoteKinds)]; options: var TOptions)
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/pushpoppragmas.idx b/compiler/pushpoppragmas.idx new file mode 100644 index 0000000000000..67eecb5b1b367 --- /dev/null +++ b/compiler/pushpoppragmas.idx @@ -0,0 +1,3 @@ +nimTitle pushpoppragmas pushpoppragmas.html module pushpoppragmas 0 +nim processPushBackendOption pushpoppragmas.html#processPushBackendOption,ConfigRef,seq[],TOptions,PNode,int proc processPushBackendOption(config: ConfigRef;\n optionsStack: var seq[(TOptions, TNoteKinds)];\n options: var TOptions; n: PNode; start: int) 34 +nim processPopBackendOption pushpoppragmas.html#processPopBackendOption.t,ConfigRef,seq[],TOptions template processPopBackendOption(config: ConfigRef;\n optionsStack: var seq[(TOptions, TNoteKinds)];\n options: var TOptions) 53 diff --git a/compiler/renderer.html b/compiler/renderer.html new file mode 100644 index 0000000000000..dddfc6437dc94 --- /dev/null +++ b/compiler/renderer.html @@ -0,0 +1,376 @@ + + + + + + + +renderer + + + + + + + + + + + + + + + + +
+
+

renderer

+
+ +
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
TRenderFlag = enum
+  renderNone, renderNoBody, renderNoComments, renderDocComments,
+  renderNoPragmas, renderIds, renderNoProcDefs, renderSyms,
+  renderRunnableExamples, renderIr, renderNonExportedFields, renderExpandUsing,
+  renderNoPostfix
+
+ + + Source   +Edit   + +
+
+
+
TRenderFlags = set[TRenderFlag]
+
+ + + Source   +Edit   + +
+
+
+
TRenderTok = object
+  kind*: TokType
+  length*: int16
+  sym*: PSym
+
+ + + Source   +Edit   + +
+
+
+
TRenderTokSeq = seq[TRenderTok]
+
+ + + Source   +Edit   + +
+
+
+
TSrcGen = object
+  indent*: int
+  lineLen*: int
+  pos*: int
+  idx*: int
+  tokens*: TRenderTokSeq
+  buf*: string
+  pendingNL*: int
+  comStack*: seq[PNode]
+  flags*: TRenderFlags
+  when defined(nimpretty):
+  fid*: FileIndex
+  config*: ConfigRef
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(n: PNode): string {....raises: [Exception, KeyError], tags: [RootEffect],
+                             forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bracketKind(g: TSrcGen; n: PNode): BracketKind {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getNextTok(r: var TSrcGen; kind: var TokType; literal: var string) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getTokSym(r: TSrcGen): PSym {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initTokRender(n: PNode; renderFlags: TRenderFlags = {}): TSrcGen {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isKeyword(i: PIdent): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc renderDefinitionName(s: PSym; noQuotes = false): string {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Returns the definition name of the symbol.

+

If noQuotes is false the symbol may be returned in backticks. This will happen if the name happens to be a keyword or the first character is not part of the SymStartChars set.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc renderModule(n: PNode; outfile: string; renderFlags: TRenderFlags = {};
+                  fid = FileIndex(-1); conf: ConfigRef = nil) {.
+    ...raises: [Exception, KeyError, IOError, ValueError, ERecoverableError], tags: [
+    RootEffect, WriteIOEffect, ReadDirEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc renderTree(n: PNode; renderFlags: TRenderFlags = {}): string {.
+    ...raises: [Exception, KeyError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/renderer.idx b/compiler/renderer.idx new file mode 100644 index 0000000000000..791559c82c33f --- /dev/null +++ b/compiler/renderer.idx @@ -0,0 +1,28 @@ +nimTitle renderer renderer.html module renderer 0 +nim renderNone renderer.html#renderNone TRenderFlag.renderNone 25 +nim renderNoBody renderer.html#renderNoBody TRenderFlag.renderNoBody 25 +nim renderNoComments renderer.html#renderNoComments TRenderFlag.renderNoComments 25 +nim renderDocComments renderer.html#renderDocComments TRenderFlag.renderDocComments 25 +nim renderNoPragmas renderer.html#renderNoPragmas TRenderFlag.renderNoPragmas 25 +nim renderIds renderer.html#renderIds TRenderFlag.renderIds 25 +nim renderNoProcDefs renderer.html#renderNoProcDefs TRenderFlag.renderNoProcDefs 25 +nim renderSyms renderer.html#renderSyms TRenderFlag.renderSyms 25 +nim renderRunnableExamples renderer.html#renderRunnableExamples TRenderFlag.renderRunnableExamples 25 +nim renderIr renderer.html#renderIr TRenderFlag.renderIr 25 +nim renderNonExportedFields renderer.html#renderNonExportedFields TRenderFlag.renderNonExportedFields 25 +nim renderExpandUsing renderer.html#renderExpandUsing TRenderFlag.renderExpandUsing 25 +nim renderNoPostfix renderer.html#renderNoPostfix TRenderFlag.renderNoPostfix 25 +nim TRenderFlag renderer.html#TRenderFlag enum TRenderFlag 25 +nim TRenderFlags renderer.html#TRenderFlags type TRenderFlags 30 +nim TRenderTok renderer.html#TRenderTok object TRenderTok 31 +nim TRenderTokSeq renderer.html#TRenderTokSeq type TRenderTokSeq 40 +nim TSrcGen renderer.html#TSrcGen object TSrcGen 41 +nim renderTree renderer.html#renderTree,PNode,TRenderFlags proc renderTree(n: PNode; renderFlags: TRenderFlags = {}): string 63 +nim isKeyword renderer.html#isKeyword,PIdent proc isKeyword(i: PIdent): bool 77 +nim renderDefinitionName renderer.html#renderDefinitionName,PSym proc renderDefinitionName(s: PSym; noQuotes = false): string 94 +nim bracketKind renderer.html#bracketKind,TSrcGen,PNode proc bracketKind(g: TSrcGen; n: PNode): BracketKind 1002 +nim `$` renderer.html#$,PNode proc `$`(n: PNode): string 1842 +nim renderModule renderer.html#renderModule,PNode,string,TRenderFlags,ConfigRef proc renderModule(n: PNode; outfile: string; renderFlags: TRenderFlags = {};\n fid = FileIndex(-1); conf: ConfigRef = nil) 1844 +nim initTokRender renderer.html#initTokRender,PNode,TRenderFlags proc initTokRender(n: PNode; renderFlags: TRenderFlags = {}): TSrcGen 1866 +nim getNextTok renderer.html#getNextTok,TSrcGen,TokType,string proc getNextTok(r: var TSrcGen; kind: var TokType; literal: var string) 1870 +nim getTokSym renderer.html#getTokSym,TSrcGen proc getTokSym(r: TSrcGen): PSym 1880 diff --git a/compiler/renderverbatim.html b/compiler/renderverbatim.html new file mode 100644 index 0000000000000..0a23ee011b4d8 --- /dev/null +++ b/compiler/renderverbatim.html @@ -0,0 +1,120 @@ + + + + + + + +renderverbatim + + + + + + + + + + + + + + + + +
+
+

renderverbatim

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ ast, options, msgs +
+
+
+

Procs

+
+
+
+
proc extractRunnableExamplesSource(conf: ConfigRef; n: PNode; indent = 0): string {.
+    ...raises: [], tags: [ReadIOEffect], forbids: [].}
+
+ + TLineInfo.offsetA,offsetB would be cleaner but it's only enabled for nimpretty, we'd need to check performance impact to enable it for nimdoc. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/renderverbatim.idx b/compiler/renderverbatim.idx new file mode 100644 index 0000000000000..6f0df637040e1 --- /dev/null +++ b/compiler/renderverbatim.idx @@ -0,0 +1,2 @@ +nimTitle renderverbatim renderverbatim.html module renderverbatim 0 +nim extractRunnableExamplesSource renderverbatim.html#extractRunnableExamplesSource,ConfigRef,PNode,int proc extractRunnableExamplesSource(conf: ConfigRef; n: PNode; indent = 0): string 91 diff --git a/compiler/reorder.html b/compiler/reorder.html new file mode 100644 index 0000000000000..1b45fabc1b5bf --- /dev/null +++ b/compiler/reorder.html @@ -0,0 +1,142 @@ + + + + + + + +reorder + + + + + + + + + + + + + + + + +
+
+

reorder

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc includeModule(graph: ModuleGraph; s: PSym; fileIdx: FileIndex): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc reorder(graph: ModuleGraph; n: PNode; module: PSym): PNode {....raises: [
+    OSError, Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    ReadEnvEffect, ReadIOEffect, RootEffect, ReadDirEffect, WriteIOEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/reorder.idx b/compiler/reorder.idx new file mode 100644 index 0000000000000..7fc86a3d092b4 --- /dev/null +++ b/compiler/reorder.idx @@ -0,0 +1,3 @@ +nimTitle reorder reorder.html module reorder 0 +nim includeModule reorder.html#includeModule,ModuleGraph,PSym,FileIndex proc includeModule(graph: ModuleGraph; s: PSym; fileIdx: FileIndex): PNode 119 +nim reorder reorder.html#reorder,ModuleGraph,PNode,PSym proc reorder(graph: ModuleGraph; n: PNode; module: PSym): PNode 421 diff --git a/compiler/rodutils.html b/compiler/rodutils.html new file mode 100644 index 0000000000000..f68398ecd7bfb --- /dev/null +++ b/compiler/rodutils.html @@ -0,0 +1,265 @@ + + + + + + + +rodutils + + + + + + + + + + + + + + + + +
+
+

rodutils

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Serialization utilities for the compiler.

+
+

Procs

+
+
+
+
proc decodeStr(s: cstring; pos: var int): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc decodeVBiggestInt(s: cstring; pos: var int): BiggestInt {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc decodeVInt(s: cstring; pos: var int): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc encodeStr(s: string; result: var string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc encodeVBiggestInt(x: BiggestInt; result: var string) {....raises: [],
+    tags: [], forbids: [].}
+
+ + encode a biggest int as a variable length base 190 int. + Source   +Edit   + +
+
+ +
+
+
+
proc encodeVInt(x: int; result: var string) {....raises: [], tags: [], forbids: [].}
+
+ + encode an int as a variable length base 190 int. + Source   +Edit   + +
+
+ +
+
+
+
proc toStrMaxPrecision(f: BiggestFloat | float32): string
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator decodeStrArray(s: cstring): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator decodeVIntArray(s: cstring): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/rodutils.idx b/compiler/rodutils.idx new file mode 100644 index 0000000000000..245518c2c4e44 --- /dev/null +++ b/compiler/rodutils.idx @@ -0,0 +1,10 @@ +nimTitle rodutils rodutils.html module rodutils 0 +nim toStrMaxPrecision rodutils.html#toStrMaxPrecision proc toStrMaxPrecision(f: BiggestFloat | float32): string 47 +nim encodeStr rodutils.html#encodeStr,string,string proc encodeStr(s: string; result: var string) 68 +nim decodeStr rodutils.html#decodeStr,cstring,int proc decodeStr(s: cstring; pos: var int): string 81 +nim encodeVBiggestInt rodutils.html#encodeVBiggestInt,BiggestInt,string proc encodeVBiggestInt(x: BiggestInt; result: var string) 127 +nim encodeVInt rodutils.html#encodeVInt,int,string proc encodeVInt(x: int; result: var string) 136 +nim decodeVInt rodutils.html#decodeVInt,cstring,int proc decodeVInt(s: cstring; pos: var int): int 159 +nim decodeVBiggestInt rodutils.html#decodeVBiggestInt,cstring,int proc decodeVBiggestInt(s: cstring; pos: var int): BiggestInt 162 +nim decodeVIntArray rodutils.html#decodeVIntArray.i,cstring iterator decodeVIntArray(s: cstring): int 167 +nim decodeStrArray rodutils.html#decodeStrArray.i,cstring iterator decodeStrArray(s: cstring): string 173 diff --git a/compiler/ropes.html b/compiler/ropes.html new file mode 100644 index 0000000000000..2e377019736f0 --- /dev/null +++ b/compiler/ropes.html @@ -0,0 +1,378 @@ + + + + + + + +ropes + + + + + + + + + + + + + + + + +
+
+

ropes

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ pathutils +
+
+
+

Types

+
+
+
FormatStr = string
+
+ + + Source   +Edit   + +
+
+
+
Rope = string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `%`(frmt: static[FormatStr]; args: openArray[Rope]): Rope
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc equalsFile(r: Rope; filename: AbsoluteFile): bool {....raises: [IOError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + returns true if the contents of the file f equal r. If f does not exist, false is returned. + Source   +Edit   + +
+
+
+
proc equalsFile(s: Rope; f: File): bool {....raises: [IOError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + returns true if the contents of the file f equal r. + Source   +Edit   + +
+
+ +
+
+
+
proc freeze(r: Rope) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newRopeAppender(cap = 80): string {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc prepend(a: var Rope; b: string) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc resetRopeCache() {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rope(f: BiggestFloat): Rope {....raises: [], tags: [], forbids: [].}
+
+ + Converts a float to a rope. + Source   +Edit   + +
+
+
+
proc rope(i: BiggestInt): Rope {....raises: [], tags: [], forbids: [].}
+
+ + Converts an int to a rope. + Source   +Edit   + +
+
+ +
+
+
+
proc runtimeFormat(frmt: FormatStr; args: openArray[Rope]): Rope {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc writeRope(f: File; r: Rope) {....raises: [IOError], tags: [WriteIOEffect],
+                                   forbids: [].}
+
+ + writes a rope to a file. + Source   +Edit   + +
+
+
+
proc writeRope(head: Rope; filename: AbsoluteFile): bool {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template addf(c: var Rope; frmt: FormatStr; args: openArray[Rope])
+
+ + shortcut for add(c, frmt % args). + Source   +Edit   + +
+
+ +
+
+
+
template rope(s: string): string
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/ropes.idx b/compiler/ropes.idx new file mode 100644 index 0000000000000..4e635969f254d --- /dev/null +++ b/compiler/ropes.idx @@ -0,0 +1,20 @@ +nimTitle ropes ropes.html module ropes 0 +nim FormatStr ropes.html#FormatStr type FormatStr 18 +nim Rope ropes.html#Rope type Rope 22 +nim newRopeAppender ropes.html#newRopeAppender,int proc newRopeAppender(cap = 80): string 24 +nim freeze ropes.html#freeze,Rope proc freeze(r: Rope) 27 +nim resetRopeCache ropes.html#resetRopeCache proc resetRopeCache() 29 +nim rope ropes.html#rope.t,string template rope(s: string): string 31 +nim rope ropes.html#rope,BiggestInt proc rope(i: BiggestInt): Rope 33 +nim rope ropes.html#rope,BiggestFloat proc rope(f: BiggestFloat): Rope 37 +nim writeRope ropes.html#writeRope,File,Rope proc writeRope(f: File; r: Rope) 41 +nim writeRope ropes.html#writeRope,Rope,AbsoluteFile proc writeRope(head: Rope; filename: AbsoluteFile): bool 45 +nim prepend ropes.html#prepend,Rope,string proc prepend(a: var Rope; b: string) 54 +nim runtimeFormat ropes.html#runtimeFormat,FormatStr,openArray[Rope] proc runtimeFormat(frmt: FormatStr; args: openArray[Rope]): Rope 56 +nim `%` ropes.html#%,static[FormatStr],openArray[Rope] proc `%`(frmt: static[FormatStr]; args: openArray[Rope]): Rope 109 +nim addf ropes.html#addf.t,Rope,FormatStr,openArray[Rope] template addf(c: var Rope; frmt: FormatStr; args: openArray[Rope]) 112 +nim equalsFile ropes.html#equalsFile,Rope,File proc equalsFile(s: Rope; f: File): bool 119 +nim equalsFile ropes.html#equalsFile,Rope,AbsoluteFile proc equalsFile(r: Rope; filename: AbsoluteFile): bool 151 +nimgrp rope ropes.html#rope-procs-all proc 33 +nimgrp writerope ropes.html#writeRope-procs-all proc 41 +nimgrp equalsfile ropes.html#equalsFile-procs-all proc 119 diff --git a/compiler/saturate.html b/compiler/saturate.html new file mode 100644 index 0000000000000..5a9e2d9a21a83 --- /dev/null +++ b/compiler/saturate.html @@ -0,0 +1,195 @@ + + + + + + + +saturate + + + + + + + + + + + + + + + + +
+
+

saturate

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Saturated arithmetic routines. XXX Make part of the stdlib?

+
+

Procs

+
+
+
+
proc `|*|`(a, b: BiggestInt): BiggestInt {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `|+|`(a, b: BiggestInt): BiggestInt {....raises: [], tags: [], forbids: [].}
+
+ + saturated addition. + Source   +Edit   + +
+
+ +
+
+
+
proc `|-|`(a, b: BiggestInt): BiggestInt {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `|abs|`(a: BiggestInt): BiggestInt {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `|div|`(a, b: BiggestInt): BiggestInt {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `|mod|`(a, b: BiggestInt): BiggestInt {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/saturate.idx b/compiler/saturate.idx new file mode 100644 index 0000000000000..01defc5fe0670 --- /dev/null +++ b/compiler/saturate.idx @@ -0,0 +1,7 @@ +nimTitle saturate saturate.html module saturate 0 +nim `|+|` saturate.html#|+|,BiggestInt,BiggestInt proc `|+|`(a, b: BiggestInt): BiggestInt 12 +nim `|-|` saturate.html#|-|,BiggestInt,BiggestInt proc `|-|`(a, b: BiggestInt): BiggestInt 22 +nim `|abs|` saturate.html#|abs|,BiggestInt proc `|abs|`(a: BiggestInt): BiggestInt 31 +nim `|div|` saturate.html#|div|,BiggestInt,BiggestInt proc `|div|`(a, b: BiggestInt): BiggestInt 38 +nim `|mod|` saturate.html#|mod|,BiggestInt,BiggestInt proc `|mod|`(a, b: BiggestInt): BiggestInt 48 +nim `|*|` saturate.html#|*|,BiggestInt,BiggestInt proc `|*|`(a, b: BiggestInt): BiggestInt 54 diff --git a/compiler/scriptconfig.html b/compiler/scriptconfig.html new file mode 100644 index 0000000000000..a874cc3235dc8 --- /dev/null +++ b/compiler/scriptconfig.html @@ -0,0 +1,147 @@ + + + + + + + +scriptconfig + + + + + + + + + + + + + + + + +
+
+

scriptconfig

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Implements the new configuration system for Nim. Uses Nim as a scripting language.

+ +
+

Procs

+
+
+
+
proc runNimScript(cache: IdentCache; scriptName: AbsoluteFile;
+                  idgen: IdGenerator; freshDefines = true; conf: ConfigRef;
+                  stream: PLLStream) {....raises: [Exception, ValueError, KeyError,
+    IOError, ERecoverableError, OSError, EOFError, ESuggestDone], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    WriteDirEffect, TimeEffect, ExecIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setupVM(module: PSym; cache: IdentCache; scriptName: string;
+             graph: ModuleGraph; idgen: IdGenerator): PEvalContext {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/scriptconfig.idx b/compiler/scriptconfig.idx new file mode 100644 index 0000000000000..4bf4a1cc5dc38 --- /dev/null +++ b/compiler/scriptconfig.idx @@ -0,0 +1,3 @@ +nimTitle scriptconfig scriptconfig.html module scriptconfig 0 +nim setupVM scriptconfig.html#setupVM,PSym,IdentCache,string,ModuleGraph,IdGenerator proc setupVM(module: PSym; cache: IdentCache; scriptName: string; graph: ModuleGraph;\n idgen: IdGenerator): PEvalContext 34 +nim runNimScript scriptconfig.html#runNimScript,IdentCache,AbsoluteFile,IdGenerator,ConfigRef,PLLStream proc runNimScript(cache: IdentCache; scriptName: AbsoluteFile; idgen: IdGenerator;\n freshDefines = true; conf: ConfigRef; stream: PLLStream) 196 diff --git a/compiler/sem.html b/compiler/sem.html new file mode 100644 index 0000000000000..7e4cac1258c24 --- /dev/null +++ b/compiler/sem.html @@ -0,0 +1,410 @@ + + + + + + + +sem + + + + + + + + + + + + + + + + +
+
+

sem

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module implements semantic checking for calls.this module does the semantic checking of statementsThis module does the semantic transformation of the fields* iterators.This module implements Nim's object construction rules.

+ +
+

Consts

+
+
+
tyGenericLike = {tyGenericInvocation, tyGenericInst, tyArray, tySet, tySequence,
+                 tyOpenArray, tyUserTypeClassInst..tyCompositeTypeClass}
+
+ + + Source   +Edit   + +
+
+
+
tyMagicGenerics = {tySet, tySequence, tyArray, tyOpenArray}
+
+ + + Source   +Edit   + +
+
+
+
tyUserDefinedGenerics = {tyGenericInst, tyGenericInvocation, tyUserTypeClassInst}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc closePContext(graph: ModuleGraph; c: PContext; n: PNode): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, ReadIOEffect, WriteIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc commonType(c: PContext; x, y: PType): PType {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc commonType(c: PContext; x: PType; y: PNode): PType {.
+    ...raises: [Exception, KeyError], tags: [RootEffect, ReadDirEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc instGenericConvertersArg(c: PContext; a: PNode; x: TCandidate) {....raises: [
+    Exception, ValueError, KeyError, IOError, ERecoverableError, OSError,
+    EOFError], tags: [RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect,
+                      ReadEnvEffect, WriteDirEffect, TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc instGenericConvertersSons(c: PContext; n: PNode; x: TCandidate) {....raises: [
+    Exception, ValueError, KeyError, IOError, ERecoverableError, OSError,
+    EOFError], tags: [RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect,
+                      ReadEnvEffect, WriteDirEffect, TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isRecursiveType(t: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc markConvertersUsed(c: PContext; n: PNode) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newSymG(kind: TSymKind; n: PNode; c: PContext): PSym {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc notFoundError(c: PContext; n: PNode; errors: CandidateErrors) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc preparePContext(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PContext {.
+    ...raises: [IOError, Exception, ValueError, KeyError, ERecoverableError], tags: [
+    ReadIOEffect, RootEffect, ReadDirEffect, WriteIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pushProcCon(c: PContext; owner: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc semWithPContext(c: PContext; n: PNode): PNode {....raises: [OSError,
+    Exception, ValueError, KeyError, IOError, ERecoverableError, EOFError,
+    ESuggestDone, OSError, Exception, ValueError, KeyError, IOError, EOFError,
+    ERecoverableError], tags: [ReadEnvEffect, ReadIOEffect, RootEffect,
+                               ReadDirEffect, WriteIOEffect, WriteDirEffect,
+                               TimeEffect, ExecIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template commonTypeBegin(): PType
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/sem.idx b/compiler/sem.idx new file mode 100644 index 0000000000000..9839898052676 --- /dev/null +++ b/compiler/sem.idx @@ -0,0 +1,18 @@ +nimTitle sem sem.html module sem 0 +nim commonTypeBegin sem.html#commonTypeBegin.t template commonTypeBegin(): PType 136 +nim commonType sem.html#commonType,PContext,PType,PType proc commonType(c: PContext; x, y: PType): PType 138 +nim commonType sem.html#commonType,PContext,PType,PNode proc commonType(c: PContext; x: PType; y: PNode): PType 232 +nim newSymG sem.html#newSymG,TSymKind,PNode,PContext proc newSymG(kind: TSymKind; n: PNode; c: PContext): PSym 242 +nim pushProcCon sem.html#pushProcCon,PContext,PSym proc pushProcCon(c: PContext; owner: PSym) 31 +nim notFoundError sem.html#notFoundError,PContext,PNode,CandidateErrors proc notFoundError(c: PContext; n: PNode; errors: CandidateErrors) 494 +nim instGenericConvertersArg sem.html#instGenericConvertersArg,PContext,PNode,TCandidate proc instGenericConvertersArg(c: PContext; a: PNode; x: TCandidate) 693 +nim instGenericConvertersSons sem.html#instGenericConvertersSons,PContext,PNode,TCandidate proc instGenericConvertersSons(c: PContext; n: PNode; x: TCandidate) 703 +nim markConvertersUsed sem.html#markConvertersUsed,PContext,PNode proc markConvertersUsed(c: PContext; n: PNode) 709 +nim isRecursiveType sem.html#isRecursiveType,PType proc isRecursiveType(t: PType): bool 295 +nim tyUserDefinedGenerics sem.html#tyUserDefinedGenerics const tyUserDefinedGenerics 148 +nim tyMagicGenerics sem.html#tyMagicGenerics const tyMagicGenerics 151 +nim tyGenericLike sem.html#tyGenericLike const tyGenericLike 153 +nim preparePContext sem.html#preparePContext,ModuleGraph,PSym,IdGenerator proc preparePContext(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PContext 718 +nim semWithPContext sem.html#semWithPContext,PContext,PNode proc semWithPContext(c: PContext; n: PNode): PNode 834 +nim closePContext sem.html#closePContext,ModuleGraph,PContext,PNode proc closePContext(graph: ModuleGraph; c: PContext; n: PNode): PNode 862 +nimgrp commontype sem.html#commonType-procs-all proc 138 diff --git a/compiler/semdata.html b/compiler/semdata.html new file mode 100644 index 0000000000000..21b0387f8827a --- /dev/null +++ b/compiler/semdata.html @@ -0,0 +1,1771 @@ + + + + + + + +semdata + + + + + + + + + + + + + + + + +
+
+

semdata

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module contains the data structures for the semantic checking phase.

+ +
+

Types

+
+
+
ImportedModule = object
+  m*: PSym
+  case mode*: ImportMode
+  of importAll:
+    nil
+  of importSet:
+    imported*: IntSet
+  of importExcept:
+    exceptSet*: IntSet
+
+ + + Source   +Edit   + +
+
+
+
ImportMode = enum
+  importAll, importSet, importExcept
+
+ + + Source   +Edit   + +
+
+
+
PContext = ref TContext
+
+ + + Source   +Edit   + +
+
+
+
POptionEntry = ref TOptionEntry
+
+ + + Source   +Edit   + +
+
+
+
PProcCon = ref TProcCon
+
+ + + Source   +Edit   + +
+
+
+
TBorrowState = enum
+  bsNone, bsReturnNotMatch, bsNoDistinct, bsGeneric, bsNotSupported, bsMatch
+
+ + + Source   +Edit   + +
+
+
+
TContext = object of TPassContext
+  enforceVoidContext*: PType
+  voidType*: PType
+  module*: PSym
+  currentScope*: PScope
+  moduleScope*: PScope
+  imports*: seq[ImportedModule]
+  topLevelScope*: PScope
+  p*: PProcCon
+  intTypeCache*: array[-5 .. 32, PType]
+  nilTypeCache*: PType
+  matchedConcept*: ptr TMatchedConcept
+  friendModules*: seq[PSym]
+  instCounter*: int
+  templInstCounter*: ref int
+  inGenericContext*: int
+  inStaticContext*: int
+  inUnrolledContext*: int
+  compilesContextId*: int
+  compilesContextIdGenerator*: int
+  inGenericInst*: int
+  converters*: seq[PSym]
+  patterns*: seq[PSym]
+  optionStack*: seq[POptionEntry]
+  libs*: seq[PLib]
+  semConstExpr*: proc (c: PContext; n: PNode; expectedType: PType = nil): PNode {.
+      nimcall.}
+  semExpr*: proc (c: PContext; n: PNode; flags: TExprFlags = {};
+                  expectedType: PType = nil): PNode {.nimcall.}
+  semExprWithType*: proc (c: PContext; n: PNode; flags: TExprFlags = {};
+                          expectedType: PType = nil): PNode {.nimcall.}
+  semTryExpr*: proc (c: PContext; n: PNode; flags: TExprFlags = {}): PNode {.
+      nimcall.}
+  semTryConstExpr*: proc (c: PContext; n: PNode; expectedType: PType = nil): PNode {.
+      nimcall.}
+  computeRequiresInit*: proc (c: PContext; t: PType): bool {.nimcall.}
+  hasUnresolvedArgs*: proc (c: PContext; n: PNode): bool
+  semOperand*: proc (c: PContext; n: PNode; flags: TExprFlags = {}): PNode {.
+      nimcall.}
+  semConstBoolExpr*: proc (c: PContext; n: PNode): PNode {.nimcall.}
+  semOverloadedCall*: proc (c: PContext; n, nOrig: PNode; filter: TSymKinds;
+                            flags: TExprFlags; expectedType: PType = nil): PNode {.
+      nimcall.}
+  semTypeNode*: proc (c: PContext; n: PNode; prev: PType): PType {.nimcall.}
+  semInferredLambda*: proc (c: PContext; pt: LayeredIdTable; n: PNode): PNode
+  semGenerateInstance*: proc (c: PContext; fn: PSym; pt: LayeredIdTable;
+                              info: TLineInfo): PSym
+  instantiateOnlyProcType*: proc (c: PContext; pt: LayeredIdTable; prc: PSym;
+                                  info: TLineInfo): PType
+  fitDefaultNode*: proc (c: PContext; n: var PNode; expectedType: PType)
+  includedFiles*: IntSet
+  pureEnumFields*: TStrTable
+  userPragmas*: TStrTable
+  evalContext*: PEvalContext
+  unknownIdents*: IntSet
+  generics*: seq[TInstantiationPair]
+  topStmts*: int
+  lastGenericIdx*: int
+  hloLoopDetector*: int
+  inParallelStmt*: int
+  instTypeBoundOp*: proc (c: PContext; dc: PSym; t: PType; info: TLineInfo;
+                          op: TTypeAttachedOp; col: int): PSym {.nimcall.}
+  cache*: IdentCache
+  graph*: ModuleGraph
+  signatures*: TStrTable
+  recursiveDep*: string
+  suggestionsMade*: bool
+  isAmbiguous*: bool
+  features*: set[Feature]
+  inTypeContext*, inConceptDecl*: int
+  unusedImports*: seq[(PSym, TLineInfo)]
+  exportIndirections*: HashSet[(int, int)]
+  importModuleMap*: Table[int, int]
+  lastTLineInfo*: TLineInfo
+  sideEffects*: Table[int, seq[(TLineInfo, PSym)]]
+  inUncheckedAssignSection*: int
+  importModuleLookup*: Table[int, seq[int]]
+  skipTypes*: seq[PNode]
+  inTypeofContext*: int
+
+ + + Source   +Edit   + +
+
+
+
TExprFlag = enum
+  efLValue, efWantIterator, efWantIterable, efInTypeof, efNeedStatic,
+  efPreferStatic, efPreferNilResult, efWantStmt, efAllowStmt, efDetermineType,
+  efExplain, efWantValue, efOperand, efNoSemCheck, efNoEvaluateGeneric,
+  efInCall, efFromHlo, efNoSem2Check, efNoUndeclared, efIsDotCall,
+  efCannotBeDotCall, efTypeAllowed, efWantNoDefaults, efIgnoreDefaults,
+  efAllowSymChoice
+
+ + + Source   +Edit   + +
+
+
+
TExprFlags = set[TExprFlag]
+
+ + + Source   +Edit   + +
+
+
+
TInstantiationPair = object
+  genericSym*: PSym
+  inst*: PInstantiation
+
+ + + Source   +Edit   + +
+
+
+
TMatchedConcept = object
+  candidateType*: PType
+  prev*: ptr TMatchedConcept
+  depth*: int
+
+ + + Source   +Edit   + +
+
+
+
TOptionEntry = object
+  options*: TOptions
+  defaultCC*: TCallingConvention
+  dynlib*: PLib
+  notes*: TNoteKinds
+  features*: set[Feature]
+  otherPragmas*: PNode
+  warningAsErrors*: TNoteKinds
+
+ + + Source   +Edit   + +
+
+
+
TProcCon {.acyclic.} = object
+  owner*: PSym
+  resultSym*: PSym
+  nestedLoopCounter*: int
+  nestedBlockCounter*: int
+  breakInLoop*: bool
+  next*: PProcCon
+  mappingExists*: bool
+  mapping*: Table[ItemId, PSym]
+  caseContext*: seq[tuple[n: PNode, idx: int]]
+  localBindStmts*: seq[PNode]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc addConverter(c: PContext; conv: LazySym) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addConverterDef(c: PContext; conv: LazySym) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addImportFileDep(c: PContext; f: FileIndex) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addIncludeFileDep(c: PContext; f: FileIndex) {....raises: [IOError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addPattern(c: PContext; p: LazySym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addPragmaComputation(c: PContext; n: PNode) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addPureEnum(c: PContext; e: LazySym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addToGenericCache(c: PContext; s: PSym; inst: PType) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addToGenericProcCache(c: PContext; s: PSym; inst: PInstantiation) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addToLib(lib: PLib; sym: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc checkMinSonsLen(n: PNode; length: int; conf: ConfigRef) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc checkSonsLen(n: PNode; length: int; conf: ConfigRef) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc considerGenSyms(c: PContext; n: PNode) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc errorNode(c: PContext; n: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc errorType(c: PContext): PType {....raises: [], tags: [], forbids: [].}
+
+ + creates a type representing an error state + Source   +Edit   + +
+
+ +
+
+
+
proc exportSym(c: PContext; s: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc filename(c: PContext): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc get(p: PProcCon; key: PSym): PSym {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getCurrOwner(c: PContext): PSym {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getGenSym(c: PContext; s: PSym): PSym {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getIntLitType(c: PContext; literal: PNode): PType {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc illFormedAst(n: PNode; conf: ConfigRef) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc illFormedAstLocal(n: PNode; conf: ConfigRef) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isSelf(t: PType): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Is this the magical 'Self' type from concepts? + Source   +Edit   + +
+
+ +
+
+
+
proc isTopLevel(c: PContext): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isTopLevelInsideDeclaration(c: PContext; sym: PSym): bool {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lastOptionEntry(c: PContext): POptionEntry {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeAndType(c: PContext; t1, t2: PType): PType {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeInstPair(s: PSym; inst: PInstantiation): TInstantiationPair {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeNotType(c: PContext; t1: PType): PType {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeOrType(c: PContext; t1, t2: PType): PType {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makePtrType(c: PContext; baseType: PType): PType {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc makePtrType(owner: PSym; baseType: PType; idgen: IdGenerator): PType {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeRangeType(c: PContext; first, last: BiggestInt; info: TLineInfo;
+                   intType: PType = nil): PType {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeRangeWithStaticExpr(c: PContext; n: PNode): PType {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeStaticExpr(c: PContext; n: PNode): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeTypeDesc(c: PContext; typ: PType): PType {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeTypeFromExpr(c: PContext; n: PNode): PType {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeTypeSymNode(c: PContext; typ: PType; info: TLineInfo): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeTypeWithModifier(c: PContext; modifier: TTypeKind; baseType: PType): PType {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makeVarType(c: PContext; baseType: PType; kind = tyVar): PType {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc markIndirect(c: PContext; s: PSym) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newContext(graph: ModuleGraph; module: PSym): PContext {....raises: [IOError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newLib(kind: TLibKind): PLib {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newOptionEntry(conf: ConfigRef): POptionEntry {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newTypeS(kind: TTypeKind; c: PContext; son: sink PType = nil): PType {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc popCaseContext(c: PContext) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc popOptionEntry(c: PContext) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc popOwner(c: PContext) {....raises: [Exception, ValueError, KeyError, IOError,
+                                      ERecoverableError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc popProcCon(c: PContext) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pushCaseContext(c: PContext; caseNode: PNode) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pushOptionEntry(c: PContext): POptionEntry {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pushOwner(c: PContext; owner: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc put(p: PProcCon; key, val: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc reexportSym(c: PContext; s: PSym) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rememberExpansion(c: PContext; info: TLineInfo; expandedSym: PSym) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Templates and macros are very special in Nim; these have inlining semantics so after semantic checking they leave no trace in the sem'checked AST. This is very bad for IDE-like tooling ("find all usages of this template" would not work). We need special logic to remember macro/template expansions. This is done here and delegated to the "rod" file mechanism. + Source   +Edit   + +
+
+ +
+
+
+
proc scopeDepth(c: PContext): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sealRodFile(c: PContext) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setCaseContextIdx(c: PContext; idx: int) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setIntLitType(c: PContext; result: PNode) {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc storeRodNode(c: PContext; n: PNode) {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc symFromType(c: PContext; t: PType; info: TLineInfo): PSym {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc symNodeFromType(c: PContext; t: PType; info: TLineInfo): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template addExport(c: PContext; s: PSym)
+
+ + convenience to export a symbol from the current module + Source   +Edit   + +
+
+ +
+
+
+
template config(c: PContext): ConfigRef
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template encoder(c): untyped
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template localErrorNode(c: PContext; n: PNode; arg: string): PNode
+
+ + + Source   +Edit   + +
+
+
+
template localErrorNode(c: PContext; n: PNode; info: TLineInfo; arg: string): PNode
+
+ + + Source   +Edit   + +
+
+
+
template localErrorNode(c: PContext; n: PNode; info: TLineInfo; msg: TMsgKind;
+                        arg: string): PNode
+
+ + + Source   +Edit   + +
+
+
+
template localErrorNode(c: PContext; n: PNode; msg: TMsgKind; arg: string): PNode
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template packedRepr(c): untyped
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template rangeHasUnresolvedStatic(t: PType): bool
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/semdata.idx b/compiler/semdata.idx new file mode 100644 index 0000000000000..ccd7c9dfca62f --- /dev/null +++ b/compiler/semdata.idx @@ -0,0 +1,122 @@ +nimTitle semdata semdata.html module semdata 0 +nim TOptionEntry semdata.html#TOptionEntry object TOptionEntry 24 +nim POptionEntry semdata.html#POptionEntry type POptionEntry 33 +nim PProcCon semdata.html#PProcCon type PProcCon 34 +nim TProcCon semdata.html#TProcCon object TProcCon 35 +nim TMatchedConcept semdata.html#TMatchedConcept object TMatchedConcept 48 +nim TInstantiationPair semdata.html#TInstantiationPair object TInstantiationPair 53 +nim efLValue semdata.html#efLValue TExprFlag.efLValue 57 +nim efWantIterator semdata.html#efWantIterator TExprFlag.efWantIterator 57 +nim efWantIterable semdata.html#efWantIterable TExprFlag.efWantIterable 57 +nim efInTypeof semdata.html#efInTypeof TExprFlag.efInTypeof 57 +nim efNeedStatic semdata.html#efNeedStatic TExprFlag.efNeedStatic 57 +nim efPreferStatic semdata.html#efPreferStatic TExprFlag.efPreferStatic 57 +nim efPreferNilResult semdata.html#efPreferNilResult TExprFlag.efPreferNilResult 57 +nim efWantStmt semdata.html#efWantStmt TExprFlag.efWantStmt 57 +nim efAllowStmt semdata.html#efAllowStmt TExprFlag.efAllowStmt 57 +nim efDetermineType semdata.html#efDetermineType TExprFlag.efDetermineType 57 +nim efExplain semdata.html#efExplain TExprFlag.efExplain 57 +nim efWantValue semdata.html#efWantValue TExprFlag.efWantValue 57 +nim efOperand semdata.html#efOperand TExprFlag.efOperand 57 +nim efNoSemCheck semdata.html#efNoSemCheck TExprFlag.efNoSemCheck 57 +nim efNoEvaluateGeneric semdata.html#efNoEvaluateGeneric TExprFlag.efNoEvaluateGeneric 57 +nim efInCall semdata.html#efInCall TExprFlag.efInCall 57 +nim efFromHlo semdata.html#efFromHlo TExprFlag.efFromHlo 57 +nim efNoSem2Check semdata.html#efNoSem2Check TExprFlag.efNoSem2Check 57 +nim efNoUndeclared semdata.html#efNoUndeclared TExprFlag.efNoUndeclared 57 +nim efIsDotCall semdata.html#efIsDotCall TExprFlag.efIsDotCall 57 +nim efCannotBeDotCall semdata.html#efCannotBeDotCall TExprFlag.efCannotBeDotCall 57 +nim efTypeAllowed semdata.html#efTypeAllowed TExprFlag.efTypeAllowed 57 +nim efWantNoDefaults semdata.html#efWantNoDefaults TExprFlag.efWantNoDefaults 57 +nim efIgnoreDefaults semdata.html#efIgnoreDefaults TExprFlag.efIgnoreDefaults 57 +nim efAllowSymChoice semdata.html#efAllowSymChoice TExprFlag.efAllowSymChoice 57 +nim TExprFlag semdata.html#TExprFlag enum TExprFlag 57 +nim TExprFlags semdata.html#TExprFlags type TExprFlags 81 +nim importAll semdata.html#importAll ImportMode.importAll 83 +nim importSet semdata.html#importSet ImportMode.importSet 83 +nim importExcept semdata.html#importExcept ImportMode.importExcept 83 +nim ImportMode semdata.html#ImportMode enum ImportMode 83 +nim ImportedModule semdata.html#ImportedModule object ImportedModule 85 +nim PContext semdata.html#PContext type PContext 94 +nim TContext semdata.html#TContext object TContext 95 +nim bsNone semdata.html#bsNone TBorrowState.bsNone 176 +nim bsReturnNotMatch semdata.html#bsReturnNotMatch TBorrowState.bsReturnNotMatch 176 +nim bsNoDistinct semdata.html#bsNoDistinct TBorrowState.bsNoDistinct 176 +nim bsGeneric semdata.html#bsGeneric TBorrowState.bsGeneric 176 +nim bsNotSupported semdata.html#bsNotSupported TBorrowState.bsNotSupported 176 +nim bsMatch semdata.html#bsMatch TBorrowState.bsMatch 176 +nim TBorrowState semdata.html#TBorrowState enum TBorrowState 176 +nim config semdata.html#config.t,PContext template config(c: PContext): ConfigRef 179 +nim getIntLitType semdata.html#getIntLitType,PContext,PNode proc getIntLitType(c: PContext; literal: PNode): PType 181 +nim setIntLitType semdata.html#setIntLitType,PContext,PNode proc setIntLitType(c: PContext; result: PNode) 196 +nim makeInstPair semdata.html#makeInstPair,PSym,PInstantiation proc makeInstPair(s: PSym; inst: PInstantiation): TInstantiationPair 225 +nim filename semdata.html#filename,PContext proc filename(c: PContext): string 228 +nim scopeDepth semdata.html#scopeDepth,PContext proc scopeDepth(c: PContext): int 232 +nim getCurrOwner semdata.html#getCurrOwner,PContext proc getCurrOwner(c: PContext): PSym 236 +nim pushOwner semdata.html#pushOwner,PContext,PSym proc pushOwner(c: PContext; owner: PSym) 243 +nim popOwner semdata.html#popOwner,PContext proc popOwner(c: PContext) 246 +nim lastOptionEntry semdata.html#lastOptionEntry,PContext proc lastOptionEntry(c: PContext): POptionEntry 250 +nim popProcCon semdata.html#popProcCon,PContext proc popProcCon(c: PContext) 253 +nim put semdata.html#put,PProcCon,PSym,PSym proc put(p: PProcCon; key, val: PSym) 255 +nim get semdata.html#get,PProcCon,PSym proc get(p: PProcCon; key: PSym): PSym 262 +nim getGenSym semdata.html#getGenSym,PContext,PSym proc getGenSym(c: PContext; s: PSym): PSym 266 +nim considerGenSyms semdata.html#considerGenSyms,PContext,PNode proc considerGenSyms(c: PContext; n: PNode) 277 +nim newOptionEntry semdata.html#newOptionEntry,ConfigRef proc newOptionEntry(conf: ConfigRef): POptionEntry 288 +nim pushOptionEntry semdata.html#pushOptionEntry,PContext proc pushOptionEntry(c: PContext): POptionEntry 296 +nim popOptionEntry semdata.html#popOptionEntry,PContext proc popOptionEntry(c: PContext) 307 +nim newContext semdata.html#newContext,ModuleGraph,PSym proc newContext(graph: ModuleGraph; module: PSym): PContext 314 +nim packedRepr semdata.html#packedRepr.t template packedRepr(c): untyped 339 +nim encoder semdata.html#encoder.t template encoder(c): untyped 340 +nim addIncludeFileDep semdata.html#addIncludeFileDep,PContext,FileIndex proc addIncludeFileDep(c: PContext; f: FileIndex) 342 +nim addImportFileDep semdata.html#addImportFileDep,PContext,FileIndex proc addImportFileDep(c: PContext; f: FileIndex) 346 +nim addPragmaComputation semdata.html#addPragmaComputation,PContext,PNode proc addPragmaComputation(c: PContext; n: PNode) 350 +nim addConverter semdata.html#addConverter,PContext,LazySym proc addConverter(c: PContext; conv: LazySym) 360 +nim addConverterDef semdata.html#addConverterDef,PContext,LazySym proc addConverterDef(c: PContext; conv: LazySym) 365 +nim addPureEnum semdata.html#addPureEnum,PContext,LazySym proc addPureEnum(c: PContext; e: LazySym) 370 +nim addPattern semdata.html#addPattern,PContext,LazySym proc addPattern(c: PContext; p: LazySym) 376 +nim exportSym semdata.html#exportSym,PContext,PSym proc exportSym(c: PContext; s: PSym) 383 +nim reexportSym semdata.html#reexportSym,PContext,PSym proc reexportSym(c: PContext; s: PSym) 388 +nim newLib semdata.html#newLib,TLibKind proc newLib(kind: TLibKind): PLib 393 +nim addToLib semdata.html#addToLib,PLib,PSym proc addToLib(lib: PLib; sym: PSym) 397 +nim newTypeS semdata.html#newTypeS,TTypeKind,PContext,sinkPType proc newTypeS(kind: TTypeKind; c: PContext; son: sink PType = nil): PType 402 +nim makePtrType semdata.html#makePtrType,PSym,PType,IdGenerator proc makePtrType(owner: PSym; baseType: PType; idgen: IdGenerator): PType 405 +nim makePtrType semdata.html#makePtrType,PContext,PType proc makePtrType(c: PContext; baseType: PType): PType 408 +nim makeTypeWithModifier semdata.html#makeTypeWithModifier,PContext,TTypeKind,PType proc makeTypeWithModifier(c: PContext; modifier: TTypeKind; baseType: PType): PType 411 +nim makeVarType semdata.html#makeVarType,PContext,PType proc makeVarType(c: PContext; baseType: PType; kind = tyVar): PType 421 +nim makeTypeSymNode semdata.html#makeTypeSymNode,PContext,PType,TLineInfo proc makeTypeSymNode(c: PContext; typ: PType; info: TLineInfo): PNode 427 +nim makeTypeFromExpr semdata.html#makeTypeFromExpr,PContext,PNode proc makeTypeFromExpr(c: PContext; n: PNode): PType 436 +nim makeStaticExpr semdata.html#makeStaticExpr,PContext,PNode proc makeStaticExpr(c: PContext; n: PNode): PNode 450 +nim makeAndType semdata.html#makeAndType,PContext,PType,PType proc makeAndType(c: PContext; t1, t2: PType): PType 456 +nim makeOrType semdata.html#makeOrType,PContext,PType,PType proc makeOrType(c: PContext; t1, t2: PType): PType 465 +nim makeNotType semdata.html#makeNotType,PContext,PType proc makeNotType(c: PContext; t1: PType): PType 484 +nim makeRangeWithStaticExpr semdata.html#makeRangeWithStaticExpr,PContext,PNode proc makeRangeWithStaticExpr(c: PContext; n: PNode): PType 494 +nim rangeHasUnresolvedStatic semdata.html#rangeHasUnresolvedStatic.t,PType template rangeHasUnresolvedStatic(t: PType): bool 502 +nim errorType semdata.html#errorType,PContext proc errorType(c: PContext): PType 505 +nim errorNode semdata.html#errorNode,PContext,PNode proc errorNode(c: PContext; n: PNode): PNode 510 +nim localErrorNode semdata.html#localErrorNode.t,PContext,PNode,TLineInfo,TMsgKind,string template localErrorNode(c: PContext; n: PNode; info: TLineInfo; msg: TMsgKind;\n arg: string): PNode 515 +nim localErrorNode semdata.html#localErrorNode.t,PContext,PNode,TLineInfo,string template localErrorNode(c: PContext; n: PNode; info: TLineInfo; arg: string): PNode 519 +nim localErrorNode semdata.html#localErrorNode.t,PContext,PNode,TMsgKind,string template localErrorNode(c: PContext; n: PNode; msg: TMsgKind; arg: string): PNode 523 +nim localErrorNode semdata.html#localErrorNode.t,PContext,PNode,string template localErrorNode(c: PContext; n: PNode; arg: string): PNode 528 +nim makeRangeType semdata.html#makeRangeType,PContext,BiggestInt,BiggestInt,TLineInfo,PType proc makeRangeType(c: PContext; first, last: BiggestInt; info: TLineInfo;\n intType: PType = nil): PType 539 +nim isSelf semdata.html#isSelf,PType proc isSelf(t: PType): bool 549 +nim makeTypeDesc semdata.html#makeTypeDesc,PContext,PType proc makeTypeDesc(c: PContext; typ: PType): PType 553 +nim symFromType semdata.html#symFromType,PContext,PType,TLineInfo proc symFromType(c: PContext; t: PType; info: TLineInfo): PSym 560 +nim symNodeFromType semdata.html#symNodeFromType,PContext,PType,TLineInfo proc symNodeFromType(c: PContext; t: PType; info: TLineInfo): PNode 566 +nim markIndirect semdata.html#markIndirect,PContext,PSym proc markIndirect(c: PContext; s: PSym) 570 +nim illFormedAst semdata.html#illFormedAst,PNode,ConfigRef proc illFormedAst(n: PNode; conf: ConfigRef) 575 +nim illFormedAstLocal semdata.html#illFormedAstLocal,PNode,ConfigRef proc illFormedAstLocal(n: PNode; conf: ConfigRef) 578 +nim checkSonsLen semdata.html#checkSonsLen,PNode,int,ConfigRef proc checkSonsLen(n: PNode; length: int; conf: ConfigRef) 581 +nim checkMinSonsLen semdata.html#checkMinSonsLen,PNode,int,ConfigRef proc checkMinSonsLen(n: PNode; length: int; conf: ConfigRef) 584 +nim isTopLevel semdata.html#isTopLevel,PContext proc isTopLevel(c: PContext): bool 587 +nim isTopLevelInsideDeclaration semdata.html#isTopLevelInsideDeclaration,PContext,PSym proc isTopLevelInsideDeclaration(c: PContext; sym: PSym): bool 590 +nim pushCaseContext semdata.html#pushCaseContext,PContext,PNode proc pushCaseContext(c: PContext; caseNode: PNode) 594 +nim popCaseContext semdata.html#popCaseContext,PContext proc popCaseContext(c: PContext) 597 +nim setCaseContextIdx semdata.html#setCaseContextIdx,PContext,int proc setCaseContextIdx(c: PContext; idx: int) 600 +nim addExport semdata.html#addExport.t,PContext,PSym template addExport(c: PContext; s: PSym) 603 +nim storeRodNode semdata.html#storeRodNode,PContext,PNode proc storeRodNode(c: PContext; n: PNode) 607 +nim addToGenericProcCache semdata.html#addToGenericProcCache,PContext,PSym,PInstantiation proc addToGenericProcCache(c: PContext; s: PSym; inst: PInstantiation) 611 +nim addToGenericCache semdata.html#addToGenericCache,PContext,PSym,PType proc addToGenericCache(c: PContext; s: PSym; inst: PType) 616 +nim sealRodFile semdata.html#sealRodFile,PContext proc sealRodFile(c: PContext) 621 +nim rememberExpansion semdata.html#rememberExpansion,PContext,TLineInfo,PSym proc rememberExpansion(c: PContext; info: TLineInfo; expandedSym: PSym) 629 +nimgrp makeptrtype semdata.html#makePtrType-procs-all proc 405 +nimgrp localerrornode semdata.html#localErrorNode-templates-all template 515 diff --git a/compiler/semfold.html b/compiler/semfold.html new file mode 100644 index 0000000000000..f39ac93bc330d --- /dev/null +++ b/compiler/semfold.html @@ -0,0 +1,272 @@ + + + + + + + +semfold + + + + + + + + + + + + + + + + +
+
+

semfold

+
+ +
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc errorType(g: ModuleGraph): PType {....raises: [], tags: [], forbids: [].}
+
+ + creates a type representing an error state + Source   +Edit   + +
+
+ +
+
+
+
proc evalOp(m: TMagic; n, a, b, c: PNode; idgen: IdGenerator; g: ModuleGraph): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getConstExpr(m: PSym; n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode {....raises: [
+    KeyError, Exception, ValueError, IOError, ERecoverableError, Exception,
+    ValueError, KeyError, IOError, ERecoverableError], tags: [ReadDirEffect,
+    RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect, TimeEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc leValueConv(a, b: PNode): bool {....raises: [ERecoverableError], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newFloatNodeT(floatVal: BiggestFloat; n: PNode; g: ModuleGraph): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newIntNodeT(intVal: Int128; n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newStrNodeT(strVal: string; n: PNode; g: ModuleGraph): PNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newSymNodeTypeDesc(s: PSym; idgen: IdGenerator; info: TLineInfo): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ordinalValToString(a: PNode; g: ModuleGraph): string {.
+    ...raises: [ERecoverableError, Exception, ValueError, KeyError, IOError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/semfold.idx b/compiler/semfold.idx new file mode 100644 index 0000000000000..145930a6ed886 --- /dev/null +++ b/compiler/semfold.idx @@ -0,0 +1,10 @@ +nimTitle semfold semfold.html module semfold 0 +nim errorType semfold.html#errorType,ModuleGraph proc errorType(g: ModuleGraph): PType 24 +nim newIntNodeT semfold.html#newIntNodeT,Int128,PNode,IdGenerator,ModuleGraph proc newIntNodeT(intVal: Int128; n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode 35 +nim newFloatNodeT semfold.html#newFloatNodeT,BiggestFloat,PNode,ModuleGraph proc newFloatNodeT(floatVal: BiggestFloat; n: PNode; g: ModuleGraph): PNode 44 +nim newStrNodeT semfold.html#newStrNodeT,string,PNode,ModuleGraph proc newStrNodeT(strVal: string; n: PNode; g: ModuleGraph): PNode 52 +nim getConstExpr semfold.html#getConstExpr,PSym,PNode,IdGenerator,ModuleGraph proc getConstExpr(m: PSym; n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode 57 +nim evalOp semfold.html#evalOp,TMagic,PNode,PNode,PNode,PNode,IdGenerator,ModuleGraph proc evalOp(m: TMagic; n, a, b, c: PNode; idgen: IdGenerator; g: ModuleGraph): PNode 60 +nim ordinalValToString semfold.html#ordinalValToString,PNode,ModuleGraph proc ordinalValToString(a: PNode; g: ModuleGraph): string 98 +nim leValueConv semfold.html#leValueConv,PNode,PNode proc leValueConv(a, b: PNode): bool 348 +nim newSymNodeTypeDesc semfold.html#newSymNodeTypeDesc,PSym,IdGenerator,TLineInfo proc newSymNodeTypeDesc(s: PSym; idgen: IdGenerator; info: TLineInfo): PNode 517 diff --git a/compiler/semmacrosanity.html b/compiler/semmacrosanity.html new file mode 100644 index 0000000000000..00826cc29f60f --- /dev/null +++ b/compiler/semmacrosanity.html @@ -0,0 +1,122 @@ + + + + + + + +semmacrosanity + + + + + + + + + + + + + + + + +
+
+

semmacrosanity

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Implements type sanity checking for ASTs resulting from macros. Lots of room for improvement here.

+ +
+

Procs

+
+
+
+
proc annotateType(n: PNode; t: PType; conf: ConfigRef) {.
+    ...raises: [ERecoverableError, KeyError, Exception, ValueError, IOError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/semmacrosanity.idx b/compiler/semmacrosanity.idx new file mode 100644 index 0000000000000..0e0e61b480865 --- /dev/null +++ b/compiler/semmacrosanity.idx @@ -0,0 +1,2 @@ +nimTitle semmacrosanity semmacrosanity.html module semmacrosanity 0 +nim annotateType semmacrosanity.html#annotateType,PNode,PType,ConfigRef proc annotateType(n: PNode; t: PType; conf: ConfigRef) 89 diff --git a/compiler/semparallel.html b/compiler/semparallel.html new file mode 100644 index 0000000000000..8024eda83d77d --- /dev/null +++ b/compiler/semparallel.html @@ -0,0 +1,122 @@ + + + + + + + +semparallel + + + + + + + + + + + + + + + + +
+
+

semparallel

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Semantic checking for 'parallel'.

+ +
+

Procs

+
+
+
+
proc liftParallel(g: ModuleGraph; idgen: IdGenerator; owner: PSym; n: PNode): PNode {....raises: [
+    Exception, ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/semparallel.idx b/compiler/semparallel.idx new file mode 100644 index 0000000000000..6994b3a98e16a --- /dev/null +++ b/compiler/semparallel.idx @@ -0,0 +1,2 @@ +nimTitle semparallel semparallel.html module semparallel 0 +nim liftParallel semparallel.html#liftParallel,ModuleGraph,IdGenerator,PSym,PNode proc liftParallel(g: ModuleGraph; idgen: IdGenerator; owner: PSym; n: PNode): PNode 474 diff --git a/compiler/sempass2.html b/compiler/sempass2.html new file mode 100644 index 0000000000000..09aa8f96f672c --- /dev/null +++ b/compiler/sempass2.html @@ -0,0 +1,222 @@ + + + + + + + +sempass2 + + + + + + + + + + + + + + + + +
+
+

sempass2

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc checkForSink(config: ConfigRef; idgen: IdGenerator; owner: PSym; arg: PNode) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc checkMethodEffects(g: ModuleGraph; disp, branch: PSym) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + checks for consistent effects for multi methods. + Source   +Edit   + +
+
+ +
+
+
+
proc getEbase(g: ModuleGraph; info: TLineInfo): PType {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setEffectsForProcType(g: ModuleGraph; t: PType; n: PNode; s: PSym = nil) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc trackProc(c: PContext; s: PSym; body: PNode) {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc trackStmt(c: PContext; module: PSym; n: PNode; isTopLevel: bool) {....raises: [
+    KeyError, Exception, ValueError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/sempass2.idx b/compiler/sempass2.idx new file mode 100644 index 0000000000000..13d6af79e0b68 --- /dev/null +++ b/compiler/sempass2.idx @@ -0,0 +1,7 @@ +nimTitle sempass2 sempass2.html module sempass2 0 +nim checkForSink sempass2.html#checkForSink,ConfigRef,IdGenerator,PSym,PNode proc checkForSink(config: ConfigRef; idgen: IdGenerator; owner: PSym; arg: PNode) 10 +nim getEbase sempass2.html#getEbase,ModuleGraph,TLineInfo proc getEbase(g: ModuleGraph; info: TLineInfo): PType 419 +nim checkMethodEffects sempass2.html#checkMethodEffects,ModuleGraph,PSym,PSym proc checkMethodEffects(g: ModuleGraph; disp, branch: PSym) 1531 +nim setEffectsForProcType sempass2.html#setEffectsForProcType,ModuleGraph,PType,PNode,PSym proc setEffectsForProcType(g: ModuleGraph; t: PType; n: PNode; s: PSym = nil) 1557 +nim trackProc sempass2.html#trackProc,PContext,PSym,PNode proc trackProc(c: PContext; s: PSym; body: PNode) 1623 +nim trackStmt sempass2.html#trackStmt,PContext,PSym,PNode,bool proc trackStmt(c: PContext; module: PSym; n: PNode; isTopLevel: bool) 1742 diff --git a/compiler/semstrictfuncs.html b/compiler/semstrictfuncs.html new file mode 100644 index 0000000000000..93e77fe0f0bd5 --- /dev/null +++ b/compiler/semstrictfuncs.html @@ -0,0 +1,120 @@ + + + + + + + +semstrictfuncs + + + + + + + + + + + + + + + + +
+
+

semstrictfuncs

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

New "strict funcs" checking. Much simpler and hopefully easier to teach than the old but more advanced algorithm that can/could be found in varpartitions.nim.

+ +
+

Procs

+
+
+
+
proc isDangerousLocation(n: PNode; owner: PSym): bool {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/semstrictfuncs.idx b/compiler/semstrictfuncs.idx new file mode 100644 index 0000000000000..1a74a63166a85 --- /dev/null +++ b/compiler/semstrictfuncs.idx @@ -0,0 +1,2 @@ +nimTitle semstrictfuncs semstrictfuncs.html module semstrictfuncs 0 +nim isDangerousLocation semstrictfuncs.html#isDangerousLocation,PNode,PSym proc isDangerousLocation(n: PNode; owner: PSym): bool 17 diff --git a/compiler/semtypinst.html b/compiler/semtypinst.html new file mode 100644 index 0000000000000..d46b3af312903 --- /dev/null +++ b/compiler/semtypinst.html @@ -0,0 +1,469 @@ + + + + + + + +semtypinst + + + + + + + + + + + + + + + + +
+
+

semtypinst

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
TReplTypeVars = object
+  c*: PContext
+  typeMap*: LayeredIdTable
+  symMap*: SymMapping
+  localCache*: TypeMapping
+  info*: TLineInfo
+  allowMetaTypes*: bool
+  skipTypedesc*: bool
+  isReturnType*: bool
+  owner*: PSym
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc checkConstructedType(conf: ConfigRef; info: TLineInfo; typ: PType) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc eraseVoidParams(t: PType) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc generateTypeInstance(p: PContext; pt: LayeredIdTable; info: TLineInfo;
+                          t: PType): PType {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initTypeVars(p: PContext; typeMap: LayeredIdTable; info: TLineInfo;
+                  owner: PSym): TReplTypeVars {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc instCopyType(cl: var TReplTypeVars; t: PType): PType {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newTypeMapLayer(cl: var TReplTypeVars): LayeredIdTable {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc prepareMetatypeForSigmatch(p: PContext; pt: LayeredIdTable;
+                                info: TLineInfo; t: PType): PType {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc prepareNode(cl: var TReplTypeVars; n: PNode): PNode {.
+    ...raises: [Exception, KeyError], tags: [RootEffect], forbids: [].}
+
+ + instantiates a given generic expression, not a type node + Source   +Edit   + +
+
+ +
+
+
+
proc prepareTypesInBody(p: PContext; pt: LayeredIdTable; n: PNode;
+                        owner: PSym = nil): PNode {.
+    ...raises: [Exception, KeyError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc recomputeFieldPositions(t: PType; obj: PNode; currPosition: var int) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc replaceTypesInBody(p: PContext; pt: LayeredIdTable; n: PNode; owner: PSym;
+                        allowMetaTypes = false; fromStaticExpr = false;
+                        expectedType: PType = nil): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc replaceTypeVarsN(cl: var TReplTypeVars; n: PNode; start = 0;
+                      expectedType: PType = nil): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc replaceTypeVarsT(cl: var TReplTypeVars; t: PType; isInstValue = false): PType {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc searchInstTypes(g: ModuleGraph; key: PType): PType {.
+    ...raises: [KeyError, Exception, ValueError, ERecoverableError],
+    tags: [ReadDirEffect, RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipIntLiteralParams(t: PType; idgen: IdGenerator) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template generateTypeInstance(p: PContext; pt: LayeredIdTable; arg: PNode;
+                              t: PType): untyped
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/semtypinst.idx b/compiler/semtypinst.idx new file mode 100644 index 0000000000000..8491661e441e8 --- /dev/null +++ b/compiler/semtypinst.idx @@ -0,0 +1,18 @@ +nimTitle semtypinst semtypinst.html module semtypinst 0 +nim checkConstructedType semtypinst.html#checkConstructedType,ConfigRef,TLineInfo,PType proc checkConstructedType(conf: ConfigRef; info: TLineInfo; typ: PType) 26 +nim searchInstTypes semtypinst.html#searchInstTypes,ModuleGraph,PType proc searchInstTypes(g: ModuleGraph; key: PType): PType 34 +nim TReplTypeVars semtypinst.html#TReplTypeVars object TReplTypeVars 68 +nim replaceTypeVarsN semtypinst.html#replaceTypeVarsN,TReplTypeVars,PNode,int,PType proc replaceTypeVarsN(cl: var TReplTypeVars; n: PNode; start = 0;\n expectedType: PType = nil): PNode 85 +nim newTypeMapLayer semtypinst.html#newTypeMapLayer,TReplTypeVars proc newTypeMapLayer(cl: var TReplTypeVars): LayeredIdTable 87 +nim replaceTypeVarsT semtypinst.html#replaceTypeVarsT,TReplTypeVars,PType proc replaceTypeVarsT(cl: var TReplTypeVars; t: PType; isInstValue = false): PType 98 +nim prepareNode semtypinst.html#prepareNode,TReplTypeVars,PNode proc prepareNode(cl: var TReplTypeVars; n: PNode): PNode 102 +nim instCopyType semtypinst.html#instCopyType,TReplTypeVars,PType proc instCopyType(cl: var TReplTypeVars; t: PType): PType 387 +nim eraseVoidParams semtypinst.html#eraseVoidParams,PType proc eraseVoidParams(t: PType) 535 +nim skipIntLiteralParams semtypinst.html#skipIntLiteralParams,PType,IdGenerator proc skipIntLiteralParams(t: PType; idgen: IdGenerator) 554 +nim initTypeVars semtypinst.html#initTypeVars,PContext,LayeredIdTableObj,TLineInfo,PSym proc initTypeVars(p: PContext; typeMap: LayeredIdTable; info: TLineInfo; owner: PSym): TReplTypeVars 778 +nim replaceTypesInBody semtypinst.html#replaceTypesInBody,PContext,LayeredIdTableObj,PNode,PSym,PType proc replaceTypesInBody(p: PContext; pt: LayeredIdTable; n: PNode; owner: PSym;\n allowMetaTypes = false; fromStaticExpr = false;\n expectedType: PType = nil): PNode 784 +nim prepareTypesInBody semtypinst.html#prepareTypesInBody,PContext,LayeredIdTableObj,PNode,PSym proc prepareTypesInBody(p: PContext; pt: LayeredIdTable; n: PNode; owner: PSym = nil): PNode 794 +nim recomputeFieldPositions semtypinst.html#recomputeFieldPositions,PType,PNode,int proc recomputeFieldPositions(t: PType; obj: PNode; currPosition: var int) 813 +nim generateTypeInstance semtypinst.html#generateTypeInstance,PContext,LayeredIdTableObj,TLineInfo,PType proc generateTypeInstance(p: PContext; pt: LayeredIdTable; info: TLineInfo; t: PType): PType 829 +nim prepareMetatypeForSigmatch semtypinst.html#prepareMetatypeForSigmatch,PContext,LayeredIdTableObj,TLineInfo,PType proc prepareMetatypeForSigmatch(p: PContext; pt: LayeredIdTable; info: TLineInfo;\n t: PType): PType 845 +nim generateTypeInstance semtypinst.html#generateTypeInstance.t,PContext,LayeredIdTableObj,PNode,PType template generateTypeInstance(p: PContext; pt: LayeredIdTable; arg: PNode; t: PType): untyped 854 diff --git a/compiler/sighashes.html b/compiler/sighashes.html new file mode 100644 index 0000000000000..77afd27285bb0 --- /dev/null +++ b/compiler/sighashes.html @@ -0,0 +1,241 @@ + + + + + + + +sighashes + + + + + + + + + + + + + + + + +
+
+

sighashes

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Computes hash values for routine (proc, method etc) signatures.

+ +
+

Types

+
+
+
ConsiderFlag = enum
+  CoProc, CoType, CoOwnerSig, CoIgnoreRange, CoConsiderOwned, CoDistinct,
+  CoHashTypeInsideNode
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc hashNonProc(s: PSym): SigHash {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hashOwner(s: PSym): SigHash {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hashType(t: PType; conf: ConfigRef; flags: set[ConsiderFlag] = {CoType}): SigHash {.
+    ...raises: [OSError, Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc idOrSig(s: PSym; currentModule: string;
+             sigCollisions: var CountTable[SigHash]; conf: ConfigRef): Rope {.
+    ...raises: [OSError, Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigHash(s: PSym; conf: ConfigRef): SigHash {....raises: [OSError, Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc symBodyDigest(graph: ModuleGraph; sym: PSym): SigHash {.
+    ...raises: [OSError, Exception, KeyError], tags: [RootEffect, ReadDirEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/sighashes.idx b/compiler/sighashes.idx new file mode 100644 index 0000000000000..660dc9db81180 --- /dev/null +++ b/compiler/sighashes.idx @@ -0,0 +1,15 @@ +nimTitle sighashes sighashes.html module sighashes 0 +nim CoProc sighashes.html#CoProc ConsiderFlag.CoProc 39 +nim CoType sighashes.html#CoType ConsiderFlag.CoType 39 +nim CoOwnerSig sighashes.html#CoOwnerSig ConsiderFlag.CoOwnerSig 39 +nim CoIgnoreRange sighashes.html#CoIgnoreRange ConsiderFlag.CoIgnoreRange 39 +nim CoConsiderOwned sighashes.html#CoConsiderOwned ConsiderFlag.CoConsiderOwned 39 +nim CoDistinct sighashes.html#CoDistinct ConsiderFlag.CoDistinct 39 +nim CoHashTypeInsideNode sighashes.html#CoHashTypeInsideNode ConsiderFlag.CoHashTypeInsideNode 39 +nim ConsiderFlag sighashes.html#ConsiderFlag enum ConsiderFlag 39 +nim hashType sighashes.html#hashType,PType,ConfigRef,set[ConsiderFlag] proc hashType(t: PType; conf: ConfigRef; flags: set[ConsiderFlag] = {CoType}): SigHash 273 +nim hashNonProc sighashes.html#hashNonProc,PSym proc hashNonProc(s: PSym): SigHash 304 +nim hashOwner sighashes.html#hashOwner,PSym proc hashOwner(s: PSym): SigHash 321 +nim sigHash sighashes.html#sigHash,PSym,ConfigRef proc sigHash(s: PSym; conf: ConfigRef): SigHash 335 +nim symBodyDigest sighashes.html#symBodyDigest,ModuleGraph,PSym proc symBodyDigest(graph: ModuleGraph; sym: PSym): SigHash 341 +nim idOrSig sighashes.html#idOrSig,PSym,string,CountTable[SigHash],ConfigRef proc idOrSig(s: PSym; currentModule: string; sigCollisions: var CountTable[SigHash];\n conf: ConfigRef): Rope 410 diff --git a/compiler/sigmatch.html b/compiler/sigmatch.html new file mode 100644 index 0000000000000..740f8b02dece8 --- /dev/null +++ b/compiler/sigmatch.html @@ -0,0 +1,1070 @@ + + + + + + + +sigmatch + + + + + + + + + + + + + + + + +
+
+

sigmatch

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module implements the signature matching for resolving the call to overloaded procs, generic procs and operators.

This file implements features required for IDE support.

+

Due to Nim's nature and the fact that system.nim is always imported, there are lots of potential symbols. Furthermore thanks to templates and macros even context based analysis does not help much: In a context like let x: | where a type has to follow, that type might be constructed from a template like extractField(MyObject, fieldName). We deal with this problem by smart sorting so that the likely symbols come first. This sorting is done this way:

+
  • If there is a prefix (foo|), symbols starting with this prefix come first.
  • +
  • If the prefix is part of the name (but the name doesn't start with it), these symbols come second.
  • +
  • If we have a prefix, only symbols matching this prefix are returned and nothing else.
  • +
  • If we have no prefix, consider the context. We currently distinguish between type and non-type contexts.
  • +
  • Finally, sort matches by relevance. The relevance is determined by the number of usages, so strutils.replace comes before strutils.wordWrap.
  • +
  • In any case, sorting also considers scoping information. Local variables get high priority.
  • +
+

+ +
+

Types

+
+
+
CandidateError = object
+  sym*: PSym
+  firstMismatch*: MismatchInfo
+  diagnostics*: seq[string]
+  enabled*: bool
+
+ + + Source   +Edit   + +
+
+
+
CandidateErrors = seq[CandidateError]
+
+ + + Source   +Edit   + +
+
+
+
MismatchInfo = object
+  kind*: MismatchKind
+  arg*: int
+  formal*: PSym
+
+ + + Source   +Edit   + +
+
+
+
MismatchKind = enum
+  kUnknown, kAlreadyGiven, kUnknownNamedParam, kTypeMismatch, kVarNeeded,
+  kMissingParam, kExtraArg, kPositionalAlreadyGiven, kGenericParamTypeMismatch,
+  kMissingGenericParam, kExtraGenericParam
+
+ + + Source   +Edit   + +
+
+
+
TCandidate = object
+  c*: PContext
+  exactMatches*: int
+  state*: TCandidateState
+  callee*: PType
+  calleeSym*: PSym
+  calleeScope*: int
+  call*: PNode
+  bindings*: LayeredIdTable
+  magic*: TMagic
+  matchedErrorType*: bool
+  genericConverter*: bool
+  coerceDistincts*: bool
+  typedescMatched*: bool
+  isNoCall*: bool
+  diagnostics*: seq[string]
+  firstMismatch*: MismatchInfo
+  diagnosticsEnabled*: bool
+  newlyTypedOperands*: seq[int] ## indexes of arguments that are newly typechecked in this match
+                                ## used for type bound op additions
+
+ + + Source   +Edit   + +
+
+
+
TCandidateState = enum
+  csEmpty, csMatch, csNoMatch
+
+ + + Source   +Edit   + +
+
+
+
TCheckPointResult = enum
+  cpNone, cpFuzzy, cpExact
+
+ + + Source   +Edit   + +
+
+
+
TTypeRelFlag = enum
+  trDontBind, trNoCovariance, trBindGenericParam, trIsOutParam
+
+ + + Source   +Edit   + +
+
+
+
TTypeRelFlags = set[TTypeRelFlag]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(suggest: Suggest): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `$`(suggest: SuggestInlayHint): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc argtypeMatches(c: PContext; f, a: PType; fromHlo = false): bool {.
+    ...raises: [Exception, KeyError, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cmpCandidates(a, b: TCandidate; isFormal = true): int {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cmpTypes(c: PContext; f, a: PType): TTypeRelation {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc describeArg(c: PContext; n: PNode; i: int; startIdx = 1;
+                 prefer = preferName): string {.
+    ...raises: [Exception, KeyError, ValueError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc describeArgs(c: PContext; n: PNode; startIdx = 1; prefer = preferName): string {.
+    ...raises: [Exception, KeyError, ValueError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fieldVisible(c: PContext; f: PSym): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inCheckpoint(current, trackPos: TLineInfo): TCheckPointResult {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inferStaticParam(c: var TCandidate; lhs: PNode; rhs: BiggestInt): bool {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initCandidate(ctx: PContext; callee: PSym; binding: PNode;
+                   calleeScope = -1; diagnosticsEnabled = false): TCandidate {.
+    ...raises: [Exception, KeyError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc initCandidate(ctx: PContext; callee: PType): TCandidate {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc instTypeBoundOp(c: PContext; dc: PSym; t: PType; info: TLineInfo;
+                     op: TTypeAttachedOp; col: int): PSym {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isTracked(current, trackPos: TinyLineInfo; tokenLen: int): bool {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc isTracked(current, trackPos: TLineInfo; tokenLen: int): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc markOwnerModuleAsUsed(c: PContext; s: PSym) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc markUsed(c: PContext; info: TLineInfo; s: PSym; checkStyle = true) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc matches(c: PContext; n, nOrig: PNode; m: var TCandidate) {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc matchGenericParams(m: var TCandidate; binding: PNode; callee: PSym) {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + matches explicit generic instantiation binding against generic params of proc symbol callee state is set to csMatch if all generic params match, csEmpty if implicit generic parameters are missing (matches but cannot instantiate), csNoMatch if a constraint fails or param count doesn't match + Source   +Edit   + +
+
+ +
+
+
+
proc matchUserTypeClass(m: var TCandidate; ff, a: PType): PType {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newCandidate(ctx: PContext; callee: PSym; binding: PNode; calleeScope = -1): TCandidate {.
+    ...raises: [Exception, KeyError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newCandidate(ctx: PContext; callee: PType): TCandidate {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc paramTypesMatch(m: var TCandidate; f, a: PType; arg, argOrig: PNode): PNode {.
+    ...raises: [Exception, KeyError, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc partialMatch(c: PContext; n, nOrig: PNode; m: var TCandidate) {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc safeSemExpr(c: PContext; n: PNode): PNode {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc suggestDecl(c: PContext; n: PNode; s: PSym) {....raises: [ESuggestDone,
+    Exception, KeyError, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadIOEffect, ReadDirEffect, WriteIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc suggestEnum(c: PContext; n: PNode; t: PType) {.
+    ...raises: [Exception, KeyError, ValueError, IOError, ESuggestDone],
+    tags: [RootEffect, ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc suggestExpr(c: PContext; n: PNode) {....raises: [Exception, KeyError,
+    ValueError, IOError, ERecoverableError, ESuggestDone], tags: [RootEffect,
+    ReadIOEffect, ReadDirEffect, WriteIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc suggestExprNoCheck(c: PContext; n: PNode) {....raises: [Exception, KeyError,
+    ValueError, IOError, ERecoverableError, ESuggestDone], tags: [RootEffect,
+    ReadIOEffect, ReadDirEffect, WriteIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc suggestPragmas(c: PContext; n: PNode) {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ESuggestDone],
+    tags: [ReadDirEffect, RootEffect, ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + Suggests anything that might be a pragma
  • template that has {.pragma.}
  • +
  • macros
  • +
  • user pragmas
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
proc suggestResult(conf: ConfigRef; s: Suggest) {....raises: [Exception, IOError],
+    tags: [RootEffect, WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc suggestSentinel(c: PContext) {....raises: [KeyError, Exception, ValueError,
+    IOError], tags: [ReadDirEffect, RootEffect, ReadIOEffect, WriteIOEffect],
+                                    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc suggestStmt(c: PContext; n: PNode) {....raises: [Exception, KeyError,
+    ValueError, IOError, ERecoverableError, ESuggestDone], tags: [RootEffect,
+    ReadIOEffect, ReadDirEffect, WriteIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc suggestSym(g: ModuleGraph; info: TLineInfo; s: PSym; usageSym: var PSym;
+                isDecl = true) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + misnamed: should be 'symDeclared' + Source   +Edit   + +
+
+ +
+
+
+
proc suggestToSuggestInlayExceptionHintLeft(sug: Suggest;
+    propagatedExceptions: seq[PType]): SuggestInlayHint {.
+    ...raises: [Exception, KeyError, ValueError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc suggestToSuggestInlayExceptionHintRight(sug: Suggest;
+    propagatedExceptions: seq[PType]): SuggestInlayHint {.
+    ...raises: [Exception, KeyError, ValueError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc suggestToSuggestInlayTypeHint(sug: Suggest): SuggestInlayHint {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc symToSuggest(g: ModuleGraph; s: PSym; isLocal: bool; section: IdeCmd;
+                  info: TLineInfo; quality: range[0 .. 100];
+                  prefix: PrefixMatch; inTypeContext: bool; scope: int;
+                  useSuppliedInfo = false; endLine: uint16 = 0; endCol = 0;
+                  extractDocs = true): Suggest {.
+    ...raises: [Exception, KeyError, ValueError], tags: [RootEffect, ReadIOEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc typeRel(c: var TCandidate; f, aOrig: PType; flags: TTypeRelFlags = {}): TTypeRelation {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc writeMatches(c: TCandidate) {....raises: [Exception, KeyError],
+                                   tags: [RootEffect, ReadDirEffect],
+                                   forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template trySuggestPragmas(c: PContext; n: PNode)
+
+ + Runs suggestPragmas when compiling nimsuggest and we are querying the node + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/sigmatch.idx b/compiler/sigmatch.idx new file mode 100644 index 0000000000000..a355951d467ff --- /dev/null +++ b/compiler/sigmatch.idx @@ -0,0 +1,76 @@ +nimTitle sigmatch sigmatch.html module sigmatch 0 +nim kUnknown sigmatch.html#kUnknown MismatchKind.kUnknown 24 +nim kAlreadyGiven sigmatch.html#kAlreadyGiven MismatchKind.kAlreadyGiven 24 +nim kUnknownNamedParam sigmatch.html#kUnknownNamedParam MismatchKind.kUnknownNamedParam 24 +nim kTypeMismatch sigmatch.html#kTypeMismatch MismatchKind.kTypeMismatch 24 +nim kVarNeeded sigmatch.html#kVarNeeded MismatchKind.kVarNeeded 24 +nim kMissingParam sigmatch.html#kMissingParam MismatchKind.kMissingParam 24 +nim kExtraArg sigmatch.html#kExtraArg MismatchKind.kExtraArg 24 +nim kPositionalAlreadyGiven sigmatch.html#kPositionalAlreadyGiven MismatchKind.kPositionalAlreadyGiven 24 +nim kGenericParamTypeMismatch sigmatch.html#kGenericParamTypeMismatch MismatchKind.kGenericParamTypeMismatch 24 +nim kMissingGenericParam sigmatch.html#kMissingGenericParam MismatchKind.kMissingGenericParam 24 +nim kExtraGenericParam sigmatch.html#kExtraGenericParam MismatchKind.kExtraGenericParam 24 +nim MismatchKind sigmatch.html#MismatchKind enum MismatchKind 24 +nim MismatchInfo sigmatch.html#MismatchInfo object MismatchInfo 29 +nim csEmpty sigmatch.html#csEmpty TCandidateState.csEmpty 35 +nim csMatch sigmatch.html#csMatch TCandidateState.csMatch 35 +nim csNoMatch sigmatch.html#csNoMatch TCandidateState.csNoMatch 35 +nim TCandidateState sigmatch.html#TCandidateState enum TCandidateState 35 +nim CandidateError sigmatch.html#CandidateError object CandidateError 38 +nim CandidateErrors sigmatch.html#CandidateErrors type CandidateErrors 44 +nim TCandidate sigmatch.html#TCandidate object TCandidate 46 +nim trDontBind sigmatch.html#trDontBind TTypeRelFlag.trDontBind 92 +nim trNoCovariance sigmatch.html#trNoCovariance TTypeRelFlag.trNoCovariance 92 +nim trBindGenericParam sigmatch.html#trBindGenericParam TTypeRelFlag.trBindGenericParam 92 +nim trIsOutParam sigmatch.html#trIsOutParam TTypeRelFlag.trIsOutParam 92 +nim TTypeRelFlag sigmatch.html#TTypeRelFlag enum TTypeRelFlag 92 +nim TTypeRelFlags sigmatch.html#TTypeRelFlags type TTypeRelFlags 98 +nim markUsed sigmatch.html#markUsed,PContext,TLineInfo,PSym proc markUsed(c: PContext; info: TLineInfo; s: PSym; checkStyle = true) 105 +nim markOwnerModuleAsUsed sigmatch.html#markOwnerModuleAsUsed,PContext,PSym proc markOwnerModuleAsUsed(c: PContext; s: PSym) 106 +nim initCandidate sigmatch.html#initCandidate,PContext,PType proc initCandidate(ctx: PContext; callee: PType): TCandidate 117 +nim typeRel sigmatch.html#typeRel,TCandidate,PType,PType,TTypeRelFlags proc typeRel(c: var TCandidate; f, aOrig: PType; flags: TTypeRelFlags = {}): TTypeRelation 136 +nim matchGenericParams sigmatch.html#matchGenericParams,TCandidate,PNode,PSym proc matchGenericParams(m: var TCandidate; binding: PNode; callee: PSym) 171 +nim initCandidate sigmatch.html#initCandidate,PContext,PSym,PNode,int proc initCandidate(ctx: PContext; callee: PSym; binding: PNode; calleeScope = -1;\n diagnosticsEnabled = false): TCandidate 243 +nim newCandidate sigmatch.html#newCandidate,PContext,PSym,PNode,int proc newCandidate(ctx: PContext; callee: PSym; binding: PNode; calleeScope = -1): TCandidate 272 +nim newCandidate sigmatch.html#newCandidate,PContext,PType proc newCandidate(ctx: PContext; callee: PType): TCandidate 276 +nim writeMatches sigmatch.html#writeMatches,TCandidate proc writeMatches(c: TCandidate) 392 +nim cmpCandidates sigmatch.html#cmpCandidates,TCandidate,TCandidate proc cmpCandidates(a, b: TCandidate; isFormal = true): int 410 +nim describeArg sigmatch.html#describeArg,PContext,PNode,int,int proc describeArg(c: PContext; n: PNode; i: int; startIdx = 1; prefer = preferName): string 474 +nim describeArgs sigmatch.html#describeArgs,PContext,PNode,int proc describeArgs(c: PContext; n: PNode; startIdx = 1; prefer = preferName): string 478 +nim matchUserTypeClass sigmatch.html#matchUserTypeClass,TCandidate,PType,PType proc matchUserTypeClass(m: var TCandidate; ff, a: PType): PType 882 +nim inferStaticParam sigmatch.html#inferStaticParam,TCandidate,PNode,BiggestInt proc inferStaticParam(c: var TCandidate; lhs: PNode; rhs: BiggestInt): bool 1031 +nim cmpTypes sigmatch.html#cmpTypes,PContext,PType,PType proc cmpTypes(c: PContext; f, a: PType): TTypeRelation 2171 +nim paramTypesMatch sigmatch.html#paramTypesMatch,TCandidate,PType,PType,PNode,PNode proc paramTypesMatch(m: var TCandidate; f, a: PType; arg, argOrig: PNode): PNode 2641 +nim partialMatch sigmatch.html#partialMatch,PContext,PNode,PNode,TCandidate proc partialMatch(c: PContext; n, nOrig: PNode; m: var TCandidate) 3036 +nim matches sigmatch.html#matches,PContext,PNode,PNode,TCandidate proc matches(c: PContext; n, nOrig: PNode; m: var TCandidate) 3041 +nim argtypeMatches sigmatch.html#argtypeMatches,PContext,PType,PType proc argtypeMatches(c: PContext; f, a: PType; fromHlo = false): bool 3104 +nim instTypeBoundOp sigmatch.html#instTypeBoundOp,PContext,PSym,PType,TLineInfo,TTypeAttachedOp,int proc instTypeBoundOp(c: PContext; dc: PSym; t: PType; info: TLineInfo;\n op: TTypeAttachedOp; col: int): PSym 3117 +nim symToSuggest sigmatch.html#symToSuggest,ModuleGraph,PSym,bool,IdeCmd,TLineInfo,range[],PrefixMatch,bool,int,uint16,int proc symToSuggest(g: ModuleGraph; s: PSym; isLocal: bool; section: IdeCmd;\n info: TLineInfo; quality: range[0 .. 100]; prefix: PrefixMatch;\n inTypeContext: bool; scope: int; useSuppliedInfo = false;\n endLine: uint16 = 0; endCol = 0; extractDocs = true): Suggest 139 +nim `$` sigmatch.html#$,SuggestInlayHint proc `$`(suggest: SuggestInlayHint): string 207 +nim `$` sigmatch.html#$,Suggest proc `$`(suggest: Suggest): string 224 +nim suggestToSuggestInlayTypeHint sigmatch.html#suggestToSuggestInlayTypeHint,Suggest proc suggestToSuggestInlayTypeHint(sug: Suggest): SuggestInlayHint 272 +nim suggestToSuggestInlayExceptionHintLeft sigmatch.html#suggestToSuggestInlayExceptionHintLeft,Suggest,seq[PType] proc suggestToSuggestInlayExceptionHintLeft(sug: Suggest;\n propagatedExceptions: seq[PType]): SuggestInlayHint 284 +nim suggestToSuggestInlayExceptionHintRight sigmatch.html#suggestToSuggestInlayExceptionHintRight,Suggest,seq[PType] proc suggestToSuggestInlayExceptionHintRight(sug: Suggest;\n propagatedExceptions: seq[PType]): SuggestInlayHint 296 +nim suggestResult sigmatch.html#suggestResult,ConfigRef,Suggest proc suggestResult(conf: ConfigRef; s: Suggest) 308 +nim fieldVisible sigmatch.html#fieldVisible,PContext,PSym proc fieldVisible(c: PContext; f: PSym): bool 352 +nim cpNone sigmatch.html#cpNone TCheckPointResult.cpNone 541 +nim cpFuzzy sigmatch.html#cpFuzzy TCheckPointResult.cpFuzzy 541 +nim cpExact sigmatch.html#cpExact TCheckPointResult.cpExact 541 +nim TCheckPointResult sigmatch.html#TCheckPointResult enum TCheckPointResult 541 +nim inCheckpoint sigmatch.html#inCheckpoint,TLineInfo,TLineInfo proc inCheckpoint(current, trackPos: TLineInfo): TCheckPointResult 544 +nim isTracked sigmatch.html#isTracked,TLineInfo,TLineInfo,int proc isTracked(current, trackPos: TLineInfo; tokenLen: int): bool 555 +nim isTracked sigmatch.html#isTracked,TinyLineInfo,TinyLineInfo,int proc isTracked(current, trackPos: TinyLineInfo; tokenLen: int): bool 565 +nim suggestSym sigmatch.html#suggestSym,ModuleGraph,TLineInfo,PSym,PSym proc suggestSym(g: ModuleGraph; info: TLineInfo; s: PSym; usageSym: var PSym;\n isDecl = true) 621 +nim safeSemExpr sigmatch.html#safeSemExpr,PContext,PNode proc safeSemExpr(c: PContext; n: PNode): PNode 720 +nim suggestExprNoCheck sigmatch.html#suggestExprNoCheck,PContext,PNode proc suggestExprNoCheck(c: PContext; n: PNode) 749 +nim suggestExpr sigmatch.html#suggestExpr,PContext,PNode proc suggestExpr(c: PContext; n: PNode) 778 +nim suggestDecl sigmatch.html#suggestDecl,PContext,PNode,PSym proc suggestDecl(c: PContext; n: PNode; s: PSym) 781 +nim suggestStmt sigmatch.html#suggestStmt,PContext,PNode proc suggestStmt(c: PContext; n: PNode) 791 +nim suggestEnum sigmatch.html#suggestEnum,PContext,PNode,PType proc suggestEnum(c: PContext; n: PNode; t: PType) 794 +nim suggestPragmas sigmatch.html#suggestPragmas,PContext,PNode proc suggestPragmas(c: PContext; n: PNode) 800 +nim trySuggestPragmas sigmatch.html#trySuggestPragmas.t,PContext,PNode template trySuggestPragmas(c: PContext; n: PNode) 824 +nim suggestSentinel sigmatch.html#suggestSentinel,PContext proc suggestSentinel(c: PContext) 832 +nimgrp $ sigmatch.html#$-procs-all proc 207 +nimgrp initcandidate sigmatch.html#initCandidate-procs-all proc 117 +nimgrp istracked sigmatch.html#isTracked-procs-all proc 555 +nimgrp newcandidate sigmatch.html#newCandidate-procs-all proc 272 diff --git a/compiler/sourcemap.html b/compiler/sourcemap.html new file mode 100644 index 0000000000000..5df7311437527 --- /dev/null +++ b/compiler/sourcemap.html @@ -0,0 +1,231 @@ + + + + + + + +sourcemap + + + + + + + + + + + + + + + + +
+
+

sourcemap

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Types

+
+
+
SourceMap = object
+  version*: int
+  sources*: seq[string]
+  names*: seq[string]
+  mappings*: string
+  file*: string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func encode(values: seq[int]): string {....raises: [], tags: [], forbids: [].}
+
+ + Encodes a series of integers into a VLQ base64 encoded string + Source   +Edit   + +
+
+ +
+
+
+
proc genSourceMap(source: string; outFile: string): SourceMap {.
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func parse(source: string): SourceInfo {....raises: [ValueError], tags: [],
+    forbids: [].}
+
+ + Parses the JS output for embedded line info So it can convert those into a series of mappings + Source   +Edit   + +
+
+ +
+
+
+
func toSourceMap(info: SourceInfo; file: string): SourceMap {....raises: [],
+    tags: [], forbids: [].}
+
+ + Convert from high level SourceInfo into the required SourceMap object + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator tokenize(line: string): (int, string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Goes through a line and splits it into Nim identifiers and normal JS code. This allows us to map mangled names back to Nim names. Yields (column, name). Doesn't yield anything but identifiers. See mangleName in compiler/jsgen.nim for how name mangling is done + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/sourcemap.idx b/compiler/sourcemap.idx new file mode 100644 index 0000000000000..592495eac70c9 --- /dev/null +++ b/compiler/sourcemap.idx @@ -0,0 +1,7 @@ +nimTitle sourcemap sourcemap.html module sourcemap 0 +nim SourceMap sourcemap.html#SourceMap object SourceMap 25 +nim encode sourcemap.html#encode,seq[int] proc encode(values: seq[int]): string 63 +nim tokenize sourcemap.html#tokenize.i,string iterator tokenize(line: string): (int, string) 95 +nim parse sourcemap.html#parse,string proc parse(source: string): SourceInfo 126 +nim toSourceMap sourcemap.html#toSourceMap,SourceInfo,string proc toSourceMap(info: SourceInfo; file: string): SourceMap 160 +nim genSourceMap sourcemap.html#genSourceMap,string,string proc genSourceMap(source: string; outFile: string): SourceMap 203 diff --git a/compiler/spawn.html b/compiler/spawn.html new file mode 100644 index 0000000000000..016efc4d66dcb --- /dev/null +++ b/compiler/spawn.html @@ -0,0 +1,173 @@ + + + + + + + +spawn + + + + + + + + + + + + + + + + +
+
+

spawn

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module implements threadpool's spawn.

+ +
+

Types

+
+
+
TSpawnResult = enum
+  srVoid, srFlowVar, srByVar
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc spawnResult(t: PType; inParallel: bool): TSpawnResult {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc wrapProcForSpawn(g: ModuleGraph; idgen: IdGenerator; owner: PSym;
+                      spawnExpr: PNode; retType: PType; barrier: PNode = nil;
+                      dest: PNode = nil): PNode {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/spawn.idx b/compiler/spawn.idx new file mode 100644 index 0000000000000..6caf12fe3ae41 --- /dev/null +++ b/compiler/spawn.idx @@ -0,0 +1,7 @@ +nimTitle spawn spawn.html module spawn 0 +nim srVoid spawn.html#srVoid TSpawnResult.srVoid 27 +nim srFlowVar spawn.html#srFlowVar TSpawnResult.srFlowVar 27 +nim srByVar spawn.html#srByVar TSpawnResult.srByVar 27 +nim TSpawnResult spawn.html#TSpawnResult enum TSpawnResult 27 +nim spawnResult spawn.html#spawnResult,PType,bool proc spawnResult(t: PType; inParallel: bool): TSpawnResult 34 +nim wrapProcForSpawn spawn.html#wrapProcForSpawn,ModuleGraph,IdGenerator,PSym,PNode,PType,PNode,PNode proc wrapProcForSpawn(g: ModuleGraph; idgen: IdGenerator; owner: PSym;\n spawnExpr: PNode; retType: PType; barrier: PNode = nil;\n dest: PNode = nil): PNode 330 diff --git a/compiler/suggestsymdb.html b/compiler/suggestsymdb.html new file mode 100644 index 0000000000000..d34c0b37b58fa --- /dev/null +++ b/compiler/suggestsymdb.html @@ -0,0 +1,500 @@ + + + + + + + +suggestsymdb + + + + + + + + + + + + + + + + +
+
+

suggestsymdb

+
+ +
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ ast, lineinfos, msgs +
+
+
+

Types

+
+
+
PackedBoolArray = object
+
+ + + Source   +Edit   + +
+
+
+
SuggestFileSymbolDatabase = object
+  lineInfo*: seq[TinyLineInfo]
+  sym*: seq[PSym]
+  caughtExceptions*: seq[seq[PType]]
+  caughtExceptionsSet*: PackedBoolArray
+  isDecl*: PackedBoolArray
+  fileIndex*: FileIndex
+  trackCaughtExceptions*: bool
+  isSorted*: bool
+
+ + + Source   +Edit   + +
+
+ +
+
SymInfoPair = object
+  sym*: PSym
+  info*: TLineInfo
+  caughtExceptions*: seq[PType]
+  caughtExceptionsSet*: bool
+  isDecl*: bool
+
+ + + Source   +Edit   + +
+
+
+
TinyLineInfo = object
+  line*: uint16
+  col*: int16
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `==`(a, b: SymInfoPair): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `[]`(s: PackedBoolArray; idx: int): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `[]=`(s: var PackedBoolArray; idx: int; v: bool) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc add(s: var PackedBoolArray; v: bool) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc add(s: var SuggestFileSymbolDatabase; v: SymInfoPair) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc add(s: var SuggestSymbolDatabase; v: SymInfoPair;
+         trackCaughtExceptions: bool) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func cmp(a: TinyLineInfo; b: TinyLineInfo): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func compare(s: var SuggestFileSymbolDatabase; i, j: int): int {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc exactEquals(a, b: TinyLineInfo): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc findSymInfoIndex(s: var SuggestFileSymbolDatabase; li: TLineInfo): int {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getSymInfoPair(s: SuggestFileSymbolDatabase; idx: int): SymInfoPair {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func high(s: PackedBoolArray): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func low(s: PackedBoolArray): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func newPackedBoolArray(): PackedBoolArray {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newSuggestFileSymbolDatabase(aFileIndex: FileIndex;
+                                  aTrackCaughtExceptions: bool): SuggestFileSymbolDatabase {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc reverse(s: var PackedBoolArray) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc reverse(s: var SuggestFileSymbolDatabase) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sort(s: var SuggestFileSymbolDatabase) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/suggestsymdb.idx b/compiler/suggestsymdb.idx new file mode 100644 index 0000000000000..333768a08399e --- /dev/null +++ b/compiler/suggestsymdb.idx @@ -0,0 +1,26 @@ +nimTitle suggestsymdb suggestsymdb.html module suggestsymdb 0 +nim PackedBoolArray suggestsymdb.html#PackedBoolArray object PackedBoolArray 5 +nim TinyLineInfo suggestsymdb.html#TinyLineInfo object TinyLineInfo 9 +nim SymInfoPair suggestsymdb.html#SymInfoPair object SymInfoPair 13 +nim SuggestFileSymbolDatabase suggestsymdb.html#SuggestFileSymbolDatabase object SuggestFileSymbolDatabase 20 +nim SuggestSymbolDatabase suggestsymdb.html#SuggestSymbolDatabase type SuggestSymbolDatabase 30 +nim newPackedBoolArray suggestsymdb.html#newPackedBoolArray proc newPackedBoolArray(): PackedBoolArray 33 +nim low suggestsymdb.html#low,PackedBoolArray proc low(s: PackedBoolArray): int 39 +nim high suggestsymdb.html#high,PackedBoolArray proc high(s: PackedBoolArray): int 42 +nim `[]` suggestsymdb.html#[],PackedBoolArray,int proc `[]`(s: PackedBoolArray; idx: int): bool 45 +nim `[]=` suggestsymdb.html#[]=,PackedBoolArray,int,bool proc `[]=`(s: var PackedBoolArray; idx: int; v: bool) 48 +nim add suggestsymdb.html#add,PackedBoolArray,bool proc add(s: var PackedBoolArray; v: bool) 54 +nim reverse suggestsymdb.html#reverse,PackedBoolArray proc reverse(s: var PackedBoolArray) 59 +nim getSymInfoPair suggestsymdb.html#getSymInfoPair,SuggestFileSymbolDatabase,int proc getSymInfoPair(s: SuggestFileSymbolDatabase; idx: int): SymInfoPair 67 +nim reverse suggestsymdb.html#reverse,SuggestFileSymbolDatabase proc reverse(s: var SuggestFileSymbolDatabase) 88 +nim newSuggestFileSymbolDatabase suggestsymdb.html#newSuggestFileSymbolDatabase,FileIndex,bool proc newSuggestFileSymbolDatabase(aFileIndex: FileIndex; aTrackCaughtExceptions: bool): SuggestFileSymbolDatabase 95 +nim exactEquals suggestsymdb.html#exactEquals,TinyLineInfo,TinyLineInfo proc exactEquals(a, b: TinyLineInfo): bool 107 +nim `==` suggestsymdb.html#==,SymInfoPair,SymInfoPair proc `==`(a, b: SymInfoPair): bool 110 +nim cmp suggestsymdb.html#cmp,TinyLineInfo,TinyLineInfo proc cmp(a: TinyLineInfo; b: TinyLineInfo): int 113 +nim compare suggestsymdb.html#compare,SuggestFileSymbolDatabase,int,int proc compare(s: var SuggestFileSymbolDatabase; i, j: int): int 118 +nim sort suggestsymdb.html#sort,SuggestFileSymbolDatabase proc sort(s: var SuggestFileSymbolDatabase) 184 +nim add suggestsymdb.html#add,SuggestFileSymbolDatabase,SymInfoPair proc add(s: var SuggestFileSymbolDatabase; v: SymInfoPair) 188 +nim add suggestsymdb.html#add,SuggestSymbolDatabase,SymInfoPair,bool proc add(s: var SuggestSymbolDatabase; v: SymInfoPair; trackCaughtExceptions: bool) 201 +nim findSymInfoIndex suggestsymdb.html#findSymInfoIndex,SuggestFileSymbolDatabase,TLineInfo proc findSymInfoIndex(s: var SuggestFileSymbolDatabase; li: TLineInfo): int 204 +nimgrp reverse suggestsymdb.html#reverse-procs-all proc 59 +nimgrp add suggestsymdb.html#add-procs-all proc 54 diff --git a/compiler/syntaxes.html b/compiler/syntaxes.html new file mode 100644 index 0000000000000..0c88452a29c8d --- /dev/null +++ b/compiler/syntaxes.html @@ -0,0 +1,168 @@ + + + + + + + +syntaxes + + + + + + + + + + + + + + + + +
+
+

syntaxes

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Implements the dispatcher for the different parsers.

+ +
+

Procs

+
+
+
+
proc openParser(p: var Parser; fileIdx: FileIndex; inputstream: PLLStream;
+                cache: IdentCache; config: ConfigRef) {.
+    ...raises: [IOError, Exception, ValueError, KeyError, ERecoverableError], tags: [
+    ReadIOEffect, RootEffect, ReadDirEffect, WriteIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc parseFile(fileIdx: FileIndex; cache: IdentCache; config: ConfigRef): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setupParser(p: var Parser; fileIdx: FileIndex; cache: IdentCache;
+                 config: ConfigRef): bool {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/syntaxes.idx b/compiler/syntaxes.idx new file mode 100644 index 0000000000000..e8307fac2e831 --- /dev/null +++ b/compiler/syntaxes.idx @@ -0,0 +1,4 @@ +nimTitle syntaxes syntaxes.html module syntaxes 0 +nim openParser syntaxes.html#openParser,Parser,FileIndex,PLLStream,IdentCache,ConfigRef proc openParser(p: var Parser; fileIdx: FileIndex; inputstream: PLLStream;\n cache: IdentCache; config: ConfigRef) 119 +nim setupParser syntaxes.html#setupParser,Parser,FileIndex,IdentCache,ConfigRef proc setupParser(p: var Parser; fileIdx: FileIndex; cache: IdentCache;\n config: ConfigRef): bool 129 +nim parseFile syntaxes.html#parseFile,FileIndex,IdentCache,ConfigRef proc parseFile(fileIdx: FileIndex; cache: IdentCache; config: ConfigRef): PNode 139 diff --git a/compiler/theindex.html b/compiler/theindex.html new file mode 100644 index 0000000000000..fef35c45443c6 --- /dev/null +++ b/compiler/theindex.html @@ -0,0 +1,17371 @@ + + + + + + + +Index + + + + + + + + + + + + + + + + +
+
+

Index

+ Modules: aliasanalysis, aliases, ast, astalgo, astmsgs, astyaml, bitsets, btrees, cbuilderbase, ccgutils, cgen, cgendata, cgmeth, closureiters, cmdlinehelper, commands, concepts, condsyms, depends, dfa, docgen, docgen2, enumtostr, errorhandling, evaltempl, expanddefaults, extccomp, filter_tmpl, filters, gorgeimpl, guards, ic/bitabs, ic/cbackend, ic/dce, ic/ic, ic/iclineinfos, ic/integrity, ic/navigator, ic/packed_ast, ic/replayer, ic/rodfiles, idents, importer, index, injectdestructors, int128, isolation_check, jsgen, lambdalifting, layeredtable, lexer, liftdestructors, liftlocals, lineinfos, linter, llstream, lookups, lowerings, macrocacheimpl, magicsys, main, mangleutils, modulegraphs, modulepaths, modules, msgs, nilcheck, nim, nimblecmd, nimconf, nimlexbase, nimpaths, nimsets, nodejs, nodekinds, nversion, optimizer, options, packages, parampatterns, parser, pathutils, patterns, pipelines, pipelineutils, platform, pluginsupport, pragmas, prefixmatches, procfind, pushpoppragmas, renderer, renderverbatim, reorder, rodutils, ropes, saturate, scriptconfig, sem, semdata, semfold, semmacrosanity, semparallel, sempass2, semstrictfuncs, semtypinst, sighashes, sigmatch, sourcemap, spawn, suggestsymdb, syntaxes, transf, trees, treetab, typeallowed, types, typesrenderer, varpartitions, vm, vmconv, vmdef, vmdeps, vmgen, vmmarshal, vmprofiler, vtables, wordrecg.

API symbols

+
`$`:
+
`%`:
+
`*=`:
+
`*`:
+
`+=`:
+
`+`:
+
`-=`:
+
`-`:
+
`/`:
+
`<=`:
+
`<`:
+
`==`:
+
`>=`:
+
`>`:
+
`??`:
+
`[]=`:
+
`[]`:
+
`div`:
+
`mod`:
+
`shl`:
+
`shr`:
+
`|*|`:
+
`|+|`:
+
`|-|`:
+
`|abs|`:
+
`|div|`:
+
`|mod|`:
+
abs:
+
AbsoluteDir:
+
AbsoluteFile:
+
absOutFile:
+
abstractInst:
+
abstractInstOwned:
+
abstractPtrs:
+
abstractRange:
+
abstractVar:
+
abstractVarRange:
+
add:
+
addAllowNil:
+
addAsgnFact:
+
addCaseBranchFacts:
+
addCmdPrefix:
+
addCompileOption:
+
addCompileOptionCmd:
+
addCompilerProc:
+
addConverter:
+
addConverterDef:
+
addDecl:
+
addDeclaredLoc:
+
addDeclaredLocMaybe:
+
addDeclAt:
+
addDedent:
+
addDep:
+
addDiscriminantFact:
+
addDispatchers:
+
addDotDependency:
+
addExport:
+
addExported:
+
addExternalFileToCompile:
+
addExternalFileToLink:
+
addf:
+
addFact:
+
addFactLe:
+
addFactLt:
+
addFactNeg:
+
addField:
+
addFileExt:
+
addFileToCompile:
+
addFloatValue:
+
addHidden:
+
addIdent:
+
addImportFileDep:
+
addIncludeDep:
+
addIncludeFileDep:
+
addInt128:
+
addInt64Literal:
+
addInterfaceDecl:
+
addInterfaceDeclAt:
+
addInterfaceOverloadableSymAt:
+
addIntLiteral:
+
addIntValue:
+
addLineComment:
+
addLineEnd:
+
addLineEndDedent:
+
addLineEndIndent:
+
addLinkOption:
+
addLinkOptionCmd:
+
addLocalCompileOption:
+
addMethod:
+
addMethodToGeneric:
+
addNewline:
+
addNode:
+
addOverloadableSymAt:
+
addPackage:
+
addParam:
+
addPath:
+
addPattern:
+
addPragmaAndCallConvMismatch:
+
addPragmaComputation:
+
addPrelimDecl:
+
addPureEnum:
+
addReexport:
+
addSonNilAllowed:
+
addSonSkipIntLit:
+
addSym:
+
addSymDef:
+
addToGenericCache:
+
addToGenericProcCache:
+
addToHex:
+
addToLib:
+
addTrmacro:
+
addTypeDeclVerboseMaybe:
+
addTypeHeader:
+
addTypeNodeDeclaredLoc:
+
addUint64Literal:
+
addUniqueField:
+
addUniqueSym:
+
addVar:
+
addYamlString:
+
aliases:
+
AliasKind:
+
align:
+
AliveContext:
+
AliveSyms:
+
aliveSymsSection:
+
allNodes:
+
allowCast:
+
AllowCommonBase:
+
allowInfiniteLoops:
+
allowSemcheckedAstModification:
+
allRoutinePragmas:
+
allScopes:
+
allSyms:
+
AmbiguousCall:
+
ambiguousIdentifierMsg:
+
analyseObjectWithTypeField:
+
annotateType:
+
AnyPath:
+
Apo:
+
appendToModule:
+
applyRule:
+
aqNoAlias:
+
aqNone:
+
aqShouldAlias:
+
arAddressableConst:
+
arDiscriminant:
+
argtypeMatches:
+
arLentValue:
+
arLocalLValue:
+
arLValue:
+
arMaybe:
+
arNo:
+
arNone:
+
arStrange:
+
arYes:
+
asink:
+
assignIfDefault:
+
assignment:
+
assignType:
+
astdef:
+
attachedAsgn:
+
attachedDeepCopy:
+
attachedDestructor:
+
attachedDup:
+
attachedOpsSection:
+
AttachedOpToStr:
+
attachedSink:
+
attachedTrace:
+
attachedWasMoved:
+
backendC:
+
backendCpp:
+
backendFlagsSection:
+
backendInvalid:
+
backendJs:
+
backendObjc:
+
BACKSPACE:
+
base:
+
base10:
+
base16:
+
base2:
+
base8:
+
baseClass:
+
baseOfDistinct:
+
beforeRetNeeded:
+
BEL:
+
belongsToProjectPackage:
+
belongsToProjectPackageMaybeNil:
+
belongsToStdlib:
+
BenchIC:
+
bindConcreteTypeToUserTypeClass:
+
BiTable:
+
bitand:
+
bitnot:
+
bitor:
+
bitSetCard:
+
bitSetContains:
+
bitSetDiff:
+
bitSetEquals:
+
bitSetExcl:
+
bitSetIn:
+
bitSetIncl:
+
bitSetInit:
+
bitSetIntersect:
+
bitSetSymDiff:
+
bitSetToWord:
+
bitSetUnion:
+
bitxor:
+
BModule:
+
BModuleList:
+
bodiesSection:
+
bodyPos:
+
boolArg:
+
boolLit:
+
borrowChecking:
+
BProc:
+
bracketKind:
+
bsGeneric:
+
bsMatch:
+
bsNoDistinct:
+
bsNone:
+
bsNotSupported:
+
bsReturnNotMatch:
+
BTree:
+
buildAdd:
+
buildCall:
+
Builder:
+
buildLe:
+
byteExcess:
+
callableDefs:
+
callCCompiler:
+
callCodegenProc:
+
callOperator:
+
canAlias:
+
CandidateError:
+
CandidateErrors:
+
canFormAcycle:
+
cannotOpen:
+
canon:
+
canonicalImport:
+
canonicalImportAux:
+
canonicalizePath:
+
canRaise:
+
canRaiseConservative:
+
cardSet:
+
caseObjDefaultBranch:
+
caseStmtMacros:
+
castToInt64:
+
castToUInt64:
+
CC:
+
ccBcc:
+
ccCDecl:
+
ccCLang:
+
ccClangCl:
+
ccClosure:
+
ccEnv:
+
ccFastCall:
+
ccGcc:
+
ccgIntroducedPtr:
+
ccgKeywordsHigh:
+
ccgKeywordsLow:
+
CChar:
+
ccHasSaneOverflow:
+
ccHipcc:
+
ccIcc:
+
ccIcl:
+
ccInline:
+
ccLLVM_Gcc:
+
ccMember:
+
ccNimCall:
+
ccNintendoSwitch:
+
ccNoConvention:
+
ccNoInline:
+
ccNone:
+
ccNvcc:
+
CConstPointer:
+
ccSafeCall:
+
ccStdCall:
+
ccSysCall:
+
ccTcc:
+
ccThisCall:
+
ccVcc:
+
Cfile:
+
CfileFlag:
+
CfileList:
+
cFloatValue:
+
cfsData:
+
cfsDatInitProc:
+
cfsDynLibInit:
+
cfsForwardTypes:
+
cfsFrameDefines:
+
cfsHeaders:
+
cfsInitProc:
+
cfsProcHeaders:
+
cfsProcs:
+
cfsSeqTypes:
+
cfsStrData:
+
cfsTypeInfo:
+
cfsTypeInit1:
+
cfsTypeInit3:
+
cfsTypes:
+
cfsVars:
+
cgDeclFrmt:
+
cgenModules:
+
CgenPass:
+
cgenWriteModules:
+
changeDetectedViaJsonBuildInstructions:
+
changeFileExt:
+
charArg:
+
checkAmbiguity:
+
checkBorrowedLocations:
+
checkConstructedType:
+
checkFieldAccess:
+
checkFirstLineIndentation:
+
checkForSideEffects:
+
checkForSink:
+
checkIntegrity:
+
checkIsolate:
+
checkMethodEffects:
+
checkMinSonsLen:
+
checkModule:
+
checkModuleName:
+
checkNil:
+
checkPragmaUse:
+
checkPureEnumFields:
+
checkSonsLen:
+
ChecksOptions:
+
checkSumsSection:
+
checkUndeclared:
+
checkUnsignedConversions:
+
CInt:
+
cInt64Literal:
+
cIntLiteral:
+
cIntType:
+
cIntValue:
+
classify:
+
classifyViewType:
+
clearNimblePath:
+
close:
+
closeBaseLexer:
+
closeDoc:
+
closeJson:
+
closeLexer:
+
closeParser:
+
closePContext:
+
closeRodFile:
+
closeScope:
+
closeShadowScope:
+
cmdBackends:
+
cmdBuildindex:
+
cmdCheck:
+
cmdCompileToC:
+
cmdCompileToCpp:
+
cmdCompileToJS:
+
cmdCompileToOC:
+
cmdCrun:
+
cmdCtags:
+
cmdDoc:
+
cmdDoc0:
+
cmdDoc2tex:
+
cmdDocLike:
+
cmdDump:
+
cmdGendepend:
+
cmdIdeTools:
+
cmdInteractive:
+
cmdJsondoc:
+
cmdJsondoc0:
+
cmdJsonscript:
+
cmdM:
+
cmdMd2html:
+
cmdMd2tex:
+
cmdNimscript:
+
cmdNone:
+
cmdNop:
+
cmdParse:
+
cmdRod:
+
cmdRst2html:
+
cmdRst2tex:
+
cmdTcc:
+
cmdUnknown:
+
cmp:
+
cmpCandidates:
+
cmpIgnoreStyle:
+
cmpPaths:
+
cmpScopes:
+
cmpTypes:
+
CNil:
+
CoConsiderOwned:
+
CodegenFlag:
+
codeReordering:
+
CoDistinct:
+
CoHashTypeInsideNode:
+
CoIgnoreRange:
+
collectVTableDispatchers:
+
ColOffset:
+
Command:
+
commandBuildIndex:
+
commandBuildIndexJson:
+
commandDoc:
+
commandJson:
+
commandLineDesc:
+
commandLineIdx:
+
commandRst2Html:
+
commandRst2TeX:
+
commandTags:
+
comment:
+
comment=:
+
commonOptimizations:
+
commonSuperclass:
+
commonType:
+
commonTypeBegin:
+
compare:
+
compareTypes:
+
compatibleEffects:
+
compilationCachePresent:
+
compilePipelineModule:
+
compilePipelineProject:
+
compilePipelineSystemModule:
+
compilerProcsSection:
+
CompilesId:
+
compiletimeFFI:
+
complement:
+
completeCfilePath:
+
completeGeneratedFilePath:
+
completePartialOp:
+
computeAliveSyms:
+
computeCursors:
+
computeGraphPartitions:
+
computeSize:
+
computeSizeAlign:
+
conceptMatch:
+
ConcreteTypes:
+
config:
+
configComplete:
+
configMismatch:
+
ConfigRef:
+
configSection:
+
connectPipelineCallbacks:
+
ConsiderFlag:
+
considerGenSyms:
+
considerQuotedIdent:
+
ConstantDataTypes:
+
constParameters:
+
constPragmas:
+
constructCfg:
+
contains:
+
containsCompileTimeOnly:
+
containsGarbageCollectedRef:
+
containsGenericType:
+
containsHiddenPointer:
+
containsManagedMemory:
+
containsNode:
+
containsObject:
+
containsSets:
+
containsTyRef:
+
containsUnresolvedType:
+
ControlFlowGraph:
+
converterPragmas:
+
convertersSection:
+
CoOwnerSig:
+
CoProc:
+
copyFile:
+
copyInto:
+
copyIntoKind:
+
copyNode:
+
copyObjectSet:
+
copyrightYear:
+
copyStrTable:
+
copySym:
+
copyTree:
+
copyTreeWithoutNode:
+
copyType:
+
copyTypeProps:
+
CoType:
+
countDefinedSymbols:
+
cpExact:
+
cpFuzzy:
+
cpNone:
+
CPointer:
+
cppDefine:
+
cppNimSharedKeywords:
+
cpsInit:
+
cpsLocals:
+
cpsStmts:
+
CPU:
+
cpuAlpha:
+
cpuAmd64:
+
cpuArm:
+
cpuArm64:
+
cpuAVR:
+
cpuE2k:
+
cpuEsp:
+
cpuHppa:
+
cpuI386:
+
cpuIa64:
+
cpuJS:
+
cpuLoongArch64:
+
cpuM68k:
+
cpuMips:
+
cpuMips64:
+
cpuMips64el:
+
cpuMipsel:
+
cpuMSP430:
+
cpuNimVM:
+
cpuNone:
+
cpuPowerpc:
+
cpuPowerpc64:
+
cpuPowerpc64el:
+
cpuRiscV32:
+
cpuRiscV64:
+
cpuSparc:
+
cpuSparc64:
+
cpuVm:
+
cpuWasm32:
+
CR:
+
create:
+
createClosureIterStateType:
+
createDir:
+
createDocLink:
+
createMagic:
+
createModuleAlias:
+
createObj:
+
createTypeBoundOps:
+
csEmpty:
+
csMatch:
+
csNoMatch:
+
ctArray:
+
ctBool:
+
ctChar:
+
ctCString:
+
ctfeWhitelist:
+
ctFloat:
+
ctFloat128:
+
ctFloat32:
+
ctFloat64:
+
ctInt:
+
ctInt16:
+
ctInt32:
+
ctInt64:
+
ctInt8:
+
ctNimSeq:
+
ctNimStr:
+
ctProc:
+
ctPtr:
+
ctPtrToArray:
+
ctStruct:
+
ctUInt:
+
ctUInt16:
+
ctUInt32:
+
ctUInt64:
+
ctUInt8:
+
ctVoid:
+
cUint64Literal:
+
cUintType:
+
cUintValue:
+
currentLen:
+
cursorInference:
+
CustomError:
+
customPath:
+
CVoid:
+
cyclicTree:
+
cyclicType:
+
dcEq:
+
dcEqIgnoreDistinct:
+
dcEqOrDistinctOf:
+
debug:
+
debugEchoCode:
+
debugScopes:
+
declarativeDefs:
+
declarePureEnumField:
+
decodeStr:
+
decodeStrArray:
+
decodeVBiggestInt:
+
decodeVInt:
+
decodeVIntArray:
+
deduplicate:
+
def:
+
DefaultConfig:
+
DefaultConfigNims:
+
DefaultGlobalOptions:
+
defaultOffset:
+
DefaultOptions:
+
defaultParamSeparator:
+
DefaultSetElements:
+
definedSymbolNames:
+
defineSymbol:
+
delSon:
+
demangleModuleName:
+
depsSection:
+
describeArg:
+
describeArgs:
+
destructor:
+
detailedInfo:
+
differ:
+
diffSets:
+
directIntLit:
+
directViewType:
+
dirExists:
+
disabledSf:
+
disableNimblePath:
+
discardSons:
+
dispatcherPos:
+
dispatchersSection:
+
divMod:
+
doAbort:
+
docCls:
+
DocConfig:
+
docCss:
+
Docgen2JsonPass:
+
Docgen2Pass:
+
Docgen2TexPass:
+
docHackJs:
+
docHackJsFname:
+
docHackNim:
+
docRootDefault:
+
DocTexConfig:
+
documentRaises:
+
doesImply:
+
doNothing:
+
dontInlineConstant:
+
doRaise:
+
dotdotMangle:
+
dotOperators:
+
dump:
+
dup:
+
dynamicBindSym:
+
eat:
+
echoCfg:
+
echoCode:
+
efAllowStmt:
+
efAllowSymChoice:
+
efCannotBeDotCall:
+
efCompat:
+
efDetermineType:
+
efEffectsDelayed:
+
efExplain:
+
effectListLen:
+
EffectsCompat:
+
effectSpec:
+
efFromHlo:
+
efIgnoreDefaults:
+
efInCall:
+
efInTypeof:
+
efIsDotCall:
+
efLValue:
+
efNeedStatic:
+
efNoEvaluateGeneric:
+
efNoSem2Check:
+
efNoSemCheck:
+
efNoUndeclared:
+
efOperand:
+
efPreferNilResult:
+
efPreferStatic:
+
efRaisesDiffer:
+
efRaisesUnknown:
+
efTagsDiffer:
+
efTagsIllegal:
+
efTagsUnknown:
+
efTypeAllowed:
+
efWantIterable:
+
efWantIterator:
+
efWantNoDefaults:
+
efWantStmt:
+
efWantValue:
+
elementType:
+
ElemSize:
+
elemType:
+
emConst:
+
emitGenerics:
+
emOptimize:
+
emptyNodeId:
+
emptyRange:
+
emRepl:
+
emStaticExpr:
+
emStaticStmt:
+
encode:
+
encodeName:
+
encoder:
+
encodeStr:
+
encodeSym:
+
encodeType:
+
encodeVBiggestInt:
+
encodeVInt:
+
EndianToStr:
+
EndOfFile:
+
endsWith:
+
endsWithOpr:
+
ensuresEffects:
+
enter:
+
enumFieldPragmas:
+
enumHasHoles:
+
enumToStringProcsSection:
+
envName:
+
eqTypeFlags:
+
equalParams:
+
equalSets:
+
equalsFile:
+
eraseVoidParams:
+
ERecoverableError:
+
errArgsNeedRunOption:
+
errCannotOpenFile:
+
errFailedMove:
+
errFatal:
+
errFloatToString:
+
errGenerated:
+
errIllFormedAstX:
+
errInternal:
+
errMax:
+
errMin:
+
ErrorHandler:
+
ErrorKind:
+
errorNode:
+
errorSubNode:
+
errorSym:
+
errorToString:
+
errorType:
+
errorUndeclaredIdentifier:
+
errorUndeclaredIdentifierHint:
+
errorUseQualifier:
+
errProveInit:
+
errRstFootnoteMismatch:
+
errRstGeneralParseError:
+
errRstGridTableNotImplemented:
+
errRstIllformedTable:
+
errRstInvalidDirectiveX:
+
errRstInvalidField:
+
errRstMarkdownIllformedTable:
+
errRstMissingClosing:
+
errRstNewSectionExpected:
+
errRstSandboxedDirective:
+
errUnknown:
+
errUser:
+
errXExpected:
+
errXMustBeCompileTime:
+
ESC:
+
eStdErr:
+
eStdOut:
+
ESuggestDone:
+
evalConstExpr:
+
evalExpr:
+
evalFrom:
+
evalImport:
+
evalImportExcept:
+
evalMacroCall:
+
evalOnce:
+
evalOp:
+
EvalPass:
+
evalStaticExpr:
+
evalStaticStmt:
+
evalStmt:
+
evalTemplate:
+
evalTemplateLimit:
+
ExactConstraints:
+
exactEquals:
+
ExactGcSafety:
+
ExactGenericParams:
+
exactReplica:
+
ExactTypeDescValues:
+
excCpp:
+
exceptionEffects:
+
ExceptionSystem:
+
excGoto:
+
excNone:
+
excQuirky:
+
excSetjmp:
+
execExternalProgram:
+
execProc:
+
existsConfigVar:
+
expandDefault:
+
expandDone:
+
expectIdent:
+
expectIdentOrKeyw:
+
explanationsBaseUrl:
+
ExportableSymKinds:
+
exportsSection:
+
exportSym:
+
ExpressionCannotBeCalled:
+
exprPragmas:
+
exprRoot:
+
exprStructuralEquivalent:
+
externIntLit:
+
externSIntLit:
+
externUIntLit:
+
extract:
+
extractFilename:
+
extractPragma:
+
extractRange:
+
extractRunnableExamplesSource:
+
fastLog2:
+
fatal:
+
fatalMsgs:
+
Feature:
+
FF:
+
fieldPragmas:
+
fieldVisible:
+
fileExists:
+
fileIdx:
+
FileIndex:
+
fileInfoIdx:
+
fileInfoKnown:
+
filename:
+
FilenameOption:
+
fileSymbols:
+
fillObjectFields:
+
filterReplace:
+
filterStrip:
+
filterTmpl:
+
finalCodegenActions:
+
finalJSCodeGen:
+
findFile:
+
findFlags:
+
findModule:
+
findNodeJs:
+
findPragma:
+
findProjectNimFile:
+
findStr:
+
findSymInfoIndex:
+
findType:
+
findUnresolvedStatic:
+
finishGenerateDoc:
+
firstABxInstr:
+
FirstCallConv:
+
firstFloat:
+
firstGenericParam:
+
FirstGenericParamAt:
+
firstIdentExcluding:
+
firstOrd:
+
FirstParamAt:
+
firstParamType:
+
firstSon:
+
fitsRegister:
+
flags:
+
flattenStmts:
+
flexibleOptionalParams:
+
floatInt64Align:
+
FloatLike:
+
floatRangeCheck:
+
flushDot:
+
foAbs:
+
foCanonical:
+
foldAlignOf:
+
foldOffsetOf:
+
foldSizeOf:
+
foLegacyRelProj:
+
foName:
+
forbiddenEffects:
+
force:
+
foreignPackageNotesDefault:
+
foRelProject:
+
fork:
+
forLoopMacros:
+
formatMsg:
+
FormatStr:
+
forVarPragmas:
+
foStacktrace:
+
frameDeclared:
+
freeze:
+
frEmbedded:
+
frHeader:
+
frNone:
+
fromLit:
+
fromSystem:
+
FullId:
+
gcArc:
+
gcAtomicArc:
+
gcBoehm:
+
gcGo:
+
gcHooks:
+
gcMarkAndSweep:
+
gCmdLineInfo:
+
gcNone:
+
gcOrc:
+
gcRefc:
+
gcRegions:
+
GcTypeKinds:
+
gcUnselected:
+
genAddrOf:
+
genBuiltin:
+
genCaseObjDiscMapping:
+
GenDependPass:
+
genDeref:
+
genEnumToStrProc:
+
generateCode:
+
generatedMagics:
+
generateDoc:
+
generateDot:
+
generateIfMethodDispatchers:
+
generateIndex:
+
generateJson:
+
generateTags:
+
generateTypeInstance:
+
genericAliasDepth:
+
genericBodyParams:
+
genericConstraint:
+
genericHead:
+
genericInstParamPairs:
+
genericInstParams:
+
genericInvocationAndBodyElements:
+
genericInvocationParamPairs:
+
genericInvocationParams:
+
genericInvocationParamsLen:
+
genericParamHasConstraints:
+
genericParamsInMacroCall:
+
genericParamsLen:
+
genericParamsPos:
+
genericRoot:
+
genericsOpenSym:
+
GenericTypes:
+
genExpr:
+
genFieldDefect:
+
genHigh:
+
genIfDispatcher:
+
genLen:
+
genPrefix:
+
genProc:
+
genProcAux:
+
genSourceMap:
+
genStmt:
+
genSubDir:
+
genSuccessX:
+
genTopLevelStmt:
+
genTypeInfo:
+
get:
+
getAlign:
+
getAttachedOp:
+
getBody:
+
getBool:
+
getClockStr:
+
getClosureIterResult:
+
getColNumber:
+
getCompileCFileCmd:
+
getCompilerProc:
+
getConfigVar:
+
getConstExpr:
+
getCurrentLine:
+
getCurrOwner:
+
getDateStr:
+
getDeclPragma:
+
getDispatcher:
+
getDispatchers:
+
getDocHacksJs:
+
getEbase:
+
getEnvParam:
+
getFieldFromObj:
+
getFileId:
+
getFloat:
+
getFloatLitType:
+
getFloatValue:
+
getGenSym:
+
getGlobalValue:
+
getHash:
+
getIdent:
+
getIndentWidth:
+
getInfoContext:
+
getInfoContextLen:
+
getInt:
+
getInt64:
+
getIntLitType:
+
getKeyId:
+
getLineInfo:
+
getMagic:
+
getMagicEqSymForType:
+
getMethodsPerType:
+
getModule:
+
getModuleName:
+
getNamedParamFromList:
+
getNextTok:
+
getNimbleFile:
+
getNimcacheDir:
+
getNimScriptSymbol:
+
getNode:
+
getNodeAddr:
+
getNodeId:
+
getNullValue:
+
getOrDefault:
+
getOrdValue:
+
getOrdValueAux:
+
getOrIncl:
+
getOutFile:
+
getPackage:
+
getPackageId:
+
getPackageName:
+
getPackageSymbol:
+
getPathVersionChecksum:
+
getPIdent:
+
getPragmaStmt:
+
getPragmaVal:
+
getPrecedence:
+
getPrefixDir:
+
getProcConvMismatch:
+
getProcHeader:
+
getRelativePathFromConfigPath:
+
getReturnType:
+
getRoot:
+
getSize:
+
getStateField:
+
getStr:
+
getString:
+
getStrOrChar:
+
getSymFromList:
+
getSymInfoPair:
+
getSymRepr:
+
getSysMagic:
+
getSysSym:
+
getSystemConfigPath:
+
getSysType:
+
getTok:
+
getTokSym:
+
getToStringProc:
+
getUniqueType:
+
getUserConfigPath:
+
getVar:
+
ggDebug:
+
globalAssert:
+
globalError:
+
gloptNone:
+
Goal:
+
goto:
+
GrowthFactor:
+
handleCmdInput:
+
handleCR:
+
handleDocOutputOptions:
+
handleLF:
+
handleStdinInput:
+
harmlessOptions:
+
has2Sons:
+
hasAssume:
+
hasAtLeastXsons:
+
hasAttribute:
+
hasBuiltinUnreachable:
+
hasComputedGoto:
+
hasCpp:
+
hasCurFramePointer:
+
HasDatInitProc:
+
hasDeclspec:
+
hasDestructor:
+
hasDisabledAsgn:
+
hasElementType:
+
hasFFI:
+
hasGcGuard:
+
hasGnuAsm:
+
hash:
+
hasHint:
+
hashMainCompilationParams:
+
hashNode:
+
hashNonProc:
+
hashOwner:
+
hashString:
+
hashTree:
+
hashType:
+
hasLitId:
+
HasModuleInitProc:
+
hasNext:
+
hasNilSon:
+
hasPattern:
+
hasPragma:
+
hasSideEffect:
+
hasSon:
+
hasSonWith:
+
hasSubnodeWith:
+
hasSwitchRange:
+
hasTinyCBackend:
+
hasWarn:
+
hasXsons:
+
hcrOn:
+
hExt:
+
hiddenSection:
+
high:
+
highBound:
+
hintCC:
+
hintCodeBegin:
+
hintCodeEnd:
+
hintConditionAlwaysFalse:
+
hintConditionAlwaysTrue:
+
hintConf:
+
hintConvFromXtoItselfNotNeeded:
+
hintConvToBaseNotNeeded:
+
hintDeclaredLoc:
+
hintDependency:
+
hintDuplicateModuleImport:
+
hintExecuting:
+
hintExpandMacro:
+
hintExprAlwaysX:
+
hintExtendedContext:
+
hintGCStats:
+
hintGlobalVar:
+
hintLinking:
+
hintMax:
+
hintMin:
+
hintMsgOrigin:
+
hintName:
+
hintPath:
+
hintPattern:
+
hintPerformance:
+
hintProcessing:
+
hintProcessingStmt:
+
hintQuitCalled:
+
hintSource:
+
hintStackTrace:
+
hintSuccess:
+
hintSuccessX:
+
hintUnknownHint:
+
hintUser:
+
hintUserRaw:
+
hintXCannotRaiseY:
+
hintXDeclaredButNotUsed:
+
htmldocsDir:
+
htmldocsDirname:
+
HtmlExt:
+
id:
+
ideChanged:
+
ideChk:
+
ideChkFile:
+
IdeCmd:
+
ideCon:
+
ideDeclaration:
+
ideDef:
+
ideDus:
+
ideExpand:
+
ideGlobalSymbols:
+
ideHighlight:
+
ideInlayHints:
+
ideKnown:
+
ideMod:
+
ideMsg:
+
ideNone:
+
IdentCache:
+
identLen:
+
ideOutline:
+
ideProject:
+
ideRecompile:
+
ideSug:
+
ideType:
+
ideUse:
+
IdGenerator:
+
idGeneratorForPackage:
+
idGeneratorFromModule:
+
idgenFromLoadedModule:
+
idOrSig:
+
idTableGet:
+
idTablePut:
+
Iface:
+
IfBuilder:
+
IfBuilderState:
+
IgnoreCC:
+
IgnoreFlags:
+
IgnoreRangeShallow:
+
IgnoreTupleFields:
+
iiTableGet:
+
iiTablePut:
+
ikids:
+
illegalCustomPragma:
+
illFormedAst:
+
illFormedAstLocal:
+
immutableView:
+
implicitPragmas:
+
impliesNotNil:
+
impNo:
+
importAll:
+
importAllSymbols:
+
importantComments:
+
importcCond:
+
importcCondVar:
+
importedItems:
+
ImportedModule:
+
importExcept:
+
ImportMode:
+
importSet:
+
impUnknown:
+
impYes:
+
InBlock:
+
inc:
+
inCheckpoint:
+
inclDynlibOverride:
+
includeFileChanged:
+
includeHeader:
+
includeModule:
+
includesStringh:
+
incompleteType:
+
indAndComment:
+
indexType:
+
indirectAccess:
+
inferGenericTypes:
+
inferStaticParam:
+
info:
+
inheritanceDiff:
+
IniExt:
+
initBiTable:
+
initBlock:
+
initBTree:
+
initCandidate:
+
initDefines:
+
initDefinesProg:
+
initEncoder:
+
initIdentIter:
+
initIITable:
+
initLayeredTypeMap:
+
initModuleIter:
+
initMsgConfig:
+
initNodeTable:
+
initObjectSet:
+
initOperators:
+
initOrcDefines:
+
initOverloadIter:
+
initPackedDecoder:
+
initRodIter:
+
initRodIterAllSyms:
+
initStrTable:
+
initStrTables:
+
initSymMapping:
+
initTabIter:
+
initTokRender:
+
initTypeMapping:
+
initTypeVars:
+
initVars:
+
injectDestructorCalls:
+
inSet:
+
InstantiationInfo:
+
instCopyType:
+
instGenericConvertersArg:
+
instGenericConvertersSons:
+
instLoc:
+
Instr:
+
InstrKind:
+
instTypeBoundOp:
+
Int128:
+
IntegralTypes:
+
interestingCaseExpr:
+
interfaceSymbol:
+
interfaceSymbols:
+
internalAssert:
+
internalError:
+
interp:
+
interpreterCode:
+
InterpreterPass:
+
intersectSets:
+
IntLike:
+
invalidateFacts:
+
InvalidFileIdx:
+
invalidGenericInst:
+
InvalidKey:
+
invalidPragma:
+
ioFailure:
+
isActive:
+
isAlive:
+
isAmbiguous:
+
isAnalysableFieldAccess:
+
isAssignable:
+
isAtom:
+
isBothMetaConvertible:
+
isCachedModule:
+
isCallExpr:
+
isCaseObj:
+
isCharArrayPtr:
+
isClosure:
+
isClosureIterator:
+
isCompileTimeOnly:
+
isCompileTimeProc:
+
isConstExpr:
+
isConvertible:
+
isDangerousLocation:
+
isDeepConstExpr:
+
isDefectException:
+
isDefectOrCatchableError:
+
isDefined:
+
isDirty:
+
isDiscriminantField:
+
isDynlibOverride:
+
isEmpty:
+
isEmptyContainer:
+
isEmptyTupleType:
+
isEmptyType:
+
isEqual:
+
isException:
+
isExplicitCallConv:
+
isFinal:
+
isFloatLit:
+
isFromIntLit:
+
isGCedMem:
+
isGeneric:
+
isGenericAlias:
+
isGenericParams:
+
isGenericRoutine:
+
isGenericRoutineStrict:
+
isHeaderFile:
+
isImportedException:
+
isInferred:
+
isInferredConvertible:
+
isInfixAs:
+
isInlineIterator:
+
isIntConv:
+
isIntLit:
+
isIterator:
+
isKeyword:
+
isLValue:
+
isMetaType:
+
isNewStyleConcept:
+
isNimcall:
+
isNimIdentifier:
+
isNone:
+
isNoSideEffectPragma:
+
isons:
+
isOperator:
+
isOrdinalType:
+
isOutParam:
+
isPartOf:
+
isPureObject:
+
isRange:
+
isRecursiveType:
+
isRefPtrObject:
+
isResolvedUserTypeClass:
+
isRoutine:
+
isRunnableExamples:
+
isSelf:
+
isShadowScope:
+
isSingletonTupleType:
+
isSinkParam:
+
isSinkType:
+
isSinkTypeForParam:
+
isSubrange:
+
isSubtype:
+
isTopLevel:
+
isTopLevelInsideDeclaration:
+
isTracked:
+
isTrival:
+
isTrue:
+
isTupleRecursive:
+
isUnresolvedStatic:
+
isUnsigned:
+
isVSCompatible:
+
ItemId:
+
items:
+
iteratorPragmas:
+
iterOverType:
+
ithSon:
+
jmpDiff:
+
JSgenPass:
+
jsNoLambdaLifting:
+
jsonBuildInstructionsFile:
+
JsonExt:
+
kAlreadyGiven:
+
keepOpenArrayConversions:
+
kExtraArg:
+
kExtraGenericParam:
+
kGenericParamTypeMismatch:
+
kids:
+
kidsLen:
+
kind:
+
kMissingGenericParam:
+
kMissingParam:
+
kPositionalAlreadyGiven:
+
kTypeMismatch:
+
kUnknown:
+
kUnknownNamedParam:
+
kVarNeeded:
+
lacksMTypeField:
+
lambdaPragmas:
+
largeInstrs:
+
last:
+
LastCallConv:
+
lastFloat:
+
lastOptionEntry:
+
lastOrd:
+
lastOverloadScope:
+
lastSon:
+
laxEffects:
+
LayeredIdTable:
+
LayeredIdTableObj:
+
LazyInstantiation:
+
LazySym:
+
LazyType:
+
leave:
+
LegacyFeature:
+
len:
+
lengthOrd:
+
letPragmas:
+
Letters:
+
leValue:
+
leValueConv:
+
Lexer:
+
lexMessage:
+
lexMessageTok:
+
LF:
+
lfDynamicLib:
+
lfEnforceDeref:
+
lfExportLib:
+
lfHeader:
+
lfImportCompilerProc:
+
lfIndirect:
+
lfNoDecl:
+
lfNoDeepCopy:
+
lfPrepareForMutation:
+
lfSingleUse:
+
libDynamic:
+
libHeader:
+
liftForLoop:
+
liftIterSym:
+
liftIterToProc:
+
liftLambdas:
+
liftLambdasForTopLevel:
+
liftLocalsIfRequested:
+
liftParallel:
+
liftTypeBoundOps:
+
liMessage:
+
LineInfoManager:
+
lineInfoToStr:
+
linkTo:
+
lintReport:
+
listCPUnames:
+
listHints:
+
listOSnames:
+
listSymbolNames:
+
listWarnings:
+
LitId:
+
litId:
+
llsFile:
+
llsNone:
+
llsStdIn:
+
llsString:
+
llStreamClose:
+
llStreamOpen:
+
llStreamOpenStdIn:
+
llStreamRead:
+
llStreamReadAll:
+
llStreamReadLine:
+
llStreamWrite:
+
llStreamWriteln:
+
load:
+
loadAny:
+
loadCompilerProc:
+
loadConfigs:
+
loadConfigsAndProcessCmdLine:
+
loadConfigsAndRunMainCommand:
+
loaded:
+
LoadedModule:
+
loadHeader:
+
loading:
+
loadNodes:
+
loadOrderedTable:
+
loadPackedSym:
+
loadPrim:
+
loadProcBody:
+
loadRodFile:
+
loadSection:
+
loadSeq:
+
loadSymFromId:
+
loadTypeFromId:
+
localError:
+
localErrorNode:
+
localScopesFrom:
+
localSearchInScope:
+
locCall:
+
locData:
+
locExpr:
+
locField:
+
locGlobalVar:
+
locLocalVar:
+
locNone:
+
locOther:
+
locParam:
+
locProc:
+
locTemp:
+
log:
+
lookup:
+
lookUp:
+
lookUpCandidates:
+
lookupFieldAgain:
+
lookupInRecord:
+
loop:
+
low:
+
lowBound:
+
lowerSwap:
+
lowerTupleUnpacking:
+
Lrz:
+
mAbsI:
+
mAccessEnv:
+
mAccessTypeField:
+
macroPragmas:
+
mAddF64:
+
mAddI:
+
mAddr:
+
mAddU:
+
mainCommand:
+
mainCommandArg:
+
makeAddr:
+
makeAndType:
+
makeClosure:
+
makeCString:
+
makeInstPair:
+
makeModule:
+
makeNotType:
+
makeOrType:
+
makePtrType:
+
makeRangeType:
+
makeRangeWithStaticExpr:
+
makeSingleLineCString:
+
makeStaticExpr:
+
makeStdinModule:
+
makeStmtList:
+
makeTypeDesc:
+
makeTypeFromExpr:
+
makeTypeSymNode:
+
makeTypeWithModifier:
+
makeVarType:
+
mAlignOf:
+
mAnd:
+
mangle:
+
mangleModuleName:
+
mangleParamExt:
+
mangleProcNameExt:
+
mAppendSeqElem:
+
mAppendStrCh:
+
mAppendStrStr:
+
mAppType:
+
markClientsDirty:
+
markConvertersUsed:
+
markDirty:
+
markIndirect:
+
markOwnerModuleAsUsed:
+
markUsed:
+
mArray:
+
mArrGet:
+
mArrPut:
+
mArrToSeq:
+
mAsgn:
+
mAshrI:
+
maskBytes:
+
maskUInt16:
+
maskUInt32:
+
maskUInt64:
+
maskUInt8:
+
mAstToStr:
+
matches:
+
matchGenericParams:
+
matchNodeKinds:
+
matchUserTypeClass:
+
MaxSetElements:
+
MaxStackSize:
+
maybe:
+
MaybeNil:
+
mBitandI:
+
mBitnotI:
+
mBitorI:
+
mBitxorI:
+
mBool:
+
mBoolDefine:
+
mBoolToStr:
+
mBuildCPU:
+
mBuildOS:
+
mBuiltinType:
+
mCard:
+
mChar:
+
mCharToStr:
+
mChr:
+
mCompileDate:
+
mCompileOption:
+
mCompileOptionArg:
+
mCompiles:
+
mCompileTime:
+
mConStrStr:
+
mCpuEndian:
+
mCstring:
+
mCStrToStr:
+
mdbg:
+
mDec:
+
mDeclared:
+
mDeclaredInScope:
+
mDeepCopy:
+
mDefault:
+
mDefined:
+
mDestroy:
+
mDistinct:
+
mDivF64:
+
mDivI:
+
mDivU:
+
mDotDot:
+
mDup:
+
mEcho:
+
mEnsureMove:
+
mEnumToStr:
+
mEqB:
+
mEqCh:
+
mEqCString:
+
mEqEnum:
+
mEqF64:
+
mEqI:
+
mEqIdent:
+
mEqNimrodNode:
+
mEqProc:
+
mEqRef:
+
mEqSet:
+
mEqStr:
+
mergeShadowScope:
+
message:
+
methodCall:
+
methodDef:
+
methodPragmas:
+
methodsForGeneric:
+
methodsPerGenericTypeSection:
+
methodsPerTypeSection:
+
methodsSection:
+
mException:
+
mExcl:
+
mExists:
+
mExit:
+
mExpandToAst:
+
mExpr:
+
mFieldPairs:
+
mFields:
+
mFinished:
+
mFloat:
+
mFloat128:
+
mFloat32:
+
mFloat64:
+
mForall:
+
mGCref:
+
mGCunref:
+
mGenericDefine:
+
mGetImpl:
+
mGetImplTransf:
+
mGetTypeInfo:
+
mGetTypeInfoV2:
+
mHigh:
+
mHostCPU:
+
mHostOS:
+
mIff:
+
mImplies:
+
mInc:
+
mIncl:
+
mInSet:
+
mInstantiationInfo:
+
mInt:
+
mInt16:
+
mInt32:
+
mInt64:
+
mInt8:
+
mIntDefine:
+
mIs:
+
miscPos:
+
mIsMainModule:
+
MismatchInfo:
+
MismatchKind:
+
mIsNil:
+
mIsolate:
+
mIsPartOf:
+
mIterableType:
+
mLeB:
+
mLeCh:
+
mLeEnum:
+
mLeF64:
+
mLeI:
+
mLengthArray:
+
mLengthOpenArray:
+
mLengthSeq:
+
mLengthStr:
+
mLePtr:
+
mLeSet:
+
mLeStr:
+
mLeU:
+
mLow:
+
mLtB:
+
mLtCh:
+
mLtEnum:
+
mLtF64:
+
mLtI:
+
mLtPtr:
+
mLtSet:
+
mLtStr:
+
mLtU:
+
mMaxI:
+
mMinI:
+
mMinusSet:
+
mModI:
+
mModU:
+
mMove:
+
mMulF64:
+
mMulI:
+
mMulSet:
+
mMulU:
+
mNAdd:
+
mNAddMultiple:
+
mNBindSym:
+
mNCallSite:
+
mNccInc:
+
mNccValue:
+
mNChild:
+
mNCopyNimNode:
+
mNCopyNimTree:
+
mNcsAdd:
+
mNcsAt:
+
mNcsIncl:
+
mNcsLen:
+
mNctGet:
+
mNctHasNext:
+
mNctLen:
+
mNctNext:
+
mNctPut:
+
mNDel:
+
mNError:
+
mNew:
+
mNewFinalize:
+
mNewSeq:
+
mNewSeqOfCap:
+
mNewString:
+
mNewStringOfCap:
+
mNFloatVal:
+
mNGenSym:
+
mNGetType:
+
mNHint:
+
mNIdent:
+
mNil:
+
mNimvm:
+
mNIntVal:
+
mNKind:
+
mNLen:
+
mNLineInfo:
+
mNNewNimNode:
+
mNodeId:
+
mNone:
+
mNot:
+
mNSetChild:
+
mNSetFloatVal:
+
mNSetIdent:
+
mNSetIntVal:
+
mNSetStrVal:
+
mNSetSymbol:
+
mNSigHash:
+
mNSizeOf:
+
mNStrVal:
+
mNSymbol:
+
mNSymKind:
+
mNWarning:
+
ModuleBackendFlag:
+
moduleFromRodFile:
+
ModuleGraph:
+
moduleHasChanged:
+
ModuleId:
+
moduleIndex:
+
ModuleIter:
+
moduleOpenForCodegen:
+
ModuleStatus:
+
mOf:
+
mOffsetOf:
+
mOld:
+
mOmpParFor:
+
mOpenArray:
+
mOpenArrayToSeq:
+
mOr:
+
mOrd:
+
mOrdinal:
+
mParallel:
+
mParseBiggestFloat:
+
mParseExprToAst:
+
mParseStmtToAst:
+
mPlugin:
+
mPlusSet:
+
mPNimrodNode:
+
mPointer:
+
mPred:
+
mPrivateAccess:
+
mProcCall:
+
mPtr:
+
mQuoteAst:
+
mRange:
+
mRef:
+
mRepr:
+
mRunnableExamples:
+
mSameNodeType:
+
mSeq:
+
mSet:
+
mSetLengthSeq:
+
mSetLengthStr:
+
MsgConfig:
+
MsgFlag:
+
MsgFlags:
+
MsgKindToStr:
+
msgKindToString:
+
msgNoUnitSep:
+
msgQuit:
+
msgSkipHook:
+
msgStdout:
+
msgWriteln:
+
mShallowCopy:
+
mShlI:
+
mShrI:
+
mSizeOf:
+
mSlice:
+
mSlurp:
+
mSpawn:
+
mStatic:
+
mStaticExec:
+
mStmt:
+
mStrDefine:
+
mString:
+
mStrToIdent:
+
mStrToStr:
+
mSubF64:
+
mSubI:
+
mSubU:
+
mSucc:
+
mSwap:
+
mSymIsInstantiationOf:
+
mSymOwner:
+
mTrace:
+
mTuple:
+
mType:
+
mTypeDesc:
+
mTypeOf:
+
mTypeTrait:
+
mUInt:
+
mUInt16:
+
mUInt32:
+
mUInt64:
+
mUInt8:
+
multiFormat:
+
mUnaryMinusF64:
+
mUnaryMinusI:
+
mUnaryMinusI64:
+
mUnaryPlusF64:
+
mUnaryPlusI:
+
mUncheckedArray:
+
mUnown:
+
mustRehash:
+
mutableView:
+
MutationInfo:
+
mVar:
+
mVarargs:
+
mVoid:
+
mVoidType:
+
mWasMoved:
+
mXor:
+
mXorSet:
+
mZeroDefault:
+
namePos:
+
namespaceSection:
+
nameToCC:
+
nameToCPU:
+
nameToOS:
+
navDefinition:
+
navDefusages:
+
navUsages:
+
needsCompilation:
+
NegOne:
+
newAsgnStmt:
+
newAtom:
+
newBuilder:
+
newCandidate:
+
newConfigRef:
+
newContext:
+
newCtx:
+
newDeref:
+
newDocumentor:
+
newDotExpr:
+
newError:
+
newFastAsgnStmt:
+
newFastMoveStmt:
+
newFloatNode:
+
newFloatNodeP:
+
newFloatNodeT:
+
newIdentCache:
+
newIdentNode:
+
newIdentNodeP:
+
newIntLit:
+
newIntNode:
+
newIntNodeP:
+
newIntNodeT:
+
newIntTypeNode:
+
newLib:
+
newLineInfo:
+
NewLines:
+
newModule:
+
newModuleGraph:
+
newModuleList:
+
newNode:
+
newNodeI:
+
newNodeIT:
+
newNodeP:
+
newOpenSym:
+
newOptionEntry:
+
newPackageCache:
+
newPackedBoolArray:
+
newPartialConfigRef:
+
newProc:
+
newProcNode:
+
newProcType:
+
newRopeAppender:
+
newSons:
+
newStrNode:
+
newStrNodeP:
+
newStrNodeT:
+
newSuggestFileSymbolDatabase:
+
newSym:
+
newSymG:
+
newSymNode:
+
newSymNodeTypeDesc:
+
newTree:
+
newTreeFrom:
+
newTreeI:
+
newTreeIT:
+
newTryFinally:
+
newTupleAccess:
+
newTupleAccessRaw:
+
newType:
+
newTypeMapLayer:
+
newTypeS:
+
newVersion:
+
next:
+
nextIdentExcluding:
+
nextIdentIter:
+
nextIter:
+
nextModuleIter:
+
nextOverloadIter:
+
nextRodIter:
+
nextTry:
+
nextTypeId:
+
nfAllConst:
+
nfAllFieldsSet:
+
nfBase16:
+
nfBase2:
+
nfBase8:
+
nfBlockArg:
+
nfDefaultParam:
+
nfDefaultRefsParam:
+
nfDisabledOpenSym:
+
nfDotField:
+
nfDotSetter:
+
nfExecuteOnReload:
+
nfExplicitCall:
+
nfExprCall:
+
nfFirstWrite:
+
nfFromTemplate:
+
nfHasComment:
+
nfIsPtr:
+
nfIsRef:
+
nfLastRead:
+
nfLL:
+
nfNone:
+
nfNoRewrite:
+
nfPreventCg:
+
nfSem:
+
nfSkipFieldChecking:
+
nfTransf:
+
Nil:
+
Nilability:
+
NilableTypes:
+
nilItemId:
+
nilOrSysInt:
+
nimblePath:
+
nimbleSubs:
+
NimBool:
+
NimChar:
+
NimCompilerApiVersion:
+
NimCstring:
+
nimdocOutCls:
+
nimdocOutCss:
+
nimEnableCovariance:
+
nimErrorFlagAccessed:
+
nimErrorFlagDeclared:
+
nimErrorFlagDisabled:
+
NimExt:
+
NimFalse:
+
NimFloat:
+
NimFloat128:
+
NimFloat32:
+
NimFloat64:
+
NimInf:
+
NimInt:
+
NimInt16:
+
NimInt32:
+
NimInt64:
+
NimInt8:
+
nimKeywordsHigh:
+
nimKeywordsLow:
+
NimNan:
+
NimNil:
+
nimNodeFlag:
+
NimProg:
+
NimStrlitFlag:
+
NimTrue:
+
NimUint:
+
NimUint16:
+
NimUint32:
+
NimUint64:
+
NimUint8:
+
nkAccQuoted:
+
nkAddr:
+
nkArgList:
+
nkAsgn:
+
nkAsmStmt:
+
nkBind:
+
nkBindStmt:
+
nkBlockExpr:
+
nkBlockStmt:
+
nkBlockType:
+
nkBracket:
+
nkBracketExpr:
+
nkBreakState:
+
nkBreakStmt:
+
nkCall:
+
nkCallKinds:
+
nkCallStrLit:
+
nkCaseStmt:
+
nkCast:
+
nkCharLit:
+
nkChckRange:
+
nkChckRange64:
+
nkChckRangeF:
+
nkCheckedFieldExpr:
+
nkClosedSymChoice:
+
nkClosure:
+
nkComesFrom:
+
nkCommand:
+
nkCommentStmt:
+
nkConstDef:
+
nkConstSection:
+
nkConstTy:
+
nkContinueStmt:
+
nkConv:
+
nkConverterDef:
+
nkCStringToString:
+
nkCurly:
+
nkCurlyExpr:
+
nkDefer:
+
nkDerefExpr:
+
nkDiscardStmt:
+
nkDistinctTy:
+
nkDo:
+
nkDotCall:
+
nkDotExpr:
+
nkEffectList:
+
nkElifBranch:
+
nkElifExpr:
+
nkElse:
+
nkElseExpr:
+
nkEmpty:
+
nkEnumFieldDef:
+
nkEnumTy:
+
nkError:
+
nkExceptBranch:
+
nkExportExceptStmt:
+
nkExportStmt:
+
nkExprColonExpr:
+
nkExprEqExpr:
+
nkFastAsgn:
+
nkFinally:
+
nkFloat128Lit:
+
nkFloat32Lit:
+
nkFloat64Lit:
+
nkFloatLit:
+
nkFloatLiterals:
+
nkFormalParams:
+
nkForStmt:
+
nkFromStmt:
+
nkFuncDef:
+
nkGenericParams:
+
nkGotoState:
+
nkHiddenAddr:
+
nkHiddenCallConv:
+
nkHiddenDeref:
+
nkHiddenStdConv:
+
nkHiddenSubConv:
+
nkHiddenTryStmt:
+
nkIdent:
+
nkIdentDefs:
+
nkIdentKinds:
+
nkIfExpr:
+
nkIfStmt:
+
nkImportAs:
+
nkImportExceptStmt:
+
nkImportStmt:
+
nkIncludeStmt:
+
nkInfix:
+
nkInt16Lit:
+
nkInt32Lit:
+
nkInt64Lit:
+
nkInt8Lit:
+
nkIntLit:
+
nkIteratorDef:
+
nkIteratorTy:
+
nkLambda:
+
nkLambdaKinds:
+
nkLastBlockStmts:
+
nkLetSection:
+
nkLiterals:
+
nkMacroDef:
+
nkMethodDef:
+
nkMixinStmt:
+
nkModuleRef:
+
nkNilLit:
+
nkNilRodNode:
+
nkNone:
+
nkObjConstr:
+
nkObjDownConv:
+
nkObjectTy:
+
nkObjUpConv:
+
nkOfBranch:
+
nkOfInherit:
+
nkOpenSym:
+
nkOpenSymChoice:
+
nkOutTy:
+
nkPar:
+
nkParForStmt:
+
nkPattern:
+
nkPostfix:
+
nkPragma:
+
nkPragmaBlock:
+
nkPragmaCallKinds:
+
nkPragmaExpr:
+
nkPrefix:
+
nkProcDef:
+
nkProcTy:
+
nkPtrTy:
+
nkRaiseStmt:
+
nkRange:
+
nkRecCase:
+
nkRecList:
+
nkRecWhen:
+
nkRefTy:
+
nkReplayAction:
+
nkReturnStmt:
+
nkRStrLit:
+
nkSinkAsgn:
+
nkState:
+
nkStaticExpr:
+
nkStaticStmt:
+
nkStaticTy:
+
nkStmtList:
+
nkStmtListExpr:
+
nkStmtListType:
+
nkStringToCString:
+
nkStrKinds:
+
nkStrLit:
+
nkSym:
+
nkSymChoices:
+
nkTableConstr:
+
nkTemplateDef:
+
nkTripleStrLit:
+
nkTryStmt:
+
nkTupleClassTy:
+
nkTupleConstr:
+
nkTupleTy:
+
nkType:
+
nkTypeClassTy:
+
nkTypeDef:
+
nkTypeOfExpr:
+
nkTypeSection:
+
nkUInt16Lit:
+
nkUInt32Lit:
+
nkUInt64Lit:
+
nkUInt8Lit:
+
nkUIntLit:
+
nkUsingStmt:
+
nkVarSection:
+
nkVarTuple:
+
nkVarTy:
+
nkWhen:
+
nkWhenExpr:
+
nkWhenStmt:
+
nkWhileStmt:
+
nkWith:
+
nkWithout:
+
nkYieldStmt:
+
no:
+
NodeId:
+
NodePos:
+
nodesToIgnoreSet:
+
nodeTableGet:
+
nodeTablePut:
+
nodeTableTestOrSet:
+
NoLineInfo:
+
nominalRoot:
+
NoneLike:
+
NonePass:
+
nonPragmaWordsHigh:
+
nonPragmaWordsLow:
+
normalizeKind:
+
noSafePoints:
+
noStrictDefs:
+
NotesVerbosity:
+
notFoundError:
+
notnil:
+
noView:
+
numArgs:
+
numbersSection:
+
numChars:
+
NumericalBase:
+
numLines:
+
objectSetContains:
+
objectSetContainsOrIncl:
+
objectSetIncl:
+
objHasKidsValid:
+
OffsetAccum:
+
oimDone:
+
oimNoQualifier:
+
oimOtherModule:
+
oimSelfModule:
+
oimSymChoice:
+
oimSymChoiceLocalLookup:
+
ok:
+
oKeepVariableNames:
+
oldExperimentalFeatures:
+
onDef:
+
onDefResolveForward:
+
One:
+
OnHeap:
+
onProcessing:
+
OnPrompt:
+
OnStack:
+
OnStatic:
+
OnUnknown:
+
onUse:
+
opcAddFloat:
+
opcAddImmInt:
+
opcAddInt:
+
opcAddrNode:
+
opcAddrReg:
+
opcAddSeqElem:
+
opcAddStrCh:
+
opcAddStrStr:
+
opcAddu:
+
opcAsgnComplex:
+
opcAsgnConst:
+
opcAsgnFloat:
+
opcAsgnInt:
+
opcAsgnRef:
+
opcAshrInt:
+
opcBitandInt:
+
opcBitnotInt:
+
opcBitorInt:
+
opcBitxorInt:
+
opcBranch:
+
opcCallSite:
+
opcCard:
+
opcCast:
+
opcCastFloatToInt32:
+
opcCastFloatToInt64:
+
opcCastIntToFloat32:
+
opcCastIntToFloat64:
+
opcCastIntToPtr:
+
opcCastPtrToInt:
+
opcConcatStr:
+
opcContainsSet:
+
opcConv:
+
opcDivFloat:
+
opcDivInt:
+
opcDivu:
+
opcEcho:
+
opcEof:
+
opcEqCString:
+
opcEqFloat:
+
opcEqIdent:
+
opcEqInt:
+
opcEqNimNode:
+
opcEqRef:
+
opcEqSet:
+
opcEqStr:
+
opcExcept:
+
opcExcl:
+
opcFastAsgnComplex:
+
opcFinally:
+
opcFinallyEnd:
+
opcFJmp:
+
opcGenSym:
+
opcGetImpl:
+
opcGetImplTransf:
+
opcGorge:
+
OpChars:
+
opcIncl:
+
opcInclRange:
+
opcIndCall:
+
opcIndCallAsgn:
+
opcInvalidField:
+
opcIs:
+
opcIsNil:
+
opcJmp:
+
opcJmpBack:
+
opcLdArr:
+
opcLdArrAddr:
+
opcLdConst:
+
opcLdDeref:
+
opcLdGlobal:
+
opcLdGlobalAddr:
+
opcLdGlobalAddrDerefFFI:
+
opcLdGlobalDerefFFI:
+
opcLdImmInt:
+
opcLdNull:
+
opcLdNullReg:
+
opcLdObj:
+
opcLdObjAddr:
+
opcLdStrIdx:
+
opcLdStrIdxAddr:
+
opcLeFloat:
+
opcLeInt:
+
opcLenCstring:
+
opcLenSeq:
+
opcLenStr:
+
opcLeSet:
+
opcLeStr:
+
opcLeu:
+
opcLtFloat:
+
opcLtInt:
+
opcLtSet:
+
opcLtStr:
+
opcLtu:
+
opcMinusSet:
+
opcModInt:
+
opcModu:
+
opcMulFloat:
+
opcMulInt:
+
opcMulSet:
+
opcMulu:
+
opcNAdd:
+
opcNAddMultiple:
+
opcNarrowS:
+
opcNarrowU:
+
opcNBindSym:
+
opcNccInc:
+
opcNccValue:
+
opcNChild:
+
opcNCopyLineInfo:
+
opcNCopyNimNode:
+
opcNCopyNimTree:
+
opcNcsAdd:
+
opcNcsAt:
+
opcNcsIncl:
+
opcNcsLen:
+
opcNctGet:
+
opcNctHasNext:
+
opcNctLen:
+
opcNctNext:
+
opcNctPut:
+
opcNDel:
+
opcNDynBindSym:
+
opcNError:
+
opcNew:
+
opcNewSeq:
+
opcNewStr:
+
opcNFloatVal:
+
opcNGetLineInfo:
+
opcNGetSize:
+
opcNGetType:
+
opcNHint:
+
opcNIdent:
+
opcNIntVal:
+
opcNKind:
+
opcNNewNimNode:
+
opcNodeId:
+
opcNodeToReg:
+
opcNot:
+
opcNSetChild:
+
opcNSetFloatVal:
+
opcNSetIdent:
+
opcNSetIntVal:
+
opcNSetLineInfoColumn:
+
opcNSetLineInfoFile:
+
opcNSetLineInfoLine:
+
opcNSetStrVal:
+
opcNSetSymbol:
+
opcNSigHash:
+
opcNStrVal:
+
opcNSymbol:
+
opcNSymKind:
+
opcNWarning:
+
opcode:
+
opcOf:
+
opcParseExprToAst:
+
opcParseFloat:
+
opcParseStmtToAst:
+
opcPlusSet:
+
opcQueryErrorFlag:
+
opcQuit:
+
opcRaise:
+
opcRangeChck:
+
opcRepr:
+
opcRet:
+
opcSameNodeType:
+
opcSetLenSeq:
+
opcSetLenStr:
+
opcSetType:
+
opcShlInt:
+
opcShrInt:
+
opcSignExtend:
+
opcSlice:
+
opcSlurp:
+
opcStrToIdent:
+
opcSubFloat:
+
opcSubImmInt:
+
opcSubInt:
+
opcSubu:
+
opcSymIsInstantiationOf:
+
opcSymOwner:
+
opcTJmp:
+
opcTry:
+
opcTypeTrait:
+
opcUnaryMinusFloat:
+
opcUnaryMinusInt:
+
opcWrArr:
+
opcWrDeref:
+
opcWrObj:
+
opcWrStrIdx:
+
opcXor:
+
opcXorSet:
+
opcYldVal:
+
opcYldYoid:
+
open:
+
openBaseLexer:
+
openHtml:
+
openJson:
+
openLexer:
+
openParser:
+
openScope:
+
openShadowScope:
+
openSym:
+
openTex:
+
Operators:
+
opGorge:
+
opMapTypeImplToAst:
+
opMapTypeInstToAst:
+
opMapTypeToAst:
+
oprHigh:
+
oprLow:
+
opSlurp:
+
optAssert:
+
optBenchmarkVM:
+
optBoundsCheck:
+
optByRef:
+
optCDebug:
+
optCompileOnly:
+
optCursorInference:
+
optDeclaredLocs:
+
optDocInternal:
+
optDynlibOverrideAll:
+
optEmbedOrigSrc:
+
optEnableDeepCopy:
+
optExcessiveStackTrace:
+
optFieldCheck:
+
optForceFullMake:
+
optGenCDeps:
+
optGenDynLib:
+
optGenGuiApp:
+
optGenIndex:
+
optGenIndexOnly:
+
optGenMapping:
+
optGenScript:
+
optGenStaticLib:
+
optHints:
+
optHotCodeReloading:
+
optIdeDebug:
+
optIdeExceptionInlayHints:
+
optIdeTerse:
+
optimize:
+
optImplicitStatic:
+
optImportHidden:
+
optInd:
+
optInfCheck:
+
optJsBigInt64:
+
optLineDir:
+
optLineTrace:
+
optListCmd:
+
optMemTracker:
+
optMixedMode:
+
optMultiMethods:
+
optNaNCheck:
+
optNoImportdoc:
+
optNoLinking:
+
optNoMain:
+
optNone:
+
optNoNimblePath:
+
optObjCheck:
+
optOptimizeSize:
+
optOptimizeSpeed:
+
optOverflowCheck:
+
optOwnedRefs:
+
optPanics:
+
optPar:
+
optPreserveOrigSource:
+
optProduceAsm:
+
optProfiler:
+
optProfileVM:
+
optQuirky:
+
optRangeCheck:
+
optRefCheck:
+
optRun:
+
optSeqDestructors:
+
optShowAllMismatches:
+
optShowNonExportedFields:
+
optSinkInference:
+
optSkipParentConfigFiles:
+
optSkipProjConfigFile:
+
optSkipSystemConfigFile:
+
optSkipUserConfigFile:
+
optSourcemap:
+
optStackTrace:
+
optStackTraceMsgs:
+
optStaticBoundsCheck:
+
optStdout:
+
optStyleCheck:
+
optStyleError:
+
optStyleHint:
+
optStyleUsages:
+
optThreadAnalysis:
+
optThreads:
+
optTinyRtti:
+
optTlsEmulation:
+
optTrMacros:
+
optUseColors:
+
optUseNimcache:
+
optWarns:
+
optWasNimscript:
+
optWholeProject:
+
OrdinalType:
+
ordinalValToString:
+
originatingModule:
+
OS:
+
osAix:
+
osAmiga:
+
osAndroid:
+
osAny:
+
osAtari:
+
osCrossos:
+
osDos:
+
osDragonfly:
+
osFreebsd:
+
osFreeRTOS:
+
osGenode:
+
osHaiku:
+
osIos:
+
osIrix:
+
osJS:
+
osLinux:
+
osMacos:
+
osMacosx:
+
osMorphos:
+
osNetbsd:
+
osNetware:
+
osNimVM:
+
osNintendoSwitch:
+
osNone:
+
osNuttX:
+
osOpenbsd:
+
osOs2:
+
osPalmos:
+
ospCaseInsensitive:
+
ospLacksThreadVars:
+
ospNeedsPIC:
+
ospPosix:
+
osQnx:
+
osSkyos:
+
osSolaris:
+
osStandalone:
+
osVxWorks:
+
osWindows:
+
osZephyr:
+
outdated:
+
overlap:
+
overloadableEnums:
+
OverloadableSyms:
+
owner:
+
pack:
+
PackageModuleId:
+
PackedBoolArray:
+
PackedConfig:
+
PackedDecoder:
+
PackedEncoder:
+
PackedInstantiation:
+
PackedItemId:
+
PackedLib:
+
PackedLineInfo:
+
PackedModule:
+
PackedModuleGraph:
+
PackedNode:
+
packedRepr:
+
PackedSym:
+
PackedTree:
+
PackedType:
+
pairs:
+
parallel:
+
paramName:
+
paramPragmas:
+
paramsEqual:
+
paramsIncompatible:
+
paramsLen:
+
paramsNotEqual:
+
paramsPos:
+
paramTypePairs:
+
paramTypes:
+
paramTypesMatch:
+
paramTypeToNodeIndex:
+
parent:
+
Parent:
+
parentModule:
+
parLineInfo:
+
parMessage:
+
parse:
+
parseAll:
+
parseCommand:
+
parseDecimalInt128:
+
parseFile:
+
parseIdeCmd:
+
Parser:
+
parseString:
+
parseSymbol:
+
parseTopLevelStmt:
+
partialInitModule:
+
partialMatch:
+
Partitions:
+
passCmd1:
+
passCmd2:
+
passPP:
+
patch:
+
PathKinds0:
+
PathKinds1:
+
pathSubs:
+
patternPos:
+
pcmDifferentCallConv:
+
pcmNoSideEffect:
+
pcmNotGcSafe:
+
pcmNotIterator:
+
PContext:
+
PCtx:
+
PDoc:
+
PersistentNodeFlags:
+
PEvalContext:
+
pickSym:
+
PickyBackendAliases:
+
PickyCAliases:
+
PIdent:
+
PInstantiation:
+
PipelinePass:
+
PLib:
+
PLLStream:
+
Plugin:
+
pluginMatches:
+
PNode:
+
popCaseContext:
+
popInfoContext:
+
popOptionEntry:
+
popOwner:
+
popProcCon:
+
POptionEntry:
+
PPassContext:
+
PProc:
+
PProcCon:
+
pragma:
+
pragmaAsm:
+
pragmaCallable:
+
pragmaNoForward:
+
pragmasEffects:
+
pragmasPos:
+
pragmaToOptions:
+
preferDesc:
+
preferExported:
+
preferGenericArg:
+
preferInferredEffects:
+
preferInlayHint:
+
preferMixed:
+
preferModuleInfo:
+
preferName:
+
preferResolved:
+
preferTypeName:
+
PrefixMatch:
+
prefixMatch:
+
prepare:
+
prepareConfigNotes:
+
prepareMetatypeForSigmatch:
+
prepareNode:
+
preparePContext:
+
prepareToWriteOutput:
+
prepareTypesInBody:
+
prePass:
+
prepend:
+
prependCurDir:
+
presentationPath:
+
prettyTok:
+
preventStackTrace:
+
previouslyInferred:
+
printTok:
+
ProcConvMismatch:
+
procDefs:
+
processArgument:
+
processCmdLineAndProjectPath:
+
processCommand:
+
processImplicitImports:
+
processJSCodeGen:
+
processNode:
+
processNodeJson:
+
processPipelineModule:
+
processPopBackendOption:
+
processPushBackendOption:
+
processSpecificNote:
+
processSwitch:
+
procInstCacheItems:
+
procInstCacheSection:
+
procPragmas:
+
procSec:
+
procTypePragmas:
+
produceDestructorForDiscriminator:
+
ProfileData:
+
ProfileInfo:
+
Profiler:
+
propagateToOwner:
+
propSpec:
+
proveLe:
+
PScope:
+
PStackFrame:
+
PSym:
+
PtrLikeKinds:
+
PType:
+
pureEnumsSection:
+
pushCaseContext:
+
pushInfoContext:
+
pushOptionEntry:
+
pushOwner:
+
pushProcCon:
+
put:
+
qualifiedLookUp:
+
quitOrRaise:
+
quotedFilename:
+
quoteExpr:
+
quoteShell:
+
raiseRecoverableError:
+
rangeHasUnresolvedStatic:
+
rawAddField:
+
rawAddSon:
+
rawCloseScope:
+
rawDirectAccess:
+
rawGetTok:
+
rawIndirectAccess:
+
rawMessage:
+
RawTypeMismatchError:
+
readConfigFile:
+
readExceptSet:
+
readOnlySf:
+
recomputeFieldPositions:
+
recordAdd:
+
recordInc:
+
recordIncl:
+
recordPut:
+
reexportsSection:
+
reexportSym:
+
refresh:
+
regA:
+
regAMask:
+
regAShift:
+
regB:
+
regBMask:
+
regBShift:
+
regBx:
+
regBxMask:
+
regBxMax:
+
regBxMin:
+
regBxShift:
+
regC:
+
regCMask:
+
regCShift:
+
registerAdditionalOps:
+
registerCallback:
+
registerCompilerProc:
+
registerInitProcs:
+
registerModule:
+
registerModuleById:
+
registerNimScriptSymbol:
+
regOMask:
+
regOShift:
+
RelativeDir:
+
RelativeFile:
+
relativeJumps:
+
relativeTo:
+
relevantCol:
+
rememberEmittedTypeInfo:
+
rememberExpansion:
+
rememberFlag:
+
rememberStartupConfig:
+
removeFile:
+
removeTrailingDirSep:
+
renderDefinitionName:
+
renderDocComments:
+
renderExpandUsing:
+
renderIds:
+
renderIr:
+
renderModule:
+
renderNoBody:
+
renderNoComments:
+
renderNone:
+
renderNonExportedFields:
+
renderNoPostfix:
+
renderNoPragmas:
+
renderNoProcDefs:
+
renderOutType:
+
renderParamNames:
+
renderParamTypes:
+
renderPlainSymbolName:
+
renderRunnableExamples:
+
renderSyms:
+
renderTree:
+
reorder:
+
replaceFirstSon:
+
replaceSon:
+
replaceTypesInBody:
+
replaceTypeVarsN:
+
replaceTypeVarsT:
+
replayBackendProcs:
+
replayGenericCacheInformation:
+
replayStateChanges:
+
requiresEffects:
+
requiresInit:
+
resetAllModules:
+
resetCompilationLists:
+
resetForBackend:
+
resetIdentCache:
+
resetIdTable:
+
resetNimScriptSymbols:
+
resetRopeCache:
+
resetSystemArtifacts:
+
resetSysTypes:
+
resolveAttachedOp:
+
resolveMod:
+
resultPos:
+
returnType:
+
reverse:
+
rkFloat:
+
rkInt:
+
rkNode:
+
rkNodeAddr:
+
rkNone:
+
rkRegisterAddr:
+
RodExt:
+
RodFile:
+
RodFileError:
+
RodFileVersion:
+
RodIter:
+
RodSection:
+
rodViewer:
+
Rope:
+
rope:
+
routineDefs:
+
routineKinds:
+
rstWarnings:
+
runJsonBuildInstructions:
+
runNimScript:
+
runtimeFormat:
+
s:
+
Safe:
+
safeArrLen:
+
safeInheritanceDiff:
+
safeLen:
+
safeSemExpr:
+
safeSkipTypes:
+
sameBackendType:
+
sameBackendTypeIgnoreRange:
+
sameBackendTypePickyAliases:
+
sameConstant:
+
sameDistinctTypes:
+
sameEnumTypes:
+
sameFlags:
+
sameLocation:
+
sameObjectTypes:
+
sameSubexprs:
+
sameTree:
+
sameTrees:
+
sameTupleLengths:
+
sameType:
+
sameTypeOrNil:
+
sameValue:
+
saveRodFile:
+
scopeDepth:
+
sealRodFile:
+
searchForCompilerproc:
+
searchForProc:
+
searchInScopes:
+
searchInScopesAllCandidatesFilterBy:
+
searchInScopesFilterBy:
+
searchInstTypes:
+
searchTypeFor:
+
secondSon:
+
semAsmOrEmit:
+
semCaptureSym:
+
semConceptDeclaration:
+
semNodeKindConstraints:
+
SemPass:
+
semtabAll:
+
semWithPContext:
+
seNoSideEffect:
+
seSideEffect:
+
setAttachedOp:
+
setAttachedOpPartial:
+
setBaseFlags:
+
setCaseContextIdx:
+
setCC:
+
setCmd:
+
setCommandEarly:
+
setConfigVar:
+
setDefaultLibpath:
+
setDirtyFile:
+
setEffectsForProcType:
+
setErrorMaxHighMaybe:
+
setFromProjectName:
+
setGlobalValue:
+
setHash:
+
setHasRange:
+
setIndexType:
+
setInfoContextLen:
+
setInfoRecursive:
+
setIntLitType:
+
setLastSon:
+
setMethodsPerType:
+
setNote:
+
setNoteDefaults:
+
setOutFile:
+
setOwner:
+
setPipeLinePass:
+
setResult:
+
setReturnType:
+
setSon:
+
setSons:
+
setSonsLen:
+
setTarget:
+
setTargetFromSystem:
+
setToPreviousLayer:
+
setToStringProc:
+
setupCgen:
+
setupCompileTimeVar:
+
setupDependPass:
+
setupEvalGen:
+
setupGlobalCtx:
+
setupJSgen:
+
setupParser:
+
setupVM:
+
setUseIc:
+
seUnknown:
+
Severity:
+
sfAddrTaken:
+
sfAllUntyped:
+
sfAnon:
+
sfBase:
+
sfBorrow:
+
sfByCopy:
+
sfCallsite:
+
sfCodegenDecl:
+
sfCompilerProc:
+
sfCompileTime:
+
sfCompileToCpp:
+
sfCompileToObjc:
+
sfConstructor:
+
sfCppMember:
+
sfCppNonPod:
+
sfCursor:
+
sfCustomPragma:
+
sfDeprecated:
+
sfDirty:
+
sfDiscardable:
+
sfDiscriminant:
+
sfDispatcher:
+
sfEffectsDelayed:
+
sfError:
+
sfEscapes:
+
sfExperimental:
+
sfExplain:
+
sfExportc:
+
sfExported:
+
sfForceLift:
+
sfForward:
+
sfFromGeneric:
+
sfGeneratedOp:
+
sfGeneratedType:
+
sfGenSym:
+
sfGlobal:
+
sfGoto:
+
sfImportc:
+
sfInfixCall:
+
sfInjectDestructors:
+
sfMainModule:
+
sfMangleCpp:
+
sfMember:
+
sfNamedParamCall:
+
sfNeverRaises:
+
sfNoalias:
+
sfNoForward:
+
sfNoInit:
+
sfNonReloadable:
+
sfNoReturn:
+
sfNoSideEffect:
+
sfOverridden:
+
sfPure:
+
sfRegister:
+
sfReorder:
+
sfRequiresInit:
+
sfShadowed:
+
sfSideEffect:
+
sfSingleUsedTemp:
+
sfSystemModule:
+
sfSystemRaisesDefect:
+
sfTemplateParam:
+
sfTemplateRedefinition:
+
sfThread:
+
sfUsed:
+
sfUsedInFinallyOrExcept:
+
sfVirtual:
+
sfVolatile:
+
sfWasForwarded:
+
sfWasGenSym:
+
sfWrittenTo:
+
shallowCopy:
+
showNonExportedFields:
+
sideChannelSection:
+
SigHash:
+
sigHash:
+
signature:
+
signatureLen:
+
sihkException:
+
sihkParameter:
+
sihkType:
+
simpleSlice:
+
simulateLoadedModule:
+
sizeOnDisc:
+
skConditional:
+
skConst:
+
skConverter:
+
skDynLib:
+
skEnumField:
+
skError:
+
skField:
+
skForVar:
+
skFunc:
+
skGenericParam:
+
skipAddr:
+
skipCodegen:
+
skipColon:
+
skipComment:
+
skipConv:
+
skipConvCastAndClosure:
+
skipConvDfa:
+
skipConvTakeType:
+
skipGenericAlias:
+
skipGenericOwner:
+
skipHidden:
+
skipHiddenAddr:
+
skipHiddenSubConv:
+
skipInd:
+
skipIntLit:
+
skipIntLiteralParams:
+
skipModifier:
+
skipPragmaExpr:
+
skipPtrs:
+
skipStmtList:
+
skipTypes:
+
skipTypesOrNil:
+
skIterator:
+
skLabel:
+
skLet:
+
skLocalVars:
+
skMacro:
+
skMethod:
+
skModule:
+
skPackage:
+
skParam:
+
skProc:
+
skProcKinds:
+
skResult:
+
skStub:
+
skTemp:
+
skTemplate:
+
skType:
+
skUnknown:
+
skVar:
+
slotEmpty:
+
slotFixedLet:
+
slotFixedVar:
+
slotSomeTemp:
+
slotTempComplex:
+
slotTempFloat:
+
slotTempInt:
+
slotTempPerm:
+
slotTempStr:
+
slotTempUnknown:
+
Snippet:
+
someInSet:
+
someSym:
+
someSymAmb:
+
someSymFromImportTable:
+
sons:
+
sons2:
+
sons3:
+
sonsFrom1:
+
sonsReadonly:
+
sonsWithoutLast2:
+
soperand:
+
sort:
+
sortBucket:
+
sortVTableDispatchers:
+
sourceLine:
+
SourceMap:
+
span:
+
spawnResult:
+
spellSuggestSecretSauce:
+
splitFile:
+
srByVar:
+
srFlowVar:
+
srVoid:
+
StartSize:
+
stdlibDirs:
+
StdOrrKind:
+
stdOrrStderr:
+
stdOrrStdout:
+
stdPrefix:
+
stmtPragmas:
+
stmtPragmasTopLevel:
+
stmtsContainPragma:
+
stopCompile:
+
store:
+
storeAny:
+
storeAttachedProcDef:
+
stored:
+
storeExpansion:
+
storeHeader:
+
storeInstantiation:
+
storeOrderedTable:
+
storePrim:
+
storeRodNode:
+
storeSection:
+
storeSeq:
+
storeSym:
+
storeTypeInst:
+
storing:
+
strArg:
+
stressTest:
+
strictCaseObjects:
+
strictDefs:
+
strictEffects:
+
strictFuncs:
+
strictNotNil:
+
stringsSection:
+
strTableAdd:
+
strTableAdds:
+
strTableContains:
+
strTableGet:
+
strTableIncl:
+
strTableInclReportConflict:
+
StructuralEquivTypes:
+
stupidStmtListExpr:
+
styleCheckDef:
+
styleCheckUse:
+
Suggest:
+
suggestDecl:
+
suggestEnum:
+
suggestErrorsIter:
+
suggestExpr:
+
suggestExprNoCheck:
+
SuggestFileSymbolDatabase:
+
SuggestInlayHint:
+
SuggestInlayHintKind:
+
Suggestions:
+
suggestPragmas:
+
suggestQuit:
+
suggestResult:
+
suggestSentinel:
+
suggestStmt:
+
suggestSym:
+
SuggestSymbolDatabase:
+
suggestSymbolsIter:
+
suggestToSuggestInlayExceptionHintLeft:
+
suggestToSuggestInlayExceptionHintRight:
+
suggestToSuggestInlayTypeHint:
+
suggestWriteln:
+
symBodyDigest:
+
SymbolFilesOption:
+
SymChars:
+
symdiffSets:
+
symFromType:
+
SymId:
+
symId:
+
SymInfoPair:
+
SymMapping:
+
symnamesSection:
+
symNodeFromType:
+
symsSection:
+
SymStartChars:
+
symTabReplace:
+
symToSuggest:
+
symToYaml:
+
systemModuleSym:
+
systemModuleSyms:
+
sysTypeFromName:
+
szIllegalRecursion:
+
szTooBigSize:
+
szUncomputedSize:
+
szUnknownSize:
+
Tabulator:
+
taConcept:
+
taField:
+
tagEffects:
+
TagsExt:
+
taHeap:
+
taIsCastable:
+
taIsDefaultField:
+
taIsOpenArray:
+
taIsTemplateOrMacro:
+
takeType:
+
TAliasRequest:
+
TAnalysisResult:
+
taNoUntyped:
+
taProcContextIsNotMacro:
+
Target:
+
targetSizeSignedToKind:
+
targetSizeUnsignedToKind:
+
TAssignableResult:
+
taVoid:
+
TBackend:
+
TBaseLexer:
+
TBitSet:
+
TBlock:
+
TBorrowState:
+
TCallingConvention:
+
TCandidate:
+
TCandidateState:
+
TCFileSection:
+
TCFileSections:
+
TCheckPointResult:
+
TCmdLinePass:
+
TContext:
+
TCProcFlag:
+
TCProcSection:
+
TCProcSections:
+
TCtx:
+
TCTypeKind:
+
TDest:
+
TDistinctCompare:
+
templatePragmas:
+
Ten:
+
TErrorHandling:
+
TErrorOutput:
+
TErrorOutputs:
+
testCompileOption:
+
testCompileOptionArg:
+
TEvalMode:
+
TexExt:
+
TExprFlag:
+
TExprFlags:
+
tfAcyclic:
+
tfBorrowDot:
+
tfByCopy:
+
tfByRef:
+
tfCapturesEnv:
+
tfCheckedForDestructor:
+
tfCompleteStruct:
+
tfConceptMatchedTypeSym:
+
tfContravariant:
+
tfCovariant:
+
tfEffectSystemWorkaround:
+
tfEnumHasHoles:
+
tfExplicit:
+
tfExplicitCallConv:
+
tfFinal:
+
tfFromGeneric:
+
tfGcSafe:
+
tfGenericHasDestructor:
+
tfGenericTypeParam:
+
tfHasAsgn:
+
tfHasGCedMem:
+
tfHasMeta:
+
tfHasOwned:
+
tfHasStatic:
+
TFileInfo:
+
tfImplicitStatic:
+
tfImplicitTypeParam:
+
tfIncompleteStruct:
+
tfInferrableStatic:
+
tfInheritable:
+
tfIsConstructor:
+
tfIsOutParam:
+
tfIterator:
+
tfNeedsFullInit:
+
tfNonConstExpr:
+
tfNoSideEffect:
+
tfNotNil:
+
tfObjHasKids:
+
tfPacked:
+
tfPartial:
+
tfRefsAnonObj:
+
tfRequiresInit:
+
tfResolved:
+
tfRetType:
+
tfReturnsNew:
+
tfSendable:
+
tfShallow:
+
tfThread:
+
tfTriggersCompileTime:
+
TFullReg:
+
tfUnion:
+
tfUnresolved:
+
tfVarargs:
+
tfVarIsPtr:
+
tfWeakCovariant:
+
tfWildcard:
+
TGCMode:
+
TGlobalOption:
+
TGlobalOptions:
+
theindexFname:
+
threadVarAccessed:
+
TIdent:
+
TIdentIter:
+
TIIPair:
+
TIIPairSeq:
+
TIITable:
+
TImplication:
+
TInfoCC:
+
TInfoCCProp:
+
TInfoCCProps:
+
TInfoCPU:
+
TInfoOS:
+
TInfoOSProp:
+
TInfoOSProps:
+
TInstantiation:
+
TInstantiationPair:
+
TInstr:
+
TInstrType:
+
TinyLineInfo:
+
tkAccent:
+
tkAddr:
+
tkAnd:
+
tkAs:
+
tkAsm:
+
tkBind:
+
tkBlock:
+
tkBracketDotLe:
+
tkBracketDotRi:
+
tkBracketLe:
+
tkBracketLeColon:
+
tkBracketRi:
+
tkBreak:
+
tkCase:
+
tkCast:
+
tkCharLit:
+
tkColon:
+
tkColonColon:
+
tkComma:
+
tkComment:
+
tkConcept:
+
tkConst:
+
tkContinue:
+
tkConverter:
+
tkCurlyDotLe:
+
tkCurlyDotRi:
+
tkCurlyLe:
+
tkCurlyRi:
+
tkCustomLit:
+
tkDefer:
+
tkDiscard:
+
tkDistinct:
+
tkDiv:
+
tkDo:
+
tkDot:
+
tkDotDot:
+
tkElif:
+
tkElse:
+
tkEnd:
+
tkEnum:
+
tkEof:
+
tkEquals:
+
tkExcept:
+
tkExport:
+
tkFinally:
+
tkFloat128Lit:
+
tkFloat32Lit:
+
tkFloat64Lit:
+
tkFloatLit:
+
tkFor:
+
tkFrom:
+
tkFunc:
+
tkGStrLit:
+
tkGTripleStrLit:
+
tkHideableEnd:
+
tkHideableStart:
+
tkIf:
+
tkImport:
+
tkIn:
+
tkInclude:
+
tkInfixOpr:
+
tkInt16Lit:
+
tkInt32Lit:
+
tkInt64Lit:
+
tkInt8Lit:
+
tkInterface:
+
tkIntLit:
+
tkInvalid:
+
tkIs:
+
tkIsnot:
+
tkIterator:
+
tkLet:
+
tkMacro:
+
tkMethod:
+
tkMixin:
+
tkMod:
+
tkNil:
+
tkNot:
+
tkNotin:
+
tkObject:
+
tkOf:
+
tkOpr:
+
tkOr:
+
tkOut:
+
tkParDotLe:
+
tkParDotRi:
+
tkParLe:
+
tkParRi:
+
tkPostfixOpr:
+
tkPrefixOpr:
+
tkProc:
+
tkPtr:
+
tkRaise:
+
tkRef:
+
tkReturn:
+
tkRStrLit:
+
tkSemiColon:
+
tkShl:
+
tkShr:
+
tkSpaces:
+
tkStatic:
+
tkStrLit:
+
tkSymbol:
+
tkTemplate:
+
tkTripleStrLit:
+
tkTry:
+
tkTuple:
+
tkType:
+
tkUInt16Lit:
+
tkUInt32Lit:
+
tkUInt64Lit:
+
tkUInt8Lit:
+
tkUIntLit:
+
tkUsing:
+
tkVar:
+
tkWhen:
+
tkWhile:
+
tkXor:
+
tkYield:
+
TLabel:
+
TLib:
+
TLibKind:
+
TLineInfo:
+
TLLRepl:
+
TLLStream:
+
TLLStreamKind:
+
TLoc:
+
TLocFlag:
+
TLocFlags:
+
TLocKind:
+
TLookupFlag:
+
TMagic:
+
TMatchedConcept:
+
TModel:
+
TMsgKind:
+
TNode:
+
TNodeFlag:
+
TNodeFlags:
+
TNodeKind:
+
TNodeKinds:
+
TNodePair:
+
TNodePairSeq:
+
TNodeSeq:
+
TNodeTable:
+
TNoteKind:
+
TNoteKinds:
+
toAbsolute:
+
toAbsoluteDir:
+
toBitSet:
+
TObjectSeq:
+
TObjectSet:
+
toCChar:
+
toColumn:
+
toFileIndex:
+
toFileIndexCached:
+
toFileLineCol:
+
toFilename:
+
toFilenameOption:
+
toFloat64:
+
toFullPath:
+
toFullPathConsiderDirty:
+
toGeneratedFile:
+
toHex:
+
toHumanStr:
+
toInt:
+
toInt128:
+
toInt16:
+
toInt32:
+
toInt64:
+
toInt64Checked:
+
toInt8:
+
Token:
+
tokenize:
+
TokenSpacing:
+
tokKeywordHigh:
+
tokKeywordLow:
+
TokType:
+
TokTypes:
+
toLinenumber:
+
toLit:
+
toMsgFilename:
+
tooBig:
+
toObject:
+
toObjectFromRefPtrGeneric:
+
toObjFile:
+
toPackedGeneratedProcDef:
+
toPackedItemId:
+
toPackedNode:
+
toPackedNodeTopLevel:
+
TOpcode:
+
topLevelSection:
+
toProjPath:
+
TOption:
+
TOptionEntry:
+
TOptions:
+
toRef:
+
toReplaySection:
+
toRodFile:
+
toSourceMap:
+
toString:
+
toStrMaxPrecision:
+
toTimeLit:
+
toTreeSet:
+
toUInt:
+
toUInt16:
+
toUInt32:
+
toUInt64:
+
toUInt8:
+
toVar:
+
TOverloadIter:
+
TOverloadIterMode:
+
TPair:
+
TPairSeq:
+
TParamsEquality:
+
TPass:
+
TPassClose:
+
TPassContext:
+
TPassOpen:
+
TPassProcess:
+
TPosition:
+
TPreferedDesc:
+
TProcCon:
+
trackPosInvalidFileIdx:
+
trackProc:
+
trackStmt:
+
Transformation:
+
transformBody:
+
transformClosureIterator:
+
transformExpr:
+
TransformFlag:
+
TransformFlags:
+
transformStmt:
+
transitionGenericParamToType:
+
transitionIntKind:
+
transitionIntToFloatKind:
+
transitionNoneToSym:
+
transitionRoutineSymKind:
+
transitionSonsKind:
+
transitionSymKindCommon:
+
transitionToLet:
+
translateId:
+
trBindGenericParam:
+
trDontBind:
+
treeToYaml:
+
TRegister:
+
TRegisterKind:
+
TRenderFlag:
+
TRenderFlags:
+
TRenderTok:
+
TRenderTokSeq:
+
TReplTypeVars:
+
trIsOutParam:
+
trmacrosSection:
+
trNoCovariance:
+
truncateInferredTypeCandidates:
+
trySuggestPragmas:
+
TSandboxFlag:
+
TSandboxFlags:
+
TScope:
+
tsEof:
+
TSideEffectAnalysis:
+
tsLeading:
+
TSlotKind:
+
TSpawnResult:
+
TSpecialWord:
+
TSpecialWords:
+
TSrcGen:
+
TStackFrame:
+
TStorageLoc:
+
tsTrailing:
+
TStringSeq:
+
TStrTable:
+
TSym:
+
TSymFlag:
+
TSymFlags:
+
TSymKind:
+
TSymKinds:
+
TSystemCC:
+
TSystemCPU:
+
TSystemOS:
+
TTabIter:
+
TType:
+
TTypeAllowedFlag:
+
TTypeAllowedFlags:
+
TTypeAttachedOp:
+
TTypeCmpFlag:
+
TTypeCmpFlags:
+
TTypeFieldResult:
+
TTypeFlag:
+
TTypeFlags:
+
TTypeIter:
+
TTypeKind:
+
TTypeKinds:
+
TTypePredicate:
+
TTypeRelation:
+
TTypeRelFlag:
+
TTypeRelFlags:
+
TTypeSeq:
+
tupleTypePairs:
+
tyAlias:
+
tyAnd:
+
tyAnything:
+
tyArray:
+
tyBool:
+
tyBuiltInTypeClass:
+
tyChar:
+
tyCompositeTypeClass:
+
tyConcept:
+
tyCstring:
+
tyDistinct:
+
tyEmpty:
+
tyEnum:
+
tyError:
+
tyFloat:
+
tyFloat128:
+
tyFloat32:
+
tyFloat64:
+
tyForward:
+
tyFromExpr:
+
tyGenericBody:
+
tyGenericInst:
+
tyGenericInvocation:
+
tyGenericLike:
+
tyGenericParam:
+
tyInferred:
+
tyInt:
+
tyInt16:
+
tyInt32:
+
tyInt64:
+
tyInt8:
+
tyIterable:
+
tyLent:
+
tyMagicGenerics:
+
tyMetaTypes:
+
tyNil:
+
tyNone:
+
tyNot:
+
tyObject:
+
tyOpenArray:
+
tyOr:
+
tyOrdinal:
+
tyOwned:
+
typ:
+
typeAllowed:
+
typeBodyImpl:
+
typeBoundOps:
+
TypeCache:
+
TypeCacheWithOwner:
+
typeCompleted:
+
typedescInst:
+
typedescPtrs:
+
typeId:
+
typeInfoSection:
+
typeInstCacheItems:
+
typeInstCacheSection:
+
TypeMapping:
+
typeMismatch:
+
typeNameAndDesc:
+
typePragmas:
+
typeRel:
+
typesSection:
+
typeToString:
+
typeToYaml:
+
tyPointer:
+
tyProc:
+
typSym:
+
tyPtr:
+
tyPureObject:
+
tyRange:
+
tyRef:
+
tySequence:
+
tySet:
+
tySink:
+
tyStatic:
+
tyString:
+
tyTuple:
+
tyTypeClasses:
+
tyTyped:
+
tyTypeDesc:
+
tyUInt:
+
tyUInt16:
+
tyUInt32:
+
tyUInt64:
+
tyUInt8:
+
tyUncheckedArray:
+
tyUntyped:
+
tyUserDefinedGenerics:
+
tyUserTypeClass:
+
tyUserTypeClasses:
+
tyUserTypeClassInst:
+
tyVar:
+
tyVarargs:
+
tyVoid:
+
undefined:
+
undefSymbol:
+
underspecifiedPairs:
+
unicodeOperators:
+
unionSets:
+
uniqueModuleName:
+
uniqueSyms:
+
unknownLineInfo:
+
unmarkAllDirty:
+
unpack:
+
Unreachable:
+
unregisterArcOrc:
+
uoperand:
+
upName:
+
use:
+
useAliveDataFromDce:
+
useCache:
+
useEffectSystem:
+
userTypeClassInstParams:
+
usesThreadVars:
+
usesWriteBarrier:
+
useWriteTracking:
+
v2Sf:
+
varPragmas:
+
vccAndC:
+
verboseTypeMismatch:
+
Version:
+
VersionAsString:
+
versionSection:
+
views:
+
ViewTypeKind:
+
VmArgs:
+
VmCallback:
+
vmopsDanger:
+
VT:
+
vtables:
+
wAcyclic:
+
wAddr:
+
WaitingElseIf:
+
WaitingIf:
+
wAlign:
+
wAlignas:
+
wAlignof:
+
wAnd:
+
wantMainModule:
+
warnAboveMaxSizeSet:
+
warnAnyEnumConv:
+
warnBareExcept:
+
warnCannotOpen:
+
warnCannotOpenFile:
+
warnCaseTransition:
+
warnCastSizes:
+
warnCommentXIgnored:
+
warnConfigDeprecated:
+
warnCstringConv:
+
warnCycleCreated:
+
warnDeprecated:
+
warnDestructor:
+
warnDotLikeOps:
+
warnEachIdentIsTuple:
+
warnEffect:
+
warnFileChanged:
+
warnGcMem:
+
warnGcUnsafe:
+
warnGcUnsafe2:
+
warnGlobalVarConstructorTemporary:
+
warnHoleEnumConv:
+
warnIgnoredSymbolInjection:
+
warnImplicitDefaultValue:
+
warnImplicitTemplateRedefinition:
+
warnInconsistentSpacing:
+
warningDeprecated:
+
warnInheritFromException:
+
warnLockLevel:
+
warnMax:
+
warnMin:
+
warnObservableStores:
+
warnOctalEscape:
+
warnProveField:
+
warnProveIndex:
+
warnProveInit:
+
warnPtrToCstringConv:
+
warnResultShadowed:
+
warnResultUsed:
+
warnRstAmbiguousLink:
+
warnRstBrokenLink:
+
warnRstFieldXNotSupported:
+
warnRstLanguageXNotSupported:
+
warnRstRedefinitionOfLabel:
+
warnRstStyle:
+
warnRstUnknownSubstitutionX:
+
warnRstUnusedImportdoc:
+
warnSmallLshouldNotBeUsed:
+
warnStaticIndexCheck:
+
warnStdPrefix:
+
warnStmtListLambda:
+
warnStrictNotNil:
+
warnSuspiciousEnumConv:
+
warnTypelessParam:
+
warnUninit:
+
warnUnknownMagic:
+
warnUnnamedBreak:
+
warnUnreachableCode:
+
warnUnreachableElse:
+
warnUnsafeCode:
+
warnUnsafeDefault:
+
warnUnsafeSetLen:
+
warnUnusedImportX:
+
warnUseBase:
+
warnUser:
+
warnWriteToForeignHeap:
+
warnXIsNeverRead:
+
warnXmightNotBeenInit:
+
wAs:
+
wAsm:
+
wAsmNoStackFrame:
+
wAsmSyntax:
+
wAssert:
+
wAssertions:
+
wAssume:
+
wAuto:
+
wBase:
+
wBind:
+
wBitsize:
+
wBlock:
+
wBool:
+
wBoolDefine:
+
wBorrow:
+
wBoundChecks:
+
wBreak:
+
wByCopy:
+
wByRef:
+
wCallconv:
+
wCallsite:
+
wCase:
+
wCast:
+
wCatch:
+
wCdecl:
+
wChar:
+
wChar16:
+
wChar32:
+
wChecks:
+
wClass:
+
wClosure:
+
wCodegenDecl:
+
wColon:
+
wColonColon:
+
wCompile:
+
wCompilerProc:
+
wCompileTime:
+
wCompl:
+
wCompleteStruct:
+
wComputedGoto:
+
wConcept:
+
wConst:
+
wConstCast:
+
wConstexpr:
+
wConstructor:
+
wContinue:
+
wConverter:
+
wCore:
+
wCppNonPod:
+
wCursor:
+
wDeadCodeElimUnused:
+
wDebugger:
+
wDecltype:
+
wDefault:
+
wDefer:
+
wDefine:
+
wDelegator:
+
wDelete:
+
wDeprecated:
+
wDestructor:
+
wDirty:
+
wDiscard:
+
wDiscardable:
+
wDistinct:
+
wDiv:
+
wDo:
+
wDoctype:
+
wDot:
+
wDotDot:
+
wDouble:
+
wDynamicCast:
+
wDynlib:
+
weakLeValue:
+
wEffects:
+
wEffectsOf:
+
wElif:
+
wElse:
+
wEmit:
+
wEnd:
+
wEnforceNoRaises:
+
wEnsures:
+
wEnum:
+
wEquals:
+
wError:
+
wExcept:
+
wExecuteOnReload:
+
wExperimental:
+
wExplain:
+
wExplicit:
+
wExport:
+
wExportc:
+
wExportCpp:
+
wExportNims:
+
wExtern:
+
wFalse:
+
wFastcall:
+
wFatal:
+
wFieldChecks:
+
wFinal:
+
wFinally:
+
wFloat:
+
wFloatChecks:
+
wFor:
+
wForbids:
+
wFriend:
+
wFrom:
+
wFunc:
+
wGcSafe:
+
wGensym:
+
wGlobal:
+
wGoto:
+
wGuard:
+
wHeader:
+
whichAlias:
+
whichInitProcs:
+
whichKeyword:
+
whichPragma:
+
wHint:
+
wHintAsError:
+
wHints:
+
wIf:
+
wImmediate:
+
wImplicitStatic:
+
wImport:
+
wImportc:
+
wImportCompilerProc:
+
wImportCpp:
+
wImportHidden:
+
wImportJs:
+
wImportObjC:
+
wIn:
+
wInclude:
+
wIncompleteStruct:
+
wInfChecks:
+
wInheritable:
+
wInject:
+
wInline:
+
wInOut:
+
wInt:
+
wIntDefine:
+
wInterface:
+
wInvalid:
+
wInvariant:
+
wIs:
+
wIsnot:
+
wIterator:
+
withInfo:
+
wLet:
+
wLib:
+
wLiftLocals:
+
wLine:
+
wLinearScanEnd:
+
wLineDir:
+
wLineTrace:
+
wLink:
+
wLinksys:
+
wLocalPassc:
+
wLocks:
+
wLong:
+
wMacro:
+
wMagic:
+
wMember:
+
wMemTracker:
+
wMethod:
+
wMinus:
+
wMixin:
+
wMod:
+
wMutable:
+
wNamespace:
+
wNanChecks:
+
wNew:
+
wNil:
+
wNilChecks:
+
wNimcall:
+
wNoalias:
+
wNoconv:
+
wNodecl:
+
wNoDestroy:
+
wNoexcept:
+
wNoForward:
+
wNoInit:
+
wNoInline:
+
wNonReloadable:
+
wNoreturn:
+
wNoRewrite:
+
wNoSideEffect:
+
wNosinks:
+
wNot:
+
wNotin:
+
wNullptr:
+
wObjChecks:
+
wObject:
+
wOf:
+
wOff:
+
wOn:
+
wOneWay:
+
wOperator:
+
wOptimization:
+
wOr:
+
wordExcess:
+
wOut:
+
wOverflowChecks:
+
wOverride:
+
wPackage:
+
wPacked:
+
wPartial:
+
wPassc:
+
wPassl:
+
wPatterns:
+
wPop:
+
wPragma:
+
wPrivate:
+
wProc:
+
wProcVar:
+
wProfiler:
+
wProtected:
+
wPtr:
+
wPublic:
+
wPure:
+
wPush:
+
wQuirky:
+
wRaise:
+
wRaises:
+
wRangeChecks:
+
wrapInComesFrom:
+
wrapProcForSpawn:
+
wReads:
+
wRedefine:
+
wRef:
+
wRegister:
+
wReinterpretCast:
+
wReorder:
+
wRequires:
+
wRequiresInit:
+
wRestrict:
+
wReturn:
+
writeCommandLineUsage:
+
writeFile:
+
writeJsonBuildInstructions:
+
writeMapping:
+
writeMatches:
+
writeOnlySf:
+
writeOutput:
+
writeOutputJson:
+
writeRodFiles:
+
writeRope:
+
wrongHeader:
+
WrongNumberOfArguments:
+
wrongRedefinition:
+
wrongSection:
+
wRunnableExamples:
+
wSafecall:
+
wSafecode:
+
wSendable:
+
wShallow:
+
wShl:
+
wShort:
+
wShr:
+
wSideEffect:
+
wSigned:
+
wSinkInference:
+
wSize:
+
wSizeof:
+
wStackTrace:
+
wStar:
+
wStatic:
+
wStaticAssert:
+
wStaticBoundchecks:
+
wStaticCast:
+
wStdcall:
+
wStdErr:
+
wStdIn:
+
wStdOut:
+
wStrDefine:
+
wStruct:
+
wStyleChecks:
+
wSubsChar:
+
wSwitch:
+
wSyscall:
+
wSystemRaisesDefect:
+
wTags:
+
wTemplate:
+
wThis:
+
wThiscall:
+
wThread:
+
wThreadLocal:
+
wThreadVar:
+
wThrow:
+
wTrMacros:
+
wTrue:
+
wTry:
+
wTuple:
+
wType:
+
wTypedef:
+
wTypeid:
+
wTypename:
+
wTypeof:
+
wUnchecked:
+
wUncheckedAssign:
+
wUndef:
+
wUnderscore:
+
wUnion:
+
wUnroll:
+
wUnsigned:
+
wUsed:
+
wUsing:
+
wVar:
+
wVarargs:
+
wVirtual:
+
wVoid:
+
wVolatile:
+
wWarning:
+
wWarningAsError:
+
wWarnings:
+
wWchar:
+
wWhen:
+
wWhile:
+
wWrite:
+
wWrites:
+
wXor:
+
wYield:
+
yes:
+
Zero:
+
+ +
+
+ + + diff --git a/compiler/transf.html b/compiler/transf.html new file mode 100644 index 0000000000000..eb4238e8250c4 --- /dev/null +++ b/compiler/transf.html @@ -0,0 +1,229 @@ + + + + + + + +transf + + + + + + + + + + + + + + + + +
+
+

transf

+
+ +
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
TransformFlag = enum
+  useCache, keepOpenArrayConversions, force
+
+ + + Source   +Edit   + +
+
+
+
TransformFlags = set[TransformFlag]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc commonOptimizations(g: ModuleGraph; idgen: IdGenerator; c: PSym; n: PNode): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    TimeEffect], forbids: [].}
+
+ + Merges adjacent constant expressions of the children of the & call into a single constant expression. It also inlines constant expressions which are not complex. + Source   +Edit   + +
+
+ +
+
+
+
proc transformBody(g: ModuleGraph; idgen: IdGenerator; prc: PSym;
+                   flags: TransformFlags): PNode {....raises: [KeyError, Exception,
+    ValueError, IOError, ERecoverableError, OSError], tags: [ReadDirEffect,
+    RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect, TimeEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc transformExpr(g: ModuleGraph; idgen: IdGenerator; module: PSym; n: PNode;
+                   flags: TransformFlags = {}): PNode {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc transformStmt(g: ModuleGraph; idgen: IdGenerator; module: PSym; n: PNode;
+                   flags: TransformFlags = {}): PNode {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/transf.idx b/compiler/transf.idx new file mode 100644 index 0000000000000..8e2f649bc3bd2 --- /dev/null +++ b/compiler/transf.idx @@ -0,0 +1,10 @@ +nimTitle transf transf.html module transf 0 +nim useCache transf.html#useCache TransformFlag.useCache 33 +nim keepOpenArrayConversions transf.html#keepOpenArrayConversions TransformFlag.keepOpenArrayConversions 33 +nim force transf.html#force TransformFlag.force 33 +nim TransformFlag transf.html#TransformFlag enum TransformFlag 33 +nim TransformFlags transf.html#TransformFlags type TransformFlags 35 +nim transformBody transf.html#transformBody,ModuleGraph,IdGenerator,PSym,TransformFlags proc transformBody(g: ModuleGraph; idgen: IdGenerator; prc: PSym;\n flags: TransformFlags): PNode 37 +nim commonOptimizations transf.html#commonOptimizations,ModuleGraph,IdGenerator,PSym,PNode proc commonOptimizations(g: ModuleGraph; idgen: IdGenerator; c: PSym; n: PNode): PNode 984 +nim transformStmt transf.html#transformStmt,ModuleGraph,IdGenerator,PSym,PNode,TransformFlags proc transformStmt(g: ModuleGraph; idgen: IdGenerator; module: PSym; n: PNode;\n flags: TransformFlags = {}): PNode 1264 +nim transformExpr transf.html#transformExpr,ModuleGraph,IdGenerator,PSym,PNode,TransformFlags proc transformExpr(g: ModuleGraph; idgen: IdGenerator; module: PSym; n: PNode;\n flags: TransformFlags = {}): PNode 1274 diff --git a/compiler/trees.html b/compiler/trees.html new file mode 100644 index 0000000000000..81bbddbb85cac --- /dev/null +++ b/compiler/trees.html @@ -0,0 +1,449 @@ + + + + + + + +trees + + + + + + + + + + + + + + + + +
+
+

trees

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ ast, wordrecg, idents +
+
+
+

Procs

+
+
+
+
proc cyclicTree(n: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc dontInlineConstant(orig, cnst: PNode): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc effectSpec(n: PNode; effectType: TSpecialWord): PNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc exprStructuralEquivalent(a, b: PNode; strictSymEquality = false): bool {.
+    ...raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc extractRange(k: TNodeKind; n: PNode; a, b: int): PNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc findPragma(n: PNode; which: TSpecialWord): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc flattenStmts(n: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getMagic(op: PNode): TMagic {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getRoot(n: PNode): PSym {....raises: [], tags: [], forbids: [].}
+
+ + getRoot takes a path n. A path is an lvalue expression like obj.x[i].y. The root of a path is the symbol that can be determined as the owner; obj in the example. + Source   +Edit   + +
+
+ +
+
+
+
proc isCaseObj(n: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isConstExpr(n: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isDeepConstExpr(n: PNode; preventInheritance = false): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isNoSideEffectPragma(n: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isRange(n: PNode): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isRunnableExamples(n: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc propSpec(n: PNode; effectType: TSpecialWord): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sameTree(a, b: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipAddr(n: PNode): PNode {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc stupidStmtListExpr(n: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc whichPragma(n: PNode): TSpecialWord {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/trees.idx b/compiler/trees.idx new file mode 100644 index 0000000000000..e1e8da91c690d --- /dev/null +++ b/compiler/trees.idx @@ -0,0 +1,21 @@ +nimTitle trees trees.html module trees 0 +nim cyclicTree trees.html#cyclicTree,PNode proc cyclicTree(n: PNode): bool 26 +nim exprStructuralEquivalent trees.html#exprStructuralEquivalent,PNode,PNode proc exprStructuralEquivalent(a, b: PNode; strictSymEquality = false): bool 34 +nim sameTree trees.html#sameTree,PNode,PNode proc sameTree(a, b: PNode): bool 62 +nim getMagic trees.html#getMagic,PNode proc getMagic(op: PNode): TMagic 86 +nim isConstExpr trees.html#isConstExpr,PNode proc isConstExpr(n: PNode): bool 95 +nim isCaseObj trees.html#isCaseObj,PNode proc isCaseObj(n: PNode): bool 99 +nim isDeepConstExpr trees.html#isDeepConstExpr,PNode proc isDeepConstExpr(n: PNode; preventInheritance = false): bool 105 +nim isRange trees.html#isRange,PNode proc isRange(n: PNode): bool 129 +nim whichPragma trees.html#whichPragma,PNode proc whichPragma(n: PNode): TSpecialWord 142 +nim isNoSideEffectPragma trees.html#isNoSideEffectPragma,PNode proc isNoSideEffectPragma(n: PNode): bool 161 +nim findPragma trees.html#findPragma,PNode,TSpecialWord proc findPragma(n: PNode; which: TSpecialWord): PNode 167 +nim effectSpec trees.html#effectSpec,PNode,TSpecialWord proc effectSpec(n: PNode; effectType: TSpecialWord): PNode 174 +nim propSpec trees.html#propSpec,PNode,TSpecialWord proc propSpec(n: PNode; effectType: TSpecialWord): PNode 185 +nim flattenStmts trees.html#flattenStmts,PNode proc flattenStmts(n: PNode): PNode 198 +nim extractRange trees.html#extractRange,TNodeKind,PNode,int,int proc extractRange(k: TNodeKind; n: PNode; a, b: int): PNode 204 +nim getRoot trees.html#getRoot,PNode proc getRoot(n: PNode): PSym 208 +nim stupidStmtListExpr trees.html#stupidStmtListExpr,PNode proc stupidStmtListExpr(n: PNode): bool 228 +nim dontInlineConstant trees.html#dontInlineConstant,PNode,PNode proc dontInlineConstant(orig, cnst: PNode): bool 233 +nim isRunnableExamples trees.html#isRunnableExamples,PNode proc isRunnableExamples(n: PNode): bool 239 +nim skipAddr trees.html#skipAddr,PNode proc skipAddr(n: PNode): PNode 244 diff --git a/compiler/treetab.html b/compiler/treetab.html new file mode 100644 index 0000000000000..6afa77d3f15fa --- /dev/null +++ b/compiler/treetab.html @@ -0,0 +1,173 @@ + + + + + + + +treetab + + + + + + + + + + + + + + + + +
+
+

treetab

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ ast, astalgo, types +
+
+
+

Procs

+
+
+
+
proc hashTree(n: PNode): Hash {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nodeTableGet(t: TNodeTable; key: PNode): int {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nodeTablePut(t: var TNodeTable; key: PNode; val: int) {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nodeTableTestOrSet(t: var TNodeTable; key: PNode; val: int): int {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/treetab.idx b/compiler/treetab.idx new file mode 100644 index 0000000000000..1b39b5bc0a7ba --- /dev/null +++ b/compiler/treetab.idx @@ -0,0 +1,5 @@ +nimTitle treetab treetab.html module treetab 0 +nim hashTree treetab.html#hashTree,PNode proc hashTree(n: PNode): Hash 19 +nim nodeTableGet treetab.html#nodeTableGet,TNodeTable,PNode proc nodeTableGet(t: TNodeTable; key: PNode): int 75 +nim nodeTablePut treetab.html#nodeTablePut,TNodeTable,PNode,int proc nodeTablePut(t: var TNodeTable; key: PNode; val: int) 89 +nim nodeTableTestOrSet treetab.html#nodeTableTestOrSet,TNodeTable,PNode,int proc nodeTableTestOrSet(t: var TNodeTable; key: PNode; val: int): int 105 diff --git a/compiler/typeallowed.html b/compiler/typeallowed.html new file mode 100644 index 0000000000000..30f20e927500a --- /dev/null +++ b/compiler/typeallowed.html @@ -0,0 +1,227 @@ + + + + + + + +typeallowed + + + + + + + + + + + + + + + + +
+
+

typeallowed

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module contains 'typeAllowed' and friends which check for invalid types like openArray[var int].

+ +
+

Types

+
+
+
TTypeAllowedFlag = enum
+  taField, taHeap, taConcept, taIsOpenArray, taNoUntyped, taIsTemplateOrMacro,
+  taProcContextIsNotMacro, taIsCastable, taIsDefaultField, taVoid
+
+ + + Source   +Edit   + +
+
+
+
TTypeAllowedFlags = set[TTypeAllowedFlag]
+
+ + + Source   +Edit   + +
+
+
+
ViewTypeKind = enum
+  noView, immutableView, mutableView
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc classifyViewType(t: PType): ViewTypeKind {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc directViewType(t: PType): ViewTypeKind {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc requiresInit(t: PType): bool {....raises: [Exception], tags: [RootEffect],
+                                    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc typeAllowed(t: PType; kind: TSymKind; c: PContext;
+                 flags: TTypeAllowedFlags = {}): PType {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/typeallowed.idx b/compiler/typeallowed.idx new file mode 100644 index 0000000000000..2bd61c298f88b --- /dev/null +++ b/compiler/typeallowed.idx @@ -0,0 +1,21 @@ +nimTitle typeallowed typeallowed.html module typeallowed 0 +nim taField typeallowed.html#taField TTypeAllowedFlag.taField 20 +nim taHeap typeallowed.html#taHeap TTypeAllowedFlag.taHeap 20 +nim taConcept typeallowed.html#taConcept TTypeAllowedFlag.taConcept 20 +nim taIsOpenArray typeallowed.html#taIsOpenArray TTypeAllowedFlag.taIsOpenArray 20 +nim taNoUntyped typeallowed.html#taNoUntyped TTypeAllowedFlag.taNoUntyped 20 +nim taIsTemplateOrMacro typeallowed.html#taIsTemplateOrMacro TTypeAllowedFlag.taIsTemplateOrMacro 20 +nim taProcContextIsNotMacro typeallowed.html#taProcContextIsNotMacro TTypeAllowedFlag.taProcContextIsNotMacro 20 +nim taIsCastable typeallowed.html#taIsCastable TTypeAllowedFlag.taIsCastable 20 +nim taIsDefaultField typeallowed.html#taIsDefaultField TTypeAllowedFlag.taIsDefaultField 20 +nim taVoid typeallowed.html#taVoid TTypeAllowedFlag.taVoid 20 +nim TTypeAllowedFlag typeallowed.html#TTypeAllowedFlag enum TTypeAllowedFlag 20 +nim TTypeAllowedFlags typeallowed.html#TTypeAllowedFlags type TTypeAllowedFlags 32 +nim typeAllowed typeallowed.html#typeAllowed,PType,TSymKind,PContext,TTypeAllowedFlags proc typeAllowed(t: PType; kind: TSymKind; c: PContext; flags: TTypeAllowedFlags = {}): PType 213 +nim noView typeallowed.html#noView ViewTypeKind.noView 220 +nim immutableView typeallowed.html#immutableView ViewTypeKind.immutableView 220 +nim mutableView typeallowed.html#mutableView ViewTypeKind.mutableView 220 +nim ViewTypeKind typeallowed.html#ViewTypeKind enum ViewTypeKind 220 +nim classifyViewType typeallowed.html#classifyViewType,PType proc classifyViewType(t: PType): ViewTypeKind 275 +nim directViewType typeallowed.html#directViewType,PType proc directViewType(t: PType): ViewTypeKind 279 +nim requiresInit typeallowed.html#requiresInit,PType proc requiresInit(t: PType): bool 291 diff --git a/compiler/types.html b/compiler/types.html new file mode 100644 index 0000000000000..a6860fb09019c --- /dev/null +++ b/compiler/types.html @@ -0,0 +1,2170 @@ + + + + + + + +types + + + + + + + + + + + + + + + + +
+
+

types

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

code owner: Arne Döring e-mail: arne.doering@gmx.net included from types.nim

+ +
+

Types

+
+
+
EffectsCompat = enum
+  efCompat, efRaisesDiffer, efRaisesUnknown, efTagsDiffer, efTagsUnknown,
+  efEffectsDelayed, efTagsIllegal
+
+ + + Source   +Edit   + +
+
+
+
OffsetAccum = object
+  maxAlign*: int32
+  offset*: int32
+
+ + + Source   +Edit   + +
+
+
+
OrdinalType = enum
+  NoneLike, IntLike, FloatLike
+
+ + + Source   +Edit   + +
+
+
+
ProcConvMismatch = enum
+  pcmNoSideEffect, pcmNotGcSafe, pcmNotIterator, pcmDifferentCallConv
+
+ + + Source   +Edit   + +
+
+
+
TDistinctCompare = enum
+  dcEq,                     ## a and b should be the same type
+  dcEqIgnoreDistinct,       ## compare symmetrically: (distinct a) == b, a == b
+                             ## or a == (distinct b)
+  dcEqOrDistinctOf           ## a equals b or a is distinct of b
+
+ + how distinct types are to be compared + Source   +Edit   + +
+
+
+
TParamsEquality = enum
+  paramsNotEqual, paramsEqual, paramsIncompatible
+
+ + + Source   +Edit   + +
+
+
+
TPreferedDesc = enum
+  preferName, preferDesc, preferExported, preferModuleInfo, preferGenericArg,
+  preferTypeName, preferResolved, preferMixed, preferInlayHint,
+  preferInferredEffects
+
+ + + Source   +Edit   + +
+
+
+
TTypeCmpFlag = enum
+  IgnoreTupleFields,        ## NOTE: Only set this flag for backends!
+  IgnoreCC, ExactTypeDescValues, ExactGenericParams, ExactConstraints,
+  ExactGcSafety, AllowCommonBase, PickyCAliases, IgnoreFlags,
+  PickyBackendAliases, IgnoreRangeShallow
+
+ + + Source   +Edit   + +
+
+
+
TTypeCmpFlags = set[TTypeCmpFlag]
+
+ + + Source   +Edit   + +
+
+
+
TTypeFieldResult = enum
+  frNone, frHeader, frEmbedded
+
+ + + Source   +Edit   + +
+
+
+
TTypeIter = proc (t: PType; closure: RootRef): bool {.nimcall.}
+
+ + + Source   +Edit   + +
+
+
+
TTypePredicate = proc (t: PType): bool {.nimcall.}
+
+ + + Source   +Edit   + +
+
+
+
TTypeRelation = enum
+  isNone, isConvertible, isIntConv, isSubtype, isSubrange,
+  isBothMetaConvertible, isInferred, isInferredConvertible, isGeneric,
+  isFromIntLit, isEqual
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
abstractInstOwned = {tyAlias, tyTypeDesc, tyGenericInst, tyDistinct, tyOrdinal,
+                     tyOwned..tySink, tyInferred}
+
+ + + Source   +Edit   + +
+
+
+
abstractPtrs = {tyVar, tyPtr, tyRef, tyGenericInst, tyDistinct, tyOrdinal,
+                tyTypeDesc, tyAlias, tyInferred, tySink, tyLent, tyOwned}
+
+ + + Source   +Edit   + +
+
+
+
abstractRange = {tyGenericInst, tyRange, tyDistinct, tyOrdinal, tyTypeDesc,
+                 tyAlias, tyInferred, tySink, tyOwned}
+
+ + + Source   +Edit   + +
+
+
+
abstractVar = {tyVar, tyGenericInst, tyDistinct, tyOrdinal, tyTypeDesc, tyAlias,
+               tyInferred, tySink, tyLent, tyOwned}
+
+ + + Source   +Edit   + +
+
+
+
skipPtrs = {tyVar, tyPtr, tyRef, tyGenericInst, tyTypeDesc, tyAlias, tyInferred,
+            tySink, tyLent, tyOwned}
+
+ + + Source   +Edit   + +
+
+
+
szIllegalRecursion = -2
+
+ + + Source   +Edit   + +
+
+
+
szTooBigSize = -4
+
+ + + Source   +Edit   + +
+
+
+
szUncomputedSize = -1
+
+ + + Source   +Edit   + +
+
+
+
szUnknownSize = -3
+
+ + + Source   +Edit   + +
+
+
+
typedescInst = {tyAlias, tyTypeDesc, tyGenericInst, tyDistinct, tyOrdinal,
+                tyOwned..tySink, tyUserTypeClass, tyInferred}
+
+ + + Source   +Edit   + +
+
+
+
typedescPtrs = {tyAlias, tyTypeDesc, tyGenericInst, tyDistinct, tyOrdinal,
+                tyPtr..tyVar, tyOwned..tyLent, tyInferred}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc addPragmaAndCallConvMismatch(message: var string; formal, actual: PType;
+                                  conf: ConfigRef) {....raises: [ValueError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addTypeDeclVerboseMaybe(result: var string; conf: ConfigRef; typ: PType) {.
+    ...raises: [Exception, ValueError, KeyError],
+    tags: [RootEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addTypeHeader(result: var string; conf: ConfigRef; typ: PType;
+                   prefer: TPreferedDesc = preferMixed;
+                   getDeclarationPath = true) {.
+    ...raises: [Exception, ValueError, KeyError],
+    tags: [RootEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc align(arg: var OffsetAccum; value: int32) {.
+    ...raises: [IllegalTypeRecursionError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc analyseObjectWithTypeField(t: PType): TTypeFieldResult {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc baseOfDistinct(t: PType; g: ModuleGraph; idgen: IdGenerator): PType {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc canFormAcycle(g: ModuleGraph; typ: PType): bool {.
+    ...raises: [Exception, KeyError], tags: [RootEffect, ReadDirEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc classify(t: PType): OrdinalType {....raises: [], tags: [], forbids: [].}
+
+ + for convenient type checking: + Source   +Edit   + +
+
+ +
+
+
+
proc commonSuperclass(a, b: PType): PType {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc compareTypes(x, y: PType; cmp: TDistinctCompare = dcEq;
+                  flags: TTypeCmpFlags = {}): bool {.
+    ...raises: [KeyError, Exception, ValueError, ERecoverableError],
+    tags: [RootEffect], forbids: [].}
+
+ + compares two type for equality (modulo type distinction) + Source   +Edit   + +
+
+ +
+
+
+
proc compatibleEffects(formal, actual: PType): EffectsCompat {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc computeSize(conf: ConfigRef; typ: PType): BiggestInt {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc computeSizeAlign(conf: ConfigRef; typ: PType) {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, Exception, ValueError,
+    KeyError, IOError, ERecoverableError], tags: [RootEffect, ReadDirEffect,
+    WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc containsCompileTimeOnly(t: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc containsGarbageCollectedRef(typ: PType): bool {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc containsGenericType(t: PType): bool {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc containsHiddenPointer(typ: PType): bool {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc containsManagedMemory(typ: PType): bool {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc containsObject(t: PType): bool {....raises: [Exception], tags: [RootEffect],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc containsTyRef(typ: PType): bool {....raises: [Exception], tags: [RootEffect],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc containsUnresolvedType(t: PType): bool {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc elemType(t: PType): PType {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc enumHasHoles(t: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc equalParams(a, b: PNode): TParamsEquality {....raises: [Exception, KeyError],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc firstFloat(t: PType): BiggestFloat {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc firstOrd(conf: ConfigRef; t: PType): Int128 {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc floatRangeCheck(x: BiggestFloat; t: PType): bool {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genericAliasDepth(t: PType): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genericRoot(t: PType): PType {....raises: [], tags: [], forbids: [].}
+
+ + gets the root generic type (tyGenericBody) from t, if t is a generic type or the body of a generic instantiation + Source   +Edit   + +
+
+ +
+
+
+
proc getAlign(conf: ConfigRef; typ: PType): BiggestInt {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getFloatValue(n: PNode): BiggestFloat {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getOrdValue(n: PNode): Int128 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc getOrdValue(n: PNode; onError: Int128): Int128 {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getOrdValueAux(n: PNode; err: var bool): Int128 {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getProcConvMismatch(c: ConfigRef; f, a: PType; rel = isNone): (
+    set[ProcConvMismatch], TTypeRelation) {....raises: [], tags: [], forbids: [].}
+
+ + Returns a set of the reason of mismatch, and the relation for conversion. + Source   +Edit   + +
+
+ +
+
+
+
proc getProcHeader(conf: ConfigRef; sym: PSym;
+                   prefer: TPreferedDesc = preferName; getDeclarationPath = true): string {.
+    ...raises: [Exception, KeyError, ValueError],
+    tags: [RootEffect, ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getReturnType(s: PSym): PType {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getSize(conf: ConfigRef; typ: PType): BiggestInt {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inc(arg: var OffsetAccum; value: int32) {.
+    ...raises: [IllegalTypeRecursionError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inheritanceDiff(a, b: PType): int {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc invalidGenericInst(f: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isCharArrayPtr(t: PType; allowPointerToChar: bool): bool {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isCompileTimeOnly(t: PType): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isDefectException(t: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isDefectOrCatchableError(t: PType): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isEmptyContainer(t: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isException(t: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isFinal(t: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isFloatLit(t: PType): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isGenericAlias(t: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isIntLit(t: PType): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isOrdinalType(t: PType; allowEnumWithHoles: bool = false): bool {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isPureObject(typ: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isRefPtrObject(t: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isSinkTypeForParam(t: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isTupleRecursive(t: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isUnsigned(t: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc iterOverType(t: PType; iter: TTypeIter; closure: RootRef): bool {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lacksMTypeField(typ: PType): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lastFloat(t: PType): BiggestFloat {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lastOrd(conf: ConfigRef; t: PType): Int128 {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lengthOrd(conf: ConfigRef; t: PType): Int128 {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lookupFieldAgain(ty: PType; field: PSym): PSym {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nominalRoot(t: PType): PType {....raises: [], tags: [], forbids: [].}
+
+ +

the "name" type of a given instance of a nominal type, i.e. the type directly associated with the symbol where the root nominal type of t was defined, skipping things like generic instances, aliases, var/sink/typedesc modifiers

+

instead of returning the uninstantiated body of a generic type, returns the type of the symbol instead (with tyGenericBody type)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc normalizeKind(conf: ConfigRef; k: TTypeKind): TTypeKind {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc safeInheritanceDiff(a, b: PType): int {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc safeSkipTypes(t: PType; kinds: TTypeKinds): PType {....raises: [], tags: [],
+    forbids: [].}
+
+ + same as 'skipTypes' but with a simple cycle detector. + Source   +Edit   + +
+
+ +
+
+
+
proc sameBackendType(x, y: PType): bool {.
+    ...raises: [KeyError, Exception, ValueError, ERecoverableError],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sameBackendTypeIgnoreRange(x, y: PType): bool {.
+    ...raises: [KeyError, Exception, ValueError, ERecoverableError],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sameBackendTypePickyAliases(x, y: PType): bool {.
+    ...raises: [KeyError, Exception, ValueError, ERecoverableError],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sameDistinctTypes(a, b: PType): bool {.inline, ...raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sameEnumTypes(a, b: PType): bool {.inline, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sameFlags(a, b: PType): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sameObjectTypes(a, b: PType): bool {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sameType(a, b: PType; flags: TTypeCmpFlags = {}): bool {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sameTypeOrNil(a, b: PType; flags: TTypeCmpFlags = {}): bool {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc searchTypeFor(t: PType; predicate: TTypePredicate): bool {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipConv(n: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipConvTakeType(n: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipGenericAlias(t: PType): PType {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipHidden(n: PNode): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc skipHiddenSubConv(n: PNode; g: ModuleGraph; idgen: IdGenerator): PNode {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc takeType(formal, arg: PType; g: ModuleGraph; idgen: IdGenerator): PType {.
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc targetSizeSignedToKind(conf: ConfigRef): TTypeKind {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc targetSizeUnsignedToKind(conf: ConfigRef): TTypeKind {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc typeMismatch(conf: ConfigRef; info: TLineInfo; formal, actual: PType;
+                  n: PNode) {....raises: [Exception, KeyError, ValueError, IOError,
+                                       ERecoverableError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc typeNameAndDesc(t: PType): string {.
+    ...raises: [Exception, KeyError, ValueError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc typeToString(typ: PType; prefer: TPreferedDesc = preferName): string {.
+    ...raises: [Exception, KeyError, ValueError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template `$`(typ: PType): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template bindConcreteTypeToUserTypeClass(tc, concrete: PType)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template foldAlignOf(conf: ConfigRef; n: PNode; fallback: PNode): PNode
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template foldOffsetOf(conf: ConfigRef; n: PNode; fallback: PNode): PNode
+
+ + Returns an int literal node of the given offsetof expression in n. Falls back to fallback, if the offsetof expression can't be processed. + Source   +Edit   + +
+
+ +
+
+
+
template foldSizeOf(conf: ConfigRef; n: PNode; fallback: PNode): PNode
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template isResolvedUserTypeClass(t: PType): bool
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/types.idx b/compiler/types.idx new file mode 100644 index 0000000000000..c160ba9e47383 --- /dev/null +++ b/compiler/types.idx @@ -0,0 +1,175 @@ +nimTitle types types.html module types 0 +nim preferName types.html#preferName TPreferedDesc.preferName 22 +nim preferDesc types.html#preferDesc TPreferedDesc.preferDesc 22 +nim preferExported types.html#preferExported TPreferedDesc.preferExported 22 +nim preferModuleInfo types.html#preferModuleInfo TPreferedDesc.preferModuleInfo 22 +nim preferGenericArg types.html#preferGenericArg TPreferedDesc.preferGenericArg 22 +nim preferTypeName types.html#preferTypeName TPreferedDesc.preferTypeName 22 +nim preferResolved types.html#preferResolved TPreferedDesc.preferResolved 22 +nim preferMixed types.html#preferMixed TPreferedDesc.preferMixed 22 +nim preferInlayHint types.html#preferInlayHint TPreferedDesc.preferInlayHint 22 +nim preferInferredEffects types.html#preferInferredEffects TPreferedDesc.preferInferredEffects 22 +nim TPreferedDesc types.html#TPreferedDesc enum TPreferedDesc 22 +nim isNone types.html#isNone TTypeRelation.isNone 36 +nim isConvertible types.html#isConvertible TTypeRelation.isConvertible 36 +nim isIntConv types.html#isIntConv TTypeRelation.isIntConv 36 +nim isSubtype types.html#isSubtype TTypeRelation.isSubtype 36 +nim isSubrange types.html#isSubrange TTypeRelation.isSubrange 36 +nim isBothMetaConvertible types.html#isBothMetaConvertible TTypeRelation.isBothMetaConvertible 36 +nim isInferred types.html#isInferred TTypeRelation.isInferred 36 +nim isInferredConvertible types.html#isInferredConvertible TTypeRelation.isInferredConvertible 36 +nim isGeneric types.html#isGeneric TTypeRelation.isGeneric 36 +nim isFromIntLit types.html#isFromIntLit TTypeRelation.isFromIntLit 36 +nim isEqual types.html#isEqual TTypeRelation.isEqual 36 +nim TTypeRelation types.html#TTypeRelation enum TTypeRelation 36 +nim pcmNoSideEffect types.html#pcmNoSideEffect ProcConvMismatch.pcmNoSideEffect 52 +nim pcmNotGcSafe types.html#pcmNotGcSafe ProcConvMismatch.pcmNotGcSafe 52 +nim pcmNotIterator types.html#pcmNotIterator ProcConvMismatch.pcmNotIterator 52 +nim pcmDifferentCallConv types.html#pcmDifferentCallConv ProcConvMismatch.pcmDifferentCallConv 52 +nim ProcConvMismatch types.html#ProcConvMismatch enum ProcConvMismatch 52 +nim typeToString types.html#typeToString,PType,TPreferedDesc proc typeToString(typ: PType; prefer: TPreferedDesc = preferName): string 58 +nim addTypeDeclVerboseMaybe types.html#addTypeDeclVerboseMaybe,string,ConfigRef,PType proc addTypeDeclVerboseMaybe(result: var string; conf: ConfigRef; typ: PType) 60 +nim `$` types.html#$.t,PType template `$`(typ: PType): string 67 +nim TTypeIter types.html#TTypeIter type TTypeIter 71 +nim TTypePredicate types.html#TTypePredicate type TTypePredicate 72 +nim iterOverType types.html#iterOverType,PType,TTypeIter,RootRef proc iterOverType(t: PType; iter: TTypeIter; closure: RootRef): bool 74 +nim paramsNotEqual types.html#paramsNotEqual TParamsEquality.paramsNotEqual 78 +nim paramsEqual types.html#paramsEqual TParamsEquality.paramsEqual 78 +nim paramsIncompatible types.html#paramsIncompatible TParamsEquality.paramsIncompatible 78 +nim TParamsEquality types.html#TParamsEquality enum TParamsEquality 78 +nim equalParams types.html#equalParams,PNode,PNode proc equalParams(a, b: PNode): TParamsEquality 87 +nim abstractPtrs types.html#abstractPtrs const abstractPtrs 93 +nim abstractVar types.html#abstractVar const abstractVar 95 +nim abstractRange types.html#abstractRange const abstractRange 97 +nim abstractInstOwned types.html#abstractInstOwned const abstractInstOwned 99 +nim skipPtrs types.html#skipPtrs const skipPtrs 100 +nim typedescPtrs types.html#typedescPtrs const typedescPtrs 103 +nim typedescInst types.html#typedescInst const typedescInst 104 +nim invalidGenericInst types.html#invalidGenericInst,PType proc invalidGenericInst(f: PType): bool 106 +nim isPureObject types.html#isPureObject,PType proc isPureObject(typ: PType): bool 109 +nim isUnsigned types.html#isUnsigned,PType proc isUnsigned(t: PType): bool 115 +nim getOrdValueAux types.html#getOrdValueAux,PNode,bool proc getOrdValueAux(n: PNode; err: var bool): Int128 118 +nim getOrdValue types.html#getOrdValue,PNode proc getOrdValue(n: PNode): Int128 140 +nim getOrdValue types.html#getOrdValue,PNode,Int128 proc getOrdValue(n: PNode; onError: Int128): Int128 145 +nim getFloatValue types.html#getFloatValue,PNode proc getFloatValue(n: PNode): BiggestFloat 151 +nim isIntLit types.html#isIntLit,PType proc isIntLit(t: PType): bool 157 +nim isFloatLit types.html#isFloatLit,PType proc isFloatLit(t: PType): bool 160 +nim addTypeHeader types.html#addTypeHeader,string,ConfigRef,PType,TPreferedDesc proc addTypeHeader(result: var string; conf: ConfigRef; typ: PType;\n prefer: TPreferedDesc = preferMixed; getDeclarationPath = true) 163 +nim getProcHeader types.html#getProcHeader,ConfigRef,PSym,TPreferedDesc proc getProcHeader(conf: ConfigRef; sym: PSym; prefer: TPreferedDesc = preferName;\n getDeclarationPath = true): string 167 +nim elemType types.html#elemType,PType proc elemType(t: PType): PType 188 +nim enumHasHoles types.html#enumHasHoles,PType proc enumHasHoles(t: PType): bool 197 +nim isOrdinalType types.html#isOrdinalType,PType,bool proc isOrdinalType(t: PType; allowEnumWithHoles: bool = false): bool 201 +nim searchTypeFor types.html#searchTypeFor,PType,TTypePredicate proc searchTypeFor(t: PType; predicate: TTypePredicate): bool 298 +nim containsObject types.html#containsObject,PType proc containsObject(t: PType): bool 305 +nim frNone types.html#frNone TTypeFieldResult.frNone 314 +nim frHeader types.html#frHeader TTypeFieldResult.frHeader 314 +nim frEmbedded types.html#frEmbedded TTypeFieldResult.frEmbedded 314 +nim TTypeFieldResult types.html#TTypeFieldResult enum TTypeFieldResult 314 +nim analyseObjectWithTypeField types.html#analyseObjectWithTypeField,PType proc analyseObjectWithTypeField(t: PType): TTypeFieldResult 346 +nim containsGarbageCollectedRef types.html#containsGarbageCollectedRef,PType proc containsGarbageCollectedRef(typ: PType): bool 359 +nim containsManagedMemory types.html#containsManagedMemory,PType proc containsManagedMemory(typ: PType): bool 368 +nim containsTyRef types.html#containsTyRef,PType proc containsTyRef(typ: PType): bool 374 +nim containsHiddenPointer types.html#containsHiddenPointer,PType proc containsHiddenPointer(typ: PType): bool 381 +nim sameBackendType types.html#sameBackendType,PType,PType proc sameBackendType(x, y: PType): bool 404 +nim isFinal types.html#isFinal,PType proc isFinal(t: PType): bool 451 +nim canFormAcycle types.html#canFormAcycle,ModuleGraph,PType proc canFormAcycle(g: ModuleGraph; typ: PType): bool 455 +nim bindConcreteTypeToUserTypeClass types.html#bindConcreteTypeToUserTypeClass.t,PType,PType template bindConcreteTypeToUserTypeClass(tc, concrete: PType) 496 +nim isResolvedUserTypeClass types.html#isResolvedUserTypeClass.t,PType template isResolvedUserTypeClass(t: PType): bool 506 +nim firstOrd types.html#firstOrd,ConfigRef,PType proc firstOrd(conf: ConfigRef; t: PType): Int128 791 +nim firstFloat types.html#firstFloat,PType proc firstFloat(t: PType): BiggestFloat 842 +nim targetSizeSignedToKind types.html#targetSizeSignedToKind,ConfigRef proc targetSizeSignedToKind(conf: ConfigRef): TTypeKind 859 +nim targetSizeUnsignedToKind types.html#targetSizeUnsignedToKind,ConfigRef proc targetSizeUnsignedToKind(conf: ConfigRef): TTypeKind 866 +nim normalizeKind types.html#normalizeKind,ConfigRef,TTypeKind proc normalizeKind(conf: ConfigRef; k: TTypeKind): TTypeKind 873 +nim lastOrd types.html#lastOrd,ConfigRef,PType proc lastOrd(conf: ConfigRef; t: PType): Int128 882 +nim lastFloat types.html#lastFloat,PType proc lastFloat(t: PType): BiggestFloat 938 +nim floatRangeCheck types.html#floatRangeCheck,BiggestFloat,PType proc floatRangeCheck(x: BiggestFloat; t: PType): bool 955 +nim lengthOrd types.html#lengthOrd,ConfigRef,PType proc lengthOrd(conf: ConfigRef; t: PType): Int128 974 +nim dcEq types.html#dcEq TDistinctCompare.dcEq 985 +nim dcEqIgnoreDistinct types.html#dcEqIgnoreDistinct TDistinctCompare.dcEqIgnoreDistinct 985 +nim dcEqOrDistinctOf types.html#dcEqOrDistinctOf TDistinctCompare.dcEqOrDistinctOf 985 +nim TDistinctCompare types.html#TDistinctCompare enum TDistinctCompare 985 +nim IgnoreTupleFields types.html#IgnoreTupleFields TTypeCmpFlag.IgnoreTupleFields 991 +nim IgnoreCC types.html#IgnoreCC TTypeCmpFlag.IgnoreCC 991 +nim ExactTypeDescValues types.html#ExactTypeDescValues TTypeCmpFlag.ExactTypeDescValues 991 +nim ExactGenericParams types.html#ExactGenericParams TTypeCmpFlag.ExactGenericParams 991 +nim ExactConstraints types.html#ExactConstraints TTypeCmpFlag.ExactConstraints 991 +nim ExactGcSafety types.html#ExactGcSafety TTypeCmpFlag.ExactGcSafety 991 +nim AllowCommonBase types.html#AllowCommonBase TTypeCmpFlag.AllowCommonBase 991 +nim PickyCAliases types.html#PickyCAliases TTypeCmpFlag.PickyCAliases 991 +nim IgnoreFlags types.html#IgnoreFlags TTypeCmpFlag.IgnoreFlags 991 +nim PickyBackendAliases types.html#PickyBackendAliases TTypeCmpFlag.PickyBackendAliases 991 +nim IgnoreRangeShallow types.html#IgnoreRangeShallow TTypeCmpFlag.IgnoreRangeShallow 991 +nim TTypeCmpFlag types.html#TTypeCmpFlag enum TTypeCmpFlag 991 +nim TTypeCmpFlags types.html#TTypeCmpFlags type TTypeCmpFlags 1004 +nim sameType types.html#sameType,PType,PType,TTypeCmpFlags proc sameType(a, b: PType; flags: TTypeCmpFlags = {}): bool 1030 +nim sameTypeOrNil types.html#sameTypeOrNil,PType,PType,TTypeCmpFlags proc sameTypeOrNil(a, b: PType; flags: TTypeCmpFlags = {}): bool 1035 +nim sameObjectTypes types.html#sameObjectTypes,PType,PType proc sameObjectTypes(a, b: PType): bool 1147 +nim sameDistinctTypes types.html#sameDistinctTypes,PType,PType proc sameDistinctTypes(a, b: PType): bool 1153 +nim sameEnumTypes types.html#sameEnumTypes,PType,PType proc sameEnumTypes(a, b: PType): bool 1156 +nim isGenericAlias types.html#isGenericAlias,PType proc isGenericAlias(t: PType): bool 1203 +nim genericAliasDepth types.html#genericAliasDepth,PType proc genericAliasDepth(t: PType): int 1206 +nim skipGenericAlias types.html#skipGenericAlias,PType proc skipGenericAlias(t: PType): PType 1213 +nim sameFlags types.html#sameFlags,PType,PType proc sameFlags(a, b: PType): bool 1218 +nim sameBackendTypeIgnoreRange types.html#sameBackendTypeIgnoreRange,PType,PType proc sameBackendTypeIgnoreRange(x, y: PType): bool 1411 +nim sameBackendTypePickyAliases types.html#sameBackendTypePickyAliases,PType,PType proc sameBackendTypePickyAliases(x, y: PType): bool 1418 +nim compareTypes types.html#compareTypes,PType,PType,TDistinctCompare,TTypeCmpFlags proc compareTypes(x, y: PType; cmp: TDistinctCompare = dcEq;\n flags: TTypeCmpFlags = {}): bool 1424 +nim inheritanceDiff types.html#inheritanceDiff,PType,PType proc inheritanceDiff(a, b: PType): int 1435 +nim commonSuperclass types.html#commonSuperclass,PType,PType proc commonSuperclass(a, b: PType): PType 1459 +nim lacksMTypeField types.html#lacksMTypeField,PType proc lacksMTypeField(typ: PType): bool 1484 +nim szUnknownSize types.html#szUnknownSize const szUnknownSize 21 +nim szIllegalRecursion types.html#szIllegalRecursion const szIllegalRecursion 22 +nim szUncomputedSize types.html#szUncomputedSize const szUncomputedSize 23 +nim szTooBigSize types.html#szTooBigSize const szTooBigSize 24 +nim OffsetAccum types.html#OffsetAccum object OffsetAccum 32 +nim inc types.html#inc,OffsetAccum,int32 proc inc(arg: var OffsetAccum; value: int32) 36 +nim align types.html#align,OffsetAccum,int32 proc align(arg: var OffsetAccum; value: int32) 50 +nim computeSizeAlign types.html#computeSizeAlign,ConfigRef,PType proc computeSizeAlign(conf: ConfigRef; typ: PType) 76 +nim foldSizeOf types.html#foldSizeOf.t,ConfigRef,PNode,PNode template foldSizeOf(conf: ConfigRef; n: PNode; fallback: PNode): PNode 471 +nim foldAlignOf types.html#foldAlignOf.t,ConfigRef,PNode,PNode template foldAlignOf(conf: ConfigRef; n: PNode; fallback: PNode): PNode 485 +nim foldOffsetOf types.html#foldOffsetOf.t,ConfigRef,PNode,PNode template foldOffsetOf(conf: ConfigRef; n: PNode; fallback: PNode): PNode 499 +nim computeSize types.html#computeSize,ConfigRef,PType proc computeSize(conf: ConfigRef; typ: PType): BiggestInt 1489 +nim getReturnType types.html#getReturnType,PSym proc getReturnType(s: PSym): PType 1493 +nim getAlign types.html#getAlign,ConfigRef,PType proc getAlign(conf: ConfigRef; typ: PType): BiggestInt 1498 +nim getSize types.html#getSize,ConfigRef,PType proc getSize(conf: ConfigRef; typ: PType): BiggestInt 1502 +nim containsGenericType types.html#containsGenericType,PType proc containsGenericType(t: PType): bool 1519 +nim containsUnresolvedType types.html#containsUnresolvedType,PType proc containsUnresolvedType(t: PType): bool 1536 +nim baseOfDistinct types.html#baseOfDistinct,PType,ModuleGraph,IdGenerator proc baseOfDistinct(t: PType; g: ModuleGraph; idgen: IdGenerator): PType 1539 +nim safeInheritanceDiff types.html#safeInheritanceDiff,PType,PType proc safeInheritanceDiff(a, b: PType): int 1553 +nim isDefectException types.html#isDefectException,PType proc isDefectException(t: PType): bool 1570 +nim efCompat types.html#efCompat EffectsCompat.efCompat 1592 +nim efRaisesDiffer types.html#efRaisesDiffer EffectsCompat.efRaisesDiffer 1592 +nim efRaisesUnknown types.html#efRaisesUnknown EffectsCompat.efRaisesUnknown 1592 +nim efTagsDiffer types.html#efTagsDiffer EffectsCompat.efTagsDiffer 1592 +nim efTagsUnknown types.html#efTagsUnknown EffectsCompat.efTagsUnknown 1592 +nim efEffectsDelayed types.html#efEffectsDelayed EffectsCompat.efEffectsDelayed 1592 +nim efTagsIllegal types.html#efTagsIllegal EffectsCompat.efTagsIllegal 1592 +nim EffectsCompat types.html#EffectsCompat enum EffectsCompat 1592 +nim compatibleEffects types.html#compatibleEffects,PType,PType proc compatibleEffects(formal, actual: PType): EffectsCompat 1601 +nim isCompileTimeOnly types.html#isCompileTimeOnly,PType proc isCompileTimeOnly(t: PType): bool 1649 +nim containsCompileTimeOnly types.html#containsCompileTimeOnly,PType proc containsCompileTimeOnly(t: PType): bool 1652 +nim safeSkipTypes types.html#safeSkipTypes,PType,TTypeKinds proc safeSkipTypes(t: PType; kinds: TTypeKinds): PType 1659 +nim NoneLike types.html#NoneLike OrdinalType.NoneLike 1667 +nim IntLike types.html#IntLike OrdinalType.IntLike 1667 +nim FloatLike types.html#FloatLike OrdinalType.FloatLike 1667 +nim OrdinalType types.html#OrdinalType enum OrdinalType 1667 +nim classify types.html#classify,PType proc classify(t: PType): OrdinalType 1670 +nim skipConv types.html#skipConv,PNode proc skipConv(n: PNode): PNode 1681 +nim skipHidden types.html#skipHidden,PNode proc skipHidden(n: PNode): PNode 1694 +nim skipConvTakeType types.html#skipConvTakeType,PNode proc skipConvTakeType(n: PNode): PNode 1706 +nim isEmptyContainer types.html#isEmptyContainer,PType proc isEmptyContainer(t: PType): bool 1710 +nim takeType types.html#takeType,PType,PType,ModuleGraph,IdGenerator proc takeType(formal, arg: PType; g: ModuleGraph; idgen: IdGenerator): PType 1718 +nim skipHiddenSubConv types.html#skipHiddenSubConv,PNode,ModuleGraph,IdGenerator proc skipHiddenSubConv(n: PNode; g: ModuleGraph; idgen: IdGenerator): PNode 1735 +nim getProcConvMismatch types.html#getProcConvMismatch,ConfigRef,PType,PType proc getProcConvMismatch(c: ConfigRef; f, a: PType; rel = isNone): (\n set[ProcConvMismatch], TTypeRelation) 1752 +nim addPragmaAndCallConvMismatch types.html#addPragmaAndCallConvMismatch,string,PType,PType,ConfigRef proc addPragmaAndCallConvMismatch(message: var string; formal, actual: PType;\n conf: ConfigRef) 1783 +nim typeNameAndDesc types.html#typeNameAndDesc,PType proc typeNameAndDesc(t: PType): string 1822 +nim typeMismatch types.html#typeMismatch,ConfigRef,TLineInfo,PType,PType,PNode proc typeMismatch(conf: ConfigRef; info: TLineInfo; formal, actual: PType; n: PNode) 1829 +nim isTupleRecursive types.html#isTupleRecursive,PType proc isTupleRecursive(t: PType): bool 1882 +nim isException types.html#isException,PType proc isException(t: PType): bool 1886 +nim isDefectOrCatchableError types.html#isDefectOrCatchableError,PType proc isDefectOrCatchableError(t: PType): bool 1908 +nim isSinkTypeForParam types.html#isSinkTypeForParam,PType proc isSinkTypeForParam(t: PType): bool 1920 +nim lookupFieldAgain types.html#lookupFieldAgain,PType,PSym proc lookupFieldAgain(ty: PType; field: PSym): PSym 1931 +nim isCharArrayPtr types.html#isCharArrayPtr,PType,bool proc isCharArrayPtr(t: PType; allowPointerToChar: bool): bool 1942 +nim isRefPtrObject types.html#isRefPtrObject,PType proc isRefPtrObject(t: PType): bool 1959 +nim nominalRoot types.html#nominalRoot,PType proc nominalRoot(t: PType): PType 1962 +nim genericRoot types.html#genericRoot,PType proc genericRoot(t: PType): PType 2025 +nimgrp getordvalue types.html#getOrdValue-procs-all proc 140 diff --git a/compiler/typesrenderer.html b/compiler/typesrenderer.html new file mode 100644 index 0000000000000..64b8bb2d3a9c6 --- /dev/null +++ b/compiler/typesrenderer.html @@ -0,0 +1,216 @@ + + + + + + + +typesrenderer + + + + + + + + + + + + + + + + +
+
+

typesrenderer

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ renderer, ast, types +
+
+
+

Consts

+
+
+
defaultParamSeparator = ","
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc renderOutType(n: PNode; toNormalize = false): string {.
+    ...raises: [Exception, KeyError, ValueError], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc renderParamNames(n: PNode; toNormalize = false): seq[string] {.
+    ...raises: [Exception, KeyError], tags: [RootEffect], forbids: [].}
+
+ + Returns parameter names of routine n. + Source   +Edit   + +
+
+ +
+
+
+
proc renderParamTypes(found: var seq[string]; n: PNode; toNormalize = false) {.
+    ...raises: [Exception, KeyError, ValueError], tags: [RootEffect], forbids: [].}
+
+ +

Recursive helper, adds to found any types, or keeps diving the AST.

+

The normal doc generator doesn't include .typ information, so the function won't render types for parameters with default values. The doc generator does include the information.

+ + Source   +Edit   + +
+
+
+
proc renderParamTypes(n: PNode; sep = defaultParamSeparator; toNormalize = false): string {.
+    ...raises: [Exception, KeyError, ValueError], tags: [RootEffect], forbids: [].}
+
+ +

Returns the types contained in n joined by sep.

+

This proc expects to be passed as n the parameters of any callable. The string output is meant for the HTML renderer. If there are no parameters, the empty string is returned. The parameters will be joined by sep but other characters may appear too, like [] or |.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc renderPlainSymbolName(n: PNode): string {....raises: [], tags: [], forbids: [].}
+
+ +

Returns the first non '*' nkIdent node from the tree.

+

Use this on documentation name nodes to extract the raw symbol name, without decorations, parameters, or anything. That can be used as the base for the HTML hyperlinks.

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/typesrenderer.idx b/compiler/typesrenderer.idx new file mode 100644 index 0000000000000..cedd8d36a4fbb --- /dev/null +++ b/compiler/typesrenderer.idx @@ -0,0 +1,8 @@ +nimTitle typesrenderer typesrenderer.html module typesrenderer 0 +nim defaultParamSeparator typesrenderer.html#defaultParamSeparator const defaultParamSeparator 17 +nim renderPlainSymbolName typesrenderer.html#renderPlainSymbolName,PNode proc renderPlainSymbolName(n: PNode): string 25 +nim renderParamNames typesrenderer.html#renderParamNames,PNode proc renderParamNames(n: PNode; toNormalize = false): seq[string] 101 +nim renderParamTypes typesrenderer.html#renderParamTypes,seq[string],PNode proc renderParamTypes(found: var seq[string]; n: PNode; toNormalize = false) 119 +nim renderParamTypes typesrenderer.html#renderParamTypes,PNode proc renderParamTypes(n: PNode; sep = defaultParamSeparator; toNormalize = false): string 144 +nim renderOutType typesrenderer.html#renderOutType,PNode proc renderOutType(n: PNode; toNormalize = false): string 158 +nimgrp renderparamtypes typesrenderer.html#renderParamTypes-procs-all proc 119 diff --git a/compiler/varpartitions.html b/compiler/varpartitions.html new file mode 100644 index 0000000000000..b135115495208 --- /dev/null +++ b/compiler/varpartitions.html @@ -0,0 +1,252 @@ + + + + + + + +varpartitions + + + + + + + + + + + + + + + + +
+
+

varpartitions

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Partition variables into different graphs. Used for Nim's write tracking, borrow checking and also for the cursor inference. The algorithm is a reinvention / variation of Steensgaard's algorithm. The used data structure is "union find" with path compression.We perform two passes over the AST:

  • Pass one (computeLiveRanges): collect livetimes of local variables and whether they are potentially re-assigned.
  • +
  • Pass two (traverse): combine local variables to abstract "graphs". Strict func checking: Ensure that graphs that are connected to const parameters are not mutated. Cursor inference: Ensure that potential cursors are not borrowed from locations that are connected to a graph that is mutated during the liveness of the cursor. (We track all possible mutations of a graph.)
  • +
+

See https://nim-lang.github.io/Nim/manual_experimental.html#view-types-algorithm for a high-level description of how borrow checking works.

+

+ +
+

Types

+
+
+
Goal = enum
+  constParameters, borrowChecking, cursorInference
+
+ + + Source   +Edit   + +
+
+
+
MutationInfo = object
+
+ + + Source   +Edit   + +
+
+
+
Partitions = object
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(config: ConfigRef; g: MutationInfo): string {.
+    ...raises: [Exception, KeyError], tags: [RootEffect, ReadDirEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc checkBorrowedLocations(par: var Partitions; body: PNode; config: ConfigRef) {.
+    ...raises: [Exception, KeyError, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc computeCursors(s: PSym; n: PNode; g: ModuleGraph) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc computeGraphPartitions(s: PSym; n: PNode; g: ModuleGraph; goals: set[Goal]): Partitions {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasSideEffect(c: var Partitions; info: var MutationInfo): bool {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/varpartitions.idx b/compiler/varpartitions.idx new file mode 100644 index 0000000000000..76416d54a8f62 --- /dev/null +++ b/compiler/varpartitions.idx @@ -0,0 +1,12 @@ +nimTitle varpartitions varpartitions.html module varpartitions 0 +nim MutationInfo varpartitions.html#MutationInfo object MutationInfo 87 +nim constParameters varpartitions.html#constParameters Goal.constParameters 94 +nim borrowChecking varpartitions.html#borrowChecking Goal.borrowChecking 94 +nim cursorInference varpartitions.html#cursorInference Goal.cursorInference 94 +nim Goal varpartitions.html#Goal enum Goal 94 +nim Partitions varpartitions.html#Partitions object Partitions 99 +nim `$` varpartitions.html#$,ConfigRef,MutationInfo proc `$`(config: ConfigRef; g: MutationInfo): string 117 +nim hasSideEffect varpartitions.html#hasSideEffect,Partitions,MutationInfo proc hasSideEffect(c: var Partitions; info: var MutationInfo): bool 132 +nim computeGraphPartitions varpartitions.html#computeGraphPartitions,PSym,PNode,ModuleGraph,set[Goal] proc computeGraphPartitions(s: PSym; n: PNode; g: ModuleGraph; goals: set[Goal]): Partitions 929 +nim checkBorrowedLocations varpartitions.html#checkBorrowedLocations,Partitions,PNode,ConfigRef proc checkBorrowedLocations(par: var Partitions; body: PNode; config: ConfigRef) 974 +nim computeCursors varpartitions.html#computeCursors,PSym,PNode,ModuleGraph proc computeCursors(s: PSym; n: PNode; g: ModuleGraph) 1003 diff --git a/compiler/vm.html b/compiler/vm.html new file mode 100644 index 0000000000000..f274056f630b7 --- /dev/null +++ b/compiler/vm.html @@ -0,0 +1,652 @@ + + + + + + + +vm + + + + + + + + + + + + + + + + +
+
+

vm

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This file implements the new evaluation engine for Nim code. An instruction is 1-3 int32s in memory, it is a register based VM.

+ +
+

Procs

+
+
+
+
proc evalConstExpr(module: PSym; idgen: IdGenerator; g: ModuleGraph; e: PNode): PNode {....raises: [
+    Exception, ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    TimeEffect, ExecIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc evalExpr(c: PCtx; n: PNode): PNode {....raises: [Exception, ValueError,
+    KeyError, IOError, ERecoverableError, OSError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect, TimeEffect,
+    ExecIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc evalMacroCall(module: PSym; idgen: IdGenerator; g: ModuleGraph;
+                   templInstCounter: ref int; n, nOrig: PNode; sym: PSym): PNode {....raises: [
+    Exception, ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    TimeEffect, ExecIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc evalStaticExpr(module: PSym; idgen: IdGenerator; g: ModuleGraph; e: PNode;
+                    prc: PSym): PNode {....raises: [Exception, ValueError,
+    KeyError, IOError, ERecoverableError, OSError], tags: [RootEffect,
+    ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect, TimeEffect,
+    ExecIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc evalStaticStmt(module: PSym; idgen: IdGenerator; g: ModuleGraph; e: PNode;
+                    prc: PSym) {....raises: [Exception, ValueError, KeyError,
+    IOError, ERecoverableError, OSError], tags: [RootEffect, ReadDirEffect,
+    WriteIOEffect, ReadIOEffect, ReadEnvEffect, TimeEffect, ExecIOEffect],
+                                 forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc evalStmt(c: PCtx; n: PNode) {....raises: [Exception, ValueError, KeyError,
+    IOError, ERecoverableError, OSError], tags: [RootEffect, ReadDirEffect,
+    WriteIOEffect, ReadIOEffect, ReadEnvEffect, TimeEffect, ExecIOEffect],
+                                   forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc execProc(c: PCtx; sym: PSym; args: openArray[PNode]): PNode {....raises: [
+    Exception, ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    TimeEffect, ExecIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getBool(a: VmArgs; i: Natural): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getFloat(a: VmArgs; i: Natural): BiggestFloat {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getGlobalValue(c: PCtx; s: PSym): PNode {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getInt(a: VmArgs; i: Natural): BiggestInt {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getNode(a: VmArgs; i: Natural): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getNodeAddr(a: VmArgs; i: Natural): PNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getString(a: VmArgs; i: Natural): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getVar(a: VmArgs; i: Natural): PNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc interpreterCode(c: PPassContext; n: PNode): PNode {....raises: [Exception,
+    ValueError, KeyError, IOError, ERecoverableError, OSError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect,
+    TimeEffect, ExecIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc numArgs(a: VmArgs): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc registerAdditionalOps(c: PCtx) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setGlobalValue(c: PCtx; s: PSym; val: PNode) {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + Does not do type checking so ensure the val matches the s.typ + Source   +Edit   + +
+
+ +
+
+
+
proc setResult(a: VmArgs; n: PNode) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc setResult(a: VmArgs; v: (BiggestInt, BiggestInt)) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc setResult(a: VmArgs; v: AbsoluteDir) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc setResult(a: VmArgs; v: BiggestFloat) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc setResult(a: VmArgs; v: BiggestInt) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc setResult(a: VmArgs; v: bool) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc setResult(a: VmArgs; v: seq[string]) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc setResult(a: VmArgs; v: string) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setupCompileTimeVar(module: PSym; idgen: IdGenerator; g: ModuleGraph;
+                         n: PNode) {....raises: [Exception, ValueError, KeyError,
+    IOError, ERecoverableError, OSError], tags: [RootEffect, ReadDirEffect,
+    WriteIOEffect, ReadIOEffect, ReadEnvEffect, TimeEffect, ExecIOEffect],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setupEvalGen(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setupGlobalCtx(module: PSym; graph: ModuleGraph; idgen: IdGenerator) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator genericParamsInMacroCall(macroSym: PSym; call: PNode): (PSym, PNode) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/vm.idx b/compiler/vm.idx new file mode 100644 index 0000000000000..1a43c78e98302 --- /dev/null +++ b/compiler/vm.idx @@ -0,0 +1,33 @@ +nimTitle vm vm.html module vm 0 +nim setResult vm.html#setResult,VmArgs,BiggestInt proc setResult(a: VmArgs; v: BiggestInt) 19 +nim setResult vm.html#setResult,VmArgs,BiggestFloat proc setResult(a: VmArgs; v: BiggestFloat) 20 +nim setResult vm.html#setResult,VmArgs,bool proc setResult(a: VmArgs; v: bool) 21 +nim setResult vm.html#setResult,VmArgs,string proc setResult(a: VmArgs; v: string) 25 +nim setResult vm.html#setResult,VmArgs,PNode proc setResult(a: VmArgs; n: PNode) 30 +nim setResult vm.html#setResult,VmArgs,AbsoluteDir proc setResult(a: VmArgs; v: AbsoluteDir) 34 +nim setResult vm.html#setResult,VmArgs,seq[string] proc setResult(a: VmArgs; v: seq[string]) 36 +nim setResult vm.html#setResult,VmArgs, proc setResult(a: VmArgs; v: (BiggestInt, BiggestInt)) 42 +nim numArgs vm.html#numArgs,VmArgs proc numArgs(a: VmArgs): int 58 +nim getInt vm.html#getInt,VmArgs,Natural proc getInt(a: VmArgs; i: Natural): BiggestInt 61 +nim getBool vm.html#getBool,VmArgs,Natural proc getBool(a: VmArgs; i: Natural): bool 62 +nim getFloat vm.html#getFloat,VmArgs,Natural proc getFloat(a: VmArgs; i: Natural): BiggestFloat 63 +nim getNode vm.html#getNode,VmArgs,Natural proc getNode(a: VmArgs; i: Natural): PNode 64 +nim getString vm.html#getString,VmArgs,Natural proc getString(a: VmArgs; i: Natural): string 65 +nim getVar vm.html#getVar,VmArgs,Natural proc getVar(a: VmArgs; i: Natural): PNode 66 +nim getNodeAddr vm.html#getNodeAddr,VmArgs,Natural proc getNodeAddr(a: VmArgs; i: Natural): PNode 74 +nim execProc vm.html#execProc,PCtx,PSym,openArray[PNode] proc execProc(c: PCtx; sym: PSym; args: openArray[PNode]): PNode 2312 +nim evalStmt vm.html#evalStmt,PCtx,PNode proc evalStmt(c: PCtx; n: PNode) 2345 +nim evalExpr vm.html#evalExpr,PCtx,PNode proc evalExpr(c: PCtx; n: PNode): PNode 2356 +nim getGlobalValue vm.html#getGlobalValue,PCtx,PSym proc getGlobalValue(c: PCtx; s: PSym): PNode 2368 +nim setGlobalValue vm.html#setGlobalValue,PCtx,PSym,PNode proc setGlobalValue(c: PCtx; s: PSym; val: PNode) 2372 +nim registerAdditionalOps vm.html#registerAdditionalOps,PCtx proc registerAdditionalOps(c: PCtx) 191 +nim setupGlobalCtx vm.html#setupGlobalCtx,PSym,ModuleGraph,IdGenerator proc setupGlobalCtx(module: PSym; graph: ModuleGraph; idgen: IdGenerator) 2379 +nim setupEvalGen vm.html#setupEvalGen,ModuleGraph,PSym,IdGenerator proc setupEvalGen(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext 2386 +nim interpreterCode vm.html#interpreterCode,PPassContext,PNode proc interpreterCode(c: PPassContext; n: PNode): PNode 2395 +nim evalConstExpr vm.html#evalConstExpr,PSym,IdGenerator,ModuleGraph,PNode proc evalConstExpr(module: PSym; idgen: IdGenerator; g: ModuleGraph; e: PNode): PNode 2431 +nim evalStaticExpr vm.html#evalStaticExpr,PSym,IdGenerator,ModuleGraph,PNode,PSym proc evalStaticExpr(module: PSym; idgen: IdGenerator; g: ModuleGraph; e: PNode;\n prc: PSym): PNode 2434 +nim evalStaticStmt vm.html#evalStaticStmt,PSym,IdGenerator,ModuleGraph,PNode,PSym proc evalStaticStmt(module: PSym; idgen: IdGenerator; g: ModuleGraph; e: PNode;\n prc: PSym) 2437 +nim setupCompileTimeVar vm.html#setupCompileTimeVar,PSym,IdGenerator,ModuleGraph,PNode proc setupCompileTimeVar(module: PSym; idgen: IdGenerator; g: ModuleGraph; n: PNode) 2440 +nim genericParamsInMacroCall vm.html#genericParamsInMacroCall.i,PSym,PNode iterator genericParamsInMacroCall(macroSym: PSym; call: PNode): (PSym, PNode) 2480 +nim evalMacroCall vm.html#evalMacroCall,PSym,IdGenerator,ModuleGraph,ref.int,PNode,PNode,PSym proc evalMacroCall(module: PSym; idgen: IdGenerator; g: ModuleGraph;\n templInstCounter: ref int; n, nOrig: PNode; sym: PSym): PNode 2491 +nimgrp setresult vm.html#setResult-procs-all proc 19 diff --git a/compiler/vmconv.html b/compiler/vmconv.html new file mode 100644 index 0000000000000..acff4b32a406a --- /dev/null +++ b/compiler/vmconv.html @@ -0,0 +1,185 @@ + + + + + + + +vmconv + + + + + + + + + + + + + + + + +
+
+

vmconv

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc fromLit(a: PNode; T: typedesc): auto
+
+ + generic PNode => type see also reverse operation toLit + Source   +Edit   + +
+
+ +
+
+
+
proc toLit[T](a: T): PNode
+
+ + generic type => PNode see also reverse operation fromLit + Source   +Edit   + +
+
+ +
+
+
+
proc toTimeLit(a: Time; c: PCtx; obj: PNode; info: TLineInfo): PNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template elementType(T: typedesc): typedesc
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/vmconv.idx b/compiler/vmconv.idx new file mode 100644 index 0000000000000..5f8cabc657da8 --- /dev/null +++ b/compiler/vmconv.idx @@ -0,0 +1,5 @@ +nimTitle vmconv vmconv.html module vmconv 0 +nim elementType vmconv.html#elementType.t,typedesc template elementType(T: typedesc): typedesc 6 +nim fromLit vmconv.html#fromLit,PNode,typedesc proc fromLit(a: PNode; T: typedesc): auto 11 +nim toLit vmconv.html#toLit,T proc toLit[T](a: T): PNode 22 +nim toTimeLit vmconv.html#toTimeLit,Time,PCtx,PNode,TLineInfo proc toTimeLit(a: Time; c: PCtx; obj: PNode; info: TLineInfo): PNode 49 diff --git a/compiler/vmdef.html b/compiler/vmdef.html new file mode 100644 index 0000000000000..0e93780090000 --- /dev/null +++ b/compiler/vmdef.html @@ -0,0 +1,953 @@ + + + + + + + +vmdef + + + + + + + + + + + + + + + + +
+
+

vmdef

+
+ +
+ Source   +Edit   + +
+ +

This module contains the type definitions for the new evaluation engine. An instruction is 1-3 int32s in memory, it is a register based VM.

+ +
+

Types

+
+
+
PCtx = ref TCtx
+
+ + + Source   +Edit   + +
+
+
+
PEvalContext = PCtx
+
+ + + Source   +Edit   + +
+
+
+
PProc = ref object
+  blocks*: seq[TBlock]
+  sym*: PSym
+  regInfo*: seq[tuple[inUse: bool, kind: TSlotKind]]
+
+ + + Source   +Edit   + +
+
+
+
Profiler = object
+  tEnter*: float
+  tos*: PStackFrame
+
+ + + Source   +Edit   + +
+
+
+
PStackFrame = ref TStackFrame
+
+ + + Source   +Edit   + +
+
+
+
TBlock = object
+  label*: PSym
+  fixups*: seq[TPosition]
+
+ + + Source   +Edit   + +
+
+
+
TCtx = object of TPassContext
+  code*: seq[TInstr]
+  debug*: seq[TLineInfo]
+  globals*: PNode
+  constants*: PNode
+  types*: seq[PType]
+  currentExceptionA*, currentExceptionB*: PNode
+  exceptionInstr*: int
+  prc*: PProc
+  module*: PSym
+  callsite*: PNode
+  mode*: TEvalMode
+  features*: TSandboxFlags
+  traceActive*: bool
+  loopIterations*: int
+  comesFromHeuristic*: TLineInfo
+  callbacks*: seq[VmCallback]
+  callbackIndex*: Table[string, int]
+  errorFlag*: string
+  cache*: IdentCache
+  config*: ConfigRef
+  graph*: ModuleGraph
+  oldErrorCount*: int
+  profiler*: Profiler
+  templInstCounter*: ref int
+  vmstateDiff*: seq[(PSym, PNode)]
+  procToCodePos*: Table[int, int]
+  cannotEval*: bool
+
+ + + Source   +Edit   + +
+
+
+
TDest = range[-1 .. 65535'u64.int]
+
+ + + Source   +Edit   + +
+
+
+
TEvalMode = enum
+  emRepl,                   ## evaluate because in REPL mode
+  emConst,                  ## evaluate for 'const' according to spec
+  emOptimize,               ## evaluate for optimization purposes (same as
+                             ## emConst?)
+  emStaticExpr,             ## evaluate for enforced compile time eval
+                             ## ('static' context)
+  emStaticStmt               ## 'static' as an expression
+
+ + reason for evaluation + Source   +Edit   + +
+
+
+
TFullReg = object
+  case kind*: TRegisterKind
+  of rkNone:
+    nil
+  of rkInt:
+    intVal*: BiggestInt
+  of rkFloat:
+    floatVal*: BiggestFloat
+  of rkNode:
+    node*: PNode
+  of rkRegisterAddr:
+    regAddr*: ptr TFullReg
+  of rkNodeAddr:
+    nodeAddr*: ptr PNode
+
+ + + Source   +Edit   + +
+
+
+
TInstr = distinct TInstrType
+
+ + + Source   +Edit   + +
+
+
+
TInstrType = uint64
+
+ + + Source   +Edit   + +
+
+
+
TOpcode = enum
+  opcEof, opcRet, opcYldYoid, opcYldVal, opcAsgnInt, opcAsgnFloat, opcAsgnRef,
+  opcAsgnComplex, opcCastIntToFloat32, opcCastIntToFloat64, opcCastFloatToInt32,
+  opcCastFloatToInt64, opcCastPtrToInt, opcCastIntToPtr, opcFastAsgnComplex,
+  opcNodeToReg, opcLdArr, opcLdArrAddr, opcWrArr, opcLdObj, opcLdObjAddr,
+  opcWrObj, opcAddrReg, opcAddrNode, opcLdDeref, opcWrDeref, opcWrStrIdx,
+  opcLdStrIdx, opcLdStrIdxAddr, opcSlice, opcAddInt, opcAddImmInt, opcSubInt,
+  opcSubImmInt, opcLenSeq, opcLenStr, opcLenCstring, opcIncl, opcInclRange,
+  opcExcl, opcCard, opcMulInt, opcDivInt, opcModInt, opcAddFloat, opcSubFloat,
+  opcMulFloat, opcDivFloat, opcShrInt, opcShlInt, opcAshrInt, opcBitandInt,
+  opcBitorInt, opcBitxorInt, opcAddu, opcSubu, opcMulu, opcDivu, opcModu,
+  opcEqInt, opcLeInt, opcLtInt, opcEqFloat, opcLeFloat, opcLtFloat, opcLeu,
+  opcLtu, opcEqRef, opcEqNimNode, opcSameNodeType, opcXor, opcNot,
+  opcUnaryMinusInt, opcUnaryMinusFloat, opcBitnotInt, opcEqStr, opcEqCString,
+  opcLeStr, opcLtStr, opcEqSet, opcLeSet, opcLtSet, opcMulSet, opcPlusSet,
+  opcMinusSet, opcXorSet, opcConcatStr, opcContainsSet, opcRepr, opcSetLenStr,
+  opcSetLenSeq, opcIsNil, opcOf, opcIs, opcParseFloat, opcConv, opcCast,
+  opcQuit, opcInvalidField, opcNarrowS, opcNarrowU, opcSignExtend, opcAddStrCh,
+  opcAddStrStr, opcAddSeqElem, opcRangeChck, opcNAdd, opcNAddMultiple, opcNKind,
+  opcNSymKind, opcNIntVal, opcNFloatVal, opcNSymbol, opcNIdent, opcNGetType,
+  opcNStrVal, opcNSigHash, opcNGetSize, opcNSetIntVal, opcNSetFloatVal,
+  opcNSetSymbol, opcNSetIdent, opcNSetStrVal, opcNNewNimNode, opcNCopyNimNode,
+  opcNCopyNimTree, opcNDel, opcGenSym, opcNccValue, opcNccInc, opcNcsAdd,
+  opcNcsIncl, opcNcsLen, opcNcsAt, opcNctPut, opcNctLen, opcNctGet,
+  opcNctHasNext, opcNctNext, opcNodeId, opcSlurp, opcGorge, opcParseExprToAst,
+  opcParseStmtToAst, opcQueryErrorFlag, opcNError, opcNWarning, opcNHint,
+  opcNGetLineInfo, opcNCopyLineInfo, opcNSetLineInfoLine, opcNSetLineInfoColumn,
+  opcNSetLineInfoFile, opcEqIdent, opcStrToIdent, opcGetImpl, opcGetImplTransf,
+  opcEcho, opcIndCall, opcIndCallAsgn, opcRaise, opcNChild, opcNSetChild,
+  opcCallSite, opcNewStr, opcTJmp, opcFJmp, opcJmp, opcJmpBack, opcBranch,
+  opcTry, opcExcept, opcFinally, opcFinallyEnd, opcNew, opcNewSeq, opcLdNull,
+  opcLdNullReg, opcLdConst, opcAsgnConst, opcLdGlobal, opcLdGlobalAddr,
+  opcLdGlobalDerefFFI, opcLdGlobalAddrDerefFFI, opcLdImmInt, opcNBindSym,
+  opcNDynBindSym, opcSetType, opcTypeTrait, opcSymOwner, opcSymIsInstantiationOf
+
+ + + Source   +Edit   + +
+
+
+
TPosition = distinct int
+
+ + + Source   +Edit   + +
+
+
+
TRegister = range[0 .. 65535'u64.int]
+
+ + + Source   +Edit   + +
+
+
+
TRegisterKind = enum
+  rkNone, rkNode, rkInt, rkFloat, rkRegisterAddr, rkNodeAddr
+
+ + + Source   +Edit   + +
+
+
+
TSandboxFlag = enum
+  allowCast,                ## allow unsafe language feature: 'cast'
+  allowInfiniteLoops         ## allow endless loops
+
+ + what the evaluation engine should allow + Source   +Edit   + +
+
+
+
TSandboxFlags = set[TSandboxFlag]
+
+ + + Source   +Edit   + +
+
+
+
TSlotKind = enum
+  slotEmpty, slotFixedVar, slotFixedLet, slotTempUnknown, slotTempInt,
+  slotTempFloat, slotTempStr, slotTempComplex, slotTempPerm
+
+ + + Source   +Edit   + +
+
+
+
TStackFrame {.acyclic.} = object
+  prc*: PSym
+  slots*: seq[TFullReg]
+  next*: PStackFrame
+  comesFrom*: int
+  safePoints*: seq[int]
+
+ + + Source   +Edit   + +
+
+
+
VmArgs = object
+  ra*, rb*, rc*: Natural = 0
+  slots*: ptr UncheckedArray[TFullReg]
+  currentException*: PNode
+  currentLineInfo*: TLineInfo
+
+ + + Source   +Edit   + +
+
+
+
VmCallback = proc (args: VmArgs) {.closure.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
byteExcess = 128
+
+ + + Source   +Edit   + +
+
+
+
firstABxInstr = opcTJmp
+
+ + + Source   +Edit   + +
+
+
+
largeInstrs = {opcConv, opcCast, opcNewSeq, opcOf}
+
+ + + Source   +Edit   + +
+
+
+
nimNodeFlag = 16
+
+ + + Source   +Edit   + +
+
+
+
regAMask = 65535'u64
+
+ + + Source   +Edit   + +
+
+
+
regAShift = 8'u64
+
+ + + Source   +Edit   + +
+
+
+
regBMask = 65535'u64
+
+ + + Source   +Edit   + +
+
+
+
regBShift = 24'u64
+
+ + + Source   +Edit   + +
+
+
+
regBxMask = 16777215'u64
+
+ + + Source   +Edit   + +
+
+
+
regBxMax = 8388607
+
+ + + Source   +Edit   + +
+
+
+
regBxMin = -8388607
+
+ + + Source   +Edit   + +
+
+
+
regBxShift = 24'u64
+
+ + + Source   +Edit   + +
+
+
+
regCMask = 65535'u64
+
+ + + Source   +Edit   + +
+
+
+
regCShift = 40'u64
+
+ + + Source   +Edit   + +
+
+
+
regOMask = 255'u64
+
+ + + Source   +Edit   + +
+
+
+
regOShift = 0'u
+
+ + + Source   +Edit   + +
+
+
+
relativeJumps = {opcTJmp, opcFJmp, opcJmp, opcJmpBack}
+
+ + + Source   +Edit   + +
+
+
+
slotSomeTemp = slotTempUnknown
+
+ + + Source   +Edit   + +
+
+
+
wordExcess = 8388608
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc newCtx(module: PSym; cache: IdentCache; g: ModuleGraph; idgen: IdGenerator): PCtx {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc refresh(c: PCtx; module: PSym; idgen: IdGenerator) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc registerCallback(c: PCtx; name: string; callback: VmCallback): int {.
+    discardable, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template jmpDiff(x: TInstr): int
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template opcode(x: TInstr): TOpcode
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template regA(x: TInstr): TRegister
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template regB(x: TInstr): TRegister
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template regBx(x: TInstr): int
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template regC(x: TInstr): TRegister
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/vmdef.idx b/compiler/vmdef.idx new file mode 100644 index 0000000000000..e3f90696e063d --- /dev/null +++ b/compiler/vmdef.idx @@ -0,0 +1,264 @@ +nimTitle vmdef vmdef.html module vmdef 0 +nim TInstrType vmdef.html#TInstrType type TInstrType 17 +nim byteExcess vmdef.html#byteExcess const byteExcess 26 +nim regOShift vmdef.html#regOShift const regOShift 31 +nim regAShift vmdef.html#regAShift const regAShift 32 +nim regBShift vmdef.html#regBShift const regBShift 33 +nim regCShift vmdef.html#regCShift const regCShift 34 +nim regBxShift vmdef.html#regBxShift const regBxShift 35 +nim regOMask vmdef.html#regOMask const regOMask 37 +nim regAMask vmdef.html#regAMask const regAMask 38 +nim regBMask vmdef.html#regBMask const regBMask 39 +nim regCMask vmdef.html#regCMask const regCMask 40 +nim regBxMask vmdef.html#regBxMask const regBxMask 41 +nim wordExcess vmdef.html#wordExcess const wordExcess 43 +nim regBxMin vmdef.html#regBxMin const regBxMin 44 +nim regBxMax vmdef.html#regBxMax const regBxMax 45 +nim TRegister vmdef.html#TRegister type TRegister 48 +nim TDest vmdef.html#TDest type TDest 49 +nim TInstr vmdef.html#TInstr type TInstr 50 +nim opcEof vmdef.html#opcEof TOpcode.opcEof 52 +nim opcRet vmdef.html#opcRet TOpcode.opcRet 52 +nim opcYldYoid vmdef.html#opcYldYoid TOpcode.opcYldYoid 52 +nim opcYldVal vmdef.html#opcYldVal TOpcode.opcYldVal 52 +nim opcAsgnInt vmdef.html#opcAsgnInt TOpcode.opcAsgnInt 52 +nim opcAsgnFloat vmdef.html#opcAsgnFloat TOpcode.opcAsgnFloat 52 +nim opcAsgnRef vmdef.html#opcAsgnRef TOpcode.opcAsgnRef 52 +nim opcAsgnComplex vmdef.html#opcAsgnComplex TOpcode.opcAsgnComplex 52 +nim opcCastIntToFloat32 vmdef.html#opcCastIntToFloat32 TOpcode.opcCastIntToFloat32 52 +nim opcCastIntToFloat64 vmdef.html#opcCastIntToFloat64 TOpcode.opcCastIntToFloat64 52 +nim opcCastFloatToInt32 vmdef.html#opcCastFloatToInt32 TOpcode.opcCastFloatToInt32 52 +nim opcCastFloatToInt64 vmdef.html#opcCastFloatToInt64 TOpcode.opcCastFloatToInt64 52 +nim opcCastPtrToInt vmdef.html#opcCastPtrToInt TOpcode.opcCastPtrToInt 52 +nim opcCastIntToPtr vmdef.html#opcCastIntToPtr TOpcode.opcCastIntToPtr 52 +nim opcFastAsgnComplex vmdef.html#opcFastAsgnComplex TOpcode.opcFastAsgnComplex 52 +nim opcNodeToReg vmdef.html#opcNodeToReg TOpcode.opcNodeToReg 52 +nim opcLdArr vmdef.html#opcLdArr TOpcode.opcLdArr 52 +nim opcLdArrAddr vmdef.html#opcLdArrAddr TOpcode.opcLdArrAddr 52 +nim opcWrArr vmdef.html#opcWrArr TOpcode.opcWrArr 52 +nim opcLdObj vmdef.html#opcLdObj TOpcode.opcLdObj 52 +nim opcLdObjAddr vmdef.html#opcLdObjAddr TOpcode.opcLdObjAddr 52 +nim opcWrObj vmdef.html#opcWrObj TOpcode.opcWrObj 52 +nim opcAddrReg vmdef.html#opcAddrReg TOpcode.opcAddrReg 52 +nim opcAddrNode vmdef.html#opcAddrNode TOpcode.opcAddrNode 52 +nim opcLdDeref vmdef.html#opcLdDeref TOpcode.opcLdDeref 52 +nim opcWrDeref vmdef.html#opcWrDeref TOpcode.opcWrDeref 52 +nim opcWrStrIdx vmdef.html#opcWrStrIdx TOpcode.opcWrStrIdx 52 +nim opcLdStrIdx vmdef.html#opcLdStrIdx TOpcode.opcLdStrIdx 52 +nim opcLdStrIdxAddr vmdef.html#opcLdStrIdxAddr TOpcode.opcLdStrIdxAddr 52 +nim opcSlice vmdef.html#opcSlice TOpcode.opcSlice 52 +nim opcAddInt vmdef.html#opcAddInt TOpcode.opcAddInt 52 +nim opcAddImmInt vmdef.html#opcAddImmInt TOpcode.opcAddImmInt 52 +nim opcSubInt vmdef.html#opcSubInt TOpcode.opcSubInt 52 +nim opcSubImmInt vmdef.html#opcSubImmInt TOpcode.opcSubImmInt 52 +nim opcLenSeq vmdef.html#opcLenSeq TOpcode.opcLenSeq 52 +nim opcLenStr vmdef.html#opcLenStr TOpcode.opcLenStr 52 +nim opcLenCstring vmdef.html#opcLenCstring TOpcode.opcLenCstring 52 +nim opcIncl vmdef.html#opcIncl TOpcode.opcIncl 52 +nim opcInclRange vmdef.html#opcInclRange TOpcode.opcInclRange 52 +nim opcExcl vmdef.html#opcExcl TOpcode.opcExcl 52 +nim opcCard vmdef.html#opcCard TOpcode.opcCard 52 +nim opcMulInt vmdef.html#opcMulInt TOpcode.opcMulInt 52 +nim opcDivInt vmdef.html#opcDivInt TOpcode.opcDivInt 52 +nim opcModInt vmdef.html#opcModInt TOpcode.opcModInt 52 +nim opcAddFloat vmdef.html#opcAddFloat TOpcode.opcAddFloat 52 +nim opcSubFloat vmdef.html#opcSubFloat TOpcode.opcSubFloat 52 +nim opcMulFloat vmdef.html#opcMulFloat TOpcode.opcMulFloat 52 +nim opcDivFloat vmdef.html#opcDivFloat TOpcode.opcDivFloat 52 +nim opcShrInt vmdef.html#opcShrInt TOpcode.opcShrInt 52 +nim opcShlInt vmdef.html#opcShlInt TOpcode.opcShlInt 52 +nim opcAshrInt vmdef.html#opcAshrInt TOpcode.opcAshrInt 52 +nim opcBitandInt vmdef.html#opcBitandInt TOpcode.opcBitandInt 52 +nim opcBitorInt vmdef.html#opcBitorInt TOpcode.opcBitorInt 52 +nim opcBitxorInt vmdef.html#opcBitxorInt TOpcode.opcBitxorInt 52 +nim opcAddu vmdef.html#opcAddu TOpcode.opcAddu 52 +nim opcSubu vmdef.html#opcSubu TOpcode.opcSubu 52 +nim opcMulu vmdef.html#opcMulu TOpcode.opcMulu 52 +nim opcDivu vmdef.html#opcDivu TOpcode.opcDivu 52 +nim opcModu vmdef.html#opcModu TOpcode.opcModu 52 +nim opcEqInt vmdef.html#opcEqInt TOpcode.opcEqInt 52 +nim opcLeInt vmdef.html#opcLeInt TOpcode.opcLeInt 52 +nim opcLtInt vmdef.html#opcLtInt TOpcode.opcLtInt 52 +nim opcEqFloat vmdef.html#opcEqFloat TOpcode.opcEqFloat 52 +nim opcLeFloat vmdef.html#opcLeFloat TOpcode.opcLeFloat 52 +nim opcLtFloat vmdef.html#opcLtFloat TOpcode.opcLtFloat 52 +nim opcLeu vmdef.html#opcLeu TOpcode.opcLeu 52 +nim opcLtu vmdef.html#opcLtu TOpcode.opcLtu 52 +nim opcEqRef vmdef.html#opcEqRef TOpcode.opcEqRef 52 +nim opcEqNimNode vmdef.html#opcEqNimNode TOpcode.opcEqNimNode 52 +nim opcSameNodeType vmdef.html#opcSameNodeType TOpcode.opcSameNodeType 52 +nim opcXor vmdef.html#opcXor TOpcode.opcXor 52 +nim opcNot vmdef.html#opcNot TOpcode.opcNot 52 +nim opcUnaryMinusInt vmdef.html#opcUnaryMinusInt TOpcode.opcUnaryMinusInt 52 +nim opcUnaryMinusFloat vmdef.html#opcUnaryMinusFloat TOpcode.opcUnaryMinusFloat 52 +nim opcBitnotInt vmdef.html#opcBitnotInt TOpcode.opcBitnotInt 52 +nim opcEqStr vmdef.html#opcEqStr TOpcode.opcEqStr 52 +nim opcEqCString vmdef.html#opcEqCString TOpcode.opcEqCString 52 +nim opcLeStr vmdef.html#opcLeStr TOpcode.opcLeStr 52 +nim opcLtStr vmdef.html#opcLtStr TOpcode.opcLtStr 52 +nim opcEqSet vmdef.html#opcEqSet TOpcode.opcEqSet 52 +nim opcLeSet vmdef.html#opcLeSet TOpcode.opcLeSet 52 +nim opcLtSet vmdef.html#opcLtSet TOpcode.opcLtSet 52 +nim opcMulSet vmdef.html#opcMulSet TOpcode.opcMulSet 52 +nim opcPlusSet vmdef.html#opcPlusSet TOpcode.opcPlusSet 52 +nim opcMinusSet vmdef.html#opcMinusSet TOpcode.opcMinusSet 52 +nim opcXorSet vmdef.html#opcXorSet TOpcode.opcXorSet 52 +nim opcConcatStr vmdef.html#opcConcatStr TOpcode.opcConcatStr 52 +nim opcContainsSet vmdef.html#opcContainsSet TOpcode.opcContainsSet 52 +nim opcRepr vmdef.html#opcRepr TOpcode.opcRepr 52 +nim opcSetLenStr vmdef.html#opcSetLenStr TOpcode.opcSetLenStr 52 +nim opcSetLenSeq vmdef.html#opcSetLenSeq TOpcode.opcSetLenSeq 52 +nim opcIsNil vmdef.html#opcIsNil TOpcode.opcIsNil 52 +nim opcOf vmdef.html#opcOf TOpcode.opcOf 52 +nim opcIs vmdef.html#opcIs TOpcode.opcIs 52 +nim opcParseFloat vmdef.html#opcParseFloat TOpcode.opcParseFloat 52 +nim opcConv vmdef.html#opcConv TOpcode.opcConv 52 +nim opcCast vmdef.html#opcCast TOpcode.opcCast 52 +nim opcQuit vmdef.html#opcQuit TOpcode.opcQuit 52 +nim opcInvalidField vmdef.html#opcInvalidField TOpcode.opcInvalidField 52 +nim opcNarrowS vmdef.html#opcNarrowS TOpcode.opcNarrowS 52 +nim opcNarrowU vmdef.html#opcNarrowU TOpcode.opcNarrowU 52 +nim opcSignExtend vmdef.html#opcSignExtend TOpcode.opcSignExtend 52 +nim opcAddStrCh vmdef.html#opcAddStrCh TOpcode.opcAddStrCh 52 +nim opcAddStrStr vmdef.html#opcAddStrStr TOpcode.opcAddStrStr 52 +nim opcAddSeqElem vmdef.html#opcAddSeqElem TOpcode.opcAddSeqElem 52 +nim opcRangeChck vmdef.html#opcRangeChck TOpcode.opcRangeChck 52 +nim opcNAdd vmdef.html#opcNAdd TOpcode.opcNAdd 52 +nim opcNAddMultiple vmdef.html#opcNAddMultiple TOpcode.opcNAddMultiple 52 +nim opcNKind vmdef.html#opcNKind TOpcode.opcNKind 52 +nim opcNSymKind vmdef.html#opcNSymKind TOpcode.opcNSymKind 52 +nim opcNIntVal vmdef.html#opcNIntVal TOpcode.opcNIntVal 52 +nim opcNFloatVal vmdef.html#opcNFloatVal TOpcode.opcNFloatVal 52 +nim opcNSymbol vmdef.html#opcNSymbol TOpcode.opcNSymbol 52 +nim opcNIdent vmdef.html#opcNIdent TOpcode.opcNIdent 52 +nim opcNGetType vmdef.html#opcNGetType TOpcode.opcNGetType 52 +nim opcNStrVal vmdef.html#opcNStrVal TOpcode.opcNStrVal 52 +nim opcNSigHash vmdef.html#opcNSigHash TOpcode.opcNSigHash 52 +nim opcNGetSize vmdef.html#opcNGetSize TOpcode.opcNGetSize 52 +nim opcNSetIntVal vmdef.html#opcNSetIntVal TOpcode.opcNSetIntVal 52 +nim opcNSetFloatVal vmdef.html#opcNSetFloatVal TOpcode.opcNSetFloatVal 52 +nim opcNSetSymbol vmdef.html#opcNSetSymbol TOpcode.opcNSetSymbol 52 +nim opcNSetIdent vmdef.html#opcNSetIdent TOpcode.opcNSetIdent 52 +nim opcNSetStrVal vmdef.html#opcNSetStrVal TOpcode.opcNSetStrVal 52 +nim opcNNewNimNode vmdef.html#opcNNewNimNode TOpcode.opcNNewNimNode 52 +nim opcNCopyNimNode vmdef.html#opcNCopyNimNode TOpcode.opcNCopyNimNode 52 +nim opcNCopyNimTree vmdef.html#opcNCopyNimTree TOpcode.opcNCopyNimTree 52 +nim opcNDel vmdef.html#opcNDel TOpcode.opcNDel 52 +nim opcGenSym vmdef.html#opcGenSym TOpcode.opcGenSym 52 +nim opcNccValue vmdef.html#opcNccValue TOpcode.opcNccValue 52 +nim opcNccInc vmdef.html#opcNccInc TOpcode.opcNccInc 52 +nim opcNcsAdd vmdef.html#opcNcsAdd TOpcode.opcNcsAdd 52 +nim opcNcsIncl vmdef.html#opcNcsIncl TOpcode.opcNcsIncl 52 +nim opcNcsLen vmdef.html#opcNcsLen TOpcode.opcNcsLen 52 +nim opcNcsAt vmdef.html#opcNcsAt TOpcode.opcNcsAt 52 +nim opcNctPut vmdef.html#opcNctPut TOpcode.opcNctPut 52 +nim opcNctLen vmdef.html#opcNctLen TOpcode.opcNctLen 52 +nim opcNctGet vmdef.html#opcNctGet TOpcode.opcNctGet 52 +nim opcNctHasNext vmdef.html#opcNctHasNext TOpcode.opcNctHasNext 52 +nim opcNctNext vmdef.html#opcNctNext TOpcode.opcNctNext 52 +nim opcNodeId vmdef.html#opcNodeId TOpcode.opcNodeId 52 +nim opcSlurp vmdef.html#opcSlurp TOpcode.opcSlurp 52 +nim opcGorge vmdef.html#opcGorge TOpcode.opcGorge 52 +nim opcParseExprToAst vmdef.html#opcParseExprToAst TOpcode.opcParseExprToAst 52 +nim opcParseStmtToAst vmdef.html#opcParseStmtToAst TOpcode.opcParseStmtToAst 52 +nim opcQueryErrorFlag vmdef.html#opcQueryErrorFlag TOpcode.opcQueryErrorFlag 52 +nim opcNError vmdef.html#opcNError TOpcode.opcNError 52 +nim opcNWarning vmdef.html#opcNWarning TOpcode.opcNWarning 52 +nim opcNHint vmdef.html#opcNHint TOpcode.opcNHint 52 +nim opcNGetLineInfo vmdef.html#opcNGetLineInfo TOpcode.opcNGetLineInfo 52 +nim opcNCopyLineInfo vmdef.html#opcNCopyLineInfo TOpcode.opcNCopyLineInfo 52 +nim opcNSetLineInfoLine vmdef.html#opcNSetLineInfoLine TOpcode.opcNSetLineInfoLine 52 +nim opcNSetLineInfoColumn vmdef.html#opcNSetLineInfoColumn TOpcode.opcNSetLineInfoColumn 52 +nim opcNSetLineInfoFile vmdef.html#opcNSetLineInfoFile TOpcode.opcNSetLineInfoFile 52 +nim opcEqIdent vmdef.html#opcEqIdent TOpcode.opcEqIdent 52 +nim opcStrToIdent vmdef.html#opcStrToIdent TOpcode.opcStrToIdent 52 +nim opcGetImpl vmdef.html#opcGetImpl TOpcode.opcGetImpl 52 +nim opcGetImplTransf vmdef.html#opcGetImplTransf TOpcode.opcGetImplTransf 52 +nim opcEcho vmdef.html#opcEcho TOpcode.opcEcho 52 +nim opcIndCall vmdef.html#opcIndCall TOpcode.opcIndCall 52 +nim opcIndCallAsgn vmdef.html#opcIndCallAsgn TOpcode.opcIndCallAsgn 52 +nim opcRaise vmdef.html#opcRaise TOpcode.opcRaise 52 +nim opcNChild vmdef.html#opcNChild TOpcode.opcNChild 52 +nim opcNSetChild vmdef.html#opcNSetChild TOpcode.opcNSetChild 52 +nim opcCallSite vmdef.html#opcCallSite TOpcode.opcCallSite 52 +nim opcNewStr vmdef.html#opcNewStr TOpcode.opcNewStr 52 +nim opcTJmp vmdef.html#opcTJmp TOpcode.opcTJmp 52 +nim opcFJmp vmdef.html#opcFJmp TOpcode.opcFJmp 52 +nim opcJmp vmdef.html#opcJmp TOpcode.opcJmp 52 +nim opcJmpBack vmdef.html#opcJmpBack TOpcode.opcJmpBack 52 +nim opcBranch vmdef.html#opcBranch TOpcode.opcBranch 52 +nim opcTry vmdef.html#opcTry TOpcode.opcTry 52 +nim opcExcept vmdef.html#opcExcept TOpcode.opcExcept 52 +nim opcFinally vmdef.html#opcFinally TOpcode.opcFinally 52 +nim opcFinallyEnd vmdef.html#opcFinallyEnd TOpcode.opcFinallyEnd 52 +nim opcNew vmdef.html#opcNew TOpcode.opcNew 52 +nim opcNewSeq vmdef.html#opcNewSeq TOpcode.opcNewSeq 52 +nim opcLdNull vmdef.html#opcLdNull TOpcode.opcLdNull 52 +nim opcLdNullReg vmdef.html#opcLdNullReg TOpcode.opcLdNullReg 52 +nim opcLdConst vmdef.html#opcLdConst TOpcode.opcLdConst 52 +nim opcAsgnConst vmdef.html#opcAsgnConst TOpcode.opcAsgnConst 52 +nim opcLdGlobal vmdef.html#opcLdGlobal TOpcode.opcLdGlobal 52 +nim opcLdGlobalAddr vmdef.html#opcLdGlobalAddr TOpcode.opcLdGlobalAddr 52 +nim opcLdGlobalDerefFFI vmdef.html#opcLdGlobalDerefFFI TOpcode.opcLdGlobalDerefFFI 52 +nim opcLdGlobalAddrDerefFFI vmdef.html#opcLdGlobalAddrDerefFFI TOpcode.opcLdGlobalAddrDerefFFI 52 +nim opcLdImmInt vmdef.html#opcLdImmInt TOpcode.opcLdImmInt 52 +nim opcNBindSym vmdef.html#opcNBindSym TOpcode.opcNBindSym 52 +nim opcNDynBindSym vmdef.html#opcNDynBindSym TOpcode.opcNDynBindSym 52 +nim opcSetType vmdef.html#opcSetType TOpcode.opcSetType 52 +nim opcTypeTrait vmdef.html#opcTypeTrait TOpcode.opcTypeTrait 52 +nim opcSymOwner vmdef.html#opcSymOwner TOpcode.opcSymOwner 52 +nim opcSymIsInstantiationOf vmdef.html#opcSymIsInstantiationOf TOpcode.opcSymIsInstantiationOf 52 +nim TOpcode vmdef.html#TOpcode enum TOpcode 52 +nim TBlock vmdef.html#TBlock object TBlock 188 +nim emRepl vmdef.html#emRepl TEvalMode.emRepl 192 +nim emConst vmdef.html#emConst TEvalMode.emConst 192 +nim emOptimize vmdef.html#emOptimize TEvalMode.emOptimize 192 +nim emStaticExpr vmdef.html#emStaticExpr TEvalMode.emStaticExpr 192 +nim emStaticStmt vmdef.html#emStaticStmt TEvalMode.emStaticStmt 192 +nim TEvalMode vmdef.html#TEvalMode enum TEvalMode 192 +nim allowCast vmdef.html#allowCast TSandboxFlag.allowCast 201 +nim allowInfiniteLoops vmdef.html#allowInfiniteLoops TSandboxFlag.allowInfiniteLoops 201 +nim TSandboxFlag vmdef.html#TSandboxFlag enum TSandboxFlag 201 +nim TSandboxFlags vmdef.html#TSandboxFlags type TSandboxFlags 204 +nim slotEmpty vmdef.html#slotEmpty TSlotKind.slotEmpty 206 +nim slotFixedVar vmdef.html#slotFixedVar TSlotKind.slotFixedVar 206 +nim slotFixedLet vmdef.html#slotFixedLet TSlotKind.slotFixedLet 206 +nim slotTempUnknown vmdef.html#slotTempUnknown TSlotKind.slotTempUnknown 206 +nim slotTempInt vmdef.html#slotTempInt TSlotKind.slotTempInt 206 +nim slotTempFloat vmdef.html#slotTempFloat TSlotKind.slotTempFloat 206 +nim slotTempStr vmdef.html#slotTempStr TSlotKind.slotTempStr 206 +nim slotTempComplex vmdef.html#slotTempComplex TSlotKind.slotTempComplex 206 +nim slotTempPerm vmdef.html#slotTempPerm TSlotKind.slotTempPerm 206 +nim TSlotKind vmdef.html#TSlotKind enum TSlotKind 206 +nim rkNone vmdef.html#rkNone TRegisterKind.rkNone 220 +nim rkNode vmdef.html#rkNode TRegisterKind.rkNode 220 +nim rkInt vmdef.html#rkInt TRegisterKind.rkInt 220 +nim rkFloat vmdef.html#rkFloat TRegisterKind.rkFloat 220 +nim rkRegisterAddr vmdef.html#rkRegisterAddr TRegisterKind.rkRegisterAddr 220 +nim rkNodeAddr vmdef.html#rkNodeAddr TRegisterKind.rkNodeAddr 220 +nim TRegisterKind vmdef.html#TRegisterKind enum TRegisterKind 220 +nim TFullReg vmdef.html#TFullReg object TFullReg 222 +nim PProc vmdef.html#PProc type PProc 232 +nim VmArgs vmdef.html#VmArgs object VmArgs 237 +nim VmCallback vmdef.html#VmCallback type VmCallback 242 +nim PCtx vmdef.html#PCtx type PCtx 244 +nim TCtx vmdef.html#TCtx object TCtx 245 +nim PStackFrame vmdef.html#PStackFrame type PStackFrame 275 +nim TStackFrame vmdef.html#TStackFrame object TStackFrame 276 +nim Profiler vmdef.html#Profiler object Profiler 285 +nim TPosition vmdef.html#TPosition type TPosition 289 +nim PEvalContext vmdef.html#PEvalContext type PEvalContext 291 +nim newCtx vmdef.html#newCtx,PSym,IdentCache,ModuleGraph,IdGenerator proc newCtx(module: PSym; cache: IdentCache; g: ModuleGraph; idgen: IdGenerator): PCtx 293 +nim refresh vmdef.html#refresh,PCtx,PSym,IdGenerator proc refresh(c: PCtx; module: PSym; idgen: IdGenerator) 300 +nim registerCallback vmdef.html#registerCallback,PCtx,string,VmCallback proc registerCallback(c: PCtx; name: string; callback: VmCallback): int 314 +nim firstABxInstr vmdef.html#firstABxInstr const firstABxInstr 320 +nim largeInstrs vmdef.html#largeInstrs const largeInstrs 321 +nim slotSomeTemp vmdef.html#slotSomeTemp const slotSomeTemp 324 +nim relativeJumps vmdef.html#relativeJumps const relativeJumps 325 +nim nimNodeFlag vmdef.html#nimNodeFlag const nimNodeFlag 328 +nim opcode vmdef.html#opcode.t,TInstr template opcode(x: TInstr): TOpcode 330 +nim regA vmdef.html#regA.t,TInstr template regA(x: TInstr): TRegister 331 +nim regB vmdef.html#regB.t,TInstr template regB(x: TInstr): TRegister 332 +nim regC vmdef.html#regC.t,TInstr template regC(x: TInstr): TRegister 333 +nim regBx vmdef.html#regBx.t,TInstr template regBx(x: TInstr): int 334 +nim jmpDiff vmdef.html#jmpDiff.t,TInstr template jmpDiff(x: TInstr): int 336 diff --git a/compiler/vmdeps.html b/compiler/vmdeps.html new file mode 100644 index 0000000000000..840048982c97e --- /dev/null +++ b/compiler/vmdeps.html @@ -0,0 +1,183 @@ + + + + + + + +vmdeps + + + + + + + + + + + + + + + + +
+
+

vmdeps

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc opMapTypeImplToAst(cache: IdentCache; t: PType; info: TLineInfo;
+                        idgen: IdGenerator): PNode {.
+    ...raises: [KeyError, Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc opMapTypeInstToAst(cache: IdentCache; t: PType; info: TLineInfo;
+                        idgen: IdGenerator): PNode {.
+    ...raises: [KeyError, Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc opMapTypeToAst(cache: IdentCache; t: PType; info: TLineInfo;
+                    idgen: IdGenerator): PNode {....raises: [KeyError, Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc opSlurp(file: string; info: TLineInfo; module: PSym; conf: ConfigRef): string {....raises: [
+    OSError, KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, ReadIOEffect, RootEffect, WriteIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/vmdeps.idx b/compiler/vmdeps.idx new file mode 100644 index 0000000000000..3aab889dc2c94 --- /dev/null +++ b/compiler/vmdeps.idx @@ -0,0 +1,5 @@ +nimTitle vmdeps vmdeps.html module vmdeps 0 +nim opSlurp vmdeps.html#opSlurp,string,TLineInfo,PSym,ConfigRef proc opSlurp(file: string; info: TLineInfo; module: PSym; conf: ConfigRef): string 18 +nim opMapTypeToAst vmdeps.html#opMapTypeToAst,IdentCache,PType,TLineInfo,IdGenerator proc opMapTypeToAst(cache: IdentCache; t: PType; info: TLineInfo; idgen: IdGenerator): PNode 323 +nim opMapTypeInstToAst vmdeps.html#opMapTypeInstToAst,IdentCache,PType,TLineInfo,IdGenerator proc opMapTypeInstToAst(cache: IdentCache; t: PType; info: TLineInfo;\n idgen: IdGenerator): PNode 328 +nim opMapTypeImplToAst vmdeps.html#opMapTypeImplToAst,IdentCache,PType,TLineInfo,IdGenerator proc opMapTypeImplToAst(cache: IdentCache; t: PType; info: TLineInfo;\n idgen: IdGenerator): PNode 333 diff --git a/compiler/vmgen.html b/compiler/vmgen.html new file mode 100644 index 0000000000000..45eaafc221698 --- /dev/null +++ b/compiler/vmgen.html @@ -0,0 +1,298 @@ + + + + + + + +vmgen + + + + + + + + + + + + + + + + +
+
+

vmgen

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

This module implements the code generator for the VM.

+ +
+

Consts

+
+
+
debugEchoCode = false
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc echoCode(c: PCtx; start = 0; last = -1) {....deprecated,
+    raises: [ValueError, Exception, KeyError],
+    tags: [RootEffect, ReadDirEffect], forbids: [].}
+
+
+ Deprecated +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fitsRegister(t: PType): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genExpr(c: PCtx; n: PNode; requiresValue = true): int {.
+    ...raises: [Exception, ValueError, KeyError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genProc(c: PCtx; s: PSym): int {....raises: [KeyError, Exception, ValueError,
+    IOError, ERecoverableError, OSError], tags: [ReadDirEffect, RootEffect,
+    WriteIOEffect, ReadIOEffect, ReadEnvEffect, TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genStmt(c: PCtx; n: PNode): int {....raises: [Exception, ValueError, KeyError,
+    IOError, ERecoverableError], tags: [RootEffect, ReadDirEffect,
+                                        WriteIOEffect, ReadIOEffect,
+                                        ReadEnvEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getNullValue(c: PCtx; typ: PType; info: TLineInfo; conf: ConfigRef): PNode {.
+    ...raises: [KeyError, Exception, ValueError, IOError, ERecoverableError], tags: [
+    ReadDirEffect, RootEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc importcCond(c: PCtx; s: PSym): bool {.inline,
+    ...raises: [KeyError, Exception], tags: [ReadDirEffect, RootEffect],
+    forbids: [].}
+
+ + return true to importc s, false to execute its body instead (refs #8405) + Source   +Edit   + +
+
+ +
+
+
+
proc importcCondVar(s: PSym): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sameConstant(a, b: PNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/vmgen.idx b/compiler/vmgen.idx new file mode 100644 index 0000000000000..683e524806507 --- /dev/null +++ b/compiler/vmgen.idx @@ -0,0 +1,11 @@ +nimTitle vmgen vmgen.html module vmgen 0 +nim debugEchoCode vmgen.html#debugEchoCode const debugEchoCode 44 +nim echoCode vmgen.html#echoCode,PCtx,int,int proc echoCode(c: PCtx; start = 0; last = -1) 114 +nim sameConstant vmgen.html#sameConstant,PNode,PNode proc sameConstant(a, b: PNode): bool 456 +nim fitsRegister vmgen.html#fitsRegister,PType proc fitsRegister(t: PType): bool 1045 +nim importcCondVar vmgen.html#importcCondVar,PSym proc importcCondVar(s: PSym): bool 1567 +nim importcCond vmgen.html#importcCond,PCtx,PSym proc importcCond(c: PCtx; s: PSym): bool 1697 +nim getNullValue vmgen.html#getNullValue,PCtx,PType,TLineInfo,ConfigRef proc getNullValue(c: PCtx; typ: PType; info: TLineInfo; conf: ConfigRef): PNode 1716 +nim genProc vmgen.html#genProc,PCtx,PSym proc genProc(c: PCtx; s: PSym): int 2114 +nim genStmt vmgen.html#genStmt,PCtx,PNode proc genStmt(c: PCtx; n: PNode): int 2310 +nim genExpr vmgen.html#genExpr,PCtx,PNode proc genExpr(c: PCtx; n: PNode; requiresValue = true): int 2319 diff --git a/compiler/vmmarshal.html b/compiler/vmmarshal.html new file mode 100644 index 0000000000000..80d3ca84088da --- /dev/null +++ b/compiler/vmmarshal.html @@ -0,0 +1,145 @@ + + + + + + + +vmmarshal + + + + + + + + + + + + + + + + +
+
+

vmmarshal

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

Implements marshaling for the VM.

+ +
+

Procs

+
+
+
+
proc loadAny(s: string; t: PType; cache: IdentCache; conf: ConfigRef;
+             idgen: IdGenerator): PNode {....raises: [IOError, OSError,
+    JsonParsingError, ValueError, Exception, KeyError, ERecoverableError], tags: [
+    ReadIOEffect, RootEffect, ReadDirEffect, WriteIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc storeAny(s: var string; t: PType; a: PNode; conf: ConfigRef) {.
+    ...raises: [Exception, KeyError, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/vmmarshal.idx b/compiler/vmmarshal.idx new file mode 100644 index 0000000000000..c9284c7b852eb --- /dev/null +++ b/compiler/vmmarshal.idx @@ -0,0 +1,3 @@ +nimTitle vmmarshal vmmarshal.html module vmmarshal 0 +nim storeAny vmmarshal.html#storeAny,string,PType,PNode,ConfigRef proc storeAny(s: var string; t: PType; a: PNode; conf: ConfigRef) 140 +nim loadAny vmmarshal.html#loadAny,string,PType,IdentCache,ConfigRef,IdGenerator proc loadAny(s: string; t: PType; cache: IdentCache; conf: ConfigRef;\n idgen: IdGenerator): PNode 309 diff --git a/compiler/vmprofiler.html b/compiler/vmprofiler.html new file mode 100644 index 0000000000000..49a03b7140119 --- /dev/null +++ b/compiler/vmprofiler.html @@ -0,0 +1,157 @@ + + + + + + + +vmprofiler + + + + + + + + + + + + + + + + +
+
+

vmprofiler

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc dump(conf: ConfigRef; pd: ProfileData): string {.
+    ...raises: [Exception, KeyError], tags: [RootEffect, ReadDirEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc enter(prof: var Profiler; c: PCtx; tos: PStackFrame) {.inline, ...raises: [],
+    tags: [TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc leave(prof: var Profiler; c: PCtx) {.inline, ...raises: [KeyError],
+    tags: [TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/vmprofiler.idx b/compiler/vmprofiler.idx new file mode 100644 index 0000000000000..af7143c12ae3e --- /dev/null +++ b/compiler/vmprofiler.idx @@ -0,0 +1,4 @@ +nimTitle vmprofiler vmprofiler.html module vmprofiler 0 +nim enter vmprofiler.html#enter,Profiler,PCtx,PStackFrame proc enter(prof: var Profiler; c: PCtx; tos: PStackFrame) 6 +nim leave vmprofiler.html#leave,Profiler,PCtx proc leave(prof: var Profiler; c: PCtx) 25 +nim dump vmprofiler.html#dump,ConfigRef,ProfileData proc dump(conf: ConfigRef; pd: ProfileData): string 29 diff --git a/compiler/vtables.html b/compiler/vtables.html new file mode 100644 index 0000000000000..56fa5745aa0bc --- /dev/null +++ b/compiler/vtables.html @@ -0,0 +1,140 @@ + + + + + + + +vtables + + + + + + + + + + + + + + + + +
+
+

vtables

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc collectVTableDispatchers(g: ModuleGraph) {.
+    ...raises: [Exception, KeyError, ValueError, IOError, ERecoverableError], tags: [
+    RootEffect, ReadDirEffect, WriteIOEffect, ReadIOEffect, ReadEnvEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sortVTableDispatchers(g: ModuleGraph) {....raises: [Exception, KeyError],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/vtables.idx b/compiler/vtables.idx new file mode 100644 index 0000000000000..04a7d5204f988 --- /dev/null +++ b/compiler/vtables.idx @@ -0,0 +1,3 @@ +nimTitle vtables vtables.html module vtables 0 +nim collectVTableDispatchers vtables.html#collectVTableDispatchers,ModuleGraph proc collectVTableDispatchers(g: ModuleGraph) 85 +nim sortVTableDispatchers vtables.html#sortVTableDispatchers,ModuleGraph proc sortVTableDispatchers(g: ModuleGraph) 123 diff --git a/compiler/wordrecg.html b/compiler/wordrecg.html new file mode 100644 index 0000000000000..8034db3f14de3 --- /dev/null +++ b/compiler/wordrecg.html @@ -0,0 +1,463 @@ + + + + + + + +wordrecg + + + + + + + + + + + + + + + + +
+
+

wordrecg

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + +
+
+ Source   +Edit   + +
+ +

+
+

Types

+
+
+
TSpecialWord = enum
+  wInvalid = "", wAddr = "addr", wAnd = "and", wAs = "as", wAsm = "asm",
+  wBind = "bind", wBlock = "block", wBreak = "break", wCase = "case",
+  wCast = "cast", wConcept = "concept", wConst = "const",
+  wContinue = "continue", wConverter = "converter", wDefer = "defer",
+  wDiscard = "discard", wDistinct = "distinct", wDiv = "div", wDo = "do",
+  wElif = "elif", wElse = "else", wEnd = "end", wEnum = "enum",
+  wExcept = "except", wExport = "export", wFinally = "finally", wFor = "for",
+  wFrom = "from", wFunc = "func", wIf = "if", wImport = "import", wIn = "in",
+  wInclude = "include", wInterface = "interface", wIs = "is", wIsnot = "isnot",
+  wIterator = "iterator", wLet = "let", wMacro = "macro", wMethod = "method",
+  wMixin = "mixin", wMod = "mod", wNil = "nil", wNot = "not", wNotin = "notin",
+  wObject = "object", wOf = "of", wOr = "or", wOut = "out", wProc = "proc",
+  wPtr = "ptr", wRaise = "raise", wRef = "ref", wReturn = "return",
+  wShl = "shl", wShr = "shr", wStatic = "static", wTemplate = "template",
+  wTry = "try", wTuple = "tuple", wType = "type", wUsing = "using",
+  wVar = "var", wWhen = "when", wWhile = "while", wXor = "xor",
+  wYield = "yield", wColon = ":", wColonColon = "::", wEquals = "=", wDot = ".",
+  wDotDot = "..", wStar = "*", wMinus = "-", wUnderscore = "_",
+  wMagic = "magic", wThread = "thread", wFinal = "final",
+  wProfiler = "profiler", wMemTracker = "memtracker", wObjChecks = "objchecks",
+  wIntDefine = "intdefine", wStrDefine = "strdefine",
+  wBoolDefine = "booldefine", wCursor = "cursor", wNoalias = "noalias",
+  wEffectsOf = "effectsOf", wUncheckedAssign = "uncheckedAssign",
+  wRunnableExamples = "runnableExamples", wImmediate = "immediate",
+  wConstructor = "constructor", wDestructor = "destructor",
+  wDelegator = "delegator", wOverride = "override", wImportCpp = "importcpp",
+  wCppNonPod = "cppNonPod", wImportObjC = "importobjc",
+  wImportCompilerProc = "importCompilerProc", wImportc = "importc",
+  wImportJs = "importjs", wExportc = "exportc", wExportCpp = "exportcpp",
+  wExportNims = "exportnims", wIncompleteStruct = "incompleteStruct",
+  wCompleteStruct = "completeStruct", wRequiresInit = "requiresInit",
+  wAlign = "align", wNodecl = "nodecl", wPure = "pure",
+  wSideEffect = "sideEffect", wHeader = "header",
+  wNoSideEffect = "noSideEffect", wGcSafe = "gcsafe", wNoreturn = "noreturn",
+  wNosinks = "nosinks", wLib = "lib", wDynlib = "dynlib",
+  wCompilerProc = "compilerproc", wCore = "core", wProcVar = "procvar",
+  wBase = "base", wUsed = "used", wFatal = "fatal", wError = "error",
+  wWarning = "warning", wHint = "hint", wWarningAsError = "warningAsError",
+  wHintAsError = "hintAsError", wLine = "line", wPush = "push", wPop = "pop",
+  wDefine = "define", wUndef = "undef", wLineDir = "lineDir",
+  wStackTrace = "stackTrace", wLineTrace = "lineTrace", wLink = "link",
+  wCompile = "compile", wLinksys = "linksys", wDeprecated = "deprecated",
+  wVarargs = "varargs", wCallconv = "callconv", wDebugger = "debugger",
+  wNimcall = "nimcall", wStdcall = "stdcall", wCdecl = "cdecl",
+  wSafecall = "safecall", wSyscall = "syscall", wInline = "inline",
+  wNoInline = "noinline", wFastcall = "fastcall", wThiscall = "thiscall",
+  wClosure = "closure", wNoconv = "noconv", wOn = "on", wOff = "off",
+  wChecks = "checks", wRangeChecks = "rangeChecks",
+  wBoundChecks = "boundChecks", wOverflowChecks = "overflowChecks",
+  wNilChecks = "nilChecks", wFloatChecks = "floatChecks",
+  wNanChecks = "nanChecks", wInfChecks = "infChecks",
+  wStyleChecks = "styleChecks", wStaticBoundchecks = "staticBoundChecks",
+  wNonReloadable = "nonReloadable", wExecuteOnReload = "executeOnReload",
+  wAssertions = "assertions", wPatterns = "patterns", wTrMacros = "trmacros",
+  wSinkInference = "sinkInference", wWarnings = "warnings", wHints = "hints",
+  wOptimization = "optimization", wRaises = "raises", wWrites = "writes",
+  wReads = "reads", wSize = "size", wEffects = "effects", wTags = "tags",
+  wForbids = "forbids", wRequires = "requires", wEnsures = "ensures",
+  wInvariant = "invariant", wAssume = "assume", wAssert = "assert",
+  wDeadCodeElimUnused = "deadCodeElim", wSafecode = "safecode",
+  wPackage = "package", wNoForward = "noforward", wReorder = "reorder",
+  wNoRewrite = "norewrite", wNoDestroy = "nodestroy", wPragma = "pragma",
+  wCompileTime = "compileTime", wNoInit = "noinit", wPassc = "passc",
+  wPassl = "passl", wLocalPassc = "localPassC", wBorrow = "borrow",
+  wDiscardable = "discardable", wFieldChecks = "fieldChecks",
+  wSubsChar = "subschar", wAcyclic = "acyclic", wShallow = "shallow",
+  wUnroll = "unroll", wLinearScanEnd = "linearScanEnd",
+  wComputedGoto = "computedGoto", wExperimental = "experimental",
+  wDoctype = "doctype", wWrite = "write", wGensym = "gensym",
+  wInject = "inject", wDirty = "dirty", wInheritable = "inheritable",
+  wThreadVar = "threadvar", wEmit = "emit",
+  wAsmNoStackFrame = "asmNoStackFrame", wAsmSyntax = "asmSyntax",
+  wImplicitStatic = "implicitStatic", wGlobal = "global",
+  wCodegenDecl = "codegenDecl", wUnchecked = "unchecked", wGuard = "guard",
+  wLocks = "locks", wPartial = "partial", wExplain = "explain",
+  wLiftLocals = "liftlocals", wEnforceNoRaises = "enforceNoRaises",
+  wSystemRaisesDefect = "systemRaisesDefect", wRedefine = "redefine",
+  wCallsite = "callsite", wQuirky = "quirky", wExtern = "extern",
+  wGoto = "goto", wRegister = "register", wUnion = "union", wPacked = "packed",
+  wVirtual = "virtual", wVolatile = "volatile", wMember = "member",
+  wByCopy = "bycopy", wByRef = "byref", wAuto = "auto", wBool = "bool",
+  wCatch = "catch", wChar = "char", wClass = "class", wCompl = "compl",
+  wConstCast = "const_cast", wDefault = "default", wDelete = "delete",
+  wDouble = "double", wDynamicCast = "dynamic_cast", wExplicit = "explicit",
+  wFalse = "false", wFloat = "float", wFriend = "friend", wInt = "int",
+  wLong = "long", wMutable = "mutable", wNamespace = "namespace", wNew = "new",
+  wOperator = "operator", wPrivate = "private", wProtected = "protected",
+  wPublic = "public", wReinterpretCast = "reinterpret_cast",
+  wRestrict = "restrict", wShort = "short", wSigned = "signed",
+  wSizeof = "sizeof", wStaticCast = "static_cast", wStruct = "struct",
+  wSwitch = "switch", wThis = "this", wThrow = "throw", wTrue = "true",
+  wTypedef = "typedef", wTypeid = "typeid", wTypeof = "typeof",
+  wTypename = "typename", wUnsigned = "unsigned", wVoid = "void",
+  wAlignas = "alignas", wAlignof = "alignof", wConstexpr = "constexpr",
+  wDecltype = "decltype", wNullptr = "nullptr", wNoexcept = "noexcept",
+  wThreadLocal = "thread_local", wStaticAssert = "static_assert",
+  wChar16 = "char16_t", wChar32 = "char32_t", wWchar = "wchar_t",
+  wStdIn = "stdin", wStdOut = "stdout", wStdErr = "stderr", wInOut = "inout",
+  wOneWay = "oneway", wBitsize = "bitsize", wImportHidden = "all",
+  wSendable = "sendable"
+
+ + + Source   +Edit   + +
+
+
+
TSpecialWords = set[TSpecialWord]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
ccgKeywordsHigh = 300
+
+ + + Source   +Edit   + +
+
+
+
ccgKeywordsLow = 234
+
+ + + Source   +Edit   + +
+
+
+
cppNimSharedKeywords = {wAsm, wBreak, wCase, wConst, wContinue, wDo, wElse,
+                        wEnum, wExport, wFor, wIf, wReturn, wStatic, wTemplate,
+                        wTry, wWhile, wUsing}
+
+ + + Source   +Edit   + +
+
+
+
nimKeywordsHigh = 66
+
+ + + Source   +Edit   + +
+
+
+
nimKeywordsLow = 4
+
+ + + Source   +Edit   + +
+
+
+
nonPragmaWordsHigh = wOneWay
+
+ + + Source   +Edit   + +
+
+
+
nonPragmaWordsLow = wAuto
+
+ + + Source   +Edit   + +
+
+
+
oprHigh = 71
+
+ + + Source   +Edit   + +
+
+
+
oprLow = 67
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc findStr[T: enum](a, b: static[T]; s: string; default: T): T
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compiler/wordrecg.idx b/compiler/wordrecg.idx new file mode 100644 index 0000000000000..ba237936b3b2a --- /dev/null +++ b/compiler/wordrecg.idx @@ -0,0 +1,317 @@ +nimTitle wordrecg wordrecg.html module wordrecg 0 +nim wInvalid wordrecg.html#wInvalid TSpecialWord.wInvalid 17 +nim wAddr wordrecg.html#wAddr TSpecialWord.wAddr 17 +nim wAnd wordrecg.html#wAnd TSpecialWord.wAnd 17 +nim wAs wordrecg.html#wAs TSpecialWord.wAs 17 +nim wAsm wordrecg.html#wAsm TSpecialWord.wAsm 17 +nim wBind wordrecg.html#wBind TSpecialWord.wBind 17 +nim wBlock wordrecg.html#wBlock TSpecialWord.wBlock 17 +nim wBreak wordrecg.html#wBreak TSpecialWord.wBreak 17 +nim wCase wordrecg.html#wCase TSpecialWord.wCase 17 +nim wCast wordrecg.html#wCast TSpecialWord.wCast 17 +nim wConcept wordrecg.html#wConcept TSpecialWord.wConcept 17 +nim wConst wordrecg.html#wConst TSpecialWord.wConst 17 +nim wContinue wordrecg.html#wContinue TSpecialWord.wContinue 17 +nim wConverter wordrecg.html#wConverter TSpecialWord.wConverter 17 +nim wDefer wordrecg.html#wDefer TSpecialWord.wDefer 17 +nim wDiscard wordrecg.html#wDiscard TSpecialWord.wDiscard 17 +nim wDistinct wordrecg.html#wDistinct TSpecialWord.wDistinct 17 +nim wDiv wordrecg.html#wDiv TSpecialWord.wDiv 17 +nim wDo wordrecg.html#wDo TSpecialWord.wDo 17 +nim wElif wordrecg.html#wElif TSpecialWord.wElif 17 +nim wElse wordrecg.html#wElse TSpecialWord.wElse 17 +nim wEnd wordrecg.html#wEnd TSpecialWord.wEnd 17 +nim wEnum wordrecg.html#wEnum TSpecialWord.wEnum 17 +nim wExcept wordrecg.html#wExcept TSpecialWord.wExcept 17 +nim wExport wordrecg.html#wExport TSpecialWord.wExport 17 +nim wFinally wordrecg.html#wFinally TSpecialWord.wFinally 17 +nim wFor wordrecg.html#wFor TSpecialWord.wFor 17 +nim wFrom wordrecg.html#wFrom TSpecialWord.wFrom 17 +nim wFunc wordrecg.html#wFunc TSpecialWord.wFunc 17 +nim wIf wordrecg.html#wIf TSpecialWord.wIf 17 +nim wImport wordrecg.html#wImport TSpecialWord.wImport 17 +nim wIn wordrecg.html#wIn TSpecialWord.wIn 17 +nim wInclude wordrecg.html#wInclude TSpecialWord.wInclude 17 +nim wInterface wordrecg.html#wInterface TSpecialWord.wInterface 17 +nim wIs wordrecg.html#wIs TSpecialWord.wIs 17 +nim wIsnot wordrecg.html#wIsnot TSpecialWord.wIsnot 17 +nim wIterator wordrecg.html#wIterator TSpecialWord.wIterator 17 +nim wLet wordrecg.html#wLet TSpecialWord.wLet 17 +nim wMacro wordrecg.html#wMacro TSpecialWord.wMacro 17 +nim wMethod wordrecg.html#wMethod TSpecialWord.wMethod 17 +nim wMixin wordrecg.html#wMixin TSpecialWord.wMixin 17 +nim wMod wordrecg.html#wMod TSpecialWord.wMod 17 +nim wNil wordrecg.html#wNil TSpecialWord.wNil 17 +nim wNot wordrecg.html#wNot TSpecialWord.wNot 17 +nim wNotin wordrecg.html#wNotin TSpecialWord.wNotin 17 +nim wObject wordrecg.html#wObject TSpecialWord.wObject 17 +nim wOf wordrecg.html#wOf TSpecialWord.wOf 17 +nim wOr wordrecg.html#wOr TSpecialWord.wOr 17 +nim wOut wordrecg.html#wOut TSpecialWord.wOut 17 +nim wProc wordrecg.html#wProc TSpecialWord.wProc 17 +nim wPtr wordrecg.html#wPtr TSpecialWord.wPtr 17 +nim wRaise wordrecg.html#wRaise TSpecialWord.wRaise 17 +nim wRef wordrecg.html#wRef TSpecialWord.wRef 17 +nim wReturn wordrecg.html#wReturn TSpecialWord.wReturn 17 +nim wShl wordrecg.html#wShl TSpecialWord.wShl 17 +nim wShr wordrecg.html#wShr TSpecialWord.wShr 17 +nim wStatic wordrecg.html#wStatic TSpecialWord.wStatic 17 +nim wTemplate wordrecg.html#wTemplate TSpecialWord.wTemplate 17 +nim wTry wordrecg.html#wTry TSpecialWord.wTry 17 +nim wTuple wordrecg.html#wTuple TSpecialWord.wTuple 17 +nim wType wordrecg.html#wType TSpecialWord.wType 17 +nim wUsing wordrecg.html#wUsing TSpecialWord.wUsing 17 +nim wVar wordrecg.html#wVar TSpecialWord.wVar 17 +nim wWhen wordrecg.html#wWhen TSpecialWord.wWhen 17 +nim wWhile wordrecg.html#wWhile TSpecialWord.wWhile 17 +nim wXor wordrecg.html#wXor TSpecialWord.wXor 17 +nim wYield wordrecg.html#wYield TSpecialWord.wYield 17 +nim wColon wordrecg.html#wColon TSpecialWord.wColon 17 +nim wColonColon wordrecg.html#wColonColon TSpecialWord.wColonColon 17 +nim wEquals wordrecg.html#wEquals TSpecialWord.wEquals 17 +nim wDot wordrecg.html#wDot TSpecialWord.wDot 17 +nim wDotDot wordrecg.html#wDotDot TSpecialWord.wDotDot 17 +nim wStar wordrecg.html#wStar TSpecialWord.wStar 17 +nim wMinus wordrecg.html#wMinus TSpecialWord.wMinus 17 +nim wUnderscore wordrecg.html#wUnderscore TSpecialWord.wUnderscore 17 +nim wMagic wordrecg.html#wMagic TSpecialWord.wMagic 17 +nim wThread wordrecg.html#wThread TSpecialWord.wThread 17 +nim wFinal wordrecg.html#wFinal TSpecialWord.wFinal 17 +nim wProfiler wordrecg.html#wProfiler TSpecialWord.wProfiler 17 +nim wMemTracker wordrecg.html#wMemTracker TSpecialWord.wMemTracker 17 +nim wObjChecks wordrecg.html#wObjChecks TSpecialWord.wObjChecks 17 +nim wIntDefine wordrecg.html#wIntDefine TSpecialWord.wIntDefine 17 +nim wStrDefine wordrecg.html#wStrDefine TSpecialWord.wStrDefine 17 +nim wBoolDefine wordrecg.html#wBoolDefine TSpecialWord.wBoolDefine 17 +nim wCursor wordrecg.html#wCursor TSpecialWord.wCursor 17 +nim wNoalias wordrecg.html#wNoalias TSpecialWord.wNoalias 17 +nim wEffectsOf wordrecg.html#wEffectsOf TSpecialWord.wEffectsOf 17 +nim wUncheckedAssign wordrecg.html#wUncheckedAssign TSpecialWord.wUncheckedAssign 17 +nim wRunnableExamples wordrecg.html#wRunnableExamples TSpecialWord.wRunnableExamples 17 +nim wImmediate wordrecg.html#wImmediate TSpecialWord.wImmediate 17 +nim wConstructor wordrecg.html#wConstructor TSpecialWord.wConstructor 17 +nim wDestructor wordrecg.html#wDestructor TSpecialWord.wDestructor 17 +nim wDelegator wordrecg.html#wDelegator TSpecialWord.wDelegator 17 +nim wOverride wordrecg.html#wOverride TSpecialWord.wOverride 17 +nim wImportCpp wordrecg.html#wImportCpp TSpecialWord.wImportCpp 17 +nim wCppNonPod wordrecg.html#wCppNonPod TSpecialWord.wCppNonPod 17 +nim wImportObjC wordrecg.html#wImportObjC TSpecialWord.wImportObjC 17 +nim wImportCompilerProc wordrecg.html#wImportCompilerProc TSpecialWord.wImportCompilerProc 17 +nim wImportc wordrecg.html#wImportc TSpecialWord.wImportc 17 +nim wImportJs wordrecg.html#wImportJs TSpecialWord.wImportJs 17 +nim wExportc wordrecg.html#wExportc TSpecialWord.wExportc 17 +nim wExportCpp wordrecg.html#wExportCpp TSpecialWord.wExportCpp 17 +nim wExportNims wordrecg.html#wExportNims TSpecialWord.wExportNims 17 +nim wIncompleteStruct wordrecg.html#wIncompleteStruct TSpecialWord.wIncompleteStruct 17 +nim wCompleteStruct wordrecg.html#wCompleteStruct TSpecialWord.wCompleteStruct 17 +nim wRequiresInit wordrecg.html#wRequiresInit TSpecialWord.wRequiresInit 17 +nim wAlign wordrecg.html#wAlign TSpecialWord.wAlign 17 +nim wNodecl wordrecg.html#wNodecl TSpecialWord.wNodecl 17 +nim wPure wordrecg.html#wPure TSpecialWord.wPure 17 +nim wSideEffect wordrecg.html#wSideEffect TSpecialWord.wSideEffect 17 +nim wHeader wordrecg.html#wHeader TSpecialWord.wHeader 17 +nim wNoSideEffect wordrecg.html#wNoSideEffect TSpecialWord.wNoSideEffect 17 +nim wGcSafe wordrecg.html#wGcSafe TSpecialWord.wGcSafe 17 +nim wNoreturn wordrecg.html#wNoreturn TSpecialWord.wNoreturn 17 +nim wNosinks wordrecg.html#wNosinks TSpecialWord.wNosinks 17 +nim wLib wordrecg.html#wLib TSpecialWord.wLib 17 +nim wDynlib wordrecg.html#wDynlib TSpecialWord.wDynlib 17 +nim wCompilerProc wordrecg.html#wCompilerProc TSpecialWord.wCompilerProc 17 +nim wCore wordrecg.html#wCore TSpecialWord.wCore 17 +nim wProcVar wordrecg.html#wProcVar TSpecialWord.wProcVar 17 +nim wBase wordrecg.html#wBase TSpecialWord.wBase 17 +nim wUsed wordrecg.html#wUsed TSpecialWord.wUsed 17 +nim wFatal wordrecg.html#wFatal TSpecialWord.wFatal 17 +nim wError wordrecg.html#wError TSpecialWord.wError 17 +nim wWarning wordrecg.html#wWarning TSpecialWord.wWarning 17 +nim wHint wordrecg.html#wHint TSpecialWord.wHint 17 +nim wWarningAsError wordrecg.html#wWarningAsError TSpecialWord.wWarningAsError 17 +nim wHintAsError wordrecg.html#wHintAsError TSpecialWord.wHintAsError 17 +nim wLine wordrecg.html#wLine TSpecialWord.wLine 17 +nim wPush wordrecg.html#wPush TSpecialWord.wPush 17 +nim wPop wordrecg.html#wPop TSpecialWord.wPop 17 +nim wDefine wordrecg.html#wDefine TSpecialWord.wDefine 17 +nim wUndef wordrecg.html#wUndef TSpecialWord.wUndef 17 +nim wLineDir wordrecg.html#wLineDir TSpecialWord.wLineDir 17 +nim wStackTrace wordrecg.html#wStackTrace TSpecialWord.wStackTrace 17 +nim wLineTrace wordrecg.html#wLineTrace TSpecialWord.wLineTrace 17 +nim wLink wordrecg.html#wLink TSpecialWord.wLink 17 +nim wCompile wordrecg.html#wCompile TSpecialWord.wCompile 17 +nim wLinksys wordrecg.html#wLinksys TSpecialWord.wLinksys 17 +nim wDeprecated wordrecg.html#wDeprecated TSpecialWord.wDeprecated 17 +nim wVarargs wordrecg.html#wVarargs TSpecialWord.wVarargs 17 +nim wCallconv wordrecg.html#wCallconv TSpecialWord.wCallconv 17 +nim wDebugger wordrecg.html#wDebugger TSpecialWord.wDebugger 17 +nim wNimcall wordrecg.html#wNimcall TSpecialWord.wNimcall 17 +nim wStdcall wordrecg.html#wStdcall TSpecialWord.wStdcall 17 +nim wCdecl wordrecg.html#wCdecl TSpecialWord.wCdecl 17 +nim wSafecall wordrecg.html#wSafecall TSpecialWord.wSafecall 17 +nim wSyscall wordrecg.html#wSyscall TSpecialWord.wSyscall 17 +nim wInline wordrecg.html#wInline TSpecialWord.wInline 17 +nim wNoInline wordrecg.html#wNoInline TSpecialWord.wNoInline 17 +nim wFastcall wordrecg.html#wFastcall TSpecialWord.wFastcall 17 +nim wThiscall wordrecg.html#wThiscall TSpecialWord.wThiscall 17 +nim wClosure wordrecg.html#wClosure TSpecialWord.wClosure 17 +nim wNoconv wordrecg.html#wNoconv TSpecialWord.wNoconv 17 +nim wOn wordrecg.html#wOn TSpecialWord.wOn 17 +nim wOff wordrecg.html#wOff TSpecialWord.wOff 17 +nim wChecks wordrecg.html#wChecks TSpecialWord.wChecks 17 +nim wRangeChecks wordrecg.html#wRangeChecks TSpecialWord.wRangeChecks 17 +nim wBoundChecks wordrecg.html#wBoundChecks TSpecialWord.wBoundChecks 17 +nim wOverflowChecks wordrecg.html#wOverflowChecks TSpecialWord.wOverflowChecks 17 +nim wNilChecks wordrecg.html#wNilChecks TSpecialWord.wNilChecks 17 +nim wFloatChecks wordrecg.html#wFloatChecks TSpecialWord.wFloatChecks 17 +nim wNanChecks wordrecg.html#wNanChecks TSpecialWord.wNanChecks 17 +nim wInfChecks wordrecg.html#wInfChecks TSpecialWord.wInfChecks 17 +nim wStyleChecks wordrecg.html#wStyleChecks TSpecialWord.wStyleChecks 17 +nim wStaticBoundchecks wordrecg.html#wStaticBoundchecks TSpecialWord.wStaticBoundchecks 17 +nim wNonReloadable wordrecg.html#wNonReloadable TSpecialWord.wNonReloadable 17 +nim wExecuteOnReload wordrecg.html#wExecuteOnReload TSpecialWord.wExecuteOnReload 17 +nim wAssertions wordrecg.html#wAssertions TSpecialWord.wAssertions 17 +nim wPatterns wordrecg.html#wPatterns TSpecialWord.wPatterns 17 +nim wTrMacros wordrecg.html#wTrMacros TSpecialWord.wTrMacros 17 +nim wSinkInference wordrecg.html#wSinkInference TSpecialWord.wSinkInference 17 +nim wWarnings wordrecg.html#wWarnings TSpecialWord.wWarnings 17 +nim wHints wordrecg.html#wHints TSpecialWord.wHints 17 +nim wOptimization wordrecg.html#wOptimization TSpecialWord.wOptimization 17 +nim wRaises wordrecg.html#wRaises TSpecialWord.wRaises 17 +nim wWrites wordrecg.html#wWrites TSpecialWord.wWrites 17 +nim wReads wordrecg.html#wReads TSpecialWord.wReads 17 +nim wSize wordrecg.html#wSize TSpecialWord.wSize 17 +nim wEffects wordrecg.html#wEffects TSpecialWord.wEffects 17 +nim wTags wordrecg.html#wTags TSpecialWord.wTags 17 +nim wForbids wordrecg.html#wForbids TSpecialWord.wForbids 17 +nim wRequires wordrecg.html#wRequires TSpecialWord.wRequires 17 +nim wEnsures wordrecg.html#wEnsures TSpecialWord.wEnsures 17 +nim wInvariant wordrecg.html#wInvariant TSpecialWord.wInvariant 17 +nim wAssume wordrecg.html#wAssume TSpecialWord.wAssume 17 +nim wAssert wordrecg.html#wAssert TSpecialWord.wAssert 17 +nim wDeadCodeElimUnused wordrecg.html#wDeadCodeElimUnused TSpecialWord.wDeadCodeElimUnused 17 +nim wSafecode wordrecg.html#wSafecode TSpecialWord.wSafecode 17 +nim wPackage wordrecg.html#wPackage TSpecialWord.wPackage 17 +nim wNoForward wordrecg.html#wNoForward TSpecialWord.wNoForward 17 +nim wReorder wordrecg.html#wReorder TSpecialWord.wReorder 17 +nim wNoRewrite wordrecg.html#wNoRewrite TSpecialWord.wNoRewrite 17 +nim wNoDestroy wordrecg.html#wNoDestroy TSpecialWord.wNoDestroy 17 +nim wPragma wordrecg.html#wPragma TSpecialWord.wPragma 17 +nim wCompileTime wordrecg.html#wCompileTime TSpecialWord.wCompileTime 17 +nim wNoInit wordrecg.html#wNoInit TSpecialWord.wNoInit 17 +nim wPassc wordrecg.html#wPassc TSpecialWord.wPassc 17 +nim wPassl wordrecg.html#wPassl TSpecialWord.wPassl 17 +nim wLocalPassc wordrecg.html#wLocalPassc TSpecialWord.wLocalPassc 17 +nim wBorrow wordrecg.html#wBorrow TSpecialWord.wBorrow 17 +nim wDiscardable wordrecg.html#wDiscardable TSpecialWord.wDiscardable 17 +nim wFieldChecks wordrecg.html#wFieldChecks TSpecialWord.wFieldChecks 17 +nim wSubsChar wordrecg.html#wSubsChar TSpecialWord.wSubsChar 17 +nim wAcyclic wordrecg.html#wAcyclic TSpecialWord.wAcyclic 17 +nim wShallow wordrecg.html#wShallow TSpecialWord.wShallow 17 +nim wUnroll wordrecg.html#wUnroll TSpecialWord.wUnroll 17 +nim wLinearScanEnd wordrecg.html#wLinearScanEnd TSpecialWord.wLinearScanEnd 17 +nim wComputedGoto wordrecg.html#wComputedGoto TSpecialWord.wComputedGoto 17 +nim wExperimental wordrecg.html#wExperimental TSpecialWord.wExperimental 17 +nim wDoctype wordrecg.html#wDoctype TSpecialWord.wDoctype 17 +nim wWrite wordrecg.html#wWrite TSpecialWord.wWrite 17 +nim wGensym wordrecg.html#wGensym TSpecialWord.wGensym 17 +nim wInject wordrecg.html#wInject TSpecialWord.wInject 17 +nim wDirty wordrecg.html#wDirty TSpecialWord.wDirty 17 +nim wInheritable wordrecg.html#wInheritable TSpecialWord.wInheritable 17 +nim wThreadVar wordrecg.html#wThreadVar TSpecialWord.wThreadVar 17 +nim wEmit wordrecg.html#wEmit TSpecialWord.wEmit 17 +nim wAsmNoStackFrame wordrecg.html#wAsmNoStackFrame TSpecialWord.wAsmNoStackFrame 17 +nim wAsmSyntax wordrecg.html#wAsmSyntax TSpecialWord.wAsmSyntax 17 +nim wImplicitStatic wordrecg.html#wImplicitStatic TSpecialWord.wImplicitStatic 17 +nim wGlobal wordrecg.html#wGlobal TSpecialWord.wGlobal 17 +nim wCodegenDecl wordrecg.html#wCodegenDecl TSpecialWord.wCodegenDecl 17 +nim wUnchecked wordrecg.html#wUnchecked TSpecialWord.wUnchecked 17 +nim wGuard wordrecg.html#wGuard TSpecialWord.wGuard 17 +nim wLocks wordrecg.html#wLocks TSpecialWord.wLocks 17 +nim wPartial wordrecg.html#wPartial TSpecialWord.wPartial 17 +nim wExplain wordrecg.html#wExplain TSpecialWord.wExplain 17 +nim wLiftLocals wordrecg.html#wLiftLocals TSpecialWord.wLiftLocals 17 +nim wEnforceNoRaises wordrecg.html#wEnforceNoRaises TSpecialWord.wEnforceNoRaises 17 +nim wSystemRaisesDefect wordrecg.html#wSystemRaisesDefect TSpecialWord.wSystemRaisesDefect 17 +nim wRedefine wordrecg.html#wRedefine TSpecialWord.wRedefine 17 +nim wCallsite wordrecg.html#wCallsite TSpecialWord.wCallsite 17 +nim wQuirky wordrecg.html#wQuirky TSpecialWord.wQuirky 17 +nim wExtern wordrecg.html#wExtern TSpecialWord.wExtern 17 +nim wGoto wordrecg.html#wGoto TSpecialWord.wGoto 17 +nim wRegister wordrecg.html#wRegister TSpecialWord.wRegister 17 +nim wUnion wordrecg.html#wUnion TSpecialWord.wUnion 17 +nim wPacked wordrecg.html#wPacked TSpecialWord.wPacked 17 +nim wVirtual wordrecg.html#wVirtual TSpecialWord.wVirtual 17 +nim wVolatile wordrecg.html#wVolatile TSpecialWord.wVolatile 17 +nim wMember wordrecg.html#wMember TSpecialWord.wMember 17 +nim wByCopy wordrecg.html#wByCopy TSpecialWord.wByCopy 17 +nim wByRef wordrecg.html#wByRef TSpecialWord.wByRef 17 +nim wAuto wordrecg.html#wAuto TSpecialWord.wAuto 17 +nim wBool wordrecg.html#wBool TSpecialWord.wBool 17 +nim wCatch wordrecg.html#wCatch TSpecialWord.wCatch 17 +nim wChar wordrecg.html#wChar TSpecialWord.wChar 17 +nim wClass wordrecg.html#wClass TSpecialWord.wClass 17 +nim wCompl wordrecg.html#wCompl TSpecialWord.wCompl 17 +nim wConstCast wordrecg.html#wConstCast TSpecialWord.wConstCast 17 +nim wDefault wordrecg.html#wDefault TSpecialWord.wDefault 17 +nim wDelete wordrecg.html#wDelete TSpecialWord.wDelete 17 +nim wDouble wordrecg.html#wDouble TSpecialWord.wDouble 17 +nim wDynamicCast wordrecg.html#wDynamicCast TSpecialWord.wDynamicCast 17 +nim wExplicit wordrecg.html#wExplicit TSpecialWord.wExplicit 17 +nim wFalse wordrecg.html#wFalse TSpecialWord.wFalse 17 +nim wFloat wordrecg.html#wFloat TSpecialWord.wFloat 17 +nim wFriend wordrecg.html#wFriend TSpecialWord.wFriend 17 +nim wInt wordrecg.html#wInt TSpecialWord.wInt 17 +nim wLong wordrecg.html#wLong TSpecialWord.wLong 17 +nim wMutable wordrecg.html#wMutable TSpecialWord.wMutable 17 +nim wNamespace wordrecg.html#wNamespace TSpecialWord.wNamespace 17 +nim wNew wordrecg.html#wNew TSpecialWord.wNew 17 +nim wOperator wordrecg.html#wOperator TSpecialWord.wOperator 17 +nim wPrivate wordrecg.html#wPrivate TSpecialWord.wPrivate 17 +nim wProtected wordrecg.html#wProtected TSpecialWord.wProtected 17 +nim wPublic wordrecg.html#wPublic TSpecialWord.wPublic 17 +nim wReinterpretCast wordrecg.html#wReinterpretCast TSpecialWord.wReinterpretCast 17 +nim wRestrict wordrecg.html#wRestrict TSpecialWord.wRestrict 17 +nim wShort wordrecg.html#wShort TSpecialWord.wShort 17 +nim wSigned wordrecg.html#wSigned TSpecialWord.wSigned 17 +nim wSizeof wordrecg.html#wSizeof TSpecialWord.wSizeof 17 +nim wStaticCast wordrecg.html#wStaticCast TSpecialWord.wStaticCast 17 +nim wStruct wordrecg.html#wStruct TSpecialWord.wStruct 17 +nim wSwitch wordrecg.html#wSwitch TSpecialWord.wSwitch 17 +nim wThis wordrecg.html#wThis TSpecialWord.wThis 17 +nim wThrow wordrecg.html#wThrow TSpecialWord.wThrow 17 +nim wTrue wordrecg.html#wTrue TSpecialWord.wTrue 17 +nim wTypedef wordrecg.html#wTypedef TSpecialWord.wTypedef 17 +nim wTypeid wordrecg.html#wTypeid TSpecialWord.wTypeid 17 +nim wTypeof wordrecg.html#wTypeof TSpecialWord.wTypeof 17 +nim wTypename wordrecg.html#wTypename TSpecialWord.wTypename 17 +nim wUnsigned wordrecg.html#wUnsigned TSpecialWord.wUnsigned 17 +nim wVoid wordrecg.html#wVoid TSpecialWord.wVoid 17 +nim wAlignas wordrecg.html#wAlignas TSpecialWord.wAlignas 17 +nim wAlignof wordrecg.html#wAlignof TSpecialWord.wAlignof 17 +nim wConstexpr wordrecg.html#wConstexpr TSpecialWord.wConstexpr 17 +nim wDecltype wordrecg.html#wDecltype TSpecialWord.wDecltype 17 +nim wNullptr wordrecg.html#wNullptr TSpecialWord.wNullptr 17 +nim wNoexcept wordrecg.html#wNoexcept TSpecialWord.wNoexcept 17 +nim wThreadLocal wordrecg.html#wThreadLocal TSpecialWord.wThreadLocal 17 +nim wStaticAssert wordrecg.html#wStaticAssert TSpecialWord.wStaticAssert 17 +nim wChar16 wordrecg.html#wChar16 TSpecialWord.wChar16 17 +nim wChar32 wordrecg.html#wChar32 TSpecialWord.wChar32 17 +nim wWchar wordrecg.html#wWchar TSpecialWord.wWchar 17 +nim wStdIn wordrecg.html#wStdIn TSpecialWord.wStdIn 17 +nim wStdOut wordrecg.html#wStdOut TSpecialWord.wStdOut 17 +nim wStdErr wordrecg.html#wStdErr TSpecialWord.wStdErr 17 +nim wInOut wordrecg.html#wInOut TSpecialWord.wInOut 17 +nim wOneWay wordrecg.html#wOneWay TSpecialWord.wOneWay 17 +nim wBitsize wordrecg.html#wBitsize TSpecialWord.wBitsize 17 +nim wImportHidden wordrecg.html#wImportHidden TSpecialWord.wImportHidden 17 +nim wSendable wordrecg.html#wSendable TSpecialWord.wSendable 17 +nim TSpecialWord wordrecg.html#TSpecialWord enum TSpecialWord 17 +nim TSpecialWords wordrecg.html#TSpecialWords type TSpecialWords 127 +nim oprLow wordrecg.html#oprLow const oprLow 130 +nim oprHigh wordrecg.html#oprHigh const oprHigh 131 +nim nimKeywordsLow wordrecg.html#nimKeywordsLow const nimKeywordsLow 133 +nim nimKeywordsHigh wordrecg.html#nimKeywordsHigh const nimKeywordsHigh 134 +nim ccgKeywordsLow wordrecg.html#ccgKeywordsLow const ccgKeywordsLow 136 +nim ccgKeywordsHigh wordrecg.html#ccgKeywordsHigh const ccgKeywordsHigh 137 +nim cppNimSharedKeywords wordrecg.html#cppNimSharedKeywords const cppNimSharedKeywords 139 +nim nonPragmaWordsLow wordrecg.html#nonPragmaWordsLow const nonPragmaWordsLow 143 +nim nonPragmaWordsHigh wordrecg.html#nonPragmaWordsHigh const nonPragmaWordsHigh 144 +nim findStr wordrecg.html#findStr,static[T],static[T],string,T proc findStr[T: enum](a, b: static[T]; s: string; default: T): T 149 diff --git a/compilesettings.html b/compilesettings.html new file mode 100644 index 0000000000000..94bf1dda7948d --- /dev/null +++ b/compilesettings.html @@ -0,0 +1,229 @@ + + + + + + + +std/compilesettings + + + + + + + + + + + + + + + + +
+
+

std/compilesettings

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module allows querying the compiler about diverse configuration settings. See also compileOption.

+
+

Types

+
+
+
MultipleValueSetting {.pure.} = enum
+  nimblePaths,              ## the nimble path(s)
+  searchPaths,              ## the search path for modules
+  lazyPaths,                ## experimental: even more paths
+  commandArgs,              ## the arguments passed to the Nim compiler
+  cincludes,                ## the #include paths passed to the C/C++ compiler
+  clibs                      ## libraries passed to the C/C++ compiler
+
+ + +settings resulting in a seq of string values + Source   +Edit   + +
+
+
+
SingleValueSetting {.pure.} = enum
+  arguments,                ## experimental: the arguments passed after '-r'
+  outFile,                  ## experimental: the output file
+  outDir,                   ## the output directory
+  nimcacheDir,              ## the location of the 'nimcache' directory
+  projectName,              ## the project's name that is being compiled
+  projectPath,              ## experimental: some path to the project that is being compiled
+  projectFull,              ## the full path to the project that is being compiled
+  command, ## experimental: the command (e.g. 'c', 'cpp', 'doc') passed to
+            ## the Nim compiler
+  commandLine,              ## experimental: the command line passed to Nim
+  linkOptions,              ## additional options passed to the linker
+  compileOptions,           ## additional options passed to the C/C++ compiler
+  ccompilerPath,            ## the path to the C/C++ compiler
+  backend, ## the backend (eg: c|cpp|objc|js); both `nim doc --backend:js`
+            ## and `nim js` would imply backend=js
+  libPath,                  ## the absolute path to the stdlib library, i.e. nim's `--lib`, since 1.5.1
+  gc {....deprecated.},        ## gc selected
+  mm                         ## memory management selected
+
+ + +settings resulting in a single string value + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc querySetting(setting: SingleValueSetting): string {.compileTime,
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Can be used to get a string compile-time option.

+

See also:

+ + +

Example:

+
const nimcache = querySetting(SingleValueSetting.nimcacheDir)
+ Source   +Edit   + +
+
+ +
+
+
+
proc querySettingSeq(setting: MultipleValueSetting): seq[string] {.compileTime,
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Can be used to get a multi-string compile-time option.

+

See also:

+ + +

Example:

+
const nimblePaths = querySettingSeq(MultipleValueSetting.nimblePaths)
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/compilesettings.idx b/compilesettings.idx new file mode 100644 index 0000000000000..9965f0b4d44ba --- /dev/null +++ b/compilesettings.idx @@ -0,0 +1,5 @@ +nimTitle compilesettings compilesettings.html module std/compilesettings 0 +nim SingleValueSetting compilesettings.html#SingleValueSetting enum SingleValueSetting 17 +nim MultipleValueSetting compilesettings.html#MultipleValueSetting enum MultipleValueSetting 38 +nim querySetting compilesettings.html#querySetting,SingleValueSetting proc querySetting(setting: SingleValueSetting): string 47 +nim querySettingSeq compilesettings.html#querySettingSeq,MultipleValueSetting proc querySettingSeq(setting: MultipleValueSetting): seq[string] 58 diff --git a/complex.html b/complex.html new file mode 100644 index 0000000000000..a3fe9b9605071 --- /dev/null +++ b/complex.html @@ -0,0 +1,1268 @@ + + + + + + + +std/complex + + + + + + + + + + + + + + + + +
+
+

std/complex

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements complex numbers and basic mathematical operations on them.

+

Complex numbers are currently generic over 64-bit or 32-bit floats.

+ +

Example:

+
import std/complex
+from std/math import almostEqual, sqrt
+
+let
+  z1 = complex(1.0, 2.0)
+  z2 = complex(3.0, -4.0)
+
+assert almostEqual(z1 + z2, complex(4.0, -2.0))
+assert almostEqual(z1 - z2, complex(-2.0, 6.0))
+assert almostEqual(z1 * z2, complex(11.0, 2.0))
+assert almostEqual(z1 / z2, complex(-0.2, 0.4))
+
+assert almostEqual(abs(z1), sqrt(5.0))
+assert almostEqual(conjugate(z1), complex(1.0, -2.0))
+
+let (r, phi) = z1.polar
+assert almostEqual(rect(r, phi), z1)

+
+

Imports

+
+ math, strformat +
+
+
+

Types

+
+
+
Complex[T] = object
+  re*, im*: T
+
+ + A complex number, consisting of a real and an imaginary part. + Source   +Edit   + +
+
+
+
Complex32 = Complex[float32]
+
+ + Alias for a complex number using 32-bit floats. + Source   +Edit   + +
+
+
+
Complex64 = Complex[float64]
+
+ + Alias for a complex number using 64-bit floats. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `$`(z: Complex): string
+
+ + Returns z's string representation as "(re, im)". +

Example:

+
doAssert $complex(1.0, 2.0) == "(1.0, 2.0)"
+ Source   +Edit   + +
+
+ +
+
+
+
func `*`[T](x, y: Complex[T]): Complex[T]
+
+ + Multiplies two complex numbers. + Source   +Edit   + +
+
+
+
func `*`[T](x: Complex[T]; y: T): Complex[T]
+
+ + Multiplies a complex number with a real number. + Source   +Edit   + +
+
+
+
func `*`[T](x: T; y: Complex[T]): Complex[T]
+
+ + Multiplies a real number with a complex number. + Source   +Edit   + +
+
+ +
+
+
+
func `*=`[T](x: var Complex[T]; y: Complex[T])
+
+ + Multiplies x by y. + Source   +Edit   + +
+
+ +
+
+
+
func `+`[T](x, y: Complex[T]): Complex[T]
+
+ + Adds two complex numbers. + Source   +Edit   + +
+
+
+
func `+`[T](x: Complex[T]; y: T): Complex[T]
+
+ + Adds a complex number to a real number. + Source   +Edit   + +
+
+
+
func `+`[T](x: T; y: Complex[T]): Complex[T]
+
+ + Adds a real number to a complex number. + Source   +Edit   + +
+
+ +
+
+
+
func `+=`[T](x: var Complex[T]; y: Complex[T])
+
+ + Adds y to x. + Source   +Edit   + +
+
+ +
+
+
+
func `-`[T](x, y: Complex[T]): Complex[T]
+
+ + Subtracts two complex numbers. + Source   +Edit   + +
+
+
+
func `-`[T](x: Complex[T]; y: T): Complex[T]
+
+ + Subtracts a real number from a complex number. + Source   +Edit   + +
+
+
+
func `-`[T](x: T; y: Complex[T]): Complex[T]
+
+ + Subtracts a complex number from a real number. + Source   +Edit   + +
+
+
+
func `-`[T](z: Complex[T]): Complex[T]
+
+ + Unary minus for complex numbers. + Source   +Edit   + +
+
+ +
+
+
+
func `-=`[T](x: var Complex[T]; y: Complex[T])
+
+ + Subtracts y from x. + Source   +Edit   + +
+
+ +
+
+
+
func `/`[T](x, y: Complex[T]): Complex[T]
+
+ + Divides two complex numbers. + Source   +Edit   + +
+
+
+
func `/`[T](x: Complex[T]; y: T): Complex[T]
+
+ + Divides a complex number by a real number. + Source   +Edit   + +
+
+
+
func `/`[T](x: T; y: Complex[T]): Complex[T]
+
+ + Divides a real number by a complex number. + Source   +Edit   + +
+
+ +
+
+
+
func `/=`[T](x: var Complex[T]; y: Complex[T])
+
+ + Divides x by y in place. + Source   +Edit   + +
+
+ +
+
+
+
func `==`[T](x, y: Complex[T]): bool
+
+ + Compares two complex numbers for equality. + Source   +Edit   + +
+
+ +
+
+
+
func abs[T](z: Complex[T]): T
+
+ + Returns the absolute value of z, that is the distance from (0, 0) to z. + Source   +Edit   + +
+
+ +
+
+
+
func abs2[T](z: Complex[T]): T
+
+ + Returns the squared absolute value of z, that is the squared distance from (0, 0) to z. This is more efficient than abs(z) ^ 2. + Source   +Edit   + +
+
+ +
+
+
+
func almostEqual[T: SomeFloat](x, y: Complex[T]; unitsInLastPlace: Natural = 4): bool
+
+ +

Checks if two complex values are almost equal, using the machine epsilon.

+

Two complex values are considered almost equal if their real and imaginary components are almost equal.

+

unitsInLastPlace is the max number of units in the last place difference tolerated when comparing two numbers. The larger the value, the more error is allowed. A 0 value means that two numbers must be exactly the same to be considered equal.

+

The machine epsilon has to be scaled to the magnitude of the values used and multiplied by the desired precision in ULPs unless the difference is subnormal.

+ + Source   +Edit   + +
+
+ +
+
+
+
func arccos[T](z: Complex[T]): Complex[T]
+
+ + Returns the inverse cosine of z. + Source   +Edit   + +
+
+ +
+
+
+
func arccosh[T](z: Complex[T]): Complex[T]
+
+ + Returns the inverse hyperbolic cosine of z. + Source   +Edit   + +
+
+ +
+
+
+
func arccot[T](z: Complex[T]): Complex[T]
+
+ + Returns the inverse cotangent of z. + Source   +Edit   + +
+
+ +
+
+
+
func arccoth[T](z: Complex[T]): Complex[T]
+
+ + Returns the inverse hyperbolic cotangent of z. + Source   +Edit   + +
+
+ +
+
+
+
func arccsc[T](z: Complex[T]): Complex[T]
+
+ + Returns the inverse cosecant of z. + Source   +Edit   + +
+
+ +
+
+
+
func arccsch[T](z: Complex[T]): Complex[T]
+
+ + Returns the inverse hyperbolic cosecant of z. + Source   +Edit   + +
+
+ +
+
+
+
func arcsec[T](z: Complex[T]): Complex[T]
+
+ + Returns the inverse secant of z. + Source   +Edit   + +
+
+ +
+
+
+
func arcsech[T](z: Complex[T]): Complex[T]
+
+ + Returns the inverse hyperbolic secant of z. + Source   +Edit   + +
+
+ +
+
+
+
func arcsin[T](z: Complex[T]): Complex[T]
+
+ + Returns the inverse sine of z. + Source   +Edit   + +
+
+ +
+
+
+
func arcsinh[T](z: Complex[T]): Complex[T]
+
+ + Returns the inverse hyperbolic sine of z. + Source   +Edit   + +
+
+ +
+
+
+
func arctan[T](z: Complex[T]): Complex[T]
+
+ + Returns the inverse tangent of z. + Source   +Edit   + +
+
+ +
+
+
+
func arctanh[T](z: Complex[T]): Complex[T]
+
+ + Returns the inverse hyperbolic tangent of z. + Source   +Edit   + +
+
+ +
+
+
+
func complex[T: SomeFloat](re: T; im: T = 0.0): Complex[T]
+
+ + Returns a Complex[T] with real part re and imaginary part im. + Source   +Edit   + +
+
+ +
+
+
+
func complex32(re: float32; im: float32 = 0.0): Complex32 {....raises: [],
+    tags: [], forbids: [].}
+
+ + Returns a Complex32 with real part re and imaginary part im. + Source   +Edit   + +
+
+ +
+
+
+
func complex64(re: float64; im: float64 = 0.0): Complex64 {....raises: [],
+    tags: [], forbids: [].}
+
+ + Returns a Complex64 with real part re and imaginary part im. + Source   +Edit   + +
+
+ +
+
+
+
func conjugate[T](z: Complex[T]): Complex[T]
+
+ + Returns the complex conjugate of z (complex(z.re, -z.im)). + Source   +Edit   + +
+
+ +
+
+
+
func cos[T](z: Complex[T]): Complex[T]
+
+ + Returns the cosine of z. + Source   +Edit   + +
+
+ +
+
+
+
func cosh[T](z: Complex[T]): Complex[T]
+
+ + Returns the hyperbolic cosine of z. + Source   +Edit   + +
+
+ +
+
+
+
func cot[T](z: Complex[T]): Complex[T]
+
+ + Returns the cotangent of z. + Source   +Edit   + +
+
+ +
+
+
+
func coth[T](z: Complex[T]): Complex[T]
+
+ + Returns the hyperbolic cotangent of z. + Source   +Edit   + +
+
+ +
+
+
+
func csc[T](z: Complex[T]): Complex[T]
+
+ + Returns the cosecant of z. + Source   +Edit   + +
+
+ +
+
+
+
func csch[T](z: Complex[T]): Complex[T]
+
+ + Returns the hyperbolic cosecant of z. + Source   +Edit   + +
+
+ +
+
+
+
func exp[T](z: Complex[T]): Complex[T]
+
+ + Computes the exponential function (e^z). + Source   +Edit   + +
+
+ +
+
+
+
proc formatValue(result: var string; value: Complex; specifier: string)
+
+ + Standard format implementation for Complex. It makes little sense to call this directly, but it is required to exist by the & macro. For complex numbers, we add a specific 'j' specifier, which formats the value as (A+Bj) like in mathematics. + Source   +Edit   + +
+
+ +
+
+
+
func inv[T](z: Complex[T]): Complex[T]
+
+ + Returns the multiplicative inverse of z (1/z). + Source   +Edit   + +
+
+ +
+
+
+
func ln[T](z: Complex[T]): Complex[T]
+
+ + Returns the (principal value of the) natural logarithm of z. + Source   +Edit   + +
+
+ +
+
+
+
func log2[T](z: Complex[T]): Complex[T]
+
+ +

Returns the logarithm base 2 of z.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func log10[T](z: Complex[T]): Complex[T]
+
+ +

Returns the logarithm base 10 of z.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func phase[T](z: Complex[T]): T
+
+ + Returns the phase (or argument) of z, that is the angle in polar representation.

result = arctan2(z.im, z.re)

+ Source   +Edit   + +
+
+ +
+
+
+
func polar[T](z: Complex[T]): tuple[r, phi: T]
+
+ + Returns z in polar coordinates.

result.r = abs(z)
result.phi = phase(z)

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func pow[T](x, y: Complex[T]): Complex[T]
+
+ + x raised to the power of y. + Source   +Edit   + +
+
+
+
func pow[T](x: Complex[T]; y: T): Complex[T]
+
+ + The complex number x raised to the power of the real number y. + Source   +Edit   + +
+
+ +
+
+
+
func rect[T](r, phi: T): Complex[T]
+
+ + Returns the complex number with polar coordinates r and phi.

result.re = r * cos(phi)
result.im = r * sin(phi)

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func sec[T](z: Complex[T]): Complex[T]
+
+ + Returns the secant of z. + Source   +Edit   + +
+
+ +
+
+
+
func sech[T](z: Complex[T]): Complex[T]
+
+ + Returns the hyperbolic secant of z. + Source   +Edit   + +
+
+ +
+
+
+
func sgn[T](z: Complex[T]): Complex[T]
+
+ + Returns the phase of z as a unit complex number, or 0 if z is 0. + Source   +Edit   + +
+
+ +
+
+
+
func sin[T](z: Complex[T]): Complex[T]
+
+ + Returns the sine of z. + Source   +Edit   + +
+
+ +
+
+
+
func sinh[T](z: Complex[T]): Complex[T]
+
+ + Returns the hyperbolic sine of z. + Source   +Edit   + +
+
+ +
+
+
+
func sqrt[T](z: Complex[T]): Complex[T]
+
+ + Computes the (principal) square root of a complex number z. + Source   +Edit   + +
+
+ +
+
+
+
func tan[T](z: Complex[T]): Complex[T]
+
+ + Returns the tangent of z. + Source   +Edit   + +
+
+ +
+
+
+
func tanh[T](z: Complex[T]): Complex[T]
+
+ + Returns the hyperbolic tangent of z. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template im(arg: float32): Complex32
+
+ + Returns arg as an imaginary number (complex32(0, arg)). + Source   +Edit   + +
+
+
+
template im(arg: float64): Complex64
+
+ + Returns arg as an imaginary number (complex64(0, arg)). + Source   +Edit   + +
+
+
+
template im(arg: typedesc[float32]): Complex32
+
+ + Returns the imaginary unit (complex32(0, 1)). + Source   +Edit   + +
+
+
+
template im(arg: typedesc[float64]): Complex64
+
+ + Returns the imaginary unit (complex64(0, 1)). + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/complex.idx b/complex.idx new file mode 100644 index 0000000000000..4c6a974f65cb2 --- /dev/null +++ b/complex.idx @@ -0,0 +1,77 @@ +nimTitle complex complex.html module std/complex 0 +nim Complex complex.html#Complex object Complex 39 +nim Complex64 complex.html#Complex64 type Complex64 42 +nim Complex32 complex.html#Complex32 type Complex32 44 +nim complex complex.html#complex,T,T proc complex[T: SomeFloat](re: T; im: T = 0.0): Complex[T] 47 +nim complex32 complex.html#complex32,float32,float32 proc complex32(re: float32; im: float32 = 0.0): Complex32 51 +nim complex64 complex.html#complex64,float64,float64 proc complex64(re: float64; im: float64 = 0.0): Complex64 55 +nim im complex.html#im.t,typedesc[float32] template im(arg: typedesc[float32]): Complex32 59 +nim im complex.html#im.t,typedesc[float64] template im(arg: typedesc[float64]): Complex64 61 +nim im complex.html#im.t,float32 template im(arg: float32): Complex32 63 +nim im complex.html#im.t,float64 template im(arg: float64): Complex64 65 +nim abs complex.html#abs,Complex[T] proc abs[T](z: Complex[T]): T 68 +nim abs2 complex.html#abs2,Complex[T] proc abs2[T](z: Complex[T]): T 73 +nim sgn complex.html#sgn,Complex[T] proc sgn[T](z: Complex[T]): Complex[T] 79 +nim conjugate complex.html#conjugate,Complex[T] proc conjugate[T](z: Complex[T]): Complex[T] 88 +nim inv complex.html#inv,Complex[T] proc inv[T](z: Complex[T]): Complex[T] 92 +nim `==` complex.html#==,Complex[T],Complex[T] proc `==`[T](x, y: Complex[T]): bool 96 +nim `+` complex.html#+,T,Complex[T] proc `+`[T](x: T; y: Complex[T]): Complex[T] 100 +nim `+` complex.html#+,Complex[T],T proc `+`[T](x: Complex[T]; y: T): Complex[T] 104 +nim `+` complex.html#+,Complex[T],Complex[T] proc `+`[T](x, y: Complex[T]): Complex[T] 108 +nim `-` complex.html#-,Complex[T] proc `-`[T](z: Complex[T]): Complex[T] 112 +nim `-` complex.html#-,T,Complex[T] proc `-`[T](x: T; y: Complex[T]): Complex[T] 116 +nim `-` complex.html#-,Complex[T],T proc `-`[T](x: Complex[T]; y: T): Complex[T] 120 +nim `-` complex.html#-,Complex[T],Complex[T] proc `-`[T](x, y: Complex[T]): Complex[T] 124 +nim `*` complex.html#*,T,Complex[T] proc `*`[T](x: T; y: Complex[T]): Complex[T] 128 +nim `*` complex.html#*,Complex[T],T proc `*`[T](x: Complex[T]; y: T): Complex[T] 132 +nim `*` complex.html#*,Complex[T],Complex[T] proc `*`[T](x, y: Complex[T]): Complex[T] 136 +nim `/` complex.html#/,Complex[T],T proc `/`[T](x: Complex[T]; y: T): Complex[T] 141 +nim `/` complex.html#/,T,Complex[T] proc `/`[T](x: T; y: Complex[T]): Complex[T] 145 +nim `/` complex.html#/,Complex[T],Complex[T] proc `/`[T](x, y: Complex[T]): Complex[T] 149 +nim `+=` complex.html#+=,Complex[T],Complex[T] proc `+=`[T](x: var Complex[T]; y: Complex[T]) 153 +nim `-=` complex.html#-=,Complex[T],Complex[T] proc `-=`[T](x: var Complex[T]; y: Complex[T]) 158 +nim `*=` complex.html#*=,Complex[T],Complex[T] proc `*=`[T](x: var Complex[T]; y: Complex[T]) 163 +nim `/=` complex.html#/=,Complex[T],Complex[T] proc `/=`[T](x: var Complex[T]; y: Complex[T]) 169 +nim sqrt complex.html#sqrt,Complex[T] proc sqrt[T](z: Complex[T]): Complex[T] 174 +nim exp complex.html#exp,Complex[T] proc exp[T](z: Complex[T]): Complex[T] 198 +nim ln complex.html#ln,Complex[T] proc ln[T](z: Complex[T]): Complex[T] 205 +nim log10 complex.html#log10,Complex[T] proc log10[T](z: Complex[T]): Complex[T] 211 +nim log2 complex.html#log2,Complex[T] proc log2[T](z: Complex[T]): Complex[T] 218 +nim pow complex.html#pow,Complex[T],Complex[T] proc pow[T](x, y: Complex[T]): Complex[T] 225 +nim pow complex.html#pow,Complex[T],T proc pow[T](x: Complex[T]; y: T): Complex[T] 263 +nim sin complex.html#sin,Complex[T] proc sin[T](z: Complex[T]): Complex[T] 267 +nim arcsin complex.html#arcsin,Complex[T] proc arcsin[T](z: Complex[T]): Complex[T] 271 +nim cos complex.html#cos,Complex[T] proc cos[T](z: Complex[T]): Complex[T] 275 +nim arccos complex.html#arccos,Complex[T] proc arccos[T](z: Complex[T]): Complex[T] 281 +nim tan complex.html#tan,Complex[T] proc tan[T](z: Complex[T]): Complex[T] 285 +nim arctan complex.html#arctan,Complex[T] proc arctan[T](z: Complex[T]): Complex[T] 289 +nim cot complex.html#cot,Complex[T] proc cot[T](z: Complex[T]): Complex[T] 293 +nim arccot complex.html#arccot,Complex[T] proc arccot[T](z: Complex[T]): Complex[T] 297 +nim sec complex.html#sec,Complex[T] proc sec[T](z: Complex[T]): Complex[T] 301 +nim arcsec complex.html#arcsec,Complex[T] proc arcsec[T](z: Complex[T]): Complex[T] 305 +nim csc complex.html#csc,Complex[T] proc csc[T](z: Complex[T]): Complex[T] 309 +nim arccsc complex.html#arccsc,Complex[T] proc arccsc[T](z: Complex[T]): Complex[T] 313 +nim sinh complex.html#sinh,Complex[T] proc sinh[T](z: Complex[T]): Complex[T] 317 +nim arcsinh complex.html#arcsinh,Complex[T] proc arcsinh[T](z: Complex[T]): Complex[T] 321 +nim cosh complex.html#cosh,Complex[T] proc cosh[T](z: Complex[T]): Complex[T] 325 +nim arccosh complex.html#arccosh,Complex[T] proc arccosh[T](z: Complex[T]): Complex[T] 329 +nim tanh complex.html#tanh,Complex[T] proc tanh[T](z: Complex[T]): Complex[T] 333 +nim arctanh complex.html#arctanh,Complex[T] proc arctanh[T](z: Complex[T]): Complex[T] 337 +nim coth complex.html#coth,Complex[T] proc coth[T](z: Complex[T]): Complex[T] 341 +nim arccoth complex.html#arccoth,Complex[T] proc arccoth[T](z: Complex[T]): Complex[T] 345 +nim sech complex.html#sech,Complex[T] proc sech[T](z: Complex[T]): Complex[T] 349 +nim arcsech complex.html#arcsech,Complex[T] proc arcsech[T](z: Complex[T]): Complex[T] 353 +nim csch complex.html#csch,Complex[T] proc csch[T](z: Complex[T]): Complex[T] 357 +nim arccsch complex.html#arccsch,Complex[T] proc arccsch[T](z: Complex[T]): Complex[T] 361 +nim phase complex.html#phase,Complex[T] proc phase[T](z: Complex[T]): T 365 +nim polar complex.html#polar,Complex[T] proc polar[T](z: Complex[T]): tuple[r, phi: T] 371 +nim rect complex.html#rect,T,T proc rect[T](r, phi: T): Complex[T] 381 +nim almostEqual complex.html#almostEqual,Complex[T: SomeFloat],Complex[T: SomeFloat],Natural proc almostEqual[T: SomeFloat](x, y: Complex[T]; unitsInLastPlace: Natural = 4): bool 391 +nim `$` complex.html#$,Complex proc `$`(z: Complex): string 410 +nim formatValue complex.html#formatValue,string,Complex,string proc formatValue(result: var string; value: Complex; specifier: string) 439 +nimgrp pow complex.html#pow-procs-all proc 225 +nimgrp - complex.html#--procs-all proc 112 +nimgrp + complex.html#+-procs-all proc 100 +nimgrp / complex.html#/-procs-all proc 141 +nimgrp * complex.html#*-procs-all proc 128 +nimgrp im complex.html#im-templates-all template 59 diff --git a/contributing.html b/contributing.html new file mode 100644 index 0000000000000..eff311deb35c6 --- /dev/null +++ b/contributing.html @@ -0,0 +1,518 @@ + + + + + + + +Contributing + + + + + + + + + + + + + + + + +
+
+

Contributing

+
+ +
+ Source   +Edit   + +
+ +

Contributing happens via "Pull requests" (PR) on GitHub. Every PR needs to be reviewed before it can be merged and the Continuous Integration should be green. The title of a PR should contain a brief description. If it fixes an issue, in addition to the number of the issue, the title should also contain a description of the issue.

+

The PR has to be approved by two core developers or by Araq.

+ +

Writing tests

There are 4 types of tests:

+
  1. runnableExamples documentation comment tests, ran by nim doc mymod.nim These end up in documentation and ensure documentation stays in sync with code.
  2. +
  3. separate test files, e.g.: tests/stdlib/tos.nim. In nim repo, testament (see below) runs all $nim/tests/*/t*.nim test files; for nimble packages, see https://github.com/nim-lang/nimble#tests.
  4. +
  5. (deprecated) tests in when isMainModule: block, ran by nim r mymod.nim. nimble test can run those in nimble packages when specified in a task "test".
  6. +
  7. (not preferred) .. code-block:: nim RST snippets; these should only be used in rst sources, in nim sources runnableExamples should now always be preferred to those for several reasons (cleaner syntax, syntax highlights, batched testing, and parameter rdoccmd allows customization).
  8. +
+

Not all the tests follow the convention here, feel free to change the ones that don't. Always leave the code cleaner than you found it.

+ +

Stdlib

Each stdlib module (anything under lib/, e.g. lib/pure/os.nim) should preferably have a corresponding separate test file, e.g. tests/stdlib/tos.nim. The old convention was to add a when isMainModule: block in the source file, which only gets executed when the tester is building the file.

+

Each test should be in a separate block: statement, such that each has its own scope. Use boolean conditions and doAssert for the testing by itself, don't rely on echo statements or similar; in particular, avoid things like echo "done". Don't use unittest.suite and unittest.test.

+

Sample test:

+

block: # foo
+  doAssert foo(1) == 10
+
+block: # bug #1234
+  static: doAssert 1+1 == 2
+
+block: # bug #1235
+  var seq2D = newSeqWith(4, newSeq[bool](2))
+  seq2D[0][0] = true
+  seq2D[1][0] = true
+  seq2D[0][1] = true
+  doAssert seq2D == @[@[true, true], @[true, false],
+                      @[false, false], @[false, false]]
+  # doAssert with `not` can now be done as follows:
+  doAssert not (1 == 2)

+

Always refer to a GitHub issue using the following exact syntax: bug #1234 as shown above, so that it's consistent and easier to search or for tooling. Some browser extensions (e.g. https://github.com/sindresorhus/refined-github) will even turn those in clickable links when it works.

+

Rationale for using a separate test file instead of when isMainModule: block:

+
  • allows custom compiler flags or testing options (see details below)
  • +
  • faster CI since they can be joined in megatest (combined into a single test)
  • +
  • avoids making the parser do un-necessary work when a source file is merely imported
  • +
  • avoids mixing source and test code when reporting line of code statistics or code coverage
  • +
+ +

Compiler

The tests for the compiler use a testing tool called testament. They are all located in tests/ (e.g.: tests/destructor/tdestructor3.nim). Each test has its own file. All test files are prefixed with t. If you want to create a file for import into another test only, use the prefix m.

+

At the beginning of every test is the expected behavior of the test. Possible keys are:

+
  • cmd: A compilation command template e.g. nim $target --threads:on $options $file
  • +
  • output: The expected output (stdout + stderr), most likely via echo
  • +
  • exitcode: Exit code of the test (via exit(number))
  • +
  • errormsg: The expected compiler error message
  • +
  • file: The file the errormsg was produced at
  • +
  • line: The line the errormsg was produced at
  • +
+

For a full spec, see here: testament/specs.nim

+

An example of a test:

+

discard """
+  errormsg: "type mismatch: got (PTest)"
+"""
+
+type
+  PTest = ref object
+
+proc test(x: PTest, y: int) = nil
+
+var buf: PTest
+buf.test()

+ +

Running tests

You can run the tests with

+

./koch tests

+

which will run a good subset of tests. Some tests may fail. If you only want to see the output of failing tests, go for

+

./koch tests --failing all

+

You can also run only a single category of tests. A category is a subdirectory in the tests/ directory. There are a couple of special categories; for a list of these, see testament/categories.nim, at the bottom.

+

./koch tests c lib # compiles / runs stdlib modules, including `isMainModule` tests
+./koch tests c megatest # runs a set of tests that can be combined into 1

+

To run a single test:

+

./koch test run <category>/<name>    # e.g.: tuples/ttuples_issues
+./koch test run tests/stdlib/tos.nim # can also provide relative path

+

For reproducible tests (to reproduce an environment more similar to the one run by Continuous Integration on GitHub actions/azure pipelines), you may want to disable your local configuration (e.g. in ~/.config/nim/nim.cfg) which may affect some tests; this can also be achieved by using export XDG_CONFIG_HOME=pathtoAlternateConfig before running ./koch commands.

+ +

Comparing tests

Test failures can be grepped using Failure:.

+

The tester can compare two test runs. First, you need to create a reference test. You'll also need to the commit id, because that's what the tester needs to know in order to compare the two.

+

git checkout devel
+DEVEL_COMMIT=$(git rev-parse HEAD)
+./koch tests

+

Then switch over to your changes and run the tester again.

+

git checkout your-changes
+./koch tests

+

Then you can ask the tester to create a testresults.html which will tell you if any new tests passed/failed.

+

./koch tests --print html $DEVEL_COMMIT

+ +

Deprecation

Backwards compatibility is important. When renaming types, procedures, etc. the old name must be marked as deprecated using the deprecated pragma:

+

# for routines (proc/template/macro/iterator) and types:
+proc oldProc(a: int, b: float): bool {.deprecated:
+    "deprecated since v1.2.3; use `newImpl: string -> int` instead".} = discard
+
+# for (const/var/let/fields) the msg is not yet supported:
+const Foo {.deprecated.}  = 1
+
+# for enum types, you can deprecate the type or some elements
+# (likewise with object types and their fields):
+type Bar {.deprecated.} = enum bar0, bar1
+type Barz  = enum baz0, baz1 {.deprecated.}, baz2

+

See also Deprecated pragma in the manual.

+ +

Documentation

When contributing new procs, be sure to add documentation, especially if the proc is public. Even private procs benefit from documentation and can be viewed using nim doc --docInternal foo.nim. Documentation begins on the line following the proc definition, and is prefixed by ## on each line.

+

Runnable code examples are also encouraged, to show typical behavior with a few test cases (typically 1 to 3 assert statements, depending on complexity). These runnableExamples are automatically run by nim doc mymodule.nim as well as testament and guarantee they stay in sync.

+

proc addBar*(a: string): string =
+  ## Adds "Bar" to `a`.
+  runnableExamples:
+    assert "baz".addBar == "bazBar"
+  result = a & "Bar"

+

See parentDir example.

+

The RestructuredText Nim uses has a special syntax for including code snippets embedded in documentation; these are not run by nim doc and therefore are not guaranteed to stay in sync, so runnableExamples is almost always preferred:

+

proc someProc*(): string =
+  ## Returns "something"
+  ##
+  ##   ```
+  ##   echo someProc() # "something"
+  ##   ```
+  result = "something" # single-hash comments do not produce documentation

+

The ``` followed by a newline and an indentation instructs the nim doc command to produce syntax-highlighted example code with the documentation (``` is sufficient inside a .nim module, while from a .md one needs to set the language explicitly as ```nim).

+

When forward declaration is used, the documentation should be included with the first appearance of the proc.

+

proc hello*(): string
+  ## Put documentation here
+proc nothing() = discard
+proc hello*(): string =
+  ## ignore this
+  echo "hello"

+

The preferred documentation style is to begin with a capital letter and use the third-person singular. That is, between:

+

proc hello*(): string =
+  ## Returns "hello"
+  result = "hello"

+

or

+

proc hello*(): string =
+  ## say hello
+  result = "hello"

+

the first is preferred.

+

When you specify an RST role (highlighting/interpretation marker) do it in the postfix form for uniformity, that is after `text in backticks`. For example an :idx: role for referencing a topic ("SQLite" in the example below) from Nim Index can be used in doc comment this way:

+

## A higher level `SQLite`:idx: database wrapper.

+

Inline monospaced text can be input using `single backticks` or ``double backticks``. The former are syntactically highlighted, the latter are not. To avoid accidental highlighting follow this rule in *.nim files:

+
  • Use single backticks for fragments of code in Nim and other programming languages, including identifiers, in *.nim files.

    +

    For languages other than Nim add a role after final backtick, e.g. for C++ inline highlighting:

    +
    `#include <stdio.h>`:cpp:
    +

    For a currently unsupported language add the :code: role, like for SQL in this example:

    +
    `SELECT * FROM <table_name>;`:code:
    +

    Highlight shell commands by :cmd: role; for command line options use :option: role, e.g.: `--docInternal`:option:.

    +
  • +
  • Use double backticks:
    • For file names: ``os.nim``
    • +
    • For fragments of strings not enclosed by " and " and not related to code, e.g. text of compiler messages
    • +
    • When code ends with a standalone \ (otherwise a combination of \ and a final ` would get escaped)
    • +
    +
  • +
+
Note: +*.rst files have :literal: as their default role. So for them the rule above is only applicable if the :nim: role is set up manually as the default [1]:
.. role:: nim(code)
+   :language: nim
+.. default-role:: nim
+

The first 2 lines are for other RST implementations, including Github one.

+
+
  this is fulfilled when doc/rstcommon.rst is included. +
+
+
+ +

Best practices

Note: these are general guidelines, not hard rules; there are always exceptions. Code reviews can just point to a specific section here to save time and propagate best practices.

+

New defined(foo) symbols need to be prefixed by the nimble package name, or by nim for symbols in nim sources (e.g. compiler, standard library). This is to avoid name conflicts across packages.

+

# if in nim sources
+when defined(allocStats): discard # bad, can cause conflicts
+when defined(nimAllocStats): discard # preferred
+# if in a package `cligen`:
+when defined(debug): discard # bad, can cause conflicts
+when defined(cligenDebug): discard # preferred

+

Take advantage of no implicit bool conversion

+

doAssert isValid() == true
+doAssert isValid() # preferred

+

Design with method call syntax chaining in mind

+

proc foo(cond: bool, lines: seq[string]) # bad
+proc foo(lines: seq[string], cond: bool) # preferred
+# can be called as: `getLines().foo(false)`

+

Use exceptions (including assert / doAssert) instead of quit rationale: https://forum.nim-lang.org/t/4089

+

quit() # bad in almost all cases
+doAssert() # preferred

+

Use doAssert (or unittest.check, unittest.require), not assert in all tests, so they'll be enabled even with --assertions:off.

+

block: # foo
+  assert foo() # bad
+  doAssert foo() # preferred

+

An exception to the above rule is runnableExamples and code-block rst blocks intended to be used as runnableExamples, which for brevity use assert instead of doAssert. Note that nim doc -d:danger main won't pass -d:danger to the runnableExamples, but nim doc --doccmd:-d:danger main would, and so would the second example below:

+

runnableExamples:
+  doAssert foo() # bad
+  assert foo() # preferred
+
+runnableExamples("-d:danger"):
+  doAssert foo() # `assert` would be disabled here, so `doAssert` makes more sense

+

Delegate printing to caller: return string instead of calling echo rationale: it's more flexible (e.g. allows the caller to call custom printing, including prepending location info, writing to log files, etc.).

+

proc foo() = echo "bar" # bad
+proc foo(): string = "bar" # preferred (usually)

+

(Ongoing debate) Consider using Option instead of return bool + var argument, unless stack allocation is needed (e.g. for efficiency).

+

proc foo(a: var Bar): bool
+proc foo(): Option[Bar]

+

Tests (including in testament) should always prefer assertions over echo, except when that's not possible. It's more precise, easier for readers and maintainers to where expected values refer to. See for example https://github.com/nim-lang/Nim/pull/9335 and https://forum.nim-lang.org/t/4089

+

echo foo() # adds a line for testament in `output:` block inside `discard`.
+doAssert foo() == [1, 2] # preferred, except when not possible to do so.

+ +

The git stuff

+

General commit rules

  1. Important, critical bugfixes that have a tiny chance of breaking somebody's code should be backported to the latest stable release branch (currently 1.4.x) and maybe also all the way back to the 1.0.x branch. The commit message should contain the tag [backport] for "backport to the latest stable release" and the tag [backport:$VERSION] for backporting back to the given $VERSION (and all newer releases).
  2. +
  3. If you introduce changes which affect backward compatibility, make breaking changes, or have PR which is tagged as [feature], the changes should be mentioned in the changelog.
  4. +
  5. All changes introduced by the commit (diff lines) must be related to the subject of the commit.

    +

    If you change something unrelated to the subject parts of the file, because your editor reformatted automatically the code or whatever different reason, this should be excluded from the commit.

    +

    Tip: Never commit everything as-is using git commit -a, but review carefully your changes with git add -p.

    +
  6. +
  7. Changes should not introduce any trailing whitespace.

    +

    Always check your changes for whitespace errors using git diff --check or add the following pre-commit hook:

    +

    #!/bin/sh
    +git diff --check --cached || exit $?

    +
  8. +
  9. Describe your commit and use your common sense. Example commit message:
    Fixes #123; refs #124
    +

    indicates that issue #123 is completely fixed (GitHub may automatically close it when the PR is committed), whereas issue #124 is referenced (e.g.: partially fixed) and won't close the issue when committed.

    +
  10. +
  11. PR body (not just PR title) should contain references to fixed/referenced GitHub issues, e.g.: fix #123 or refs #123. This is so that you get proper cross-referencing from linked issue to the PR (GitHub won't make those links with just a PR title, and commit messages aren't always sufficient to ensure that, e.g. can't be changed after a PR is merged).
  12. +
  13. Commits should be always be rebased against devel (so a fast-forward merge can happen)

    +

    e.g.: use git pull --rebase origin devel. This is to avoid messing up git history. Exceptions should be very rare: when rebase gives too many conflicts, simply squash all commits using the script shown in https://github.com/nim-lang/Nim/pull/9356

    +
  14. +
  15. Do not mix pure formatting changes (e.g. whitespace changes, nimpretty) or automated changes with other code changes: these should be in separate commits (and the merge on GitHub should not squash these into 1).
  16. +
+ +

Continuous Integration (CI)

  1. Continuous Integration is by default run on every push in a PR; this clogs the CI pipeline and affects other PR's; if you don't need it (e.g. for WIP or documentation only changes), add [skip ci] to your commit message title. This convention is supported by our GitHub actions pipelines and our azure pipeline (using custom logic, which should complete in < 1mn) as well as our former other pipelines: Appveyor and Travis.
  2. +
  3. Consider enabling CI (azure, GitHub actions and builds.sr.ht) in your own Nim fork, and waiting for CI to be green in that fork (fixing bugs as needed) before opening your PR in the original Nim repo, to reduce CI congestion. Same applies for updates on a PR: you can test commits on a separate private branch before updating the main PR.
  4. +
+ +

Debugging CI failures, flaky tests, etc

  1. First check the CI logs and search for FAIL to find why CI failed; if the failure seems related to your PR, try to fix the code instead of restarting CI.
  2. +
  3. If CI failure seems unrelated to your PR, it could be caused by a flaky test. File a bug for it if it isn't already reported. A PR push (or opening/closing PR) will re-trigger all CI jobs (even successful ones, which can be wasteful). Instead, request collaboration from the Nim team. The Nim team should follow these instructions to only restart the jobs that failed: +
  4. +
+ +

Code reviews

  1. Whenever possible, use GitHub's new 'Suggested change' in code reviews, which saves time explaining the change or applying it; see also https://forum.nim-lang.org/t/4317
  2. +
  3. When reviewing large diffs that may involve code moving around, GitHub's interface doesn't help much, as it doesn't highlight moves. Instead, you can use something like this, see visual results here:

    +

    git fetch origin pull/10431/head && git checkout FETCH_HEAD
    +git diff --color-moved-ws=allow-indentation-change --color-moved=blocks HEAD^

    +
  4. +
  5. In addition, you can view GitHub-like diffs locally to identify what was changed within a code block using diff-highlight or diff-so-fancy, e.g.:
    # put this in ~/.gitconfig:
    +[core]
    +  pager = "diff-so-fancy | less -R" # or: use: `diff-highlight`
    +
  6. +
+ +

Documentation Style

+

General Guidelines

  • See also nep1 which should probably be merged here.
  • +
  • Authors should document anything that is exported; documentation for private procs can be useful too (visible via nim doc --docInternal foo.nim).
  • +
  • Within documentation, a period (.) should follow each sentence (or sentence fragment) in a comment block. The documentation may be limited to one sentence fragment, but if multiple sentences are within the documentation, each sentence after the first should be complete and in present tense.
  • +
  • Documentation is parsed as a custom ReStructuredText (RST) with partial markdown support.
  • +
  • In nim sources, prefer single backticks to double backticks since it's simpler and nim doc supports it. Likewise with rst files: nim rst2html will render those as monospace, and adding .. default-role:: code to an rst file will also make those render as monospace when rendered directly in tools such as github.
  • +
  • (debatable) In nim sources, for links, prefer [link text](link.html) to `link text<link.html>`_ since the syntax is simpler and markdown is more common (likewise, nim rst2html also supports it in rst files).

    +

    proc someproc*(s: string, foo: int) =
    +  ## Use single backticks for inline code, e.g.: `s` or `someExpr(true)`.
    +  ## Use a backlash to follow with alphanumeric char: `int8`\s are great.

    +
  • +
+ +

Module-level documentation

Documentation of a module is placed at the top of the module itself. Each line of documentation begins with double hashes (##). Sometimes ##[ multiline docs containing code ]## is preferable, see lib/pure/times.nim. Code samples are encouraged, and should follow the general RST syntax:

+

## The `universe` module computes the answer to life, the universe, and everything.
+##
+##   ```
+##   doAssert computeAnswerString() == 42
+##   ```

+

Within this top-level comment, you can indicate the authorship and copyright of the code, which will be featured in the produced documentation.

+

## This is the best module ever. It provides answers to everything!
+##
+## :Author: Steve McQueen
+## :Copyright: 1965
+##

+

Leave a space between the last line of top-level documentation and the beginning of Nim code (the imports, etc.).

+ +

Procs, Templates, Macros, Converters, and Iterators

The documentation of a procedure should begin with a capital letter and should be in present tense. Variables referenced in the documentation should be surrounded by single tick marks:

+

proc example1*(x: int) =
+  ## Prints the value of `x`.
+  echo x

+

Whenever an example of usage would be helpful to the user, you should include one within the documentation in RST format as below.

+

proc addThree*(x, y, z: int8): int =
+  ## Adds three `int8` values, treating them as unsigned and
+  ## truncating the result.
+  ##
+  ##   ```
+  ##   # things that aren't suitable for a `runnableExamples` go in code block:
+  ##   echo execCmdEx("git pull")
+  ##   drawOnScreen()
+  ##   ```
+  runnableExamples:
+    # `runnableExamples` is usually preferred to code blocks, when possible.
+    doAssert addThree(3, 125, 6) == -122
+  result = x +% y +% z

+

The command nim doc will then correctly syntax highlight the Nim code within the documentation.

+ +

Types

Exported types should also be documented. This documentation can also contain code samples, but those are better placed with the functions to which they refer.

+

type
+  NamedQueue*[T] = object ## Provides a linked data structure with names
+                          ## throughout. It is named for convenience. I'm making
+                          ## this comment long to show how you can, too.
+    name*: string ## The name of the item
+    val*: T ## Its value
+    next*: ref NamedQueue[T] ## The next item in the queue

+

You have some flexibility when placing the documentation:

+

type
+  NamedQueue*[T] = object
+    ## Provides a linked data structure with names
+    ## throughout. It is named for convenience. I'm making
+    ## this comment long to show how you can, too.
+    name*: string ## The name of the item
+    val*: T ## Its value
+    next*: ref NamedQueue[T] ## The next item in the queue

+

Make sure to place the documentation beside or within the object.

+

type
+  ## Bad: this documentation disappears because it annotates the `type` keyword
+  ## above, not `NamedQueue`.
+  NamedQueue*[T] = object
+    name*: string ## This becomes the main documentation for the object, which
+                  ## is not what we want.
+    val*: T ## Its value
+    next*: ref NamedQueue[T] ## The next item in the queue

+ +

Var, Let, and Const

When declaring module-wide constants and values, documentation is encouraged. The placement of doc comments is similar to the type sections.

+

const
+  X* = 42 ## An awesome number.
+  SpreadArray* = [
+    [1,2,3],
+    [2,3,1],
+    [3,1,2],
+  ] ## Doc comment for `SpreadArray`.

+

Placement of comments in other areas is usually allowed, but will not become part of the documentation output and should therefore be prefaced by a single hash (#).

+

const
+  BadMathVals* = [
+    3.14, # pi
+    2.72, # e
+    0.58, # gamma
+  ] ## A bunch of badly rounded values.

+

Nim supports Unicode in comments, so the above can be replaced with the following:

+

const
+  BadMathVals* = [
+    3.14, # π
+    2.72, # e
+    0.58, # γ
+  ] ## A bunch of badly rounded values (including π!).

+ +

Evolving the stdlib

As outlined in https://github.com/nim-lang/RFCs/issues/173 there are a couple of guidelines about what should go into the stdlib, what should be added and what eventually should be removed.

+ +

What the compiler itself needs must be part of the stdlib

Maybe in the future the compiler itself can depend on Nimble packages but for the time being, we strive to have zero dependencies in the compiler as the compiler is the root of the bootstrapping process and is also used to build Nimble.

+ +

Vocabulary types must be part of the stdlib

These are types most packages need to agree on for better interoperability, for example Option[T]. This rule also covers the existing collections like Table, CountTable etc. "Sorted" containers based on a tree-like data structure are still missing and should be added.

+

Time handling, especially the Time type are also covered by this rule.

+ +

Existing, battle-tested modules stay

Reason: There is no benefit in moving them around just to fulfill some design fashion as in "Nim's core MUST BE SMALL". If you don't like an existing module, don't import it. If a compilation target (e.g. JS) cannot support a module, document this limitation.

+

This covers modules like os, osproc, strscans, strutils, strformat, etc.

+ +

Syntactic helpers can start as experimental stdlib modules

Reason: Generally speaking as external dependencies they are not exposed to enough users so that we can see if the shortcuts provide enough benefit or not. Many programmers avoid external dependencies, especially for "tiny syntactic improvements". However, this is only true for really good syntactic improvements that have the potential to clean up other parts of the Nim library substantially. If in doubt, new stdlib modules should start as external, successful Nimble packages.

+ +

Other new stdlib modules do not start as stdlib modules

As we strive for higher quality everywhere, it's easier to adopt existing, battle-tested modules eventually rather than creating modules from scratch.

+ +

Little additions are acceptable

As long as they are documented and tested well, adding little helpers to existing modules is acceptable. For two reasons:

+
  1. It makes Nim easier to learn and use in the long run. ("Why does sequtils lack a countIt? Because version 1.0 happens to have lacked it? Silly...")
  2. +
  3. To encourage contributions. Contributors often start with PRs that add simple things, then they stay and also fix bugs. Nim is an open source project and lives from people's contributions and involvement. Newly introduced issues have to be balanced against motivating new people. We know where to find perfectly designed pieces of software that have no bugs -- these are the systems that nobody uses.
  4. +
+ +

Conventions

  1. New stdlib modules should go under Nim/lib/std/. The rationale is to require users to import via import std/foo instead of import foo, which would cause potential conflicts with nimble packages. Note that this still applies for new modules in existing logical directories, e.g.: use lib/std/collections/foo.nim, not lib/pure/collections/foo.nim.
  2. +
  3. New module names should prefer plural form whenever possible, e.g.: std/sums.nim instead of std/sum.nim. In particular, this reduces chances of conflicts between module name and the symbols it defines. Furthermore, module names should use snake_case and not use capital letters, which cause issues when going from an OS without case sensitivity to an OS with it.
  4. +
+ +

Breaking Changes

Introducing breaking changes, no matter how well-intentioned, creates long-term problems for the community, in particular those looking to promote reusable Nim code in libraries: In the Nim distribution, critical security and bugfixes, language changes and community improvements are bundled in a single distribution - it is difficult to make partial upgrades with only benign changes. When one library depends on a legacy behavior, it can no longer be used together with another library that does not, breaking all downstream applications - the standard library is unique in that it sits at the root of all dependency trees.

+

There is a big difference between compile-time breaking changes and run-time breaking changes.

+ +

Run-time breaking changes

Run-time breaking changes are to be avoided at almost all costs: Nim is used for mission critical applications which depend on behaviours that are not covered by the test suite. As such, it's important that changes to the stable parts of the standard library are made avoiding changing the existing behaviors, even when the test suite continues to pass.

+

Examples of run-time breaking changes:

+
  • Raising exceptions of a new type, compared to what's currently being raised.
  • +
  • Adding unconstrained or poorly constrained generic procs or macros ("hash now works for all ref T"): This may cause code to behave differently depending only on which modules are imported - common examples include == and hash.
  • +
  • Changing behavior of existing functions like:
    • "Nim's path handling procs like getXDir now consistently lack the trailing slash"
    • +
    • "Nim's strformat implementation is now more consistent with Python"
    • +
    +
  • +
+

Instead, write new code that explicitly announces the feature you think we announced but didn't. For example, strformat does not say "it's compatible with Python", it says "inspired by Python's f-strings". This new code can be submitted to the stdlib and the old code can be deprecated or published as a Nimble package.

+

Sometimes, a run-time breaking change is most desirable: For example, a string representation of a floating point number that "roundtrips" is much better than a string representation that doesn't. These run-time breaking changes must start in the state "opt-in" via a new -d:nimPreviewX or command line flag and then should become the new default later, in follow-up versions. This way users can track regressions more easily. ("git bisect" is not an acceptable alternative, that's for Nim compiler developers, not for Nim users.)

+

Above all else, additive approaches that don't change existing behaviors should be preferred.

+ +

Compile-time breaking changes

Compile-time breaking changes are usually easier to handle, but for large code bases they can also involve a large amount of work and can hinder the adoption of a new Nim release. Additive approaches are to be preferred here as well.

+

Examples of compile-time breaking changes include (but are not limited to):

+
  • Renaming functions and modules, or moving things. Instead of a direct rename, deprecate the old name and introduce a new one.
  • +
  • Renaming the parameter names: Thanks to Nim's "named parameter" calling syntax like f(x = 0, y = 1) this is a breaking change. Instead, live with the existing parameter names.
  • +
  • Adding an enum value to an existing enum. Nim's exhaustive case statements stop compiling after such a change. Instead, consider to introduce new bool fields/parameters. This can be impractical though, so we use good judgement and our list of "important packages" to see if it doesn't break too much code out there in practice.
  • +
  • Adding a new proc to an existing stdlib module. However, for aesthetic reasons this is often preferred over introducing a new module with just a single proc inside. We use good judgement and our list of "important packages" to see if it doesn't break too much code out there in practice. The new procs need to be annotated with a .since annotation.
  • +
+ +

Compiler/language spec bugfixes

This can even be applied to compiler "bugfixes": If the compiler should have been "pickier" in its handling of typedesc, instead of "fixing typedesc handling bugs", consider the following solution:

+
  • Spec out how typedesc should really work and also spec out the cases where it should not be allowed!
  • +
  • Deprecate typedesc and name the new metatype something new like typeArg.
  • +
  • Implement the spec.
  • +
+ +

Non-breaking changes

Examples of changes that are considered non-breaking (or acceptable breaking changes) include:

+
  • Creating a new module.
  • +
  • Adding an overload to an already overloaded proc.
  • +
  • Adding new default parameters to an existing proc. It is assumed that you do not use Nim's stdlib procs's addresses (that you don't use them as first class entities).
  • +
  • Changing the calling convention from nimcall to inline (but first RFC https://github.com/nim-lang/RFCs/issues/396 needs to be implemented).
  • +
  • Changing the behavior from "crashing" into some other, well documented result (including raising a Defect, but not raising an exception that does not inherit from Defect).
  • +
  • Adding new fields to an existing object.
  • +
+

Nim's introspection facilities imply that strictly speaking almost every addition can break somebody's code. It is impractical to care about these cases, a change that only affects introspection is not considered to be a breaking change.

+

+ +
+
+ + +
+
+ + + + diff --git a/contributing.idx b/contributing.idx new file mode 100644 index 0000000000000..b6e0d1c943f82 --- /dev/null +++ b/contributing.idx @@ -0,0 +1,33 @@ +markupTitle Contributing contributing.html Contributing 0 +heading Writing tests contributing.html#writing-tests Writing tests 0 +heading Stdlib contributing.html#writing-tests-stdlib Stdlib 0 +heading Compiler contributing.html#writing-tests-compiler Compiler 0 +heading Running tests contributing.html#running-tests Running tests 0 +heading Comparing tests contributing.html#comparing-tests Comparing tests 0 +heading Deprecation contributing.html#deprecation Deprecation 0 +heading Documentation contributing.html#documentation Documentation 0 +heading Best practices contributing.html#best-practices Best practices 0 +heading The cmdgit stuff contributing.html#the-cmdgit-stuff The git stuff 0 +heading General commit rules contributing.html#the-cmdgit-stuff-general-commit-rules General commit rules 0 +heading Continuous Integration (CI) contributing.html#the-cmdgit-stuff-continuous-integration-ci Continuous Integration (CI) 0 +heading Debugging CI failures, flaky tests, etc contributing.html#the-cmdgit-stuff-debugging-ci-failures-flaky-tests-etc Debugging CI failures, flaky tests, etc 0 +heading Code reviews contributing.html#the-cmdgit-stuff-code-reviews Code reviews 0 +heading Documentation Style contributing.html#documentation-style Documentation Style 0 +heading General Guidelines contributing.html#documentation-style-general-guidelines General Guidelines 0 +heading Module-level documentation contributing.html#documentation-style-moduleminuslevel-documentation Module-level documentation 0 +heading Procs, Templates, Macros, Converters, and Iterators contributing.html#documentation-style-procs-templates-macros-converters-and-iterators Procs, Templates, Macros, Converters, and Iterators 0 +heading Types contributing.html#documentation-style-types Types 0 +heading Var, Let, and Const contributing.html#documentation-style-var-let-and-const Var, Let, and Const 0 +heading Evolving the stdlib contributing.html#evolving-the-stdlib Evolving the stdlib 0 +heading What the compiler itself needs must be part of the stdlib contributing.html#evolving-the-stdlib-what-the-compiler-itself-needs-must-be-part-of-the-stdlib What the compiler itself needs must be part of the stdlib 0 +heading Vocabulary types must be part of the stdlib contributing.html#evolving-the-stdlib-vocabulary-types-must-be-part-of-the-stdlib Vocabulary types must be part of the stdlib 0 +heading Existing, battle-tested modules stay contributing.html#evolving-the-stdlib-existing-battleminustested-modules-stay Existing, battle-tested modules stay 0 +heading Syntactic helpers can start as experimental stdlib modules contributing.html#evolving-the-stdlib-syntactic-helpers-can-start-as-experimental-stdlib-modules Syntactic helpers can start as experimental stdlib modules 0 +heading Other new stdlib modules do not start as stdlib modules contributing.html#evolving-the-stdlib-other-new-stdlib-modules-do-not-start-as-stdlib-modules Other new stdlib modules do not start as stdlib modules 0 +heading Little additions are acceptable contributing.html#evolving-the-stdlib-little-additions-are-acceptable Little additions are acceptable 0 +heading Conventions contributing.html#evolving-the-stdlib-conventions Conventions 0 +heading Breaking Changes contributing.html#breaking-changes Breaking Changes 0 +heading Run-time breaking changes contributing.html#breaking-changes-runminustime-breaking-changes Run-time breaking changes 0 +heading Compile-time breaking changes contributing.html#breaking-changes-compileminustime-breaking-changes Compile-time breaking changes 0 +heading Compiler/language spec bugfixes contributing.html#breaking-changes-compilerslashlanguage-spec-bugfixes Compiler/language spec bugfixes 0 +heading Non-breaking changes contributing.html#breaking-changes-nonminusbreaking-changes Non-breaking changes 0 diff --git a/cookies.html b/cookies.html new file mode 100644 index 0000000000000..f729903bc1b4c --- /dev/null +++ b/cookies.html @@ -0,0 +1,196 @@ + + + + + + + +std/cookies + + + + + + + + + + + + + + + + +
+
+

std/cookies

+
+ +
+ Source   +Edit   + +
+ +

This module implements helper procs for parsing Cookies.

+ +
+

Types

+
+
+
SameSite {.pure.} = enum
+  Default, None, Lax, Strict
+
+ + The SameSite cookie attribute. Default means that setCookie proc will not set SameSite attribute. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc parseCookies(s: string): StringTableRef {....raises: [], tags: [], forbids: [].}
+
+ +

Parses cookies into a string table.

+

The proc is meant to parse the Cookie header set by a client, not the "Set-Cookie" header set by servers.

+ +

Example:

+
import std/strtabs
+let cookieJar = parseCookies("a=1; foo=bar")
+assert cookieJar["a"] == "1"
+assert cookieJar["foo"] == "bar"
+ Source   +Edit   + +
+
+ +
+
+
+
proc setCookie(key, value: string; domain = ""; path = ""; expires = "";
+               noName = false; secure = false; httpOnly = false;
+               maxAge = none(int); sameSite = SameSite.Default): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Creates a command in the format of Set-Cookie: key=value; Domain=...; ...
Tip: +Cookies can be vulnerable. Consider setting secure=true, httpOnly=true and sameSite=Strict.
+ + Source   +Edit   + +
+
+
+
proc setCookie(key, value: string; expires: DateTime | Time; domain = "";
+               path = ""; noName = false; secure = false; httpOnly = false;
+               maxAge = none(int); sameSite = SameSite.Default): string
+
+ + Creates a command in the format of Set-Cookie: key=value; Domain=...; ... + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/cookies.idx b/cookies.idx new file mode 100644 index 0000000000000..ab72f215a61a8 --- /dev/null +++ b/cookies.idx @@ -0,0 +1,6 @@ +nimTitle cookies cookies.html module std/cookies 0 +nim SameSite cookies.html#SameSite enum SameSite 19 +nim parseCookies cookies.html#parseCookies,string proc parseCookies(s: string): StringTableRef 24 +nim setCookie cookies.html#setCookie,string,string,string,string,string proc setCookie(key, value: string; domain = ""; path = ""; expires = "";\n noName = false; secure = false; httpOnly = false; maxAge = none(int);\n sameSite = SameSite.Default): string 50 +nim setCookie cookies.html#setCookie,string,string,,string,string proc setCookie(key, value: string; expires: DateTime | Time; domain = ""; path = "";\n noName = false; secure = false; httpOnly = false; maxAge = none(int);\n sameSite = SameSite.Default): string 73 +nimgrp setcookie cookies.html#setCookie-procs-all proc 50 diff --git a/coro.html b/coro.html new file mode 100644 index 0000000000000..f33b1620bfb36 --- /dev/null +++ b/coro.html @@ -0,0 +1,239 @@ + + + + + + + +std/coro + + + + + + + + + + + + + + + + +
+
+

std/coro

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Nim coroutines implementation, supports several context switching methods: + + +
ucontextavailable on unix and alike (default)
setjmpavailable on unix and alike (x86/64 only)
fibersavailable and required on windows.

-d:nimCoroutines
Required to build this module.
+
-d:nimCoroutinesUcontext
Use ucontext backend.
+
-d:nimCoroutinesSetjmp
Use setjmp backend.
+
-d:nimCoroutinesSetjmpBundled
Use bundled setjmp implementation.
+

Unstable API.

+Timer support for the realtime GC. Based on https://github.com/jckarter/clay/blob/master/compiler/hirestimer.cpp

+ +
+

Types

+
+
+
CoroutineRef = ref object
+
+ + CoroutineRef holds a pointer to actual coroutine object. Public API always returns CoroutineRef instead of CoroutinePtr in order to allow holding a reference to coroutine object while it can be safely deallocated by coroutine scheduler loop. In this case Coroutine.reference.coro is set to nil. Public API checks for it being nil and gracefully fails if it is nil. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc alive(c: CoroutineRef): bool {....raises: [], tags: [], forbids: [].}
+
+ + Returns true if coroutine has not returned, false otherwise. + Source   +Edit   + +
+
+ +
+
+
+
proc nimGC_setStackBottom(theStackBottom: pointer) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc run() {....raises: [], tags: [TimeEffect], forbids: [].}
+
+ + Starts main coroutine scheduler loop which exits when all coroutines exit. Calling this proc starts execution of first coroutine. + Source   +Edit   + +
+
+ +
+
+
+
proc start(c: proc (); stacksize: int = defaultStackSize): CoroutineRef {.
+    discardable, ...raises: [], tags: [], forbids: [].}
+
+ + Schedule coroutine for execution. It does not run immediately. + Source   +Edit   + +
+
+ +
+
+
+
proc suspend(sleepTime: float = 0.0) {....raises: [], tags: [], forbids: [].}
+
+ + Stops coroutine execution and resumes no sooner than after sleeptime seconds. Until then other coroutines are executed. + Source   +Edit   + +
+
+ +
+
+
+
proc wait(c: CoroutineRef; interval = 0.01) {....raises: [], tags: [], forbids: [].}
+
+ + Returns only after coroutine c has returned. interval is time in seconds how often. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/coro.idx b/coro.idx new file mode 100644 index 0000000000000..af258a6a161f1 --- /dev/null +++ b/coro.idx @@ -0,0 +1,8 @@ +nimTitle coro coro.html module std/coro 0 +nim nimGC_setStackBottom coro.html#nimGC_setStackBottom,pointer proc nimGC_setStackBottom(theStackBottom: pointer) 42 +nim CoroutineRef coro.html#CoroutineRef type CoroutineRef 166 +nim suspend coro.html#suspend,float proc suspend(sleepTime: float = 0.0) 235 +nim start coro.html#start,proc),int proc start(c: proc (); stacksize: int = defaultStackSize): CoroutineRef 270 +nim run coro.html#run proc run() 298 +nim alive coro.html#alive,CoroutineRef proc alive(c: CoroutineRef): bool 339 +nim wait coro.html#wait,CoroutineRef,float proc wait(c: CoroutineRef; interval = 0.01) 342 diff --git a/cpuinfo.html b/cpuinfo.html new file mode 100644 index 0000000000000..e98c3a872b231 --- /dev/null +++ b/cpuinfo.html @@ -0,0 +1,123 @@ + + + + + + + +std/cpuinfo + + + + + + + + + + + + + + + + +
+
+

std/cpuinfo

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a proc to determine the number of CPUs / cores. +

Example:

+
import std/cpuinfo
+doAssert countProcessors() > 0

+
+

Imports

+
+ posix +
+
+
+

Procs

+
+
+
+
proc countProcessors(): int {....gcsafe, extern: "ncpi$1", raises: [], tags: [],
+                              forbids: [].}
+
+ + Returns the number of the processors/cores the machine has. Returns 0 if it cannot be detected. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/cpuinfo.idx b/cpuinfo.idx new file mode 100644 index 0000000000000..bf6f8b9e60928 --- /dev/null +++ b/cpuinfo.idx @@ -0,0 +1,2 @@ +nimTitle cpuinfo cpuinfo.html module std/cpuinfo 0 +nim countProcessors cpuinfo.html#countProcessors proc countProcessors(): int 107 diff --git a/cpuload.html b/cpuload.html new file mode 100644 index 0000000000000..35d7c0a282f31 --- /dev/null +++ b/cpuload.html @@ -0,0 +1,164 @@ + + + + + + + +std/cpuload + + + + + + + + + + + + + + + + +
+
+

std/cpuload

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a helper for a thread pool to determine whether creating a thread is a good idea.

+

Unstable API.

+

+
+

Imports

+
+ cpuinfo, syncio +
+
+
+

Types

+
+
+
ThreadPoolAdvice = enum
+  doNothing, doCreateThread, doShutdownThread
+
+ + + Source   +Edit   + +
+
+
+
ThreadPoolState = object
+  when defined(windows):
+  calls*: int
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc advice(s: var ThreadPoolState): ThreadPoolAdvice {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/cpuload.idx b/cpuload.idx new file mode 100644 index 0000000000000..7fba9f02c0f91 --- /dev/null +++ b/cpuload.idx @@ -0,0 +1,7 @@ +nimTitle cpuload cpuload.html module std/cpuload 0 +nim doNothing cpuload.html#doNothing ThreadPoolAdvice.doNothing 26 +nim doCreateThread cpuload.html#doCreateThread ThreadPoolAdvice.doCreateThread 26 +nim doShutdownThread cpuload.html#doShutdownThread ThreadPoolAdvice.doShutdownThread 26 +nim ThreadPoolAdvice cpuload.html#ThreadPoolAdvice enum ThreadPoolAdvice 26 +nim ThreadPoolState cpuload.html#ThreadPoolState object ThreadPoolState 31 +nim advice cpuload.html#advice,ThreadPoolState proc advice(s: var ThreadPoolState): ThreadPoolAdvice 36 diff --git a/critbits.html b/critbits.html new file mode 100644 index 0000000000000..57799d292ffa2 --- /dev/null +++ b/critbits.html @@ -0,0 +1,822 @@ + + + + + + + +std/critbits + + + + + + + + + + + + + + + + +
+
+

std/critbits

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a crit bit tree which is an efficient container for a sorted set of strings, or for a sorted mapping of strings. Based on the excellent paper by Adam Langley. (A crit bit tree is a form of radix tree or patricia trie.) +

Example:

+
import std/critbits
+from std/sequtils import toSeq
+
+var critbitAsSet: CritBitTree[void] = ["kitten", "puppy"].toCritBitTree
+doAssert critbitAsSet.len == 2
+critbitAsSet.incl("")
+doAssert "" in critbitAsSet
+critbitAsSet.excl("")
+doAssert "" notin critbitAsSet
+doAssert toSeq(critbitAsSet.items) == @["kitten", "puppy"]
+let same = ["puppy", "kitten", "puppy"].toCritBitTree
+doAssert toSeq(same.keys) == toSeq(critbitAsSet.keys)
+
+var critbitAsDict: CritBitTree[int] = {"key1": 42}.toCritBitTree
+doAssert critbitAsDict.len == 1
+critbitAsDict["key2"] = 0
+doAssert "key2" in critbitAsDict
+doAssert critbitAsDict["key2"] == 0
+critbitAsDict.excl("key1")
+doAssert "key1" notin critbitAsDict
+doAssert toSeq(critbitAsDict.pairs) == @[("key2", 0)]

+ +
+

Types

+
+
+
CritBitTree[T] = object
+
+ + The crit bit tree can either be used as a mapping from strings to some type T or as a set of strings if T is void. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `$`[T](c: CritBitTree[T]): string
+
+ + Turns c into a string representation. +

Example:

+
doAssert $CritBitTree[int].default == "{:}"
+doAssert $toCritBitTree({"key1": 1, "key2": 2}) == """{"key1": 1, "key2": 2}"""
+doAssert $CritBitTree[void].default == "{}"
+doAssert $toCritBitTree(["key1", "key2"]) == """{"key1", "key2"}"""
+ Source   +Edit   + +
+
+ +
+
+
+
func `[]`[T](c: CritBitTree[T]; key: string): lent T {.inline.}
+
+ +

Retrieves the value at c[key]. If key is not in t, the KeyError exception is raised. One can check with hasKey whether the key exists.

+

See also:

+ + + Source   +Edit   + +
+
+
+
func `[]`[T](c: var CritBitTree[T]; key: string): var T {.inline.}
+
+ +

Retrieves the value at c[key]. The value can be modified. If key is not in t, the KeyError exception is raised.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `[]=`[T](c: var CritBitTree[T]; key: string; val: sink T)
+
+ +

Alias for incl.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func commonPrefixLen[T](c: CritBitTree[T]): int {.inline.}
+
+ + Returns the length of the longest common prefix of all keys in c. If c is empty, returns 0. +

Example:

+
var c: CritBitTree[void]
+doAssert c.commonPrefixLen == 0
+incl(c, "key1")
+doAssert c.commonPrefixLen == 4
+incl(c, "key2")
+doAssert c.commonPrefixLen == 3
+ Source   +Edit   + +
+
+ +
+
+
+
func contains[T](c: CritBitTree[T]; key: string): bool {.inline.}
+
+ + Returns true if c contains the given key. +

Example:

+
var c: CritBitTree[void]
+incl(c, "key")
+doAssert c.contains("key")
+ Source   +Edit   + +
+
+ +
+
+
+
proc containsOrIncl(c: var CritBitTree[void]; key: string): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Returns true if c contains the given key. If the key does not exist, it is inserted into c.

+

See also:

+ + +

Example:

+
block:
+  var c: CritBitTree[void]
+  doAssert not c.containsOrIncl("key")
+  doAssert c.contains("key")
+block:
+  var c: CritBitTree[void]
+  incl(c, "key")
+  doAssert c.containsOrIncl("key")
+ Source   +Edit   + +
+
+
+
proc containsOrIncl[T](c: var CritBitTree[T]; key: string; val: sink T): bool
+
+ +

Returns true if c contains the given key. If the key does not exist, c[key] = val is performed.

+

See also:

+ + +

Example:

+
block:
+  var c: CritBitTree[int]
+  doAssert not c.containsOrIncl("key", 42)
+  doAssert c.contains("key")
+block:
+  var c: CritBitTree[int]
+  incl(c, "key", 21)
+  doAssert c.containsOrIncl("key", 42)
+  doAssert c["key"] == 21
+ Source   +Edit   + +
+
+ +
+
+
+
proc excl[T](c: var CritBitTree[T]; key: string)
+
+ +

Removes key (and its associated value) from the set c. If the key does not exist, nothing happens.

+

See also:

+ + +

Example:

+
var c: CritBitTree[void]
+incl(c, "key")
+excl(c, "key")
+doAssert not c.contains("key")
+ Source   +Edit   + +
+
+ +
+
+
+
func hasKey[T](c: CritBitTree[T]; key: string): bool {.inline.}
+
+ + Alias for contains. + Source   +Edit   + +
+
+ +
+
+
+
proc inc(c: var CritBitTree[int]; key: string; val: int = 1) {....raises: [],
+    tags: [], forbids: [].}
+
+ + Increments c[key] by val. +

Example:

+
var c: CritBitTree[int]
+c["key"] = 1
+inc(c, "key")
+doAssert c["key"] == 2
+ Source   +Edit   + +
+
+ +
+
+
+
proc incl(c: var CritBitTree[void]; key: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Includes key in c.

+

See also:

+ + +

Example:

+
var c: CritBitTree[void]
+incl(c, "key")
+doAssert c.hasKey("key")
+ Source   +Edit   + +
+
+
+
proc incl[T](c: var CritBitTree[T]; key: string; val: sink T)
+
+ +

Inserts key with value val into c.

+

See also:

+ + +

Example:

+
var c: CritBitTree[int]
+incl(c, "key", 42)
+doAssert c["key"] == 42
+ Source   +Edit   + +
+
+ +
+
+
+
func len[T](c: CritBitTree[T]): int {.inline.}
+
+ + Returns the number of elements in c in O(1). +

Example:

+
let c = ["key1", "key2"].toCritBitTree
+doAssert c.len == 2
+ Source   +Edit   + +
+
+ +
+
+
+
proc missingOrExcl[T](c: var CritBitTree[T]; key: string): bool
+
+ +

Returns true if c does not contain the given key. If the key does exist, c.excl(key) is performed.

+

See also:

+ + +

Example:

+
block:
+  var c: CritBitTree[void]
+  doAssert c.missingOrExcl("key")
+block:
+  var c: CritBitTree[void]
+  incl(c, "key")
+  doAssert not c.missingOrExcl("key")
+  doAssert not c.contains("key")
+ Source   +Edit   + +
+
+ +
+
+
+
proc toCritBitTree(items: sink openArray[string]): CritBitTree[void] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Creates a new CritBitTree that contains the given items. +

Example:

+
doAssert ["a", "b", "c"].toCritBitTree is CritBitTree[void]
+ Source   +Edit   + +
+
+
+
proc toCritBitTree[T](pairs: sink openArray[(string, T)]): CritBitTree[T]
+
+ + Creates a new CritBitTree that contains the given pairs. +

Example:

+
doAssert {"a": "0", "b": "1", "c": "2"}.toCritBitTree is CritBitTree[string]
+doAssert {"a": 0, "b": 1, "c": 2}.toCritBitTree is CritBitTree[int]
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator items[T](c: CritBitTree[T]): string
+
+ + Alias for keys. + Source   +Edit   + +
+
+ +
+
+
+
iterator itemsWithPrefix[T](c: CritBitTree[T]; prefix: string): string
+
+ + Alias for keysWithPrefix. + Source   +Edit   + +
+
+ +
+
+
+
iterator keys[T](c: CritBitTree[T]): string
+
+ + Yields all keys in lexicographical order. +

Example:

+
from std/sequtils import toSeq
+
+let c = {"key1": 1, "key2": 2}.toCritBitTree
+doAssert toSeq(c.keys) == @["key1", "key2"]
+ Source   +Edit   + +
+
+ +
+
+
+
iterator keysWithPrefix[T](c: CritBitTree[T]; prefix: string): string
+
+ + Yields all keys starting with prefix. +

Example:

+
from std/sequtils import toSeq
+
+let c = {"key1": 42, "key2": 43}.toCritBitTree
+doAssert toSeq(c.keysWithPrefix("key")) == @["key1", "key2"]
+ Source   +Edit   + +
+
+ +
+
+
+
iterator mpairs[T](c: var CritBitTree[T]): tuple[key: string, val: var T]
+
+ +

Yields all (key, value)-pairs of c in the lexicographical order of the corresponding keys. The yielded values can be modified.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator mpairsWithPrefix[T](c: var CritBitTree[T]; prefix: string): tuple[
+    key: string, val: var T]
+
+ +

Yields all (key, value)-pairs of c starting with prefix. The yielded values can be modified.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator mvalues[T](c: var CritBitTree[T]): var T
+
+ +

Yields all values of c in the lexicographical order of the corresponding keys. The values can be modified.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator mvaluesWithPrefix[T](c: var CritBitTree[T]; prefix: string): var T
+
+ +

Yields all values of c starting with prefix of the corresponding keys. The values can be modified.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator pairs[T](c: CritBitTree[T]): tuple[key: string, val: T]
+
+ +

Yields all (key, value)-pairs of c in the lexicographical order of the corresponding keys.

+

See also:

+ + +

Example:

+
from std/sequtils import toSeq
+
+let c = {"key1": 1, "key2": 2}.toCritBitTree
+doAssert toSeq(c.pairs) == @[(key: "key1", val: 1), (key: "key2", val: 2)]
+ Source   +Edit   + +
+
+ +
+
+
+
iterator pairsWithPrefix[T](c: CritBitTree[T]; prefix: string): tuple[
+    key: string, val: T]
+
+ +

Yields all (key, value)-pairs of c starting with prefix.

+

See also:

+ + +

Example:

+
from std/sequtils import toSeq
+
+let c = {"key1": 42, "key2": 43}.toCritBitTree
+doAssert toSeq(c.pairsWithPrefix("key")) == @[(key: "key1", val: 42), (key: "key2", val: 43)]
+ Source   +Edit   + +
+
+ +
+
+
+
iterator values[T](c: CritBitTree[T]): lent T
+
+ +

Yields all values of c in the lexicographical order of the corresponding keys.

+

See also:

+ + +

Example:

+
from std/sequtils import toSeq
+
+let c = {"key1": 1, "key2": 2}.toCritBitTree
+doAssert toSeq(c.values) == @[1, 2]
+ Source   +Edit   + +
+
+ +
+
+
+
iterator valuesWithPrefix[T](c: CritBitTree[T]; prefix: string): lent T
+
+ +

Yields all values of c starting with prefix of the corresponding keys.

+

See also:

+ + +

Example:

+
from std/sequtils import toSeq
+
+let c = {"key1": 42, "key2": 43}.toCritBitTree
+doAssert toSeq(c.valuesWithPrefix("key")) == @[42, 43]
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/critbits.idx b/critbits.idx new file mode 100644 index 0000000000000..73b804f471707 --- /dev/null +++ b/critbits.idx @@ -0,0 +1,38 @@ +nimTitle critbits critbits.html module std/critbits 0 +nim CritBitTree critbits.html#CritBitTree object CritBitTree 54 +nim len critbits.html#len,CritBitTree[T] proc len[T](c: CritBitTree[T]): int 61 +nim contains critbits.html#contains,CritBitTree[T],string proc contains[T](c: CritBitTree[T]; key: string): bool 80 +nim hasKey critbits.html#hasKey,CritBitTree[T],string proc hasKey[T](c: CritBitTree[T]; key: string): bool 89 +nim excl critbits.html#excl,CritBitTree[T],string proc excl[T](c: var CritBitTree[T]; key: string) 167 +nim missingOrExcl critbits.html#missingOrExcl,CritBitTree[T],string proc missingOrExcl[T](c: var CritBitTree[T]; key: string): bool 182 +nim containsOrIncl critbits.html#containsOrIncl,CritBitTree[T],string,sinkT proc containsOrIncl[T](c: var CritBitTree[T]; key: string; val: sink T): bool 204 +nim containsOrIncl critbits.html#containsOrIncl,CritBitTree[void],string proc containsOrIncl(c: var CritBitTree[void]; key: string): bool 230 +nim inc critbits.html#inc,CritBitTree[int],string,int proc inc(c: var CritBitTree[int]; key: string; val: int = 1) 253 +nim incl critbits.html#incl,CritBitTree[void],string proc incl(c: var CritBitTree[void]; key: string) 264 +nim incl critbits.html#incl,CritBitTree[T],string,sinkT proc incl[T](c: var CritBitTree[T]; key: string; val: sink T) 277 +nim `[]=` critbits.html#[]=,CritBitTree[T],string,sinkT proc `[]=`[T](c: var CritBitTree[T]; key: string; val: sink T) 291 +nim `[]` critbits.html#[],CritBitTree[T],string proc `[]`[T](c: CritBitTree[T]; key: string): lent T 307 +nim `[]` critbits.html#[],CritBitTree[T],string_2 proc `[]`[T](c: var CritBitTree[T]; key: string): var T 317 +nim keys critbits.html#keys.i,CritBitTree[T] iterator keys[T](c: CritBitTree[T]): string 339 +nim values critbits.html#values.i,CritBitTree[T] iterator values[T](c: CritBitTree[T]): lent T 349 +nim mvalues critbits.html#mvalues.i,CritBitTree[T] iterator mvalues[T](c: var CritBitTree[T]): var T 363 +nim items critbits.html#items.i,CritBitTree[T] iterator items[T](c: CritBitTree[T]): string 371 +nim pairs critbits.html#pairs.i,CritBitTree[T] iterator pairs[T](c: CritBitTree[T]): tuple[key: string, val: T] 375 +nim mpairs critbits.html#mpairs.i,CritBitTree[T] iterator mpairs[T](c: var CritBitTree[T]): tuple[key: string, val: var T] 389 +nim keysWithPrefix critbits.html#keysWithPrefix.i,CritBitTree[T],string iterator keysWithPrefix[T](c: CritBitTree[T]; prefix: string): string 412 +nim valuesWithPrefix critbits.html#valuesWithPrefix.i,CritBitTree[T],string iterator valuesWithPrefix[T](c: CritBitTree[T]; prefix: string): lent T 423 +nim mvaluesWithPrefix critbits.html#mvaluesWithPrefix.i,CritBitTree[T],string iterator mvaluesWithPrefix[T](c: var CritBitTree[T]; prefix: string): var T 438 +nim itemsWithPrefix critbits.html#itemsWithPrefix.i,CritBitTree[T],string iterator itemsWithPrefix[T](c: CritBitTree[T]; prefix: string): string 447 +nim pairsWithPrefix critbits.html#pairsWithPrefix.i,CritBitTree[T],string iterator pairsWithPrefix[T](c: CritBitTree[T]; prefix: string): tuple[key: string, val: T] 452 +nim mpairsWithPrefix critbits.html#mpairsWithPrefix.i,CritBitTree[T],string iterator mpairsWithPrefix[T](c: var CritBitTree[T]; prefix: string): tuple[key: string,\n val: var T] 467 +nim `$` critbits.html#$,CritBitTree[T] proc `$`[T](c: CritBitTree[T]): string 477 +nim commonPrefixLen critbits.html#commonPrefixLen,CritBitTree[T] proc commonPrefixLen[T](c: CritBitTree[T]): int 510 +nim toCritBitTree critbits.html#toCritBitTree,sinkopenArray[] proc toCritBitTree[T](pairs: sink openArray[(string, T)]): CritBitTree[T] 526 +nim toCritBitTree critbits.html#toCritBitTree,sinkopenArray[string] proc toCritBitTree(items: sink openArray[string]): CritBitTree[void] 534 +idx crit bit tree critbits.html#crit-bit-tree_1 Module critbits 0 +idx radix tree critbits.html#radix-tree_1 Module critbits 0 +idx patricia trie critbits.html#patricia-trie_1 Module critbits 0 +nimgrp containsorincl critbits.html#containsOrIncl-procs-all proc 204 +nimgrp tocritbittree critbits.html#toCritBitTree-procs-all proc 526 +nimgrp [] critbits.html#[]-procs-all proc 307 +nimgrp incl critbits.html#incl-procs-all proc 264 diff --git a/cstrutils.html b/cstrutils.html new file mode 100644 index 0000000000000..f9d981f04b284 --- /dev/null +++ b/cstrutils.html @@ -0,0 +1,204 @@ + + + + + + + +std/cstrutils + + + + + + + + + + + + + + + + +
+
+

std/cstrutils

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module supports helper routines for working with cstring without having to convert cstring to string, in order to save allocations. +

See also

+

+
+

Imports

+
+ strimpl +
+
+
+

Procs

+
+
+
+
func cmpIgnoreCase(a, b: cstring): int {....gcsafe, extern: "csuCmpIgnoreCase",
+    raises: [], tags: [], forbids: [].}
+
+ + Compares two strings in a case insensitive manner. Returns:
  • 0 if a == b
  • +
  • < 0 if a < b
  • +
  • > 0 if a > b
  • +
+ +

Example:

+
assert cmpIgnoreCase(cstring"hello", cstring"HeLLo") == 0
+assert cmpIgnoreCase(cstring"echo", cstring"hello") < 0
+assert cmpIgnoreCase(cstring"yellow", cstring"hello") > 0
+ Source   +Edit   + +
+
+ +
+
+
+
func cmpIgnoreStyle(a, b: cstring): int {....gcsafe, extern: "csuCmpIgnoreStyle",
+    raises: [], tags: [], forbids: [].}
+
+ + Semantically the same as cmp(normalize($a), normalize($b)). It is just optimized to not allocate temporary strings. This should NOT be used to compare Nim identifier names, use macros.eqIdent for that. Returns:
  • 0 if a == b
  • +
  • < 0 if a < b
  • +
  • > 0 if a > b
  • +
+ +

Example:

+
assert cmpIgnoreStyle(cstring"hello", cstring"H_e_L_Lo") == 0
+ Source   +Edit   + +
+
+ +
+
+
+
func endsWith(s, suffix: cstring): bool {....gcsafe, extern: "csuEndsWith",
+    raises: [], tags: [], forbids: [].}
+
+ +

Returns true if s ends with suffix.

+

The JS backend uses the native String.prototype.endsWith function.

+ +

Example:

+
assert endsWith(cstring"Hello, Nimion", cstring"Nimion")
+assert not endsWith(cstring"Hello, Nimion", cstring"Hello")
+assert endsWith(cstring"Hello", cstring"")
+ Source   +Edit   + +
+
+ +
+
+
+
func startsWith(s, prefix: cstring): bool {....gcsafe, extern: "csuStartsWith",
+    raises: [], tags: [], forbids: [].}
+
+ +

Returns true if s starts with prefix.

+

The JS backend uses the native String.prototype.startsWith function.

+ +

Example:

+
assert startsWith(cstring"Hello, Nimion", cstring"Hello")
+assert not startsWith(cstring"Hello, Nimion", cstring"Nimion")
+assert startsWith(cstring"Hello", cstring"")
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/cstrutils.idx b/cstrutils.idx new file mode 100644 index 0000000000000..e7ece09ec3f96 --- /dev/null +++ b/cstrutils.idx @@ -0,0 +1,6 @@ +nimTitle cstrutils cstrutils.html module std/cstrutils 0 +nim startsWith cstrutils.html#startsWith,cstring,cstring proc startsWith(s, prefix: cstring): bool 27 +nim endsWith cstrutils.html#endsWith,cstring,cstring proc endsWith(s, suffix: cstring): bool 48 +nim cmpIgnoreStyle cstrutils.html#cmpIgnoreStyle,cstring,cstring proc cmpIgnoreStyle(a, b: cstring): int 71 +nim cmpIgnoreCase cstrutils.html#cmpIgnoreCase,cstring,cstring proc cmpIgnoreCase(a, b: cstring): int 100 +heading See also cstrutils.html#see-also See also 0 diff --git a/ctypes.html b/ctypes.html new file mode 100644 index 0000000000000..bd391a60807fc --- /dev/null +++ b/ctypes.html @@ -0,0 +1,321 @@ + + + + + + + +system/ctypes + + + + + + + + + + + + + + + + +
+
+

system/ctypes

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Some type definitions for compatibility between different backends and platforms.

+
+

Types

+
+
+
BiggestFloat = float64
+
+ + is an alias for the biggest floating point type the Nim compiler supports. Currently this is float64, but it is platform-dependent in general. + Source   +Edit   + +
+
+
+
BiggestInt = int64
+
+ + is an alias for the biggest signed integer type the Nim compiler supports. Currently this is int64, but it is platform-dependent in general. + Source   +Edit   + +
+
+
+
BiggestUInt = uint64
+
+ + is an alias for the biggest unsigned integer type the Nim compiler supports. Currently this is uint64, but it is platform-dependent in general. + Source   +Edit   + +
+
+
+
ByteAddress {....deprecated: "use `uint`".} = int
+
+
+ Deprecated: use `uint` +
+ + is the signed integer type that should be used for converting pointers to integer addresses for readability. + Source   +Edit   + +
+
+
+
cchar {.importc: "char", nodecl.} = char
+
+ + This is the same as the type char in C. + Source   +Edit   + +
+
+
+
cdouble {.importc: "double", nodecl.} = float64
+
+ + This is the same as the type double in C. + Source   +Edit   + +
+
+
+
cfloat {.importc: "float", nodecl.} = float32
+
+ + This is the same as the type float in C. + Source   +Edit   + +
+
+
+
cint {.importc: "int", nodecl.} = int32
+
+ + This is the same as the type int in C. + Source   +Edit   + +
+
+
+
clong {.importc: "long", nodecl.} = int
+
+ + This is the same as the type long in C. + Source   +Edit   + +
+
+
+
clongdouble {.importc: "long double", nodecl.} = BiggestFloat
+
+ + This is the same as the type long double in C. This C type is not supported by Nim's code generator. + Source   +Edit   + +
+
+
+
clonglong {.importc: "long long", nodecl.} = int64
+
+ + This is the same as the type long long in C. + Source   +Edit   + +
+
+
+
cschar {.importc: "signed char", nodecl.} = int8
+
+ + This is the same as the type signed char in C. + Source   +Edit   + +
+
+
+
cshort {.importc: "short", nodecl.} = int16
+
+ + This is the same as the type short in C. + Source   +Edit   + +
+
+
+
csize_t {.importc: "size_t", nodecl.} = uint
+
+ + This is the same as the type size_t in C. + Source   +Edit   + +
+
+
+
cstringArray {.importc: "char**", nodecl.} = ptr UncheckedArray[cstring]
+
+ + This is binary compatible to the type char** in C. The array's high value is large enough to disable bounds checking in practice. Use cstringArrayToSeq proc to convert it into a seq[string]. + Source   +Edit   + +
+
+
+
cuchar {.importc: "unsigned char", nodecl,
+         ...deprecated: "use `char` or `uint8` instead".} = char
+
+
+ Deprecated: use `char` or `uint8` instead +
+ + Deprecated: Use uint8 instead. + Source   +Edit   + +
+
+
+
cuint {.importc: "unsigned int", nodecl.} = uint32
+
+ + This is the same as the type unsigned int in C. + Source   +Edit   + +
+
+
+
culong {.importc: "unsigned long", nodecl.} = uint
+
+ + This is the same as the type unsigned long in C. + Source   +Edit   + +
+
+
+
culonglong {.importc: "unsigned long long", nodecl.} = uint64
+
+ + This is the same as the type unsigned long long in C. + Source   +Edit   + +
+
+
+
cushort {.importc: "unsigned short", nodecl.} = uint16
+
+ + This is the same as the type unsigned short in C. + Source   +Edit   + +
+
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/ctypes.idx b/ctypes.idx new file mode 100644 index 0000000000000..1706ffeabe3a4 --- /dev/null +++ b/ctypes.idx @@ -0,0 +1,21 @@ +nimTitle ctypes ctypes.html module system/ctypes 0 +nim BiggestInt ctypes.html#BiggestInt type BiggestInt 5 +nim BiggestFloat ctypes.html#BiggestFloat type BiggestFloat 10 +nim BiggestUInt ctypes.html#BiggestUInt type BiggestUInt 15 +nim clong ctypes.html#clong type clong 28 +nim culong ctypes.html#culong type culong 30 +nim cchar ctypes.html#cchar type cchar 34 +nim cschar ctypes.html#cschar type cschar 36 +nim cshort ctypes.html#cshort type cshort 38 +nim cint ctypes.html#cint type cint 40 +nim csize_t ctypes.html#csize_t type csize_t 42 +nim clonglong ctypes.html#clonglong type clonglong 44 +nim cfloat ctypes.html#cfloat type cfloat 46 +nim cdouble ctypes.html#cdouble type cdouble 48 +nim clongdouble ctypes.html#clongdouble type clongdouble 50 +nim cuchar ctypes.html#cuchar type cuchar 54 +nim cushort ctypes.html#cushort type cushort 56 +nim cuint ctypes.html#cuint type cuint 58 +nim culonglong ctypes.html#culonglong type culonglong 60 +nim ByteAddress ctypes.html#ByteAddress type ByteAddress 64 +nim cstringArray ctypes.html#cstringArray type cstringArray 68 diff --git a/db_common.html b/db_common.html new file mode 100644 index 0000000000000..c8ae381ef6494 --- /dev/null +++ b/db_common.html @@ -0,0 +1,346 @@ + + + + + + + +src/db_connector/db_common + + + + + + + + + + + + + + + + +
+
+

src/db_connector/db_common

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

Note: +In order to use this module, run nimble install db_connector.
+

Common datatypes and definitions for all db_*.nim ( db_mysql, db_postgres, and db_sqlite) modules.

+

+
+

Types

+
+
+
DbColumn = object
+  name*: string              ## name of the column
+  tableName*: string         ## name of the table the column belongs to (optional)
+  typ*: DbType               ## type of the column
+  primaryKey*: bool          ## is this a primary key?
+  foreignKey*: bool          ## is this a foreign key?
+
+ + information about a database column + +
+
+
+
DbColumns = seq[DbColumn]
+
+ + + +
+
+
+
DbEffect = object of IOEffect
+
+ + effect that denotes a database operation + +
+
+
+
DbError = object of IOError
+
+ + exception that is raised if a database error occurs + +
+
+
+
DbType = object
+  kind*: DbTypeKind          ## the kind of the described type
+  notNull*: bool             ## does the type contain NULL?
+  name*: string              ## the name of the type
+  size*: Natural             ## the size of the datatype; 0 if of variable size
+  maxReprLen*: Natural       ## maximal length required for the representation
+  precision*, scale*: Natural ## precision and scale of the number
+  min*, max*: BiggestInt     ## the minimum and maximum of allowed values
+  validValues*: seq[string]  ## valid values of an enum or a set
+
+ + describes a database type + +
+
+
+
DbTypeKind = enum
+  dbUnknown,                ## unknown datatype
+  dbSerial,                 ## datatype used for primary auto-increment keys
+  dbNull,                   ## datatype used for the NULL value
+  dbBit,                    ## bit datatype
+  dbBool,                   ## boolean datatype
+  dbBlob,                   ## blob datatype
+  dbFixedChar,              ## string of fixed length
+  dbVarchar,                ## string datatype
+  dbJson,                   ## JSON datatype
+  dbXml,                    ## XML datatype
+  dbInt,                    ## some integer type
+  dbUInt,                   ## some unsigned integer type
+  dbDecimal,                ## decimal numbers (fixed-point number)
+  dbFloat,                  ## some floating point type
+  dbDate,                   ## a year-month-day description
+  dbTime,                   ## HH:MM:SS information
+  dbDatetime,               ## year-month-day and HH:MM:SS information,
+                             ## plus optional time or timezone information
+  dbTimestamp, ## Timestamp values are stored as the number of seconds
+                ## since the epoch ('1970-01-01 00:00:00' UTC).
+  dbTimeInterval,           ## an interval [a,b] of times
+  dbEnum,                   ## some enum
+  dbSet,                    ## set of enum values
+  dbArray,                  ## an array of values
+  dbComposite,              ## composite type (record, struct, etc)
+  dbUrl,                    ## a URL
+  dbUuid,                   ## a UUID
+  dbInet,                   ## an IP address
+  dbMacAddress,             ## a MAC address
+  dbGeometry,               ## some geometric type
+  dbPoint,                  ## Point on a plane   (x,y)
+  dbLine,                   ## Infinite line ((x1,y1),(x2,y2))
+  dbLseg,                   ## Finite line segment   ((x1,y1),(x2,y2))
+  dbBox,                    ## Rectangular box   ((x1,y1),(x2,y2))
+  dbPath,                   ## Closed or open path (similar to polygon) ((x1,y1),...)
+  dbPolygon,                ## Polygon (similar to closed path)   ((x1,y1),...)
+  dbCircle,                 ## Circle   <(x,y),r> (center point and radius)
+  dbUser1,                  ## user definable datatype 1 (for unknown extensions)
+  dbUser2,                  ## user definable datatype 2 (for unknown extensions)
+  dbUser3,                  ## user definable datatype 3 (for unknown extensions)
+  dbUser4,                  ## user definable datatype 4 (for unknown extensions)
+  dbUser5                    ## user definable datatype 5 (for unknown extensions)
+
+ + a superset of datatypes that might be supported. + +
+
+
+
ReadDbEffect = object of DbEffect
+
+ + effect that denotes a read operation + +
+
+
+
SqlQuery = distinct string
+
+ + an SQL query string + +
+
+
+
WriteDbEffect = object of DbEffect
+
+ + effect that denotes a write operation + +
+
+ +
+
+
+

Procs

+
+
+
+
proc dbError(msg: string) {.noreturn, noinline, ...raises: [DbError], tags: [],
+                            forbids: [].}
+
+ + raises an DbError exception with message msg. + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template sql(query: string): SqlQuery
+
+ +

constructs a SqlQuery from the string query. This is supposed to be used as a raw-string-literal modifier: sql"update user set counter = counter + 1"

+

If assertions are turned off, it does nothing. If assertions are turned on, later versions will check the string for valid syntax.

+ + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/db_common.idx b/db_common.idx new file mode 100644 index 0000000000000..e2b03559b3469 --- /dev/null +++ b/db_common.idx @@ -0,0 +1,52 @@ +nimTitle db_common db_common.html module src/db_connector/db_common 0 +nim DbError db_common.html#DbError object DbError 17 +nim SqlQuery db_common.html#SqlQuery type SqlQuery 19 +nim DbEffect db_common.html#DbEffect object DbEffect 22 +nim ReadDbEffect db_common.html#ReadDbEffect object ReadDbEffect 23 +nim WriteDbEffect db_common.html#WriteDbEffect object WriteDbEffect 24 +nim dbUnknown db_common.html#dbUnknown DbTypeKind.dbUnknown 26 +nim dbSerial db_common.html#dbSerial DbTypeKind.dbSerial 26 +nim dbNull db_common.html#dbNull DbTypeKind.dbNull 26 +nim dbBit db_common.html#dbBit DbTypeKind.dbBit 26 +nim dbBool db_common.html#dbBool DbTypeKind.dbBool 26 +nim dbBlob db_common.html#dbBlob DbTypeKind.dbBlob 26 +nim dbFixedChar db_common.html#dbFixedChar DbTypeKind.dbFixedChar 26 +nim dbVarchar db_common.html#dbVarchar DbTypeKind.dbVarchar 26 +nim dbJson db_common.html#dbJson DbTypeKind.dbJson 26 +nim dbXml db_common.html#dbXml DbTypeKind.dbXml 26 +nim dbInt db_common.html#dbInt DbTypeKind.dbInt 26 +nim dbUInt db_common.html#dbUInt DbTypeKind.dbUInt 26 +nim dbDecimal db_common.html#dbDecimal DbTypeKind.dbDecimal 26 +nim dbFloat db_common.html#dbFloat DbTypeKind.dbFloat 26 +nim dbDate db_common.html#dbDate DbTypeKind.dbDate 26 +nim dbTime db_common.html#dbTime DbTypeKind.dbTime 26 +nim dbDatetime db_common.html#dbDatetime DbTypeKind.dbDatetime 26 +nim dbTimestamp db_common.html#dbTimestamp DbTypeKind.dbTimestamp 26 +nim dbTimeInterval db_common.html#dbTimeInterval DbTypeKind.dbTimeInterval 26 +nim dbEnum db_common.html#dbEnum DbTypeKind.dbEnum 26 +nim dbSet db_common.html#dbSet DbTypeKind.dbSet 26 +nim dbArray db_common.html#dbArray DbTypeKind.dbArray 26 +nim dbComposite db_common.html#dbComposite DbTypeKind.dbComposite 26 +nim dbUrl db_common.html#dbUrl DbTypeKind.dbUrl 26 +nim dbUuid db_common.html#dbUuid DbTypeKind.dbUuid 26 +nim dbInet db_common.html#dbInet DbTypeKind.dbInet 26 +nim dbMacAddress db_common.html#dbMacAddress DbTypeKind.dbMacAddress 26 +nim dbGeometry db_common.html#dbGeometry DbTypeKind.dbGeometry 26 +nim dbPoint db_common.html#dbPoint DbTypeKind.dbPoint 26 +nim dbLine db_common.html#dbLine DbTypeKind.dbLine 26 +nim dbLseg db_common.html#dbLseg DbTypeKind.dbLseg 26 +nim dbBox db_common.html#dbBox DbTypeKind.dbBox 26 +nim dbPath db_common.html#dbPath DbTypeKind.dbPath 26 +nim dbPolygon db_common.html#dbPolygon DbTypeKind.dbPolygon 26 +nim dbCircle db_common.html#dbCircle DbTypeKind.dbCircle 26 +nim dbUser1 db_common.html#dbUser1 DbTypeKind.dbUser1 26 +nim dbUser2 db_common.html#dbUser2 DbTypeKind.dbUser2 26 +nim dbUser3 db_common.html#dbUser3 DbTypeKind.dbUser3 26 +nim dbUser4 db_common.html#dbUser4 DbTypeKind.dbUser4 26 +nim dbUser5 db_common.html#dbUser5 DbTypeKind.dbUser5 26 +nim DbTypeKind db_common.html#DbTypeKind enum DbTypeKind 26 +nim DbType db_common.html#DbType object DbType 70 +nim DbColumn db_common.html#DbColumn object DbColumn 80 +nim DbColumns db_common.html#DbColumns type DbColumns 86 +nim sql db_common.html#sql.t,string template sql(query: string): SqlQuery 88 +nim dbError db_common.html#dbError,string proc dbError(msg: string) 97 diff --git a/db_mysql.html b/db_mysql.html new file mode 100644 index 0000000000000..091963f6694b2 --- /dev/null +++ b/db_mysql.html @@ -0,0 +1,560 @@ + + + + + + + +src/db_connector/db_mysql + + + + + + + + + + + + + + + + +
+
+

src/db_connector/db_mysql

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

Note: +In order to use this module, run nimble install db_connector.
+

A higher level mySQL database wrapper. The same interface is implemented for other databases too.

+

See also: db_odbc, db_sqlite, db_postgres.

+ +

Parameter substitution

All db_* modules support the same form of parameter substitution. That is, using the ? (question mark) to signify the place where a value should be placed. For example:

+

sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"

+ +

Examples

+

Opening a connection to a database

import db_connector/db_mysql
+let db = open("localhost", "user", "password", "dbname")
+db.close()

+ +

Creating a table

db.exec(sql"DROP TABLE IF EXISTS myTable")
+db.exec(sql("""CREATE TABLE myTable (
+                 id integer,
+                 name varchar(50) not null)"""))

+ +

Inserting data

db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
+        "Dominik")

+ +

Larger example

import db_connector/db_mysql
+import std/math
+
+let theDb = open("localhost", "nim", "nim", "test")
+
+theDb.exec(sql"Drop table if exists myTestTbl")
+theDb.exec(sql("create table myTestTbl (" &
+    " Id    INT(11)     NOT NULL AUTO_INCREMENT PRIMARY KEY, " &
+    " Name  VARCHAR(50) NOT NULL, " &
+    " i     INT(11), " &
+    " f     DECIMAL(18,10))"))
+
+theDb.exec(sql"START TRANSACTION")
+for i in 1..1000:
+  theDb.exec(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
+        "Item#" & $i, i, sqrt(i.float))
+theDb.exec(sql"COMMIT")
+
+for x in theDb.fastRows(sql"select * from myTestTbl"):
+  echo x
+
+let id = theDb.tryInsertId(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
+        "Item#1001", 1001, sqrt(1001.0))
+echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id)
+
+theDb.close()

+

+ +
+

Types

+
+
+
DbConn = distinct PMySQL
+
+ + encapsulates a database connection + +
+
+
+
InstantRow = object
+
+ + a handle that can be used to get a row's column text on demand + +
+
+
+
Row = seq[string]
+
+ + a row of a dataset. NULL database values will be converted to nil. + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `[]`(row: InstantRow; col: int): string {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Returns text for given column of the row. + +
+
+ +
+
+
+
proc close(db: DbConn) {....tags: [DbEffect], raises: [], forbids: [].}
+
+ + closes the database connection. + +
+
+ +
+
+
+
proc dbError(db: DbConn) {.noreturn, ...raises: [DbError], tags: [], forbids: [].}
+
+ + raises a DbError exception. + +
+
+ +
+
+
+
proc dbQuote(s: string): string {....raises: [], tags: [], forbids: [].}
+
+ + DB quotes the string. Note that this doesn't escape % and _. + +
+
+ +
+
+
+
proc exec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]) {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + executes the query and raises EDB if not successful. + +
+
+ +
+
+
+
proc execAffectedRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + runs the query (typically "UPDATE") and returns the number of affected rows + +
+
+ +
+
+
+
proc getAllRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[
+    Row] {....tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + executes the query and returns the whole result dataset. + +
+
+ +
+
+
+
proc getRow(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + Retrieves a single row. If the query doesn't return any rows, this proc will return a Row with empty strings for each column. + +
+
+ +
+
+
+
proc getValue(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): string {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + executes the query and returns the first column of the first row of the result dataset. Returns "" if the dataset contains no rows or the database value is NULL. + +
+
+ +
+
+
+
proc insert(db: DbConn; query: SqlQuery; pkName: string;
+            args: varargs[string, `$`]): int64 {....tags: [WriteDbEffect],
+    raises: [DbError], forbids: [].}
+
+ + same as insertId + +
+
+ +
+
+
+
proc insertId(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
+    ...tags: [WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + executes the query (typically "INSERT") and returns the generated ID for the row. + +
+
+ +
+
+
+
proc len(row: InstantRow): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Returns number of columns in the row. + +
+
+ +
+
+
+
proc open(connection, user, password, database: string): DbConn {.
+    ...tags: [DbEffect], raises: [DbError, ValueError], forbids: [].}
+
+ + opens a database connection. Raises EDb if the connection could not be established. + +
+
+ +
+
+
+
proc setEncoding(connection: DbConn; encoding: string): bool {....tags: [DbEffect],
+    raises: [], forbids: [].}
+
+ + sets the encoding of a database connection, returns true for success, false for failure. + +
+
+ +
+
+
+
proc tryExec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): bool {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + tries to execute the query and returns true if successful, false otherwise. + +
+
+ +
+
+
+
proc tryInsert(db: DbConn; query: SqlQuery; pkName: string;
+               args: varargs[string, `$`]): int64 {....tags: [WriteDbEffect],
+    raises: [DbError], forbids: [].}
+
+ + same as tryInsertID + +
+
+ +
+
+
+
proc tryInsertId(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
+    ...tags: [WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + executes the query (typically "INSERT") and returns the generated ID for the row or -1 in case of an error. + +
+
+ +
+
+
+
proc unsafeColumnAt(row: InstantRow; index: int): cstring {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Return cstring of given column of the row + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator fastRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ +

executes the query and iterates over the result dataset.

+

This is very fast, but potentially dangerous. Use this iterator only if you require ALL the rows.

+

Breaking the fastRows() iterator during a loop will cause the next database query to raise an EDb exception Commands out of sync.

+ + +
+
+ +
+
+
+
iterator instantRows(db: DbConn; columns: var DbColumns; query: SqlQuery;
+                     args: varargs[string, `$`]): InstantRow {.
+    ...raises: [DbError], tags: [], forbids: [].}
+
+ + Same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within the iterator body. + +
+
+
+
iterator instantRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + Same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within the iterator body. + +
+
+ +
+
+
+
iterator rows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + same as fastRows, but slower and safe. + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/db_mysql.idx b/db_mysql.idx new file mode 100644 index 0000000000000..5ef895d1f4f50 --- /dev/null +++ b/db_mysql.idx @@ -0,0 +1,34 @@ +nimTitle db_mysql db_mysql.html module src/db_connector/db_mysql 0 +nim DbConn db_mysql.html#DbConn type DbConn 100 +nim Row db_mysql.html#Row type Row 101 +nim InstantRow db_mysql.html#InstantRow object InstantRow 103 +nim dbError db_mysql.html#dbError,DbConn proc dbError(db: DbConn) 108 +nim dbQuote db_mysql.html#dbQuote,string proc dbQuote(s: string): string 125 +nim tryExec db_mysql.html#tryExec,DbConn,SqlQuery,varargs[string,] proc tryExec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): bool 147 +nim exec db_mysql.html#exec,DbConn,SqlQuery,varargs[string,] proc exec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]) 157 +nim fastRows db_mysql.html#fastRows.i,DbConn,SqlQuery,varargs[string,] iterator fastRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row 172 +nim instantRows db_mysql.html#instantRows.i,DbConn,SqlQuery,varargs[string,] iterator instantRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow 199 +nim instantRows db_mysql.html#instantRows.i,DbConn,DbColumns,SqlQuery,varargs[string,] iterator instantRows(db: DbConn; columns: var DbColumns; query: SqlQuery;\n args: varargs[string, `$`]): InstantRow 280 +nim `[]` db_mysql.html#[],InstantRow,int proc `[]`(row: InstantRow; col: int): string 297 +nim unsafeColumnAt db_mysql.html#unsafeColumnAt,InstantRow,int proc unsafeColumnAt(row: InstantRow; index: int): cstring 301 +nim len db_mysql.html#len,InstantRow proc len(row: InstantRow): int 305 +nim getRow db_mysql.html#getRow,DbConn,SqlQuery,varargs[string,] proc getRow(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row 309 +nim getAllRows db_mysql.html#getAllRows,DbConn,SqlQuery,varargs[string,] proc getAllRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[Row] 325 +nim rows db_mysql.html#rows.i,DbConn,SqlQuery,varargs[string,] iterator rows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row 345 +nim getValue db_mysql.html#getValue,DbConn,SqlQuery,varargs[string,] proc getValue(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): string 350 +nim tryInsertId db_mysql.html#tryInsertId,DbConn,SqlQuery,varargs[string,] proc tryInsertId(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 357 +nim insertId db_mysql.html#insertId,DbConn,SqlQuery,varargs[string,] proc insertId(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 367 +nim tryInsert db_mysql.html#tryInsert,DbConn,SqlQuery,string,varargs[string,] proc tryInsert(db: DbConn; query: SqlQuery; pkName: string;\n args: varargs[string, `$`]): int64 374 +nim insert db_mysql.html#insert,DbConn,SqlQuery,string,varargs[string,] proc insert(db: DbConn; query: SqlQuery; pkName: string; args: varargs[string, `$`]): int64 380 +nim execAffectedRows db_mysql.html#execAffectedRows,DbConn,SqlQuery,varargs[string,] proc execAffectedRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 387 +nim close db_mysql.html#close,DbConn proc close(db: DbConn) 395 +nim open db_mysql.html#open,string,string,string,string proc open(connection, user, password, database: string): DbConn 399 +nim setEncoding db_mysql.html#setEncoding,DbConn,string proc setEncoding(connection: DbConn; encoding: string): bool 418 +nimgrp instantrows db_mysql.html#instantRows-iterators-all iterator 199 +idx mySQL db_mysql.html#mysql_1 Module db_mysql 0 +heading Parameter substitution db_mysql.html#parameter-substitution Parameter substitution 0 +heading Examples db_mysql.html#examples Examples 0 +heading Opening a connection to a database db_mysql.html#examples-opening-a-connection-to-a-database Opening a connection to a database 0 +heading Creating a table db_mysql.html#examples-creating-a-table Creating a table 0 +heading Inserting data db_mysql.html#examples-inserting-data Inserting data 0 +heading Larger example db_mysql.html#examples-larger-example Larger example 0 diff --git a/db_odbc.html b/db_odbc.html new file mode 100644 index 0000000000000..f0b8756a7ef54 --- /dev/null +++ b/db_odbc.html @@ -0,0 +1,563 @@ + + + + + + + +src/db_connector/db_odbc + + + + + + + + + + + + + + + + +
+
+

src/db_connector/db_odbc

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

Note: +In order to use this module, run nimble install db_connector.
+

A higher level ODBC database wrapper.

+

This is the same interface that is implemented for other databases.

+

This has NOT yet been (extensively) tested against ODBC drivers for Teradata, Oracle, Sybase, MSSqlvSvr, et. al. databases.

+

Currently all queries are ANSI calls, not Unicode.

+

See also: db_postgres, db_sqlite, db_mysql.

+ +

Parameter substitution

All db_* modules support the same form of parameter substitution. That is, using the ? (question mark) to signify the place where a value should be placed. For example:

+

sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"

+ +

Examples

+

Opening a connection to a database

import db_connector/db_odbc
+var db = open("localhost", "user", "password", "dbname")
+db.close()

+ +

Creating a table

db.exec(sql"DROP TABLE IF EXISTS myTable")
+db.exec(sql("""CREATE TABLE myTable (
+                 id integer,
+                 name varchar(50) not null)"""))

+ +

Inserting data

db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
+        "Andreas")

+ +

Large example

import db_connector/db_odbc
+import std/math
+
+var theDb = open("localhost", "nim", "nim", "test")
+
+theDb.exec(sql"Drop table if exists myTestTbl")
+theDb.exec(sql("create table myTestTbl (" &
+    " Id    INT(11)     NOT NULL AUTO_INCREMENT PRIMARY KEY, " &
+    " Name  VARCHAR(50) NOT NULL, " &
+    " i     INT(11), " &
+    " f     DECIMAL(18,10))"))
+
+theDb.exec(sql"START TRANSACTION")
+for i in 1..1000:
+  theDb.exec(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
+        "Item#" & $i, i, sqrt(i.float))
+theDb.exec(sql"COMMIT")
+
+for x in theDb.fastRows(sql"select * from myTestTbl"):
+  echo x
+
+let id = theDb.tryInsertId(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
+        "Item#1001", 1001, sqrt(1001.0))
+echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id)
+
+theDb.close()

+

+ +
+

Types

+
+
+
DbConn = OdbcConnTyp
+
+ + encapsulates a database connection + +
+
+
+
InstantRow = tuple[row: seq[string], len: int]
+
+ + a handle that can be used to get a row's column text on demand + +
+
+
+
Row = seq[string]
+
+ + a row of a dataset. NULL database values will be converted to nil. + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `[]`(row: InstantRow; col: int): string {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Returns text for given column of the row + +
+
+ +
+
+
+
proc close(db: var DbConn) {....tags: [WriteDbEffect], raises: [], forbids: [].}
+
+ + Closes the database connection. + +
+
+ +
+
+
+
proc dbError(db: var DbConn) {....tags: [ReadDbEffect, WriteDbEffect],
+                               raises: [DbError], forbids: [].}
+
+ + Raises an [DbError] exception with ODBC error information + +
+
+ +
+
+
+
proc dbQuote(s: string): string {.noSideEffect, ...raises: [], tags: [],
+                                  forbids: [].}
+
+ + DB quotes the string. + +
+
+ +
+
+
+
proc exec(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]) {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + Executes the query and raises EDB if not successful. + +
+
+ +
+
+
+
proc execAffectedRows(db: var DbConn; query: SqlQuery;
+                      args: varargs[string, `$`]): int64 {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + Runs the query (typically "UPDATE") and returns the number of affected rows + +
+
+ +
+
+
+
proc getAllRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[
+    Row] {....tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + Executes the query and returns the whole result dataset. + +
+
+ +
+
+
+
proc getRow(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + Retrieves a single row. If the query doesn't return any rows, this proc will return a Row with empty strings for each column. + +
+
+ +
+
+
+
proc getValue(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): string {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [], forbids: [].}
+
+ + Executes the query and returns the first column of the first row of the result dataset. Returns "" if the dataset contains no rows or the database value is NULL. + +
+
+ +
+
+
+
proc insert(db: var DbConn; query: SqlQuery; pkName: string;
+            args: varargs[string, `$`]): int64 {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + same as insertId + +
+
+ +
+
+
+
proc insertId(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + Executes the query (typically "INSERT") and returns the generated ID for the row. + +
+
+ +
+
+
+
proc len(row: InstantRow): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Returns number of columns in the row + +
+
+ +
+
+
+
proc open(connection, user, password, database: string): DbConn {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ +

Opens a database connection.

+

Raises EDb if the connection could not be established.

+

Currently the database parameter is ignored, but included to match open() in the other db_xxxxx library modules.

+ + +
+
+ +
+
+
+
proc setEncoding(connection: DbConn; encoding: string): bool {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ +

Currently not implemented for ODBC.

+

Sets the encoding of a database connection, returns true for success, false for failure. result = set_character_set(connection, encoding) == 0

+ + +
+
+ +
+
+
+
proc tryExec(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): bool {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [], forbids: [].}
+
+ + Tries to execute the query and returns true if successful, false otherwise. + +
+
+ +
+
+
+
proc tryInsert(db: var DbConn; query: SqlQuery; pkName: string;
+               args: varargs[string, `$`]): int64 {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [], forbids: [].}
+
+ + same as tryInsertID + +
+
+ +
+
+
+
proc tryInsertId(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [], forbids: [].}
+
+ + Executes the query (typically "INSERT") and returns the generated ID for the row or -1 in case of an error. + +
+
+ +
+
+
+
proc unsafeColumnAt(row: InstantRow; index: int): cstring {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Return cstring of given column of the row + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator fastRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ +

Executes the query and iterates over the result dataset.

+

This is very fast, but potentially dangerous. Use this iterator only if you require ALL the rows.

+

Breaking the fastRows() iterator during a loop may cause a driver error for subsequent queries

+

Rows are retrieved from the server at each iteration.

+ + +
+
+ +
+
+
+
iterator instantRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + Same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within the iterator body. + +
+
+ +
+
+
+
iterator rows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ +

Same as fastRows, but slower and safe.

+

This retrieves ALL rows into memory before iterating through the rows. Large dataset queries will impact on memory usage.

+ + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/db_odbc.idx b/db_odbc.idx new file mode 100644 index 0000000000000..0dba373c7ac44 --- /dev/null +++ b/db_odbc.idx @@ -0,0 +1,31 @@ +nimTitle db_odbc db_odbc.html module src/db_connector/db_odbc 0 +nim DbConn db_odbc.html#DbConn type DbConn 107 +nim Row db_odbc.html#Row type Row 108 +nim InstantRow db_odbc.html#InstantRow tuple InstantRow 110 +nim dbError db_odbc.html#dbError,DbConn proc dbError(db: var DbConn) 146 +nim dbQuote db_odbc.html#dbQuote,string proc dbQuote(s: string): string 196 +nim tryExec db_odbc.html#tryExec,DbConn,SqlQuery,varargs[string,] proc tryExec(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): bool 240 +nim exec db_odbc.html#exec,DbConn,SqlQuery,varargs[string,] proc exec(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]) 259 +nim fastRows db_odbc.html#fastRows.i,DbConn,SqlQuery,varargs[string,] iterator fastRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): Row 269 +nim instantRows db_odbc.html#instantRows.i,DbConn,SqlQuery,varargs[string,] iterator instantRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow 304 +nim `[]` db_odbc.html#[],InstantRow,int proc `[]`(row: InstantRow; col: int): string 332 +nim unsafeColumnAt db_odbc.html#unsafeColumnAt,InstantRow,int proc unsafeColumnAt(row: InstantRow; index: int): cstring 336 +nim len db_odbc.html#len,InstantRow proc len(row: InstantRow): int 340 +nim getRow db_odbc.html#getRow,DbConn,SqlQuery,varargs[string,] proc getRow(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): Row 344 +nim getAllRows db_odbc.html#getAllRows,DbConn,SqlQuery,varargs[string,] proc getAllRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[Row] 371 +nim rows db_odbc.html#rows.i,DbConn,SqlQuery,varargs[string,] iterator rows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): Row 400 +nim getValue db_odbc.html#getValue,DbConn,SqlQuery,varargs[string,] proc getValue(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): string 410 +nim tryInsertId db_odbc.html#tryInsertId,DbConn,SqlQuery,varargs[string,] proc tryInsertId(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 421 +nim insertId db_odbc.html#insertId,DbConn,SqlQuery,varargs[string,] proc insertId(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 445 +nim tryInsert db_odbc.html#tryInsert,DbConn,SqlQuery,string,varargs[string,] proc tryInsert(db: var DbConn; query: SqlQuery; pkName: string;\n args: varargs[string, `$`]): int64 453 +nim insert db_odbc.html#insert,DbConn,SqlQuery,string,varargs[string,] proc insert(db: var DbConn; query: SqlQuery; pkName: string;\n args: varargs[string, `$`]): int64 459 +nim execAffectedRows db_odbc.html#execAffectedRows,DbConn,SqlQuery,varargs[string,] proc execAffectedRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 466 +nim close db_odbc.html#close,DbConn proc close(db: var DbConn) 481 +nim open db_odbc.html#open,string,string,string,string proc open(connection, user, password, database: string): DbConn 495 +nim setEncoding db_odbc.html#setEncoding,DbConn,string proc setEncoding(connection: DbConn; encoding: string): bool 526 +heading Parameter substitution db_odbc.html#parameter-substitution Parameter substitution 0 +heading Examples db_odbc.html#examples Examples 0 +heading Opening a connection to a database db_odbc.html#examples-opening-a-connection-to-a-database Opening a connection to a database 0 +heading Creating a table db_odbc.html#examples-creating-a-table Creating a table 0 +heading Inserting data db_odbc.html#examples-inserting-data Inserting data 0 +heading Large example db_odbc.html#examples-large-example Large example 0 diff --git a/db_postgres.html b/db_postgres.html new file mode 100644 index 0000000000000..ab1666f8f4f4b --- /dev/null +++ b/db_postgres.html @@ -0,0 +1,675 @@ + + + + + + + +src/db_connector/db_postgres + + + + + + + + + + + + + + + + +
+
+

src/db_connector/db_postgres

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

Note: +In order to use this module, run nimble install db_connector.
+

A higher level PostgreSQL database wrapper. This interface is implemented for other databases also.

+

See also: db_odbc, db_sqlite, db_mysql.

+ +

Parameter substitution

All db_* modules support the same form of parameter substitution. That is, using the ? (question mark) to signify the place where a value should be placed. For example:

+

sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"

+

Note: There are two approaches to parameter substitution support by this module.

+
  1. SqlQuery using ?, ?, ?, ... (same as all the db_* modules)
  2. +
  3. SqlPrepared using $1, $2, $3, ...
  4. +
+

prepare(db, "myExampleInsert",
+        sql"""INSERT INTO myTable
+              (colA, colB, colC)
+              VALUES ($1, $2, $3)""",
+        3)

+ +

Unix Socket

Using Unix sockets instead of TCP connection can improve performance up to 30% ~ 175% for some operations.

+

To use Unix sockets with db_postgres, change the server address to the socket file path:

+

import std/db_postgres ## Change "localhost" or "127.0.0.1" to the socket file path
+let db = db_postgres.open("/run/postgresql", "user", "password", "database")
+echo db.getAllRows(sql"SELECT version();")
+db.close()

+

The socket file path is operating system specific and distribution specific, additional configuration may or may not be needed on your postgresql.conf. The Postgres server must be on the same computer and only works for Unix-like operating systems.

+ +

Examples

+

Opening a connection to a database

import db_connector/db_postgres
+let db = open("localhost", "user", "password", "dbname")
+db.close()

+ +

Creating a table

db.exec(sql"DROP TABLE IF EXISTS myTable")
+db.exec(sql("""CREATE TABLE myTable (
+                 id integer,
+                 name varchar(50) not null)"""))

+ +

Inserting data

db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
+        "Dominik")

+

+ +
+

Types

+
+
+
DbConn = PPGconn
+
+ + encapsulates a database connection + +
+
+
+
InstantRow = object
+  ## used to get a row's
+
+ + a handle that can be + +
+
+
+
Row = seq[string]
+
+ + a row of a dataset. NULL database values will be converted to nil. + +
+
+
+
SqlPrepared = distinct string
+
+ + a identifier for the prepared queries + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `[]`(row: InstantRow; col: int): string {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + returns text for given column of the row + +
+
+ +
+
+
+
proc close(db: DbConn) {....tags: [DbEffect], raises: [], forbids: [].}
+
+ + closes the database connection. + +
+
+ +
+
+
+
proc dbError(db: DbConn) {.noreturn, ...raises: [DbError], tags: [], forbids: [].}
+
+ + raises a DbError exception. + +
+
+ +
+
+
+
proc dbQuote(s: string): string {....raises: [], tags: [], forbids: [].}
+
+ + DB quotes the string. + +
+
+ +
+
+
+
proc exec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]) {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + executes the query and raises EDB if not successful. + +
+
+
+
proc exec(db: DbConn; stmtName: SqlPrepared; args: varargs[string]) {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc execAffectedRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError, ValueError],
+    forbids: [].}
+
+ + executes the query (typically "UPDATE") and returns the number of affected rows. + +
+
+
+
proc execAffectedRows(db: DbConn; stmtName: SqlPrepared;
+                      args: varargs[string, `$`]): int64 {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError, ValueError],
+    forbids: [].}
+
+ + executes the query (typically "UPDATE") and returns the number of affected rows. + +
+
+ +
+
+
+
proc getAllRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[
+    Row] {....tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + executes the query and returns the whole result dataset. + +
+
+
+
proc getAllRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): seq[
+    Row] {....tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + executes the prepared query and returns the whole result dataset. + +
+
+ +
+
+
+
proc getRow(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + retrieves a single row. If the query doesn't return any rows, this proc will return a Row with empty strings for each column. + +
+
+
+
proc getRow(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): Row {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc getValue(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): string {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + executes the query and returns the first column of the first row of the result dataset. Returns "" if the dataset contains no rows or the database value is NULL. + +
+
+
+
proc getValue(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): string {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + executes the query and returns the first column of the first row of the result dataset. Returns "" if the dataset contains no rows or the database value is NULL. + +
+
+ +
+
+
+
proc insert(db: DbConn; query: SqlQuery; pkName: string;
+            args: varargs[string, `$`]): int64 {....tags: [WriteDbEffect],
+    raises: [DbError, ValueError], forbids: [].}
+
+ + executes the query (typically "INSERT") and returns the generated ID + +
+
+ +
+
+
+
proc insertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
+    ...tags: [WriteDbEffect], raises: [DbError, ValueError], forbids: [].}
+
+ + executes the query (typically "INSERT") and returns the generated ID for the row. For Postgre this adds RETURNING id to the query, so it only works if your primary key is named id. + +
+
+ +
+
+
+
proc len(row: InstantRow): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + returns number of columns in the row + +
+
+ +
+
+
+
proc open(connection, user, password, database: string): DbConn {.
+    ...tags: [DbEffect], raises: [DbError], forbids: [].}
+
+ +

opens a database connection. Raises EDb if the connection could not be established.

+

Clients can also use Postgres keyword/value connection strings to connect.

+

Example:

+

con = open("", "", "", "host=localhost port=5432 dbname=mydb")

+

See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING for more information.

+ + +
+
+ +
+
+
+
proc prepare(db: DbConn; stmtName: string; query: SqlQuery; nParams: int): SqlPrepared {.
+    ...raises: [DbError], tags: [], forbids: [].}
+
+ + Creates a new SqlPrepared statement. Parameter substitution is done via $1, $2, $3, etc. + +
+
+ +
+
+
+
proc setEncoding(connection: DbConn; encoding: string): bool {....tags: [DbEffect],
+    raises: [], forbids: [].}
+
+ + sets the encoding of a database connection, returns true for success, false for failure. + +
+
+ +
+
+
+
proc tryExec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): bool {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + tries to execute the query and returns true if successful, false otherwise. + +
+
+
+
proc tryExec(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): bool {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [], forbids: [].}
+
+ + tries to execute the query and returns true if successful, false otherwise. + +
+
+ +
+
+
+
proc tryInsert(db: DbConn; query: SqlQuery; pkName: string;
+               args: varargs[string, `$`]): int64 {....tags: [WriteDbEffect],
+    raises: [DbError, ValueError], forbids: [].}
+
+ + executes the query (typically "INSERT") and returns the generated ID for the row or -1 in case of an error. + +
+
+ +
+
+
+
proc tryInsertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
+    ...tags: [WriteDbEffect], raises: [DbError, ValueError], forbids: [].}
+
+ + executes the query (typically "INSERT") and returns the generated ID for the row or -1 in case of an error. For Postgre this adds RETURNING id to the query, so it only works if your primary key is named id. + +
+
+ +
+
+
+
proc unsafeColumnAt(row: InstantRow; index: int): cstring {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Return cstring of given column of the row + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator fastRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + executes the query and iterates over the result dataset. This is very fast, but potentially dangerous: If the for-loop-body executes another query, the results can be undefined. For Postgres it is safe though. + +
+
+
+
iterator fastRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): Row {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + executes the query and iterates over the result dataset. This is very fast, but potentially dangerous: If the for-loop-body executes another query, the results can be undefined. For Postgres it is safe though. + +
+
+ +
+
+
+
iterator instantRows(db: DbConn; columns: var DbColumns; query: SqlQuery;
+                     args: varargs[string, `$`]): InstantRow {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + + +
+
+
+
iterator instantRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within iterator body. + +
+
+
+
iterator instantRows(db: DbConn; stmtName: SqlPrepared;
+                     args: varargs[string, `$`]): InstantRow {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within iterator body. + +
+
+ +
+
+
+
iterator rows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + same as fastRows, but slower and safe. + +
+
+
+
iterator rows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): Row {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ + same as fastRows, but slower and safe. + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/db_postgres.idx b/db_postgres.idx new file mode 100644 index 0000000000000..cb08ed0508263 --- /dev/null +++ b/db_postgres.idx @@ -0,0 +1,53 @@ +nimTitle db_postgres db_postgres.html module src/db_connector/db_postgres 0 +nim DbConn db_postgres.html#DbConn type DbConn 104 +nim Row db_postgres.html#Row type Row 105 +nim InstantRow db_postgres.html#InstantRow object InstantRow 107 +nim SqlPrepared db_postgres.html#SqlPrepared type SqlPrepared 109 +nim dbError db_postgres.html#dbError,DbConn proc dbError(db: DbConn) 111 +nim dbQuote db_postgres.html#dbQuote,string proc dbQuote(s: string): string 118 +nim tryExec db_postgres.html#tryExec,DbConn,SqlQuery,varargs[string,] proc tryExec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): bool 131 +nim tryExec db_postgres.html#tryExec,DbConn,SqlPrepared,varargs[string,] proc tryExec(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): bool 139 +nim exec db_postgres.html#exec,DbConn,SqlQuery,varargs[string,] proc exec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]) 150 +nim exec db_postgres.html#exec,DbConn,SqlPrepared,varargs[string] proc exec(db: DbConn; stmtName: SqlPrepared; args: varargs[string]) 158 +nim prepare db_postgres.html#prepare,DbConn,string,SqlQuery,int proc prepare(db: DbConn; stmtName: string; query: SqlQuery; nParams: int): SqlPrepared 200 +nim fastRows db_postgres.html#fastRows.i,DbConn,SqlQuery,varargs[string,] iterator fastRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row 238 +nim fastRows db_postgres.html#fastRows.i,DbConn,SqlPrepared,varargs[string,] iterator fastRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): Row 246 +nim instantRows db_postgres.html#instantRows.i,DbConn,SqlQuery,varargs[string,] iterator instantRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow 269 +nim instantRows db_postgres.html#instantRows.i,DbConn,SqlPrepared,varargs[string,] iterator instantRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): InstantRow 277 +nim instantRows db_postgres.html#instantRows.i,DbConn,DbColumns,SqlQuery,varargs[string,] iterator instantRows(db: DbConn; columns: var DbColumns; query: SqlQuery;\n args: varargs[string, `$`]): InstantRow 430 +nim `[]` db_postgres.html#[],InstantRow,int proc `[]`(row: InstantRow; col: int): string 452 +nim unsafeColumnAt db_postgres.html#unsafeColumnAt,InstantRow,int proc unsafeColumnAt(row: InstantRow; index: int): cstring 456 +nim len db_postgres.html#len,InstantRow proc len(row: InstantRow): int 460 +nim getRow db_postgres.html#getRow,DbConn,SqlQuery,varargs[string,] proc getRow(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row 471 +nim getRow db_postgres.html#getRow,DbConn,SqlPrepared,varargs[string,] proc getRow(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): Row 478 +nim getAllRows db_postgres.html#getAllRows,DbConn,SqlQuery,varargs[string,] proc getAllRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[Row] 493 +nim getAllRows db_postgres.html#getAllRows,DbConn,SqlPrepared,varargs[string,] proc getAllRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): seq[\n Row] 500 +nim rows db_postgres.html#rows.i,DbConn,SqlQuery,varargs[string,] iterator rows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row 507 +nim rows db_postgres.html#rows.i,DbConn,SqlPrepared,varargs[string,] iterator rows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): Row 512 +nim getValue db_postgres.html#getValue,DbConn,SqlQuery,varargs[string,] proc getValue(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): string 524 +nim getValue db_postgres.html#getValue,DbConn,SqlPrepared,varargs[string,] proc getValue(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): string 534 +nim tryInsertID db_postgres.html#tryInsertID,DbConn,SqlQuery,varargs[string,] proc tryInsertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 544 +nim insertID db_postgres.html#insertID,DbConn,SqlQuery,varargs[string,] proc insertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 560 +nim tryInsert db_postgres.html#tryInsert,DbConn,SqlQuery,string,varargs[string,] proc tryInsert(db: DbConn; query: SqlQuery; pkName: string;\n args: varargs[string, `$`]): int64 570 +nim insert db_postgres.html#insert,DbConn,SqlQuery,string,varargs[string,] proc insert(db: DbConn; query: SqlQuery; pkName: string; args: varargs[string, `$`]): int64 584 +nim execAffectedRows db_postgres.html#execAffectedRows,DbConn,SqlQuery,varargs[string,] proc execAffectedRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 592 +nim execAffectedRows db_postgres.html#execAffectedRows,DbConn,SqlPrepared,varargs[string,] proc execAffectedRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): int64 603 +nim close db_postgres.html#close,DbConn proc close(db: DbConn) 616 +nim open db_postgres.html#open,string,string,string,string proc open(connection, user, password, database: string): DbConn 620 +nim setEncoding db_postgres.html#setEncoding,DbConn,string proc setEncoding(connection: DbConn; encoding: string): bool 644 +nimgrp getallrows db_postgres.html#getAllRows-procs-all proc 493 +nimgrp getvalue db_postgres.html#getValue-procs-all proc 524 +nimgrp execaffectedrows db_postgres.html#execAffectedRows-procs-all proc 592 +nimgrp exec db_postgres.html#exec-procs-all proc 150 +nimgrp tryexec db_postgres.html#tryExec-procs-all proc 131 +nimgrp getrow db_postgres.html#getRow-procs-all proc 471 +nimgrp fastrows db_postgres.html#fastRows-iterators-all iterator 238 +nimgrp rows db_postgres.html#rows-iterators-all iterator 507 +nimgrp instantrows db_postgres.html#instantRows-iterators-all iterator 269 +idx PostgreSQL db_postgres.html#postgresql_1 Module db_postgres 0 +heading Parameter substitution db_postgres.html#parameter-substitution Parameter substitution 0 +heading Unix Socket db_postgres.html#unix-socket Unix Socket 0 +heading Examples db_postgres.html#examples Examples 0 +heading Opening a connection to a database db_postgres.html#examples-opening-a-connection-to-a-database Opening a connection to a database 0 +heading Creating a table db_postgres.html#examples-creating-a-table Creating a table 0 +heading Inserting data db_postgres.html#examples-inserting-data Inserting data 0 diff --git a/db_sqlite.html b/db_sqlite.html new file mode 100644 index 0000000000000..948eba066d09a --- /dev/null +++ b/db_sqlite.html @@ -0,0 +1,1118 @@ + + + + + + + +src/db_connector/db_sqlite + + + + + + + + + + + + + + + + +
+
+

src/db_connector/db_sqlite

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

Note: +In order to use this module, run nimble install db_connector.
+

A higher level SQLite database wrapper. This interface is implemented for other databases too.

+ +

Basic usage

The basic flow of using this module is:

+
  1. Open database connection
  2. +
  3. Execute SQL query
  4. +
  5. Close database connection
  6. +
+ +

Parameter substitution

All db_* modules support the same form of parameter substitution. That is, using the ? (question mark) to signify the place where a value should be placed. For example:

+

sql"INSERT INTO my_table (colA, colB, colC) VALUES (?, ?, ?)"

+ +

Opening a connection to a database

import db_connector/db_sqlite
+
+# user, password, database name can be empty.
+# These params are not used on db_sqlite module.
+let db = open("mytest.db", "", "", "")
+db.close()

+ +

Creating a table

db.exec(sql"DROP TABLE IF EXISTS my_table")
+db.exec(sql"""CREATE TABLE my_table (
+                 id   INTEGER,
+                 name VARCHAR(50) NOT NULL
+              )""")

+ +

Inserting data

db.exec(sql"INSERT INTO my_table (id, name) VALUES (0, ?)",
+        "Jack")

+ +

Larger example

import db_connector/db_sqlite
+import std/math
+
+let db = open("mytest.db", "", "", "")
+
+db.exec(sql"DROP TABLE IF EXISTS my_table")
+db.exec(sql"""CREATE TABLE my_table (
+                 id    INTEGER PRIMARY KEY,
+                 name  VARCHAR(50) NOT NULL,
+                 i     INT(11),
+                 f     DECIMAL(18, 10)
+              )""")
+
+db.exec(sql"BEGIN")
+for i in 1..1000:
+  db.exec(sql"INSERT INTO my_table (name, i, f) VALUES (?, ?, ?)",
+          "Item#" & $i, i, sqrt(i.float))
+db.exec(sql"COMMIT")
+
+for x in db.fastRows(sql"SELECT * FROM my_table"):
+  echo x
+
+let id = db.tryInsertId(sql"""INSERT INTO my_table (name, i, f)
+                              VALUES (?, ?, ?)""",
+                        "Item#1001", 1001, sqrt(1001.0))
+echo "Inserted item: ", db.getValue(sql"SELECT name FROM my_table WHERE id=?", id)
+
+db.close()

+ +

Storing binary data example

import std/random
+
+## Generate random float datas
+var orig = newSeq[float64](150)
+randomize()
+for x in orig.mitems:
+  x = rand(1.0)/10.0
+
+let db = open("mysqlite.db", "", "", "")
+block: ## Create database
+  ## Binary datas needs to be of type BLOB in SQLite
+  let createTableStr = sql"""CREATE TABLE test(
+    id INTEGER NOT NULL PRIMARY KEY,
+    data BLOB
+  )
+  """
+  db.exec(createTableStr)
+
+block: ## Insert data
+  var id = 1
+  ## Data needs to be converted to seq[byte] to be interpreted as binary by bindParams
+  var dbuf = newSeq[byte](orig.len*sizeof(float64))
+  copyMem(unsafeAddr(dbuf[0]), unsafeAddr(orig[0]), dbuf.len)
+  
+  ## Use prepared statement to insert binary data into database
+  var insertStmt = db.prepare("INSERT INTO test (id, data) VALUES (?, ?)")
+  insertStmt.bindParams(id, dbuf)
+  let bres = db.tryExec(insertStmt)
+  ## Check insert
+  doAssert(bres)
+  # Destroy statement
+  finalize(insertStmt)
+
+block: ## Use getValue to select data
+  var dataTest = db.getValue(sql"SELECT data FROM test WHERE id = ?", 1)
+  ## Calculate sequence size from buffer size
+  let seqSize = int(dataTest.len*sizeof(byte)/sizeof(float64))
+  ## Copy binary string data in dataTest into a seq
+  var res: seq[float64] = newSeq[float64](seqSize)
+  copyMem(unsafeAddr(res[0]), addr(dataTest[0]), dataTest.len)
+  
+  ## Check datas obtained is identical
+  doAssert res == orig
+
+db.close()

+ +

Note

This module does not implement any ORM features such as mapping the types from the schema. Instead, a seq[string] is returned for each row.

+

The reasoning is as follows:

+
  1. it's close to what many DBs offer natively (char**)
  2. +
  3. it hides the number of types that the DB supports (int? int64? decimal up to 10 places? geo coords?)
  4. +
  5. it's convenient when all you do is to forward the data to somewhere else (echo, log, put the data into a new query)
  6. +
+ +

See also

+

+ +
+

Types

+
+
+
DbConn = PSqlite3
+
+ + Encapsulates a database connection. + +
+
+
+
InstantRow = PStmt
+
+ + A handle that can be used to get a row's column text on demand. + +
+
+
+
Row = seq[string]
+
+ + A row of a dataset. NULL database values will be converted to an empty string. + +
+
+
+
SqlPrepared = distinct PStmt
+
+ + a identifier for the prepared queries + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `[]`(row: InstantRow; col: int32): string {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Returns text for given column of the row.

+

See also:

+ + + +
+
+ +
+
+
+
proc bindNull(ps: SqlPrepared; paramIdx: int) {....raises: [DbError], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc bindParam(ps: SqlPrepared; paramIdx: int; val: float64) {.
+    ...raises: [DbError], tags: [], forbids: [].}
+
+ + + +
+
+
+
proc bindParam(ps: SqlPrepared; paramIdx: int; val: int) {....raises: [DbError],
+    tags: [], forbids: [].}
+
+ + + +
+
+
+
proc bindParam(ps: SqlPrepared; paramIdx: int; val: int32) {....raises: [DbError],
+    tags: [], forbids: [].}
+
+ + + +
+
+
+
proc bindParam(ps: SqlPrepared; paramIdx: int; val: int64) {....raises: [DbError],
+    tags: [], forbids: [].}
+
+ + + +
+
+
+
proc bindParam(ps: SqlPrepared; paramIdx: int; val: openArray[byte]; copy = true) {.
+    ...raises: [DbError], tags: [], forbids: [].}
+
+ + + +
+
+
+
proc bindParam(ps: SqlPrepared; paramIdx: int; val: string; copy = true) {.
+    ...raises: [DbError], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc close(db: DbConn) {....tags: [DbEffect], raises: [DbError], forbids: [].}
+
+ +

Closes the database connection.

+

Examples:

+

let db = open("mytest.db", "", "", "")
+db.close()

+ + +
+
+ +
+
+
+
proc dbError(db: DbConn) {.noreturn, ...raises: [DbError], tags: [], forbids: [].}
+
+ +

Raises a DbError exception.

+

Examples:

+

let db = open("mytest.db", "", "", "")
+if not db.tryExec(sql"SELECT * FROM not_exist_table"):
+  dbError(db)
+db.close()

+ + +
+
+ +
+
+
+
proc dbQuote(s: string): string {....raises: [], tags: [], forbids: [].}
+
+ + Escapes the ' (single quote) char to ''. Because single quote is used for defining VARCHAR in SQL. +

Example:

+
doAssert dbQuote("'") == "''''"
+doAssert dbQuote("A Foobar's pen.") == "'A Foobar''s pen.'"
+ +
+
+ +
+
+
+
proc exec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]) {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ +

Executes the query and raises a DbError exception if not successful.

+

Examples:

+

let db = open("mytest.db", "", "", "")
+try:
+  db.exec(sql"INSERT INTO my_table (id, name) VALUES (?, ?)",
+          1, "item#1")
+except:
+  stderr.writeLine(getCurrentExceptionMsg())
+finally:
+  db.close()

+ + +
+
+ +
+
+
+
proc execAffectedRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ +

Executes the query (typically "UPDATE") and returns the number of affected rows.

+

Examples:

+

let db = open("mytest.db", "", "", "")
+
+# Records of my_table:
+# | id | name     |
+# |----|----------|
+# |  1 | item#1   |
+# |  2 | item#2   |
+
+doAssert db.execAffectedRows(sql"UPDATE my_table SET name = 'TEST'") == 2
+
+db.close()

+ + +
+
+
+
proc execAffectedRows(db: DbConn; stmtName: SqlPrepared): int64 {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc finalize(sqlPrepared: SqlPrepared) {.discardable, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc getAllRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[
+    Row] {....tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ +

Executes the query and returns the whole result dataset.

+

Examples:

+

let db = open("mytest.db", "", "", "")
+
+# Records of my_table:
+# | id | name     |
+# |----|----------|
+# |  1 | item#1   |
+# |  2 | item#2   |
+
+doAssert db.getAllRows(sql"SELECT id, name FROM my_table") == @[Row(@["1", "item#1"]), Row(@["2", "item#2"])]
+db.close()

+ + +
+
+
+
proc getAllRows(db: DbConn; stmtName: SqlPrepared): seq[Row] {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc getRow(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ +

Retrieves a single row. If the query doesn't return any rows, this proc will return a Row with empty strings for each column.

+

Examples:

+

let db = open("mytest.db", "", "", "")
+
+# Records of my_table:
+# | id | name     |
+# |----|----------|
+# |  1 | item#1   |
+# |  2 | item#2   |
+
+doAssert db.getRow(sql"SELECT id, name FROM my_table"
+                   ) == Row(@["1", "item#1"])
+doAssert db.getRow(sql"SELECT id, name FROM my_table WHERE id = ?",
+                   2) == Row(@["2", "item#2"])
+
+# Returns empty.
+doAssert db.getRow(sql"INSERT INTO my_table (id, name) VALUES (?, ?)",
+                   3, "item#3") == @[]
+doAssert db.getRow(sql"DELETE FROM my_table WHERE id = ?", 3) == @[]
+doAssert db.getRow(sql"UPDATE my_table SET name = 'ITEM#1' WHERE id = ?",
+                   1) == @[]
+db.close()

+ + +
+
+ +
+
+
+
proc getValue(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): string {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ +

Executes the query and returns the first column of the first row of the result dataset. Returns "" if the dataset contains no rows or the database value is NULL.

+

Examples:

+

let db = open("mytest.db", "", "", "")
+
+# Records of my_table:
+# | id | name     |
+# |----|----------|
+# |  1 | item#1   |
+# |  2 | item#2   |
+
+doAssert db.getValue(sql"SELECT name FROM my_table WHERE id = ?",
+                     2) == "item#2"
+doAssert db.getValue(sql"SELECT id, name FROM my_table") == "1"
+doAssert db.getValue(sql"SELECT name, id FROM my_table") == "item#1"
+
+db.close()

+ + +
+
+
+
proc getValue(db: DbConn; stmtName: SqlPrepared): string {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc insert(db: DbConn; query: SqlQuery; pkName: string;
+            args: varargs[string, `$`]): int64 {....tags: [WriteDbEffect],
+    raises: [DbError], forbids: [].}
+
+ + same as insertId + +
+
+ +
+
+
+
proc insertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
+    ...tags: [WriteDbEffect], raises: [DbError], forbids: [].}
+
+ +

Executes the query (typically "INSERT") and returns the generated ID for the row.

+

Raises a DbError exception when failed to insert row. For Postgre this adds RETURNING id to the query, so it only works if your primary key is named id.

+

Examples:

+

let db = open("mytest.db", "", "", "")
+db.exec(sql"CREATE TABLE my_table (id INTEGER, name VARCHAR(50) NOT NULL)")
+
+for i in 0..2:
+  let id = db.insertID(sql"INSERT INTO my_table (id, name) VALUES (?, ?)", i, "item#" & $i)
+  echo "LoopIndex = ", i, ", InsertID = ", id
+
+# Output:
+# LoopIndex = 0, InsertID = 1
+# LoopIndex = 1, InsertID = 2
+# LoopIndex = 2, InsertID = 3
+
+db.close()

+ + +
+
+ +
+
+
+
proc len(row: InstantRow): int32 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Returns number of columns in a row.

+

See also:

+ + + +
+
+ +
+
+
+
proc open(connection, user, password, database: string): DbConn {.
+    ...tags: [DbEffect], raises: [DbError], forbids: [].}
+
+ +

Opens a database connection. Raises a DbError exception if the connection could not be established.

+

Note: Only the connection parameter is used for sqlite.

+

Examples:

+

try:
+  let db = open("mytest.db", "", "", "")
+  ## do something...
+  ## db.getAllRows(sql"SELECT * FROM my_table")
+  db.close()
+except:
+  stderr.writeLine(getCurrentExceptionMsg())

+ + +
+
+ +
+
+
+
proc prepare(db: DbConn; q: string): SqlPrepared {....raises: [DbError], tags: [],
+    forbids: [].}
+
+ + Creates a new SqlPrepared statement. + +
+
+ +
+
+
+
proc setEncoding(connection: DbConn; encoding: string): bool {....tags: [DbEffect],
+    raises: [DbError], forbids: [].}
+
+ +

Sets the encoding of a database connection, returns true for success, false for failure.

+

Note: The encoding cannot be changed once it's been set. According to SQLite3 documentation, any attempt to change the encoding after the database is created will be silently ignored.

+ + +
+
+ +
+
+
+
proc tryExec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): bool {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ +

Tries to execute the query and returns true if successful, false otherwise.

+

Examples:

+

let db = open("mytest.db", "", "", "")
+if not db.tryExec(sql"SELECT * FROM my_table"):
+  dbError(db)
+db.close()

+ + +
+
+
+
proc tryExec(db: DbConn; stmtName: SqlPrepared): bool {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc tryInsert(db: DbConn; query: SqlQuery; pkName: string;
+               args: varargs[string, `$`]): int64 {....tags: [WriteDbEffect],
+    raises: [DbError], forbids: [].}
+
+ + same as tryInsertID + +
+
+ +
+
+
+
proc tryInsertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
+    ...tags: [WriteDbEffect], raises: [DbError], forbids: [].}
+
+ +

Executes the query (typically "INSERT") and returns the generated ID for the row or -1 in case of an error.

+

Examples:

+

let db = open("mytest.db", "", "", "")
+db.exec(sql"CREATE TABLE my_table (id INTEGER, name VARCHAR(50) NOT NULL)")
+
+doAssert db.tryInsertID(sql"INSERT INTO not_exist_table (id, name) VALUES (?, ?)",
+                        1, "item#1") == -1
+db.close()

+ + +
+
+ +
+
+
+
proc unsafeColumnAt(row: InstantRow; index: int32): cstring {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Returns cstring for given column of the row.

+

See also:

+ + + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator fastRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
+    ...tags: [ReadDbEffect], raises: [DbError, DbError], forbids: [].}
+
+ +

Executes the query and iterates over the result dataset.

+

This is very fast, but potentially dangerous. Use this iterator only if you require ALL the rows.

+

Note: Breaking the fastRows() iterator during a loop will cause the next database query to raise a DbError exception unable to close due to ....

+

Examples:

+

let db = open("mytest.db", "", "", "")
+
+# Records of my_table:
+# | id | name     |
+# |----|----------|
+# |  1 | item#1   |
+# |  2 | item#2   |
+
+for row in db.fastRows(sql"SELECT id, name FROM my_table"):
+  echo row
+
+# Output:
+# @["1", "item#1"]
+# @["2", "item#2"]
+
+db.close()

+ + +
+
+
+
iterator fastRows(db: DbConn; stmtName: SqlPrepared): Row {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + + +
+
+ +
+
+
+
iterator instantRows(db: DbConn; columns: var DbColumns; query: SqlQuery;
+                     args: varargs[string, `$`]): InstantRow {.
+    ...tags: [ReadDbEffect], raises: [DbError, DbError], forbids: [].}
+
+ +

Similar to instantRows iterator, but sets information about columns to columns.

+

Examples:

+

let db = open("mytest.db", "", "", "")
+
+# Records of my_table:
+# | id | name     |
+# |----|----------|
+# |  1 | item#1   |
+# |  2 | item#2   |
+
+var columns: DbColumns
+for row in db.instantRows(columns, sql"SELECT * FROM my_table"):
+  discard
+echo columns[0]
+
+# Output:
+# (name: "id", tableName: "my_table", typ: (kind: dbNull,
+# notNull: false, name: "INTEGER", size: 0, maxReprLen: 0, precision: 0,
+# scale: 0, min: 0, max: 0, validValues: @[]), primaryKey: false,
+# foreignKey: false)
+
+db.close()

+ + +
+
+
+
iterator instantRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow {.
+    ...tags: [ReadDbEffect], raises: [DbError, DbError], forbids: [].}
+
+ +

Similar to fastRows iterator but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within the iterator body.

+

Examples:

+

 let db = open("mytest.db", "", "", "")
+ 
+ # Records of my_table:
+ # | id | name     |
+ # |----|----------|
+ # |  1 | item#1   |
+ # |  2 | item#2   |
+ 
+ for row in db.instantRows(sql"SELECT * FROM my_table"):
+   echo "id:" & row[0]
+   echo "name:" & row[1]
+   echo "length:" & $len(row)
+ 
+ # Output:
+ # id:1
+ # name:item#1
+ # length:2
+ # id:2
+ # name:item#2
+ # length:2
+ 
+ db.close()

+ + +
+
+
+
iterator instantRows(db: DbConn; stmtName: SqlPrepared): InstantRow {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + + +
+
+ +
+
+
+
iterator rows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
+    ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
+
+ +

Similar to fastRows iterator, but slower and safe.

+

Examples:

+

let db = open("mytest.db", "", "", "")
+
+# Records of my_table:
+# | id | name     |
+# |----|----------|
+# |  1 | item#1   |
+# |  2 | item#2   |
+
+for row in db.rows(sql"SELECT id, name FROM my_table"):
+  echo row
+
+## Output:
+## @["1", "item#1"]
+## @["2", "item#2"]
+
+db.close()

+ + +
+
+
+
iterator rows(db: DbConn; stmtName: SqlPrepared): Row {.
+    ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
+
+ + + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro bindParams(ps: SqlPrepared; params: varargs[untyped]): untyped
+
+ + + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template dbBindParamError(paramIdx: int; val: varargs[untyped])
+
+ + Raises a DbError exception. + +
+
+ +
+
+
+
template exec(db: DbConn; stmtName: SqlPrepared; args: varargs[typed]): untyped
+
+ + + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/db_sqlite.idx b/db_sqlite.idx new file mode 100644 index 0000000000000..905056af34ce0 --- /dev/null +++ b/db_sqlite.idx @@ -0,0 +1,64 @@ +nimTitle db_sqlite db_sqlite.html module src/db_connector/db_sqlite 0 +nim DbConn db_sqlite.html#DbConn type DbConn 183 +nim Row db_sqlite.html#Row type Row 184 +nim InstantRow db_sqlite.html#InstantRow type InstantRow 186 +nim SqlPrepared db_sqlite.html#SqlPrepared type SqlPrepared 188 +nim bindParam db_sqlite.html#bindParam,SqlPrepared,int,int32 proc bindParam(ps: SqlPrepared; paramIdx: int; val: int32) 190 +nim bindParam db_sqlite.html#bindParam,SqlPrepared,int,int64 proc bindParam(ps: SqlPrepared; paramIdx: int; val: int64) 191 +nim bindParam db_sqlite.html#bindParam,SqlPrepared,int,int proc bindParam(ps: SqlPrepared; paramIdx: int; val: int) 192 +nim bindParam db_sqlite.html#bindParam,SqlPrepared,int,float64 proc bindParam(ps: SqlPrepared; paramIdx: int; val: float64) 193 +nim bindNull db_sqlite.html#bindNull,SqlPrepared,int proc bindNull(ps: SqlPrepared; paramIdx: int) 194 +nim bindParam db_sqlite.html#bindParam,SqlPrepared,int,string proc bindParam(ps: SqlPrepared; paramIdx: int; val: string; copy = true) 195 +nim bindParam db_sqlite.html#bindParam,SqlPrepared,int,openArray[byte] proc bindParam(ps: SqlPrepared; paramIdx: int; val: openArray[byte]; copy = true) 196 +nim dbError db_sqlite.html#dbError,DbConn proc dbError(db: DbConn) 198 +nim dbQuote db_sqlite.html#dbQuote,string proc dbQuote(s: string): string 213 +nim prepare db_sqlite.html#prepare,DbConn,string proc prepare(db: DbConn; q: string): SqlPrepared 229 +nim tryExec db_sqlite.html#tryExec,DbConn,SqlQuery,varargs[string,] proc tryExec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): bool 235 +nim tryExec db_sqlite.html#tryExec,DbConn,SqlPrepared proc tryExec(db: DbConn; stmtName: SqlPrepared): bool 258 +nim exec db_sqlite.html#exec,DbConn,SqlQuery,varargs[string,] proc exec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]) 267 +nim bindParams db_sqlite.html#bindParams.m,SqlPrepared,varargs[untyped] macro bindParams(ps: SqlPrepared; params: varargs[untyped]): untyped 287 +nim exec db_sqlite.html#exec.t,DbConn,SqlPrepared,varargs[typed] template exec(db: DbConn; stmtName: SqlPrepared; args: varargs[typed]): untyped 301 +nim fastRows db_sqlite.html#fastRows.i,DbConn,SqlQuery,varargs[string,] iterator fastRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row 337 +nim fastRows db_sqlite.html#fastRows.i,DbConn,SqlPrepared iterator fastRows(db: DbConn; stmtName: SqlPrepared): Row 378 +nim instantRows db_sqlite.html#instantRows.i,DbConn,SqlQuery,varargs[string,] iterator instantRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow 390 +nim instantRows db_sqlite.html#instantRows.i,DbConn,SqlPrepared iterator instantRows(db: DbConn; stmtName: SqlPrepared): InstantRow 430 +nim instantRows db_sqlite.html#instantRows.i,DbConn,DbColumns,SqlQuery,varargs[string,] iterator instantRows(db: DbConn; columns: var DbColumns; query: SqlQuery;\n args: varargs[string, `$`]): InstantRow 461 +nim `[]` db_sqlite.html#[],InstantRow,int32 proc `[]`(row: InstantRow; col: int32): string 499 +nim unsafeColumnAt db_sqlite.html#unsafeColumnAt,InstantRow,int32 proc unsafeColumnAt(row: InstantRow; index: int32): cstring 507 +nim len db_sqlite.html#len,InstantRow proc len(row: InstantRow): int32 515 +nim getRow db_sqlite.html#getRow,DbConn,SqlQuery,varargs[string,] proc getRow(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row 523 +nim getAllRows db_sqlite.html#getAllRows,DbConn,SqlQuery,varargs[string,] proc getAllRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[Row] 559 +nim getAllRows db_sqlite.html#getAllRows,DbConn,SqlPrepared proc getAllRows(db: DbConn; stmtName: SqlPrepared): seq[Row] 581 +nim rows db_sqlite.html#rows.i,DbConn,SqlQuery,varargs[string,] iterator rows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row 587 +nim rows db_sqlite.html#rows.i,DbConn,SqlPrepared iterator rows(db: DbConn; stmtName: SqlPrepared): Row 614 +nim getValue db_sqlite.html#getValue,DbConn,SqlQuery,varargs[string,] proc getValue(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): string 618 +nim getValue db_sqlite.html#getValue,DbConn,SqlPrepared proc getValue(db: DbConn; stmtName: SqlPrepared): string 658 +nim tryInsertID db_sqlite.html#tryInsertID,DbConn,SqlQuery,varargs[string,] proc tryInsertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 675 +nim insertID db_sqlite.html#insertID,DbConn,SqlQuery,varargs[string,] proc insertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 703 +nim tryInsert db_sqlite.html#tryInsert,DbConn,SqlQuery,string,varargs[string,] proc tryInsert(db: DbConn; query: SqlQuery; pkName: string;\n args: varargs[string, `$`]): int64 732 +nim insert db_sqlite.html#insert,DbConn,SqlQuery,string,varargs[string,] proc insert(db: DbConn; query: SqlQuery; pkName: string; args: varargs[string, `$`]): int64 738 +nim execAffectedRows db_sqlite.html#execAffectedRows,DbConn,SqlQuery,varargs[string,] proc execAffectedRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 745 +nim execAffectedRows db_sqlite.html#execAffectedRows,DbConn,SqlPrepared proc execAffectedRows(db: DbConn; stmtName: SqlPrepared): int64 769 +nim close db_sqlite.html#close,DbConn proc close(db: DbConn) 774 +nim open db_sqlite.html#open,string,string,string,string proc open(connection, user, password, database: string): DbConn 784 +nim setEncoding db_sqlite.html#setEncoding,DbConn,string proc setEncoding(connection: DbConn; encoding: string): bool 807 +nim finalize db_sqlite.html#finalize,SqlPrepared proc finalize(sqlPrepared: SqlPrepared) 819 +nim dbBindParamError db_sqlite.html#dbBindParamError.t,int,varargs[untyped] template dbBindParamError(paramIdx: int; val: varargs[untyped]) 822 +nimgrp getallrows db_sqlite.html#getAllRows-procs-all proc 559 +nimgrp getvalue db_sqlite.html#getValue-procs-all proc 618 +nimgrp execaffectedrows db_sqlite.html#execAffectedRows-procs-all proc 745 +nimgrp bindparam db_sqlite.html#bindParam-procs-all proc 190 +nimgrp tryexec db_sqlite.html#tryExec-procs-all proc 235 +nimgrp fastrows db_sqlite.html#fastRows-iterators-all iterator 337 +nimgrp rows db_sqlite.html#rows-iterators-all iterator 587 +nimgrp instantrows db_sqlite.html#instantRows-iterators-all iterator 390 +idx SQLite db_sqlite.html#sqlite_1 Module db_sqlite 0 +heading Basic usage db_sqlite.html#basic-usage Basic usage 0 +heading Parameter substitution db_sqlite.html#basic-usage-parameter-substitution Parameter substitution 0 +heading Opening a connection to a database db_sqlite.html#basic-usage-opening-a-connection-to-a-database Opening a connection to a database 0 +heading Creating a table db_sqlite.html#basic-usage-creating-a-table Creating a table 0 +heading Inserting data db_sqlite.html#basic-usage-inserting-data Inserting data 0 +heading Larger example db_sqlite.html#basic-usage-larger-example Larger example 0 +heading Storing binary data example db_sqlite.html#basic-usage-storing-binary-data-example Storing binary data example 0 +heading Note db_sqlite.html#note Note 0 +heading See also db_sqlite.html#see-also See also 0 diff --git a/dbutils.html b/dbutils.html new file mode 100644 index 0000000000000..c073fa5c19833 --- /dev/null +++ b/dbutils.html @@ -0,0 +1,119 @@ + + + + + + + +src/db_connector/private/dbutils + + + + + + + + + + + + + + + + +
+
+

src/db_connector/private/dbutils

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

+
+

Imports

+
+ db_common +
+
+
+

Templates

+
+
+
+
template dbFormatImpl(formatstr: SqlQuery;
+                      dbQuote: proc (s: string): string {.nimcall.};
+                      args: varargs[string]): string
+
+ + + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/decls.html b/decls.html new file mode 100644 index 0000000000000..44ec36f9e5dd6 --- /dev/null +++ b/decls.html @@ -0,0 +1,129 @@ + + + + + + + +std/decls + + + + + + + + + + + + + + + + +
+
+

std/decls

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements syntax sugar for some declarations.

+
+

Imports

+
+ macros +
+
+
+

Macros

+
+
+
+
macro byaddr(sect)
+
+ + Allows a syntax for l-value references, being an exact analog to auto& a = ex; in C++.
Warning: +This makes use of 2 experimental features, namely nullary templates instantiated as symbols and variable macro pragmas. For this reason, its behavior is not stable. The current implementation allows redefinition, but this is not an intended consequence.
+ +

Example:

+
var s = @[10, 11, 12]
+var a {.byaddr.} = s[0]
+a += 100
+assert s == @[110, 11, 12]
+assert a is int
+var b {.byaddr.}: int = s[0]
+assert a.addr == b.addr
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/decls.idx b/decls.idx new file mode 100644 index 0000000000000..276ba054428d2 --- /dev/null +++ b/decls.idx @@ -0,0 +1,2 @@ +nimTitle decls decls.html module std/decls 0 +nim byaddr decls.html#byaddr.m macro byaddr(sect) 5 diff --git a/decode_helpers.html b/decode_helpers.html new file mode 100644 index 0000000000000..10a51fc82a795 --- /dev/null +++ b/decode_helpers.html @@ -0,0 +1,154 @@ + + + + + + + +std/private/decode_helpers + + + + + + + + + + + + + + + + +
+
+

std/private/decode_helpers

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
+

Procs

+
+
+
+
proc decodePercent(s: openArray[char]; i: var int): char {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Converts %xx hexadecimal to the character with ordinal number xx.

+

If xx is not a valid hexadecimal value, it is left intact: only the leading % is returned as-is, and xx characters will be processed in the next step (e.g. in uri.decodeUrl) as regular characters.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc handleHexChar(c: char): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc handleHexChar(c: char; x: var int): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Converts %xx hexadecimal to the ordinal number and adds the result to x. Returns true if c is hexadecimal.

+

When c is hexadecimal, the proc is equal to x = x shl 4 + hex2Int(c).

+ +

Example:

+
var x = 0
+assert handleHexChar('a', x)
+assert x == 10
+
+assert handleHexChar('B', x)
+assert x == 171 # 10 shl 4 + 11
+
+assert not handleHexChar('?', x)
+assert x == 171 # unchanged
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/decode_helpers.idx b/decode_helpers.idx new file mode 100644 index 0000000000000..31524aae69350 --- /dev/null +++ b/decode_helpers.idx @@ -0,0 +1,5 @@ +nimTitle decode_helpers decode_helpers.html module std/private/decode_helpers 0 +nim handleHexChar decode_helpers.html#handleHexChar,char,int proc handleHexChar(c: char; x: var int): bool 1 +nim handleHexChar decode_helpers.html#handleHexChar,char proc handleHexChar(c: char): int 24 +nim decodePercent decode_helpers.html#decodePercent,openArray[char],int proc decodePercent(s: openArray[char]; i: var int): char 31 +nimgrp handlehexchar decode_helpers.html#handleHexChar-procs-all proc 1 diff --git a/deques.html b/deques.html new file mode 100644 index 0000000000000..90678d6629676 --- /dev/null +++ b/deques.html @@ -0,0 +1,791 @@ + + + + + + + +std/deques + + + + + + + + + + + + + + + + +
+
+

std/deques

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

An implementation of a deque (double-ended queue). The underlying implementation uses a seq.

Note: +None of the procs that get an individual value from the deque should be used on an empty deque.
+

If compiled with the boundChecks option, those procs will raise an IndexDefect on such access. This should not be relied upon, as -d:danger or --checks:off will disable those checks and then the procs may return garbage or crash the program.

+

As such, a check to see if the deque is empty is needed before any access, unless your program logic guarantees it indirectly.

+ +

Example:

+
import std/deques
+var a = [10, 20, 30, 40].toDeque
+
+doAssertRaises(IndexDefect, echo a[4])
+
+a.addLast(50)
+assert $a == "[10, 20, 30, 40, 50]"
+
+assert a.peekFirst == 10
+assert a.peekLast == 50
+assert len(a) == 5
+
+assert a.popFirst == 10
+assert a.popLast == 50
+assert len(a) == 3
+
+a.addFirst(11)
+a.addFirst(22)
+a.addFirst(33)
+assert $a == "[33, 22, 11, 20, 30, 40]"
+
+a.shrink(fromFirst = 1, fromLast = 2)
+assert $a == "[22, 11, 20]"
+

See also

+

+ +
+

Types

+
+
+
Deque[T] = object
+
+ +

A double-ended queue backed with a ringed seq buffer.

+

To initialize an empty deque, use the initDeque proc.

+ + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
defaultInitialSize = 4
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`[T](deq: Deque[T]): string
+
+ + Turns a deque into its string representation. +

Example:

+
let a = [10, 20, 30].toDeque
+assert $a == "[10, 20, 30]"
+ Source   +Edit   + +
+
+ +
+
+
+
func `==`[T](deq1, deq2: Deque[T]): bool
+
+ + The == operator for Deque. Returns true if both deques contains the same values in the same order. +

Example:

+
var a, b = initDeque[int]()
+a.addFirst(2)
+a.addFirst(1)
+b.addLast(1)
+b.addLast(2)
+doAssert a == b
+ Source   +Edit   + +
+
+ +
+
+
+
proc `[]`[T](deq: Deque[T]; i: BackwardsIndex): lent T {.inline.}
+
+ +

Accesses the backwards indexed i-th element.

+

deq[^1] is the last element.

+ +

Example:

+
let a = [10, 20, 30, 40, 50].toDeque
+assert a[^1] == 50
+assert a[^4] == 20
+doAssertRaises(IndexDefect, echo a[^9])
+ Source   +Edit   + +
+
+
+
proc `[]`[T](deq: Deque[T]; i: Natural): lent T {.inline.}
+
+ + Accesses the i-th element of deq. +

Example:

+
let a = [10, 20, 30, 40, 50].toDeque
+assert a[0] == 10
+assert a[3] == 40
+doAssertRaises(IndexDefect, echo a[8])
+ Source   +Edit   + +
+
+
+
proc `[]`[T](deq: var Deque[T]; i: BackwardsIndex): var T {.inline.}
+
+ +

Accesses the backwards indexed i-th element and returns a mutable reference to it.

+

deq[^1] is the last element.

+ +

Example:

+
var a = [10, 20, 30, 40, 50].toDeque
+inc(a[^1])
+assert a[^1] == 51
+ Source   +Edit   + +
+
+
+
proc `[]`[T](deq: var Deque[T]; i: Natural): var T {.inline.}
+
+ + Accesses the i-th element of deq and returns a mutable reference to it. +

Example:

+
var a = [10, 20, 30, 40, 50].toDeque
+inc(a[0])
+assert a[0] == 11
+ Source   +Edit   + +
+
+ +
+
+
+
proc `[]=`[T](deq: var Deque[T]; i: BackwardsIndex; x: sink T) {.inline.}
+
+ +

Sets the backwards indexed i-th element of deq to x.

+

deq[^1] is the last element.

+ +

Example:

+
var a = [10, 20, 30, 40, 50].toDeque
+a[^1] = 99
+a[^3] = 77
+assert $a == "[10, 20, 77, 40, 99]"
+ Source   +Edit   + +
+
+
+
proc `[]=`[T](deq: var Deque[T]; i: Natural; val: sink T) {.inline.}
+
+ + Sets the i-th element of deq to val. +

Example:

+
var a = [10, 20, 30, 40, 50].toDeque
+a[0] = 99
+a[3] = 66
+assert $a == "[99, 20, 30, 66, 50]"
+ Source   +Edit   + +
+
+ +
+
+
+
proc addFirst[T](deq: var Deque[T]; item: sink T)
+
+ +

Adds an item to the beginning of deq.

+

See also:

+ + +

Example:

+
var a = initDeque[int]()
+for i in 1 .. 5:
+  a.addFirst(10 * i)
+assert $a == "[50, 40, 30, 20, 10]"
+ Source   +Edit   + +
+
+ +
+
+
+
proc addLast[T](deq: var Deque[T]; item: sink T)
+
+ +

Adds an item to the end of deq.

+

See also:

+ + +

Example:

+
var a = initDeque[int]()
+for i in 1 .. 5:
+  a.addLast(10 * i)
+assert $a == "[10, 20, 30, 40, 50]"
+ Source   +Edit   + +
+
+ +
+
+
+
proc clear[T](deq: var Deque[T]) {.inline.}
+
+ +

Resets the deque so that it is empty.

+

See also:

+ + +

Example:

+
var a = [10, 20, 30, 40, 50].toDeque
+assert $a == "[10, 20, 30, 40, 50]"
+clear(a)
+assert len(a) == 0
+ Source   +Edit   + +
+
+ +
+
+
+
proc contains[T](deq: Deque[T]; item: T): bool {.inline.}
+
+ +

Returns true if item is in deq or false if not found.

+

Usually used via the in operator. It is the equivalent of deq.find(item) >= 0.

+ +

Example:

+
let q = [7, 9].toDeque
+assert 7 in q
+assert q.contains(7)
+assert 8 notin q
+ Source   +Edit   + +
+
+ +
+
+
+
func hash[T](deq: Deque[T]): Hash
+
+ + Hashing of Deque. + Source   +Edit   + +
+
+ +
+
+
+
proc initDeque[T](initialSize: int = defaultInitialSize): Deque[T]
+
+ +

Creates a new empty deque.

+

Optionally, the initial capacity can be reserved via initialSize as a performance optimization (default: defaultInitialSize). The length of a newly created deque will still be 0.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func len[T](deq: Deque[T]): int {.inline.}
+
+ + Returns the number of elements of deq. + Source   +Edit   + +
+
+ +
+
+
+
proc peekFirst[T](deq: Deque[T]): lent T {.inline.}
+
+ +

Returns the first element of deq, but does not remove it from the deque.

+

See also:

+ + +

Example:

+
let a = [10, 20, 30, 40, 50].toDeque
+assert $a == "[10, 20, 30, 40, 50]"
+assert a.peekFirst == 10
+assert len(a) == 5
+ Source   +Edit   + +
+
+
+
proc peekFirst[T](deq: var Deque[T]): var T {.inline.}
+
+ +

Returns a mutable reference to the first element of deq, but does not remove it from the deque.

+

See also:

+ + +

Example:

+
var a = [10, 20, 30, 40, 50].toDeque
+a.peekFirst() = 99
+assert $a == "[99, 20, 30, 40, 50]"
+ Source   +Edit   + +
+
+ +
+
+
+
proc peekLast[T](deq: Deque[T]): lent T {.inline.}
+
+ +

Returns the last element of deq, but does not remove it from the deque.

+

See also:

+ + +

Example:

+
let a = [10, 20, 30, 40, 50].toDeque
+assert $a == "[10, 20, 30, 40, 50]"
+assert a.peekLast == 50
+assert len(a) == 5
+ Source   +Edit   + +
+
+
+
proc peekLast[T](deq: var Deque[T]): var T {.inline.}
+
+ +

Returns a mutable reference to the last element of deq, but does not remove it from the deque.

+

See also:

+ + +

Example:

+
var a = [10, 20, 30, 40, 50].toDeque
+a.peekLast() = 99
+assert $a == "[10, 20, 30, 40, 99]"
+ Source   +Edit   + +
+
+ +
+
+
+
proc popFirst[T](deq: var Deque[T]): T {.inline, discardable.}
+
+ +

Removes and returns the first element of the deq.

+

See also:

+ + +

Example:

+
var a = [10, 20, 30, 40, 50].toDeque
+assert $a == "[10, 20, 30, 40, 50]"
+assert a.popFirst == 10
+assert $a == "[20, 30, 40, 50]"
+ Source   +Edit   + +
+
+ +
+
+
+
proc popLast[T](deq: var Deque[T]): T {.inline, discardable.}
+
+ +

Removes and returns the last element of the deq.

+

See also:

+ + +

Example:

+
var a = [10, 20, 30, 40, 50].toDeque
+assert $a == "[10, 20, 30, 40, 50]"
+assert a.popLast == 50
+assert $a == "[10, 20, 30, 40]"
+ Source   +Edit   + +
+
+ +
+
+
+
proc shrink[T](deq: var Deque[T]; fromFirst = 0; fromLast = 0)
+
+ +

Removes fromFirst elements from the front of the deque and fromLast elements from the back.

+

If the supplied number of elements exceeds the total number of elements in the deque, the deque will remain empty.

+

See also:

+ + +

Example:

+
var a = [10, 20, 30, 40, 50].toDeque
+assert $a == "[10, 20, 30, 40, 50]"
+a.shrink(fromFirst = 2, fromLast = 1)
+assert $a == "[30, 40]"
+ Source   +Edit   + +
+
+ +
+
+
+
proc toDeque[T](x: openArray[T]): Deque[T]
+
+ +

Creates a new deque that contains the elements of x (in the same order).

+

See also:

+ + +

Example:

+
let a = toDeque([7, 8, 9])
+assert len(a) == 3
+assert $a == "[7, 8, 9]"
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator items[T](deq: Deque[T]): lent T
+
+ +

Yields every element of deq.

+

See also:

+ + +

Example:

+
from std/sequtils import toSeq
+
+let a = [10, 20, 30, 40, 50].toDeque
+assert toSeq(a.items) == @[10, 20, 30, 40, 50]
+ Source   +Edit   + +
+
+ +
+
+
+
iterator mitems[T](deq: var Deque[T]): var T
+
+ +

Yields every element of deq, which can be modified.

+

See also:

+ + +

Example:

+
var a = [10, 20, 30, 40, 50].toDeque
+assert $a == "[10, 20, 30, 40, 50]"
+for x in mitems(a):
+  x = 5 * x - 1
+assert $a == "[49, 99, 149, 199, 249]"
+ Source   +Edit   + +
+
+ +
+
+
+
iterator pairs[T](deq: Deque[T]): tuple[key: int, val: T]
+
+ + Yields every (position, value)-pair of deq. +

Example:

+
from std/sequtils import toSeq
+
+let a = [10, 20, 30].toDeque
+assert toSeq(a.pairs) == @[(0, 10), (1, 20), (2, 30)]
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/deques.idx b/deques.idx new file mode 100644 index 0000000000000..48771e8dae309 --- /dev/null +++ b/deques.idx @@ -0,0 +1,35 @@ +nimTitle deques deques.html module std/deques 0 +nim Deque deques.html#Deque object Deque 56 +nim defaultInitialSize deques.html#defaultInitialSize const defaultInitialSize 72 +nim initDeque deques.html#initDeque,int proc initDeque[T](initialSize: int = defaultInitialSize): Deque[T] 85 +nim len deques.html#len,Deque[T] proc len[T](deq: Deque[T]): int 98 +nim `[]` deques.html#[],Deque[T],Natural proc `[]`[T](deq: Deque[T]; i: Natural): lent T 118 +nim `[]` deques.html#[],Deque[T],Natural_2 proc `[]`[T](deq: var Deque[T]; i: Natural): var T 129 +nim `[]=` deques.html#[]=,Deque[T],Natural,sinkT proc `[]=`[T](deq: var Deque[T]; i: Natural; val: sink T) 140 +nim `[]` deques.html#[],Deque[T],BackwardsIndex proc `[]`[T](deq: Deque[T]; i: BackwardsIndex): lent T 152 +nim `[]` deques.html#[],Deque[T],BackwardsIndex_2 proc `[]`[T](deq: var Deque[T]; i: BackwardsIndex): var T 165 +nim `[]=` deques.html#[]=,Deque[T],BackwardsIndex,sinkT proc `[]=`[T](deq: var Deque[T]; i: BackwardsIndex; x: sink T) 178 +nim items deques.html#items.i,Deque[T] iterator items[T](deq: Deque[T]): lent T 192 +nim mitems deques.html#mitems.i,Deque[T] iterator mitems[T](deq: var Deque[T]): var T 206 +nim pairs deques.html#pairs.i,Deque[T] iterator pairs[T](deq: Deque[T]): tuple[key: int, val: T] 221 +nim contains deques.html#contains,Deque[T],T proc contains[T](deq: Deque[T]; item: T): bool 232 +nim addFirst deques.html#addFirst,Deque[T],sinkT proc addFirst[T](deq: var Deque[T]; item: sink T) 262 +nim addLast deques.html#addLast,Deque[T],sinkT proc addLast[T](deq: var Deque[T]; item: sink T) 277 +nim toDeque deques.html#toDeque,openArray[T] proc toDeque[T](x: openArray[T]): Deque[T] 292 +nim peekFirst deques.html#peekFirst,Deque[T] proc peekFirst[T](deq: Deque[T]): lent T 306 +nim peekLast deques.html#peekLast,Deque[T] proc peekLast[T](deq: Deque[T]): lent T 321 +nim peekFirst deques.html#peekFirst,Deque[T]_2 proc peekFirst[T](deq: var Deque[T]): var T 336 +nim peekLast deques.html#peekLast,Deque[T]_2 proc peekLast[T](deq: var Deque[T]): var T 351 +nim popFirst deques.html#popFirst,Deque[T] proc popFirst[T](deq: var Deque[T]): T 369 +nim popLast deques.html#popLast,Deque[T] proc popLast[T](deq: var Deque[T]): T 385 +nim clear deques.html#clear,Deque[T] proc clear[T](deq: var Deque[T]) 401 +nim shrink deques.html#shrink,Deque[T],int,int proc shrink[T](deq: var Deque[T]; fromFirst = 0; fromLast = 0) 415 +nim `$` deques.html#$,Deque[T] proc `$`[T](deq: Deque[T]): string 444 +nim `==` deques.html#==,Deque[T],Deque[T] proc `==`[T](deq1, deq2: Deque[T]): bool 456 +nim hash deques.html#hash,Deque[T] proc hash[T](deq: Deque[T]): Hash 476 +idx deque deques.html#deque_1 Module deques 0 +heading See also deques.html#see-also See also 0 +nimgrp peekfirst deques.html#peekFirst-procs-all proc 306 +nimgrp []= deques.html#[]=-procs-all proc 140 +nimgrp [] deques.html#[]-procs-all proc 118 +nimgrp peeklast deques.html#peekLast-procs-all proc 321 diff --git a/destructors.html b/destructors.html new file mode 100644 index 0000000000000..60b44ee05c25f --- /dev/null +++ b/destructors.html @@ -0,0 +1,537 @@ + + + + + + + +Nim Destructors and Move Semantics + + + + + + + + + + + + + + + + +
+
+

Nim Destructors and Move Semantics

+
+ +
+ Source   +Edit   + +
+ +

+ +
Authors:Andreas Rumpf
Version:2.2.1
+

About this document

This document describes the ARC/ORC Nim runtime which does not use classical GC algorithms anymore but is based on destructors and move semantics. The advantages are that Nim programs become oblivious to the involved heap sizes and programs are easier to write to make effective use of multi-core machines. As a nice bonus, files and sockets and the like can be written not to require manual close calls anymore.

+

This document aims to be a precise specification about how move semantics and destructors work in Nim.

+ +

Motivating example

With the language mechanisms described here, a custom seq could be written as:

+

type
+  myseq*[T] = object
+    len, cap: int
+    data: ptr UncheckedArray[T]
+
+proc `=destroy`*[T](x: myseq[T]) =
+  if x.data != nil:
+    for i in 0..<x.len: `=destroy`(x.data[i])
+    dealloc(x.data)
+
+proc `=wasMoved`*[T](x: var myseq[T]) =
+  x.data = nil
+
+proc `=trace`[T](x: var myseq[T]; env: pointer) =
+  # `=trace` allows the cycle collector `--mm:orc`
+  # to understand how to trace the object graph.
+  if x.data != nil:
+    for i in 0..<x.len: `=trace`(x.data[i], env)
+
+proc `=copy`*[T](a: var myseq[T]; b: myseq[T]) =
+  # do nothing for self-assignments:
+  if a.data == b.data: return
+  `=destroy`(a)
+  `=wasMoved`(a)
+  a.len = b.len
+  a.cap = b.cap
+  if b.data != nil:
+    a.data = cast[typeof(a.data)](alloc(a.cap * sizeof(T)))
+    for i in 0..<a.len:
+      a.data[i] = b.data[i]
+
+proc `=dup`*[T](a: myseq[T]): myseq[T] {.nodestroy.} =
+  # an optimized version of `=wasMoved(tmp); `=copy(tmp, src)`
+  # usually present if a custom `=copy` hook is overridden
+  result = myseq[T](len: a.len, cap: a.cap, data: nil)
+  if a.data != nil:
+    result.data = cast[typeof(result.data)](alloc(result.cap * sizeof(T)))
+    for i in 0..<result.len:
+      result.data[i] = `=dup`(a.data[i])
+
+proc `=sink`*[T](a: var myseq[T]; b: myseq[T]) =
+  # move assignment, optional.
+  # Compiler is using `=destroy` and `copyMem` when not provided
+  `=destroy`(a)
+  a.len = b.len
+  a.cap = b.cap
+  a.data = b.data
+
+proc add*[T](x: var myseq[T]; y: sink T) =
+  if x.len >= x.cap:
+    x.cap = max(x.len + 1, x.cap * 2)
+    x.data = cast[typeof(x.data)](realloc(x.data, x.cap * sizeof(T)))
+  x.data[x.len] = y
+  inc x.len
+
+proc `[]`*[T](x: myseq[T]; i: Natural): lent T =
+  assert i < x.len
+  x.data[i]
+
+proc `[]=`*[T](x: var myseq[T]; i: Natural; y: sink T) =
+  assert i < x.len
+  x.data[i] = y
+
+proc createSeq*[T](elems: varargs[T]): myseq[T] =
+  result = myseq[T](
+    len: elems.len,
+    cap: elems.len,
+    data: cast[typeof(result.data)](alloc(result.cap * sizeof(T))))
+  for i in 0..<result.len: result.data[i] = elems[i]
+
+proc len*[T](x: myseq[T]): int {.inline.} = x.len

+ +

Lifetime-tracking hooks

The memory management for Nim's standard string and seq types as well as other standard collections is performed via so-called "Lifetime-tracking hooks", which are particular type bound operators.

+

There are 6 different hooks for each (generic or concrete) object type T (T can also be a distinct type) that are called implicitly by the compiler.

+

(Note: The word "hook" here does not imply any kind of dynamic binding or runtime indirections, the implicit calls are statically bound and potentially inlined.)

+ +

=destroy hook

A =destroy hook frees the object's associated memory and releases other associated resources. Variables are destroyed via this hook when they go out of scope or when the routine they were declared in is about to return.

+

A =destroy hook is allowed to have a parameter of a var T or T type. Taking a var T type is deprecated. The prototype of this hook for a type T needs to be:

+

proc `=destroy`(x: T)

+

The general pattern in =destroy looks like:

+

proc `=destroy`(x: T) =
+  # first check if 'x' was moved to somewhere else:
+  if x.field != nil:
+    freeResource(x.field)

+

A =destroy is implicitly annotated with .raises: []; a destructor should not raise exceptions. For backwards compatibility the compiler produces a warning for a =destroy that does raise.

+

A =destroy can explicitly list the exceptions it can raise, if any, but this of little utility as a raising destructor is implementation defined behavior. Later versions of the language specification might cover this case precisely.

+ +

=wasMoved hook

A =wasMoved hook sets the object to a state that signifies to the destructor there is nothing to destroy.

+

The prototype of this hook for a type T needs to be:

+

proc `=wasMoved`(x: var T)

+

Usually some pointer field inside the object is set to nil:

+

proc `=wasMoved`(x: var T) =
+  x.field = nil

+ +

=sink hook

A =sink hook moves an object around, the resources are stolen from the source and passed to the destination. It is ensured that the source's destructor does not free the resources afterward by setting the object to its default value (the value the object's state started in). Setting an object x back to its default value is written as wasMoved(x). When not provided the compiler is using a combination of =destroy and copyMem instead. This is efficient hence users rarely need to implement their own =sink operator, it is enough to provide =destroy and =copy, the compiler will take care of the rest.

+

The prototype of this hook for a type T needs to be:

+

proc `=sink`(dest: var T; source: T)

+

The general pattern in =sink looks like:

+

+proc `=sink`(dest: var T; source: T) =
+  `=destroy`(dest)
+  wasMoved(dest)
+  dest.field = source.field

+

Note: =sink does not need to check for self-assignments. How self-assignments are handled is explained later in this document.

+ +

=copy hook

The ordinary assignment in Nim conceptually copies the values. The =copy hook is called for assignments that couldn't be transformed into =sink operations.

+

The prototype of this hook for a type T needs to be:

+

proc `=copy`(dest: var T; source: T)

+

The general pattern in =copy looks like:

+

proc `=copy`(dest: var T; source: T) =
+  # protect against self-assignments:
+  if dest.field != source.field:
+    `=destroy`(dest)
+    wasMoved(dest)
+    dest.field = duplicateResource(source.field)

+

The =copy proc can be marked with the {.error.} pragma. Then any assignment that otherwise would lead to a copy is prevented at compile-time. This looks like:

+

proc `=copy`(dest: var T; source: T) {.error.}

+

but a custom error message (e.g., {.error: "custom error".}) will not be emitted by the compiler. Notice that there is no = before the {.error.} pragma.

+ +

=trace hook

A custom container type can support Nim's cycle collector --mm:orc via the =trace hook. If the container does not implement =trace, cyclic data structures which are constructed with the help of the container might leak memory or resources, but memory safety is not compromised.

+

The prototype of this hook for a type T needs to be:

+

proc `=trace`(dest: var T; env: pointer)

+

env is used by ORC to keep track of its internal state, it should be passed around to calls of the built-in =trace operation.

+

Usually there will only be a need for a custom =trace when a custom =destroy that deallocates manually allocated resources is also used, and then only when there is a chance of cyclic references from items within the manually allocated resources when it is desired that --mm:orc is able to break and collect these cyclic referenced resources. Currently however, there is a mutual use problem in that whichever of =destroy/=trace is used first will automatically create a version of the other which will then conflict with the creation of the second of the pair. The workaround for this problem is to forward declare the second of the "hooks" to prevent the automatic creation.

+

The general pattern in using =destroy with =trace looks like:

+

type
+  Test[T] = object
+    size: Natural
+    arr: ptr UncheckedArray[T] # raw pointer field
+
+proc makeTest[T](size: Natural): Test[T] = # custom allocation...
+  Test[T](size: size, arr: cast[ptr UncheckedArray[T]](alloc0(sizeof(T) * size)))
+
+
+proc `=destroy`[T](dest: Test[T]) =
+  if dest.arr != nil:
+    for i in 0 ..< dest.size: dest.arr[i].`=destroy`
+    dealloc dest.arr
+
+proc `=trace`[T](dest: var Test[T]; env: pointer) =
+  if dest.arr != nil:
+    # trace the `T`'s which may be cyclic
+    for i in 0 ..< dest.size: `=trace`(dest.arr[i], env)
+
+# following may be other custom "hooks" as required...

+

Note: The =trace hooks (which are only used by --mm:orc) are currently more experimental and less refined than the other hooks.

+ +

=dup hook

A =dup hook duplicates an object. =dup(x) can be regarded as an optimization replacing a wasMoved(dest); =copy(dest, x) operation.

+

The prototype of this hook for a type T needs to be:

+

proc `=dup`(x: T): T

+

The general pattern in implementing =dup looks like:

+

type
+  Ref[T] = object
+    data: ptr T
+    rc: ptr int
+
+proc `=dup`[T](x: Ref[T]): Ref[T] =
+  result = x
+  if x.rc != nil:
+    inc x.rc[]

+ +

Move semantics

A "move" can be regarded as an optimized copy operation. If the source of the copy operation is not used afterward, the copy can be replaced by a move. This document uses the notation lastReadOf(x) to describe that x is not used afterward. This property is computed by a static control flow analysis but can also be enforced by using system.move explicitly.

+

One can query if the analysis is able to perform a move with system.ensureMove. move enforces a move operation and calls =wasMoved whereas ensureMove is an annotation that implies no runtime operation. An ensureMove annotation leads to a static error if the compiler cannot prove that a move would be safe.

+

For example:

+

proc main(normalParam: string; sinkParam: sink string) =
+  var x = "abc"
+  # valid:
+  let valid = ensureMove x
+  # invalid:
+  let invalid = ensureMove normalParam
+  # valid:
+  let alsoValid = ensureMove sinkParam

+ +

Swap

The need to check for self-assignments and also the need to destroy previous objects inside =copy and =sink is a strong indicator to treat system.swap as a builtin primitive of its own that simply swaps every field in the involved objects via copyMem or a comparable mechanism. In other words, swap(a, b) is not implemented as let tmp = move(b); b = move(a); a = move(tmp).

+

This has further consequences:

+
  • Objects that contain pointers that point to the same object are not supported by Nim's model. Otherwise swapped objects would end up in an inconsistent state.
  • +
  • Seqs can use realloc in the implementation.
  • +
+ +

Sink parameters

To move a variable into a collection usually sink parameters are involved. A location that is passed to a sink parameter should not be used afterward. This is ensured by a static analysis over a control flow graph. If it cannot be proven to be the last usage of the location, a copy is done instead and this copy is then passed to the sink parameter.

+

A sink parameter may be consumed once in the proc's body but doesn't have to be consumed at all. The reason for this is that signatures like proc put(t: var Table; k: sink Key, v: sink Value) should be possible without any further overloads and put might not take ownership of k if k already exists in the table. Sink parameters enable an affine type system, not a linear type system.

+

The employed static analysis is limited and only concerned with local variables; however, object and tuple fields are treated as separate entities:

+

proc consume(x: sink Obj) = discard "no implementation"
+
+proc main =
+  let tup = (Obj(), Obj())
+  consume tup[0]
+  # ok, only tup[0] was consumed, tup[1] is still alive:
+  echo tup[1]

+

Sometimes it is required to explicitly move a value into its final position:

+

proc main =
+  var dest, src: array[10, string]
+  # ...
+  for i in 0..high(dest): dest[i] = move(src[i])

+

An implementation is allowed, but not required to implement even more move optimizations (and the current implementation does not).

+ +

Sink parameter inference

The current implementation can do a limited form of sink parameter inference. But it has to be enabled via --sinkInference:on, either on the command line or via a push pragma.

+

To enable it for a section of code, one can use {.push sinkInference: on.} ... {.pop.}.

+

The .nosinks pragma can be used to disable this inference for a single routine:

+

proc addX(x: T; child: T) {.nosinks.} =
+  x.s.add child

+

The details of the inference algorithm are currently undocumented.

+ +

Rewrite rules

Note: There are two different allowed implementation strategies:

+
  1. The produced finally section can be a single section that is wrapped around the complete routine body.
  2. +
  3. The produced finally section is wrapped around the enclosing scope.
  4. +
+

The current implementation follows strategy (2). This means that resources are destroyed at the scope exit.

+
var x: T; stmts
+---------------             (destroy-var)
+var x: T; try stmts
+finally: `=destroy`(x)
+
+
+g(f(...))
+------------------------    (nested-function-call)
+g(let tmp;
+bitwiseCopy tmp, f(...);
+tmp)
+finally: `=destroy`(tmp)
+
+
+x = f(...)
+------------------------    (function-sink)
+`=sink`(x, f(...))
+
+
+x = lastReadOf z
+------------------          (move-optimization)
+`=sink`(x, z)
+`=wasMoved`(z)
+
+
+v = v
+------------------   (self-assignment-removal)
+discard "nop"
+
+
+x = y
+------------------          (copy)
+`=copy`(x, y)
+
+
+f_sink(g())
+-----------------------     (call-to-sink)
+f_sink(g())
+
+
+f_sink(notLastReadOf y)
+--------------------------     (copy-to-sink)
+(let tmp = `=dup`(y);
+f_sink(tmp))
+
+
+f_sink(lastReadOf y)
+-----------------------     (move-to-sink)
+f_sink(y)
+`=wasMoved`(y)
+ +

Object and array construction

Object and array construction is treated as a function call where the function has sink parameters.

+ +

Destructor removal

=wasMoved(x) followed by a =destroy(x) operation cancel each other out. An implementation is encouraged to exploit this in order to improve efficiency and code sizes. The current implementation does perform this optimization.

+ +

Self assignments

=sink in combination with =wasMoved can handle self-assignments but it's subtle.

+

The simple case of x = x cannot be turned into =sink(x, x); =wasMoved(x) because that would lose x's value. The solution is that simple self-assignments that consist of

+
  • Symbols: x = x
  • +
  • Field access: x.f = x.f
  • +
  • Array, sequence or string access with indices known at compile-time: x[0] = x[0]
  • +
+

are transformed into an empty statement that does nothing. The compiler is free to optimize further cases.

+

The complex case looks like a variant of x = f(x), we consider x = select(rand() < 0.5, x, y) here:

+

proc select(cond: bool; a, b: sink string): string =
+  if cond:
+    result = a # moves a into result
+  else:
+    result = b # moves b into result
+
+proc main =
+  var x = "abc"
+  var y = "xyz"
+  # possible self-assignment:
+  x = select(true, x, y)

+

Is transformed into:

+

proc select(cond: bool; a, b: sink string): string =
+  try:
+    if cond:
+      `=sink`(result, a)
+      `=wasMoved`(a)
+    else:
+      `=sink`(result, b)
+      `=wasMoved`(b)
+  finally:
+    `=destroy`(b)
+    `=destroy`(a)
+
+proc main =
+  var
+    x: string
+    y: string
+  try:
+    `=sink`(x, "abc")
+    `=sink`(y, "xyz")
+    `=sink`(x, select(true,
+      let blitTmp = x
+      `=wasMoved`(x)
+      blitTmp,
+      let blitTmp = y
+      `=wasMoved`(y)
+      blitTmp))
+    echo [x]
+  finally:
+    `=destroy`(y)
+    `=destroy`(x)

+

As can be manually verified, this transformation is correct for self-assignments.

+ +

Lent type

proc p(x: sink T) means that the proc p takes ownership of x. To eliminate even more creation/copy <-> destruction pairs, a proc's return type can be annotated as lent T. This is useful for "getter" accessors that seek to allow an immutable view into a container.

+

The sink and lent annotations allow us to remove most (if not all) superfluous copies and destructions.

+

lent T is like var T a hidden pointer. It is proven by the compiler that the pointer does not outlive its origin. No destructor call is injected for expressions of type lent T or of type var T.

+

type
+  Tree = object
+    kids: seq[Tree]
+
+proc construct(kids: sink seq[Tree]): Tree =
+  result = Tree(kids: kids)
+  # converted into:
+  `=sink`(result.kids, kids); `=wasMoved`(kids)
+  `=destroy`(kids)
+
+proc `[]`*(x: Tree; i: int): lent Tree =
+  result = x.kids[i]
+  # borrows from 'x', this is transformed into:
+  # result = addr x.kids[i]
+  # This means 'lent' is like 'var T' a hidden pointer.
+  # Unlike 'var' this hidden pointer cannot be used to mutate the object.
+
+iterator children*(t: Tree): lent Tree =
+  for x in t.kids: yield x
+
+proc main =
+  # everything turned into moves:
+  let t = construct(@[construct(@[]), construct(@[])])
+  echo t[0] # accessor does not copy the element!

+ +

The cursor pragma

Under the --mm:arc|orc modes Nim's ref type is implemented via the same runtime "hooks" and thus via reference counting. This means that cyclic structures cannot be freed immediately (--mm:orc ships with a cycle collector). With the cursor pragma one can break up cycles declaratively:

+

type
+  Node = ref object
+    left: Node # owning ref
+    right {.cursor.}: Node # non-owning ref

+

But please notice that this is not C++'s weak_ptr, it means the right field is not involved in the reference counting, it is a raw pointer without runtime checks.

+

Automatic reference counting also has the disadvantage that it introduces overhead when iterating over linked structures. The cursor pragma can also be used to avoid this overhead:

+

var it {.cursor.} = listRoot
+while it != nil:
+  use(it)
+  it = it.next

+

In fact, cursor more generally prevents object construction/destruction pairs and so can also be useful in other contexts. The alternative solution would be to use raw pointers (ptr) instead which is more cumbersome and also more dangerous for Nim's evolution: Later on, the compiler can try to prove cursor pragmas to be safe, but for ptr the compiler has to remain silent about possible problems.

+ +

Cursor inference / copy elision

The current implementation also performs cursor inference. Cursor inference is a form of copy elision.

+

To see how and when we can do that, think about this question: In dest = src when do we really have to materialize the full copy? - Only if dest or src are mutated afterward. If dest is a local variable that is simple to analyze. And if src is a location derived from a formal parameter, we also know it is not mutated! In other words, we do a compile-time copy-on-write analysis.

+

This means that "borrowed" views can be written naturally and without explicit pointer indirections:

+

proc main(tab: Table[string, string]) =
+  let v = tab["key"] # inferred as cursor because 'tab' is not mutated.
+  # no copy into 'v', no destruction of 'v'.
+  use(v)
+  useItAgain(v)

+ +

Hook lifting

The hooks of a tuple type (A, B, ...) are generated by lifting the hooks of the involved types A, B, ... to the tuple type. In other words, a copy x = y is implemented as x[0] = y[0]; x[1] = y[1]; ..., likewise for =sink and =destroy.

+

Other value-based compound types like object and array are handled correspondingly. For object however, the compiler-generated hooks can be overridden. This can also be important to use an alternative traversal of the involved data structure that is more efficient or in order to avoid deep recursions.

+ +

Hook generation

The ability to override a hook leads to a phase ordering problem:

+

type
+  Foo[T] = object
+
+proc main =
+  var f: Foo[int]
+  # error: destructor for 'f' called here before
+  # it was seen in this module.
+
+proc `=destroy`[T](f: Foo[T]) =
+  discard

+

The solution is to define proc `=destroy`[T](f: Foo[T]) before it is used. The compiler generates implicit hooks for all types in strategic places so that an explicitly provided hook that comes too "late" can be detected reliably. These strategic places have been derived from the rewrite rules and are as follows:

+
  • In the construct let/var x = ... (var/let binding) hooks are generated for typeof(x).
  • +
  • In x = ... (assignment) hooks are generated for typeof(x).
  • +
  • In f(...) (function call) hooks are generated for typeof(f(...)).
  • +
  • For every sink parameter x: sink T the hooks are generated for typeof(x).
  • +
+ +

nodestroy pragma

The experimental nodestroy pragma inhibits hook injections. This can be used to specialize the object traversal in order to avoid deep recursions:

+

type Node = ref object
+  x, y: int32
+  left, right: Node
+
+type Tree = object
+  root: Node
+
+proc `=destroy`(t: Tree) {.nodestroy.} =
+  # use an explicit stack so that we do not get stack overflows:
+  var s: seq[Node] = @[t.root]
+  while s.len > 0:
+    let x = s.pop
+    if x.left != nil: s.add(x.left)
+    if x.right != nil: s.add(x.right)
+    # free the memory explicitly:
+    `=dispose`(x)
+  # notice how even the destructor for 's' is not called implicitly
+  # anymore thanks to .nodestroy, so we have to call it on our own:
+  `=destroy`(s)

+

As can be seen from the example, this solution is hardly sufficient and should eventually be replaced by a better solution.

+ +

Copy on write

String literals are implemented as "copy on write". When assigning a string literal to a variable, a copy of the literal won't be created. Instead the variable simply points to the literal. The literal is shared between different variables which are pointing to it. The copy operation is deferred until the first write.

+

For example:

+

var x = "abc"  # no copy
+var y = x      # no copy
+y[0] = 'h'     # copy

+

The abstraction fails for addr x because whether the address is going to be used for mutations is unknown. prepareMutation needs to be called before the "address of" operation. For example:

+

var x = "abc"
+var y = x
+
+prepareMutation(y)
+moveMem(addr y[0], addr x[0], 3)
+assert y == "abc"

+

+ +
+
+ + +
+
+ + + + diff --git a/destructors.idx b/destructors.idx new file mode 100644 index 0000000000000..fe615dbaafed0 --- /dev/null +++ b/destructors.idx @@ -0,0 +1,27 @@ +markupTitle Nim Destructors and Move Semantics destructors.html Nim Destructors and Move Semantics 0 +heading About this document destructors.html#about-this-document About this document 0 +heading Motivating example destructors.html#motivating-example Motivating example 0 +heading Lifetime-tracking hooks destructors.html#lifetimeminustracking-hooks Lifetime-tracking hooks 0 +heading nim=destroy hook destructors.html#lifetimeminustracking-hooks-nimeqdestroy-hook =destroy hook 0 +heading nim=wasMoved hook destructors.html#lifetimeminustracking-hooks-nimeqwasmoved-hook =wasMoved hook 0 +heading nim=sink hook destructors.html#lifetimeminustracking-hooks-nimeqsink-hook =sink hook 0 +heading nim=copy hook destructors.html#lifetimeminustracking-hooks-nimeqcopy-hook =copy hook 0 +heading nim=trace hook destructors.html#lifetimeminustracking-hooks-nimeqtrace-hook =trace hook 0 +heading nim=dup hook destructors.html#lifetimeminustracking-hooks-nimeqdup-hook =dup hook 0 +heading Move semantics destructors.html#move-semantics Move semantics 0 +heading Swap destructors.html#swap Swap 0 +heading Sink parameters destructors.html#sink-parameters Sink parameters 0 +heading Sink parameter inference destructors.html#sink-parameter-inference Sink parameter inference 0 +idx .nosinks destructors.html#dotnosinks_1 Sink parameter inference 0 +heading Rewrite rules destructors.html#rewrite-rules Rewrite rules 0 +heading Object and array construction destructors.html#object-and-array-construction Object and array construction 0 +heading Destructor removal destructors.html#destructor-removal Destructor removal 0 +heading Self assignments destructors.html#self-assignments Self assignments 0 +heading Lent type destructors.html#lent-type Lent type 0 +heading The cursor pragma destructors.html#the-cursor-pragma The cursor pragma 0 +heading Cursor inference / copy elision destructors.html#cursor-inference-slash-copy-elision Cursor inference / copy elision 0 +heading Hook lifting destructors.html#hook-lifting Hook lifting 0 +heading Hook generation destructors.html#hook-generation Hook generation 0 +heading nodestroy pragma destructors.html#nodestroy-pragma nodestroy pragma 0 +idx nodestroy destructors.html#nodestroy_1 nodestroy pragma 0 +heading Copy on write destructors.html#copy-on-write Copy on write 0 diff --git a/diff.html b/diff.html new file mode 100644 index 0000000000000..cb49b396c58f6 --- /dev/null +++ b/diff.html @@ -0,0 +1,205 @@ + + + + + + + +experimental/diff + + + + + + + + + + + + + + + + +
+
+

experimental/diff

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements an algorithm to compute the diff between two sequences of lines.

+ +

Example:

+
import experimental/diff
+assert diffInt(
+  [0, 1, 2, 3, 4, 5, 6, 7, 8],
+  [-1, 1, 2, 3, 4, 5, 666, 7, 42]) ==
+  @[Item(startA: 0, startB: 0, deletedA: 1, insertedB: 1),
+    Item(startA: 6, startB: 6, deletedA: 1, insertedB: 1),
+    Item(startA: 8, startB: 8, deletedA: 1, insertedB: 1)]
+

Example:

+
import experimental/diff
+# 2 samples of text (from "The Call of Cthulhu" by Lovecraft)
+let txt0 = """
+abc
+def ghi
+jkl2"""
+let txt1 = """
+bacx
+abc
+def ghi
+jkl"""
+assert diffText(txt0, txt1) ==
+  @[Item(startA: 0, startB: 0, deletedA: 0, insertedB: 1),
+    Item(startA: 2, startB: 3, deletedA: 1, insertedB: 1)]

+ +
+

Types

+
+
+
Item = object
+  startA*: int               ## Start Line number in Data A.
+  startB*: int               ## Start Line number in Data B.
+  deletedA*: int             ## Number of changes in Data A.
+  insertedB*: int            ## Number of changes in Data B.
+
+ + An Item in the list of differences. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc diffInt(arrayA, arrayB: openArray[int]): seq[Item] {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Find the difference in 2 arrays of integers.

+

arrayA A-version of the numbers (usually the old one)

+

arrayB B-version of the numbers (usually the new one)

+

Returns a sequence of Items that describe the differences.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc diffText(textA, textB: string): seq[Item] {....raises: [KeyError], tags: [],
+    forbids: [].}
+
+ +

Find the difference in 2 text documents, comparing by textlines.

+

The algorithm itself is comparing 2 arrays of numbers so when comparing 2 text documents each line is converted into a (hash) number. This hash-value is computed by storing all textlines into a common hashtable so i can find duplicates in there, and generating a new number each time a new textline is inserted.

+

textA A-version of the text (usually the old one)

+

textB B-version of the text (usually the new one)

+

Returns a seq of Items that describe the differences.

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/diff.idx b/diff.idx new file mode 100644 index 0000000000000..b82645f79d32a --- /dev/null +++ b/diff.idx @@ -0,0 +1,5 @@ +nimTitle diff diff.html module experimental/diff 0 +nim Item diff.html#Item object Item 52 +nim diffInt diff.html#diffInt,openArray[int],openArray[int] proc diffInt(arrayA, arrayB: openArray[int]): seq[Item] 281 +nim diffText diff.html#diffText,string,string proc diffText(textA, textB: string): seq[Item] 305 +idx diff diff.html#diff_1 Module diff 0 diff --git a/digitsutils.html b/digitsutils.html new file mode 100644 index 0000000000000..9a30206f5f701 --- /dev/null +++ b/digitsutils.html @@ -0,0 +1,175 @@ + + + + + + + +std/private/digitsutils + + + + + + + + + + + + + + + + +
+
+

std/private/digitsutils

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
+

Procs

+
+
+
+
proc addInt(result: var string; x: int) {.inline, enforceNoRaises, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc addInt(result: var string; x: int64) {.enforceNoRaises, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Converts integer to its string representation and appends it to result. +

Example:

+
var s = "foo"
+s.addInt(45)
+assert s == "foo45"
+ Source   +Edit   + +
+
+
+
func addInt(result: var string; x: uint64) {.enforceNoRaises, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc trailingZeros2Digits(digits: uint32): int {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc utoa2Digits(buf: var openArray[char]; pos: int; digits: uint32) {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/digitsutils.idx b/digitsutils.idx new file mode 100644 index 0000000000000..ffb389d970593 --- /dev/null +++ b/digitsutils.idx @@ -0,0 +1,7 @@ +nimTitle digitsutils digitsutils.html module std/private/digitsutils 0 +nim utoa2Digits digitsutils.html#utoa2Digits,openArray[char],int,uint32 proc utoa2Digits(buf: var openArray[char]; pos: int; digits: uint32) 32 +nim trailingZeros2Digits digitsutils.html#trailingZeros2Digits,uint32 proc trailingZeros2Digits(digits: uint32): int 37 +nim addInt digitsutils.html#addInt,string,uint64 proc addInt(result: var string; x: uint64) 85 +nim addInt digitsutils.html#addInt,string,int64 proc addInt(result: var string; x: int64) 92 +nim addInt digitsutils.html#addInt,string,int proc addInt(result: var string; x: int) 115 +nimgrp addint digitsutils.html#addInt-procs-all proc 85 diff --git a/dirs.html b/dirs.html new file mode 100644 index 0000000000000..35e1daf068926 --- /dev/null +++ b/dirs.html @@ -0,0 +1,327 @@ + + + + + + + +std/dirs + + + + + + + + + + + + + + + + +
+
+

std/dirs

+
+ +
+ Source   +Edit   + +
+ +

This module implements directory handling.

+
+

Imports

+
+ paths, osdirs +
+
+
+

Procs

+
+
+
+
proc createDir(dir: Path) {.inline, ...tags: [WriteDirEffect, ReadDirEffect],
+                            raises: [OSError, IOError], forbids: [].}
+
+ +

Creates the directory dir.

+

The directory may contain several subdirectories that do not exist yet. The full path is created. If this fails, OSError is raised.

+

It does not fail if the directory already exists because for most usages this does not indicate an error.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc dirExists(dir: Path): bool {.inline, ...tags: [ReadDirEffect], sideEffect,
+                                  ...raises: [], forbids: [].}
+
+ + Returns true if the directory dir exists. If dir is a file, false is returned. Follows symlinks. + Source   +Edit   + +
+
+ +
+
+
+
proc existsOrCreateDir(dir: Path): bool {.inline,
+    ...tags: [WriteDirEffect, ReadDirEffect], raises: [OSError, IOError],
+    forbids: [].}
+
+ +

Checks if a directory dir exists, and creates it otherwise.

+

Does not create parent directories (raises OSError if parent directories do not exist). Returns true if the directory already exists, and false otherwise.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc moveDir(source, dest: Path) {.inline, ...tags: [ReadIOEffect, WriteIOEffect],
+                                   raises: [OSError, IOError], forbids: [].}
+
+ +

Moves a directory from source to dest.

+

Symlinks are not followed: if source contains symlinks, they themself are moved, not their target.

+

If this fails, OSError is raised.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc removeDir(dir: Path; checkDir = false) {.inline,
+    ...tags: [WriteDirEffect, ReadDirEffect], raises: [OSError], forbids: [].}
+
+ +

Removes the directory dir including all subdirectories and files in dir (recursively).

+

If this fails, OSError is raised. This does not fail if the directory never existed in the first place, unless checkDir = true.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setCurrentDir(newDir: Path) {.inline, ...tags: [], raises: [OSError],
+                                   forbids: [].}
+
+ +

Sets the current working directory; OSError is raised if newDir cannot been set.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator walkDir(dir: Path; relative = false; checkDir = false;
+                 skipSpecial = false): tuple[kind: PathComponent, path: Path] {.
+    ...tags: [ReadDirEffect], raises: [OSError], forbids: [].}
+
+ +

Walks over the directory dir and yields for each directory or file in dir. The component type and full path for each item are returned.

+

Walking is not recursive.

+
  • If relative is true (default: false) the resulting path is shortened to be relative to dir, otherwise the full path is returned.
  • +
  • If checkDir is true, OSError is raised when dir doesn't exist.
  • +
  • If skipSpecial is true, then (besides all directories) only regular files (without special "file" objects like FIFOs, device files, etc) will be yielded on Unix.
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
iterator walkDirRec(dir: Path; yieldFilter = {pcFile}; followFilter = {pcDir};
+                    relative = false; checkDir = false; skipSpecial = false): Path {.
+    ...tags: [ReadDirEffect], raises: [OSError], forbids: [].}
+
+ +

Recursively walks over the directory dir and yields for each file or directory in dir.

+

Options relative, checkdir, skipSpecial are explained in walkDir iterator description.

+
Warning: +Modifying the directory structure while the iterator is traversing may result in undefined behavior!
+

Walking is recursive. followFilter controls the behaviour of the iterator:

+ + + + + +
yieldFiltermeaning
pcFileyield real files (default)
pcLinkToFileyield symbolic links to files
pcDiryield real directories
pcLinkToDiryield symbolic links to directories
+ + +
followFiltermeaning
pcDirfollow real directories (default)
pcLinkToDirfollow symbolic links to directories

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/dirs.idx b/dirs.idx new file mode 100644 index 0000000000000..04f08abdac23e --- /dev/null +++ b/dirs.idx @@ -0,0 +1,12 @@ +nimTitle dirs dirs.html module std/dirs 0 +nim dirExists dirs.html#dirExists,Path proc dirExists(dir: Path): bool 11 +nim createDir dirs.html#createDir,Path proc createDir(dir: Path) 16 +nim existsOrCreateDir dirs.html#existsOrCreateDir,Path proc existsOrCreateDir(dir: Path): bool 31 +nim removeDir dirs.html#removeDir,Path proc removeDir(dir: Path; checkDir = false) 43 +nim moveDir dirs.html#moveDir,Path,Path proc moveDir(source, dest: Path) 58 +nim walkDir dirs.html#walkDir.i,Path iterator walkDir(dir: Path; relative = false; checkDir = false; skipSpecial = false): tuple[\n kind: PathComponent, path: Path] 73 +nim walkDirRec dirs.html#walkDirRec.i,Path iterator walkDirRec(dir: Path; yieldFilter = {pcFile}; followFilter = {pcDir};\n relative = false; checkDir = false; skipSpecial = false): Path 91 +nim setCurrentDir dirs.html#setCurrentDir,Path proc setCurrentDir(newDir: Path) 129 +idx current working directory dirs.html#current-working-directory_1 Module dirs 0 +idx directory dirs.html#directory_1 Module dirs 0 +idx directory dirs.html#directory_2 Module dirs 0 diff --git a/distros.html b/distros.html new file mode 100644 index 0000000000000..174603dce2c5e --- /dev/null +++ b/distros.html @@ -0,0 +1,327 @@ + + + + + + + +std/distros + + + + + + + + + + + + + + + + +
+
+

std/distros

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements the basics for Linux distribution ("distro") detection and the OS's native package manager. Its primary purpose is to produce output for Nimble packages, like:

To complete the installation, run:
+
+sudo apt-get install libblas-dev
+sudo apt-get install libvoodoo
+

The above output could be the result of a code snippet like:

+

if detectOs(Ubuntu):
+  foreignDep "lbiblas-dev"
+  foreignDep "libvoodoo"

+

See packaging for hints on distributing Nim using OS packages.

+

+ +
+

Types

+
+
+
Distribution {.pure.} = enum
+  Windows,                  ## some version of Windows
+  Posix,                    ## some POSIX system
+  MacOSX,                   ## some version of OSX
+  Linux,                    ## some version of Linux
+  Ubuntu, Debian, Gentoo, Fedora, RedHat, OpenSUSE, Manjaro, Elementary, Zorin,
+  CentOS, Deepin, ArchLinux, Artix, Antergos, PCLinuxOS, Mageia, LXLE, Solus,
+  Lite, Slackware, Androidx86, Puppy, Peppermint, Tails, AntiX, Kali,
+  SparkyLinux, Apricity, BlackLab, Bodhi, TrueOS, ArchBang, KaOS, WattOS,
+  Korora, Simplicity, RemixOS, OpenMandriva, Netrunner, Alpine, BlackArch,
+  Ultimate, Gecko, Parrot, KNOPPIX, GhostBSD, Sabayon, Salix, Q4OS, ClearOS,
+  Container, ROSA, Zenwalk, Parabola, ChaletOS, BackBox, MXLinux, Vector, Maui,
+  Qubes, RancherOS, Oracle, TinyCore, Robolinux, Trisquel, Voyager, Clonezilla,
+  SteamOS, Absolute, NixOS, ## NixOS or a Nix build environment
+  AUSTRUMI, Arya, Porteus, AVLinux, Elive, Bluestar, SliTaz, Solaris, Chakra,
+  Wifislax, Scientific, ExTiX, Rockstor, GoboLinux, Void, BSD, FreeBSD, NetBSD,
+  OpenBSD, DragonFlyBSD, Haiku
+
+ + the list of known distributions + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
foreignDeps: seq[string] = @[]
+
+ + Registered foreign deps. + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
LacksDevPackages = {Distribution.Gentoo, Distribution.Slackware,
+                    Distribution.ArchLinux, Distribution.Artix,
+                    Distribution.Antergos, Distribution.BlackArch,
+                    Distribution.ArchBang}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc echoForeignDeps() {....raises: [], tags: [], forbids: [].}
+
+ + Writes the list of registered foreign deps to stdout. + Source   +Edit   + +
+
+ +
+
+
+
proc foreignCmd(cmd: string; requiresSudo = false) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Registers a foreign command to the internal list of commands that can be queried later. + Source   +Edit   + +
+
+ +
+
+
+
proc foreignDep(foreignPackageName: string) {....raises: [OSError, IOError],
+    tags: [ExecIOEffect, ReadIOEffect, RootEffect, ReadEnvEffect], forbids: [].}
+
+ + Registers foreignPackageName to the internal list of foreign deps. It is your job to ensure that the package name is correct. + Source   +Edit   + +
+
+ +
+
+
+
proc foreignDepInstallCmd(foreignPackageName: string): (string, bool) {.
+    ...raises: [OSError, IOError],
+    tags: [ExecIOEffect, ReadIOEffect, RootEffect, ReadEnvEffect], forbids: [].}
+
+ + Returns the distro's native command to install foreignPackageName and whether it requires root/admin rights. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template detectOs(d: untyped): bool
+
+ + Distro/OS detection. For convenience, the required Distribution. qualifier is added to the enum value. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/distros.idx b/distros.idx new file mode 100644 index 0000000000000..98034a549761a --- /dev/null +++ b/distros.idx @@ -0,0 +1,9 @@ +nimTitle distros distros.html module std/distros 0 +nim Distribution distros.html#Distribution enum Distribution 36 +nim LacksDevPackages distros.html#LacksDevPackages const LacksDevPackages 138 +nim detectOs distros.html#detectOs.t,untyped template detectOs(d: untyped): bool 207 +nim foreignDeps distros.html#foreignDeps var foreignDeps 214 +nim foreignCmd distros.html#foreignCmd,string proc foreignCmd(cmd: string; requiresSudo = false) 216 +nim foreignDepInstallCmd distros.html#foreignDepInstallCmd,string proc foreignDepInstallCmd(foreignPackageName: string): (string, bool) 225 +nim foreignDep distros.html#foreignDep,string proc foreignDep(foreignPackageName: string) 270 +nim echoForeignDeps distros.html#echoForeignDeps proc echoForeignDeps() 276 diff --git a/docgen.html b/docgen.html new file mode 100644 index 0000000000000..811f1c97b4d0d --- /dev/null +++ b/docgen.html @@ -0,0 +1,501 @@ + + + + + + + +Nim DocGen Tools Guide + + + + + + + + + + + + + + + + +
+
+

Nim DocGen Tools Guide

+
+ +
+ Source   +Edit   + +
+ +

+ +
Author:Erik O'Leary
Version:2.2.1
+

Introduction

This document describes the documentation generation tools built into the Nim compiler, which can generate HTML, Latex and JSON output from input .nim files and projects. The output documentation will include the module dependencies (import), any top-level documentation comments (##), and exported symbols (*), including procedures, types, and variables.

+ + + + +
commandoutput format
nim doc.html HTML
nim doc2tex.tex LaTeX
nim jsondoc.json JSON

Nim can generate HTML and LaTeX from input Markdown and RST (reStructuredText) files as well, which is intended for writing standalone documents like user's guides and technical specifications. See Nim-flavored Markdown and reStructuredText document for the description of this feature and particularly section Nim-flavored Markdown and reStructuredText: Command line usage for the full list of supported commands.

+ +

Quick start

Generate HTML documentation for a file:

+

nim doc <filename>.nim

+

Generate HTML documentation for a whole project:

+

# delete any htmldocs/*.idx file before starting
+nim doc --project --index:on --git.url:<url> --git.commit:<tag> --outdir:htmldocs <main_filename>.nim
+# this will generate html files, a theindex.html index, css and js under `htmldocs`
+# See also `--docroot` to specify a relative root.
+# to get search (dochacks.js) to work locally, you need a server otherwise
+# CORS will prevent opening file:// urls; this works:
+python3 -m http.server 7029 --directory htmldocs
+# When --outdir is omitted it defaults to $projectPath/htmldocs,
+# or `$nimcache/htmldocs` with `--usenimcache` which avoids clobbering your sources;
+# and likewise without `--project`.
+# Adding `-r` will open in a browser directly.
+# Use `--showNonExports` to show non-exported fields of an exported type.

+ +

Documentation Comments

Any comments which are preceded by a double-hash (##), are interpreted as documentation. Comments are parsed as RST (see reference), providing Nim module authors the ability to easily generate richly formatted documentation with only their well-documented code! Basic Markdown syntax is also supported inside the doc comments.

+

Example:

+

type Person* = object
+  ## This type contains a description of a person
+  name: string
+  age: int

+

Outputs:

+
Person* = object
+  name: string
+  age: int
+

This type contains a description of a person

+

Field documentation comments can be added to fields like so:

+

var numValues: int ## \
+  ## `numValues` stores the number of values

+

Note that without the * following the name of the type, the documentation for this type would not be generated. Documentation will only be generated for exported types/procedures/etc.

+

It's recommended to always add exactly one space after ## for readability of comments — this extra space will be cropped from the parsed comments and won't influence RST formatting.

+
Note: +

Generally, this baseline indentation level inside a documentation comment may not be 1: it can be any since it is determined by the offset of the first non-whitespace character in the comment. After that indentation must be consistent on the following lines of the same comment. If you still need to add an additional indentation at the very beginning (for RST block quote syntax) use backslash \ before it:

+

## \
+##
+##    Block quote at the first line.
+##
+## Paragraph.

+
+ +

Structuring output directories

Basic directory for output is set by --outdir:OUTDIR switch, by default OUTDIR is htmldocs sub-directory in the directory of the processed file.

+

There are 2 basic options as to how generated HTML output files are stored:

+
  1. complex hierarchy when docgen-compiling with --project, which follows directory structure of the project itself. So nim doc replicates project's directory structure inside --outdir:OUTDIR directory. --project is well suited for projects that have 1 main module. File name clashes are impossible in this case.
  2. +
  3. flattened structure, where user-provided script goes through all needed input files and calls commands like nim doc with --outdir:OUTDIR switch, thus putting all HTML (and .idx) files into 1 directory.
    Important: +Make sure that you don't have files with same base name like x.nim and x.md in the same package, otherwise you'll have name conflict for x.html.
    +
    Tip: +

    To structure your output directories and avoid file name clashes you can split your project into different packages -- parts of your repository that are docgen-compiled with different --outdir:OUTDIR options.

    +

    An example of such strategy is Nim repository itself which has:

    +
    • its stdlib .nim files from different directories and .md documentation from doc/ directory are all docgen-compiled into --outdir:web/upload/<version>/ directory
    • +
    • its .nim files from compiler/ directory are docgen-compiled into --outdir:web/upload/<version>/compiler/ directory. Interestingly, it's compiled with complex hierarchy using --project switch.
    • +
    +

    Contents of web/upload/<version> are then deployed into Nim's Web server.

    +

    This output directory structure allows to work correctly with files like compiler/docgen.nim (implementation) and doc/docgen.md (user documentation) in 1 repository.

    +
    +
  4. +
+ +

Index files

Index (.idx) files are used for 2 different purposes:

+
  1. easy cross-referencing between different .nim and/or .md / .rst files described in Nim external referencing
  2. +
  3. creating a whole-project index for searching of symbols and keywords, see Buildindex command.
  4. +
+ +

Document Types

+

Example of Nim file input

The following examples will generate documentation for this sample Nim module, aptly named doc/docgen_sample.nim:

+

## This module is a sample.
+
+import std/strutils
+
+proc helloWorld*(times: int) =
+  ## Takes an integer and outputs
+  ## as many indented "hello world!"s
+
+  for i in 0 .. times-1:
+    echo "hello world!".indent(2) # using indent to avoid `UnusedImport`
+
+helloWorld(5)
+

+

All the below commands save their output to htmldocs directory relative to the directory of file; hence the output for this sample will be in doc/htmldocs.

+ +

HTML

The generation of HTML documents is done via the doc command. This command takes either a single .nim file, outputting a single .html file with the same base filename, or multiple .nim files, outputting multiple .html files and, optionally, an index file.

+

The doc command:

+

nim doc docgen_sample.nim

+

Partial Output:

+
...
+proc helloWorld(times: int) {.raises: [], tags: [].}
+...
+

The full output can be seen here: docgen_sample.html. It runs after semantic checking and includes pragmas attached implicitly by the compiler.

+ +

LaTeX

LaTeX files are intended to be converted to PDF, especially for offline reading or making hard copies. (LaTeX output is oftentimes better than HTML -> PDF conversion).

+

The doc2tex command:

+

nim doc2tex docgen_sample.nim
+cd htmldocs
+xelatex docgen_sample.tex
+xelatex docgen_sample.tex
+# It is usually necessary to run `xelatex` 2 times (or even 3 times for
+# large documents) to get all labels generated.
+# That depends on this warning in the end of `xelatex` output:
+#   LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.

+

The output is docgen_sample.pdf.

+ +

JSON

The generation of JSON documents is done via the jsondoc command. This command takes in a .nim file and outputs a .json file with the same base filename. Note that this tool is built off of the doc command (previously doc2), and contains the same information.

+

The jsondoc command:

+

nim jsondoc docgen_sample.nim

+

Output:

+
{
+  "orig": "docgen_sample.nim",
+  "nimble": "",
+  "moduleDescription": "This module is a sample",
+  "entries": [
+    {
+      "name": "helloWorld",
+      "type": "skProc",
+      "line": 5,
+      "col": 0,
+      "description": "Takes an integer and outputs as many &quot;hello world!&quot;s",
+      "code": "proc helloWorld(times: int) {.raises: [], tags: [].}"
+    }
+  ]
+}
+

Similarly to the old doc command, the old jsondoc command has been renamed to jsondoc0.

+

The jsondoc0 command:

+

nim jsondoc0 docgen_sample.nim

+

Output:

+
[
+  {
+    "comment": "This module is a sample."
+  },
+  {
+    "name": "helloWorld",
+    "type": "skProc",
+    "description": "Takes an integer and outputs as many &quot;hello world!&quot;s",
+    "code": "proc helloWorld*(times: int)"
+  }
+]
+

Note that the jsondoc command outputs its JSON without pretty-printing it, while jsondoc0 outputs pretty-printed JSON.

+ +

Simple documentation links

It's possible to use normal Markdown/RST syntax to manually reference Nim symbols using HTML anchors, however Nim has an automatic facility that makes referencing inside .nim and .md/.rst files and between them easy and seamless. The point is that such links will be resolved automatically by nim doc (or md2html, or jsondoc, or doc2tex, ...). And, unlike manual links, such automatic links check that their target exists -- a warning is emitted for any broken link, so you avoid broken links in your project.

+

Nim treats both .md/.rst files and .nim modules (their doc comment part) as documents uniformly. Hence all directions of referencing are equally possible having the same syntax:

+
  1. .md/rst -> itself (internal). See Nim-flavored Markdown and reStructuredText: Markup local referencing.
  2. +
  3. .md/rst -> external .md/rst. See Nim-flavored Markdown and reStructuredText: Markup external referencing. To summarize, referencing in .md/.rst files was already described in Nim-flavored Markdown and reStructuredText (particularly it described usage of index files for referencing), while in this document we focus on Nim-specific details.
  4. +
  5. .md/rst -> external .nim. See Nim external referencing.
  6. +
  7. .nim -> itself (internal). See Nim local referencing.
  8. +
  9. .nim -> external .md/rst. See Nim-flavored Markdown and reStructuredText: Markup external referencing.
  10. +
  11. .nim -> external .nim. See Nim external referencing.
  12. +
+

To put it shortly, local referencing always works out of the box, external referencing requires to use .. importdoc:: <file> directive to import file and to ensure that the corresponding .idx file was generated.

+

Syntax for referencing is basically the same as for normal markup. Recall from Nim-flavored Markdown and reStructuredText: Referencing that our parser supports two equivalent syntaxes for referencing, Markdown and RST one. So to reference proc f one should use something like that, depending on markup type:

+
Markdown                    RST
+
+Ref. [proc f] or [f]        Ref. `proc f`_ or just f_ for a one-word case
+ +

Nim local referencing

You can reference Nim identifiers from Nim documentation comments inside their .nim file (or inside a .rst file included from a .nim). This pertains to any exported symbol like proc, const, iterator, etc. Link text is either one word or a group of words enclosed by delimiters (brackets [...] for Markdown or backticks `...`_ for RST). Link text will be displayed as is while link target will be set to the anchor [1] of Nim symbol that corresponds to link text.

+

[1] anchors' format is described in HTML anchor generation section below.

+

If you have a constant:

+

const pi* = 3.14

+

then it should be referenced in one of the 2 forms:

+
  1. non-qualified (no symbol kind specification):
    pi_
    +
  2. +
  3. qualified (with symbol kind specification):
    `const pi`_
    +
  4. +
+

For routine kinds there are more options. Consider this definition:

+

proc foo*(a: int, b: float): string

+

Generally following syntax is allowed for referencing foo:

+
  • short (without parameters):
    1. non-qualified:
      foo_
      +
    2. +
    3. qualified:
      `proc foo`_
      +
    4. +
    +
  • +
  • longer variants (with parameters):
    1. non-qualified:
      1. specifying parameters names:
        `foo(a, b)`_
        +
      2. +
      3. specifying parameters types:
        `foo(int, float)`_
        +
      4. +
      5. specifying both names and types:
        `foo(a: int, b: float)`_
        +
      6. +
      7. output parameter can also be specified if you wish:
        `foo(a: int, b: float): string`_
        +
      8. +
      +
    2. +
    3. qualified: all 4 options above are valid. Particularly you can use the full format:
      `proc foo(a: int, b: float): string`_
      +
    4. +
    +
  • +
+
Tip: +Avoid cluttering your text with extraneous information by using one of shorter forms:
binarySearch_
+`binarySearch(a, key, cmp)`_
+

Brevity is better for reading! If you use a short form and have an ambiguity problem (see below) then just add some additional info.

+
+

Symbol kind like proc can also be specified in the postfix form:

+
`foo proc`_
+`walkDir(d: string) iterator`_
+
Warning: +An ambiguity in resolving documentation links may arise because of:
  1. clash with other RST anchors
    • manually setup anchors
    • +
    • automatically set up, e.g. section names
    • +
    +
  2. +
  3. collision with other Nim symbols:
    • routines with different parameters can exist e.g. for proc and template. In this case they are split between their corresponding sections in output file. Qualified references are useful in this case -- just disambiguate by referring to these sections explicitly:
      See `foo proc`_ and `foo template`_.
      +
    • +
    • because in Nim proc and iterator belong to different namespaces, so there can be a collision even if parameters are the same. Use `proc foo`_ or `iterator foo`_ then.
    • +
    +
  4. +
+

Any ambiguity is always reported with Nim compiler warnings and an anchor with higher priority is selected. Manual anchors have highest priority, then go automatic RST anchors; then Nim-generated anchors (while procs have higher priority than other Nim symbol kinds).

+
+

Generic parameters can also be used. All in all, this long form will be recognized fine:

+
`proc binarySearch*[T; K](a: openArray[T], key: K, cmp: proc(T, K)): int`_
+

Limitations:

+
  1. The parameters of a nested routine type can be specified only with types (without parameter names, see form A.2 above). E.g. for this signature:

    +

    proc binarySearch*[T, K](a: openArray[T]; key: K;
    +                         cmp: proc (x: T; y: K): int {.closure.}): int
    +                                    ~~    ~~   ~~~~~

    +

    you cannot use names underlined by ~~ so it must be referenced with cmp: proc(T, K). Hence these forms are valid:

    +
    `binarySearch(a: openArray[T], key: K, cmp: proc(T, K))`_
    +`binarySearch(openArray[T], K, proc(T, K))`_
    +`binarySearch(a, key, cmp)`_
    +
  2. +
  3. Default values in routine parameters are not recognized, one needs to specify the type and/or name instead. E.g. for referencing proc f(x = 7) use one of the mentioned forms:
    `f(int)`_ or `f(x)`_ or `f(x: int)`_.
    +
  4. +
  5. Generic parameters must be given the same way as in the definition of referenced symbol.
    • their names should be the same
    • +
    • parameters list should be given the same way, e.g. without substitutions between commas (,) and semicolons (;).
    • +
    +
  6. +
+
Note: +

A bit special case is operators (as their signature is also defined with `):

+

func `$`(x: MyType): string
+func `[]`*[T](x: openArray[T]): T

+

A short form works without additional backticks:

+
`$`_
+`[]`_
+

However for fully-qualified reference copy-pasting backticks (`) into other backticks will not work in our RST parser (because we use Markdown-like inline markup rules). You need either to delete backticks or keep them and escape with backslash \:

+
no backticks: `func $`_
+escaped:  `func \`$\``_
+no backticks: `func [][T](x: openArray[T]): T`_
+escaped:  `func \`[]\`[T](x: openArray[T]): T`_
+
+
Note: +Types that defined as enum, or object, or tuple can also be referenced with those names directly (instead of type):
type CopyFlag = enum
+  ...
+## Ref. `CopyFlag enum`_
+
+ +

Nim external referencing

Just like for Nim-flavored Markdown and reStructuredText: Markup external referencing, which saves markup anchors, the Nim symbols are also saved in .idx files, so one needs to generate them beforehand, and they should be loaded by an .. importdoc:: directive. Arguments to .. importdoc:: is a comma-separated list of Nim modules or Markdown/RST documents.

+

--index:only tells Nim to only generate .idx file and do not attempt to generate HTML/LaTeX output. For .nim modules there are 2 alternatives to work with .idx files:

+
  1. using Project switch implies generation of .idx files, however, if importdoc is called on upper modules as its arguments, their .idx are not yet created. Thus one should generate all required .idx first:

    +

    nim doc --project --index:only <main>.nim
    +nim doc --project <main>.nim

    +
  2. +
  3. or run nim doc --index:only <module.nim> command for all (used) Nim modules in your project. Then run nim doc <module.nim> on them for output HTML generation.
    Warning: +A mere nim doc --index:on may fail on an attempt to do importdoc from another module (for which .idx was not yet generated), that's why --index:only shall be used instead.
    +

    For .md/.rst markup documents point 2 is the only option.

    +
  4. +
+

Then, you can freely use something like this in your_module.nim:

+

## .. importdoc::  user_manual.md, another_module.nim
+
+...
+## Ref. [some section from User Manual].
+
+...
+## Ref. [proc f]
+## (assuming you have a proc `f` in ``another_module``).

+

and compile it by nim doc. Note that link text will be automatically prefixed by the module name of symbol, so you will see something like "Ref. another_module: proc f" in the generated output.

+

It's also possible to reference a whole module by prefixing or suffixing full canonical module name with "module":

+
Ref. [module subdir/name] or [subdir/name module].
+

Markup documents as a whole can be referenced just by their title (or by their file name if the title was not set) without any prefix.

+
Tip: +During development process the stage of .idx files generation can be done only once, after that you use already generated .idx files while working with a document being developed (unless you do incompatible changes to referenced documents).
+
Hint: +After changing a referenced document file one may need to regenerate its corresponding .idx file to get correct results. Of course, when referencing internally inside any given .nim file, it's not needed, one can even immediately use any freshly added anchor (a document's own .idx file is not used for resolving its internal links).
+

If an importdoc directive fails to find a .idx, then an error is emitted.

+

In case of such compilation failures please note that:

+
  • all relative paths, given to importdoc, relate to insides of OUTDIR, and not project's directory structure.
  • +
  • importdoc searches for .idx in --outdir:OUTDIR directory (htmldocs by default) and not around original modules, so:
    Tip: +look into OUTDIR to understand what's going on.
    +
  • +
  • also keep in mind that .html and .idx files should always be output to the same directory, so check this and, if it's not true, check that both runs with and without --index:only have all other options the same.
  • +
+

To summarize, for 2 basic options of Structuring output directories compilation options are different:

+
  1. complex hierarchy with --project switch.

    +

    As the original project's directory structure is replicated in OUTDIR, all passed paths are related to this structure also.

    +

    E.g. if a module path1/module.nim does .. importdoc:: path2/another.nim then docgen tries to load file OUTDIR/path1/path2/another.idx.

    +
    Note: +

    markup documents are just placed into the specified directory OUTDIR by default (i.e. they are not affected by --project), so if you have PROJECT/doc/manual.md document and want to use complex hierarchy (with doc/), compile it with --docroot:

    +

    # 1st stage
    +nim md2html --outdir:OUTDIR --docroot:/absolute/path/to/PROJECT \
    +     --index:only PROJECT/doc/manual.md
    +...
    +# 2nd stage
    +nim md2html --outdir:OUTDIR --docroot:/absolute/path/to/PROJECT \
    +                  PROJECT/doc/manual.md

    +

    Then the output file will be placed as OUTDIR/doc/manual.idx. So if you have PROJECT/path1/module.nim, then manual.md can be referenced as ../doc/manual.md.

    +
    +
  2. +
  3. flattened structure.

    +

    E.g. if a module path1/module.nim does .. importdoc:: path2/another.nim then docgen tries to load OUTDIR/path2/another.idx, so the path path1 does not matter and providing path2 can be useful only in the case it contains another package that was placed there using --outdir:OUTDIR/path2.

    +

    The links' text will be prefixed as another: ... in both cases.

    +
    Warning: +Again, the same --outdir:OUTDIR option should be provided to both doc --index:only / md2html --index:only and final generation by doc/md2html inside 1 package.
    +
  4. +
+

To temporarily disable importdoc, e.g. if you don't need correct link resolution at the moment, use a --noImportdoc switch (only warnings about unresolved links will be generated for external references).

+ +

Related Options

+

Project switch

nim doc --project filename.nim

+

This will recursively generate documentation of all Nim modules imported into the input module that belong to the Nimble package that filename.nim belongs to. The index files and the corresponding theindex.html will also be generated.

+ +

Index switch

nim doc --index:on filename.nim

+

This will generate an index of all the exported symbols in the input Nim module, and put it into a neighboring file with the extension of .idx. The index file is line-oriented (newlines have to be escaped). Each line represents a tab-separated record of several columns, the first two mandatory, the rest optional. See the Index (idx) file format section for details.

+
Note: +--index switch only affects creation of .idx index files, while user-searchable Index HTML file is created by buildIndex command.
+ +

Buildindex command

Once index files have been generated for one or more modules, the Nim compiler command nim buildIndex directory can be run to go over all the index files in the specified directory to generate a theindex.html file:

+

nim buildIndex -o:path/to/htmldocs/theindex.html path/to/htmldocs

+ +

See source switch

nim doc --git.url:<url> filename.nim

+

With the git.url switch the See source hyperlink will appear below each documented item in your source code pointing to the implementation of that item on a GitHub repository. You can click the link to see the implementation of the item.

+

The git.commit switch overrides the hardcoded devel branch in config/nimdoc.cfg. This is useful to link to a different branch e.g. --git.commit:master, or to a tag e.g. --git.commit:1.2.3 or a commit.

+

Source URLs are generated as href="${url}/tree/${commit}/${path}#L${line}" by default and thus compatible with GitHub but not with GitLab.

+

Similarly, git.devel switch overrides the hardcoded devel branch for the Edit link which is also useful if you have a different working branch than devel e.g. --git.devel:master.

+

Edit URLs are generated as href="${url}/tree/${devel}/${path}#L${line}" by default.

+

You can edit config/nimdoc.cfg and modify the doc.item.seesrc value with a hyperlink to your own code repository.

+

In the case of Nim's own documentation, the commit value is just a commit hash to append to a formatted URL to https://github.com/nim-lang/Nim.

+ +

Other Input Formats

The Nim compiler also has support for RST (reStructuredText) files with the rst2html and rst2tex commands. Documents like this one are initially written in a dialect of RST which adds support for Nim source code highlighting with the .. code-block:: nim prefix. code-block also supports highlighting of a few other languages supported by the packages/docutils/highlite module.

+

See Markdown and RST markup languages for usage of those commands.

+ +

HTML anchor generation

When you run the rst2html command, all sections in the RST document will get an anchor you can hyperlink to. Usually, you can guess the anchor lower casing the section title and replacing spaces with dashes, and in any case, you can get it from the table of contents. But when you run the doc command to generate API documentation, some symbol get one or two anchors at the same time: a numerical identifier, or a plain name plus a complex name.

+

The numerical identifier is just a random number. The number gets assigned according to the section and position of the symbol in the file being processed and you should not rely on it being constant: if you add or remove a symbol the numbers may shuffle around.

+

The plain name of a symbol is a simplified version of its fully exported signature. Variables or constants have the same plain name symbol as their complex name. The plain name for procs, templates, and other callable types will be their unquoted value after removing parameters, return types, and pragmas. The plain name allows short and nice linking of symbols that works unless you have a module with collisions due to overloading.

+

If you hyperlink a plain name symbol and there are other matches on the same HTML file, most browsers will go to the first one. To differentiate the rest, you will need to use the complex name. A complex name for a callable type is made up of several parts:

+

(plain symbol)(.type),(first param)?(,param type)*

+

The first thing to note is that all callable types have at least a comma, even if they don't have any parameters. If there are parameters, they are represented by their types and will be comma-separated. To the plain symbol a suffix may be added depending on the type of the callable:

+ + + + + + + +
Callable typeSuffix
proc, funcempty string
macro.m
method.e
iterator.i
template.t
converter.c

The relationship of type to suffix is made by the proc complexName in the compiler/docgen.nim file. Here are some examples of complex names for symbols in the system module.

+ + +

Index (idx) file format

Files with the .idx extension are generated when you use the Index switch along with commands to generate documentation from source or text files. You can programmatically generate indices with the setIndexTerm() and writeIndexFile() procs. The purpose of idx files is to hold the interesting symbols and their HTML references so they can be later concatenated into a big index file with mergeIndexes(). This section documents the file format in detail.

+

Index files are line-oriented and tab-separated (newline and tab characters have to be escaped). Each line represents a record with 6 fields. The content of these columns is:

+
  1. Discriminator tag denoting type of the index entry, allowed values are:
    markupTitle
    +
    a title for .md/.rst document
    +
    nimTitle
    +
    a title of .nim module
    +
    heading
    +
    heading of sections, can be both in Nim and markup files
    +
    idx
    +
    terms marked with :idx: role
    +
    nim
    +
    a Nim symbol
    +
    nimgrp
    +
    a Nim group for overloadable symbols like procs
    +
    +
  2. +
  3. Mandatory term being indexed. Terms can include quoting according to Nim's rules (e.g. `^`).
  4. +
  5. Base filename plus anchor hyperlink (e.g. algorithm.html#*,int,SortOrder).
  6. +
  7. Optional human-readable string to display as a hyperlink. If the value is not present or is the empty string, the hyperlink will be rendered using the term. Prefix whitespace indicates that this entry is not for an API symbol but for a TOC entry.
  8. +
  9. Optional title or description of the hyperlink. Browsers usually display this as a tooltip after hovering a moment over the hyperlink.
  10. +
  11. A line number of file where the entry was defined.
  12. +
+

The index generation tools differentiate between documentation generated from .nim files and documentation generated from .md or .rst files by tag nimTitle or markupTitle in the 1st line of the .idx file.

+ +

Additional resources

+

The output for HTML and LaTeX comes from the config/nimdoc.cfg and config/nimdoc.tex.cfg configuration files. You can add and modify these files to your project to change the look of the docgen output.

+

You can import the packages/docutils/rstgen module in your programs if you want to reuse the compiler's documentation generation procs.

+

+ +
+
+ + +
+
+ + + + diff --git a/docgen.idx b/docgen.idx new file mode 100644 index 0000000000000..686dea4496b91 --- /dev/null +++ b/docgen.idx @@ -0,0 +1,24 @@ +markupTitle Nim DocGen Tools Guide docgen.html Nim DocGen Tools Guide 0 +heading Introduction docgen.html#introduction Introduction 0 +idx documentation generation tools docgen.html#documentation-generation-tools_1 Introduction 0 +heading Quick start docgen.html#introduction-quick-start Quick start 0 +heading Documentation Comments docgen.html#introduction-documentation-comments Documentation Comments 0 +heading Structuring output directories docgen.html#introduction-structuring-output-directories Structuring output directories 0 +heading Index files docgen.html#introduction-index-files Index files 0 +heading Document Types docgen.html#document-types Document Types 0 +heading Example of Nim file input docgen.html#document-types-example-of-nim-file-input Example of Nim file input 0 +heading HTML docgen.html#document-types-html HTML 0 +heading LaTeX docgen.html#document-types-latex LaTeX 0 +heading JSON docgen.html#document-types-json JSON 0 +heading Simple documentation links docgen.html#simple-documentation-links Simple documentation links 0 +heading Nim local referencing docgen.html#simple-documentation-links-nim-local-referencing Nim local referencing 0 +heading Nim external referencing docgen.html#simple-documentation-links-nim-external-referencing Nim external referencing 0 +heading Related Options docgen.html#related-options Related Options 0 +heading Project switch docgen.html#related-options-project-switch Project switch 0 +heading Index switch docgen.html#related-options-index-switch Index switch 0 +heading Buildindex command docgen.html#related-options-buildindex-command Buildindex command 0 +heading See source switch docgen.html#related-options-see-source-switch See source switch 0 +heading Other Input Formats docgen.html#other-input-formats Other Input Formats 0 +heading HTML anchor generation docgen.html#html-anchor-generation HTML anchor generation 0 +heading Index (idx) file format docgen.html#index-idx-file-format Index (idx) file format 0 +heading Additional resources docgen.html#additional-resources Additional resources 0 diff --git a/docgen_sample.html b/docgen_sample.html new file mode 100644 index 0000000000000..b0c6dac096087 --- /dev/null +++ b/docgen_sample.html @@ -0,0 +1,106 @@ + + + + + + + +doc/docgen_sample + + + + + + + + + + + + + + + + +
+
+

doc/docgen_sample

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

This module is a sample.

+
+

Procs

+
+
+
+
proc helloWorld(times: int) {....raises: [], tags: [], forbids: [].}
+
+ + Takes an integer and outputs as many indented "hello world!"s + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/dochack.js b/dochack.js new file mode 100644 index 0000000000000..d2a5732b97db8 --- /dev/null +++ b/dochack.js @@ -0,0 +1,1619 @@ +/* Generated by the Nim Compiler v2.2.1 */ +var framePtr = null; +var excHandler = 0; +var lastJSError = null; +var NTI33554466 = {size: 0,kind: 1,base: null,node: null,finalizer: null}; +var NTI687865870 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI33554435 = {size: 0,kind: 31,base: null,node: null,finalizer: null}; +var NTI922746960 = {size: 0,kind: 31,base: null,node: null,finalizer: null}; +var NTI922746967 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI134217745 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217749 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217751 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555167 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555175 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554449 = {size: 0,kind: 28,base: null,node: null,finalizer: null}; +var NTI33554450 = {size: 0,kind: 29,base: null,node: null,finalizer: null}; +var NTI33555174 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33555171 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555172 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217741 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217743 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NNI134217743 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217743.node = NNI134217743; +var NNI134217741 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217741.node = NNI134217741; +var NNI33555172 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555172.node = NNI33555172; +NTI33555174.base = NTI33555171; +NTI33555175.base = NTI33555171; +var NNI33555171 = {kind: 2, len: 5, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "parent", len: 0, typ: NTI33555174, name: "parent", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}, +{kind: 1, offset: "message", len: 0, typ: NTI33554449, name: "msg", sons: null}, +{kind: 1, offset: "trace", len: 0, typ: NTI33554449, name: "trace", sons: null}, +{kind: 1, offset: "up", len: 0, typ: NTI33555175, name: "up", sons: null}]}; +NTI33555171.node = NNI33555171; +var NNI33555167 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555167.node = NNI33555167; +NTI33555171.base = NTI33555167; +NTI33555172.base = NTI33555171; +NTI134217741.base = NTI33555172; +NTI134217743.base = NTI134217741; +var NNI134217751 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217751.node = NNI134217751; +NTI134217751.base = NTI33555172; +var NNI134217749 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217749.node = NNI134217749; +NTI134217749.base = NTI33555172; +var NNI134217745 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217745.node = NNI134217745; +NTI134217745.base = NTI33555172; +var NNI922746967 = {kind: 2, len: 2, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "a", len: 0, typ: NTI922746960, name: "a", sons: null}, +{kind: 1, offset: "b", len: 0, typ: NTI33554435, name: "b", sons: null}]}; +NTI922746967.node = NNI922746967; +var NNI687865870 = {kind: 2, len: 2, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "Field0", len: 0, typ: NTI33554435, name: "Field0", sons: null}, +{kind: 1, offset: "Field1", len: 0, typ: NTI33554466, name: "Field1", sons: null}]}; +NTI687865870.node = NNI687865870; + +function mnewString(len_p0) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; i++) {result[i] = 0;} + return result; + + + +} + +function toJSStr(s_p0) { + var result_33556910 = null; + + var res_33556964 = newSeq__system_u2507((s_p0).length); + var i_33556965 = 0; + var j_33556966 = 0; + Label1: { + Label2: while (true) { + if (!(i_33556965 < (s_p0).length)) break Label2; + var c_33556967 = s_p0[i_33556965]; + if ((c_33556967 < 128)) { + res_33556964[j_33556966] = String.fromCharCode(c_33556967); + i_33556965 += 1; + } + else { + var helper_33556993 = newSeq__system_u2507(0); + Label3: { + Label4: while (true) { + if (!true) break Label4; + var code_33556994 = c_33556967.toString(16); + if ((((code_33556994) == null ? 0 : (code_33556994).length) == 1)) { + helper_33556993.push("%0");; + } + else { + helper_33556993.push("%");; + } + + helper_33556993.push(code_33556994);; + i_33556965 += 1; + if ((((s_p0).length <= i_33556965) || (s_p0[i_33556965] < 128))) { + break Label3; + } + + c_33556967 = s_p0[i_33556965]; + } + }; +++excHandler; + try { + res_33556964[j_33556966] = decodeURIComponent(helper_33556993.join("")); +--excHandler; +} catch (EXCEPTION) { + var prevJSError = lastJSError; + lastJSError = EXCEPTION; + --excHandler; + res_33556964[j_33556966] = helper_33556993.join(""); + lastJSError = prevJSError; + } finally { + } + } + + j_33556966 += 1; + } + }; + if (res_33556964.length < j_33556966) { for (var i = res_33556964.length ; i < j_33556966 ; ++i) res_33556964.push(null); } + else { res_33556964.length = j_33556966; }; + result_33556910 = res_33556964.join(""); + + return result_33556910; + +} + +function raiseException(e_p0, ename_p1) { + e_p0.name = ename_p1; + if ((excHandler == 0)) { + unhandledException(e_p0); + } + + throw e_p0; + + +} + +function addInt(a_p0, b_p1) { + var result = a_p0 + b_p1; + checkOverflowInt(result); + return result; + + + +} + +function chckRange(i_p0, a_p1, b_p2) { + var result_33557361 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557361 = i_p0; + break BeforeRet; + } + else { + raiseRangeError(); + } + + }; + + return result_33557361; + +} + +function setConstr() { + var result = {}; + for (var i = 0; i < arguments.length; ++i) { + var x = arguments[i]; + if (typeof(x) == "object") { + for (var j = x[0]; j <= x[1]; ++j) { + result[j] = true; + } + } else { + result[x] = true; + } + } + return result; + + + +} +var ConstSet1 = setConstr(17, 16, 4, 18, 27, 19, 23, 22, 21); + +function nimCopy(dest_p0, src_p1, ti_p2) { + var result_33557321 = null; + + switch (ti_p2.kind) { + case 21: + case 22: + case 23: + case 5: + if (!(isFatPointer__system_u2869(ti_p2))) { + result_33557321 = src_p1; + } + else { + result_33557321 = [src_p1[0], src_p1[1]]; + } + + break; + case 19: + if (dest_p0 === null || dest_p0 === undefined) { + dest_p0 = {}; + } + else { + for (var key in dest_p0) { delete dest_p0[key]; } + } + for (var key in src_p1) { dest_p0[key] = src_p1[key]; } + result_33557321 = dest_p0; + + break; + case 18: + case 17: + if (!((ti_p2.base == null))) { + result_33557321 = nimCopy(dest_p0, src_p1, ti_p2.base); + } + else { + if ((ti_p2.kind == 17)) { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {m_type: ti_p2} : dest_p0; + } + else { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {} : dest_p0; + } + } + nimCopyAux(result_33557321, src_p1, ti_p2.node); + break; + case 4: + case 16: + if(ArrayBuffer.isView(src_p1)) { + if(dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new src_p1.constructor(src_p1); + } else { + dest_p0.set(src_p1, 0); + } + result_33557321 = dest_p0; + } else { + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + } + + break; + case 24: + case 27: + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + + break; + case 28: + if (src_p1 !== null) { + result_33557321 = src_p1.slice(0); + } + + break; + default: + result_33557321 = src_p1; + break; + } + + return result_33557321; + +} + +function chckIndx(i_p0, a_p1, b_p2) { + var result_33557356 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557356 = i_p0; + break BeforeRet; + } + else { + raiseIndexError(i_p0, a_p1, b_p2); + } + + }; + + return result_33557356; + +} + +function makeNimstrLit(c_p0) { + var result = []; + for (var i = 0; i < c_p0.length; ++i) { + result[i] = c_p0.charCodeAt(i); + } + return result; + + + +} + +function subInt(a_p0, b_p1) { + var result = a_p0 - b_p1; + checkOverflowInt(result); + return result; + + + +} + +function cstrToNimstr(c_p0) { + var ln = c_p0.length; + var result = new Array(ln); + var r = 0; + for (var i = 0; i < ln; ++i) { + var ch = c_p0.charCodeAt(i); + + if (ch < 128) { + result[r] = ch; + } + else { + if (ch < 2048) { + result[r] = (ch >> 6) | 192; + } + else { + if (ch < 55296 || ch >= 57344) { + result[r] = (ch >> 12) | 224; + } + else { + ++i; + ch = 65536 + (((ch & 1023) << 10) | (c_p0.charCodeAt(i) & 1023)); + result[r] = (ch >> 18) | 240; + ++r; + result[r] = ((ch >> 12) & 63) | 128; + } + ++r; + result[r] = ((ch >> 6) & 63) | 128; + } + ++r; + result[r] = (ch & 63) | 128; + } + ++r; + } + return result; + + + +} +var ConstSet2 = setConstr([65, 90]); +var ConstSet3 = setConstr(95, 32, 46); +var ConstSet4 = setConstr(95, 32, 46); + +function mulInt(a_p0, b_p1) { + var result = a_p0 * b_p1; + checkOverflowInt(result); + return result; + + + +} +var ConstSet5 = setConstr([97, 122]); +var ConstSet6 = setConstr([65, 90], [97, 122]); +var ConstSet7 = setConstr([97, 122]); +var ConstSet8 = setConstr([65, 90]); +var ConstSet9 = setConstr([65, 90], [97, 122]); + +function nimMax(a_p0, b_p1) { + var Temporary1; + + var result_33557148 = 0; + + BeforeRet: { + if ((b_p1 <= a_p0)) { + Temporary1 = a_p0; + } + else { + Temporary1 = b_p1; + } + + result_33557148 = Temporary1; + break BeforeRet; + }; + + return result_33557148; + +} + +function nimMin(a_p0, b_p1) { + var Temporary1; + + var result_33557144 = 0; + + BeforeRet: { + if ((a_p0 <= b_p1)) { + Temporary1 = a_p0; + } + else { + Temporary1 = b_p1; + } + + result_33557144 = Temporary1; + break BeforeRet; + }; + + return result_33557144; + +} + +function addChar(x_p0, c_p1) { + x_p0.push(c_p1); + + +} +var objectID_1140850866 = [0]; + +function setTheme(theme_p0) { + document.documentElement.setAttribute("data-theme", theme_p0); + window.localStorage.setItem("theme", theme_p0); + + +} + +function add__system_u1942(x_p0, x_p0_Idx, y_p1) { + if (x_p0[x_p0_Idx] === null) { x_p0[x_p0_Idx] = []; } + var off = x_p0[x_p0_Idx].length; + x_p0[x_p0_Idx].length += y_p1.length; + for (var i = 0; i < y_p1.length; ++i) { + x_p0[x_p0_Idx][off+i] = y_p1.charCodeAt(i); + } + + + +} + +function newSeq__system_u2507(len_p0) { + var result_33556943 = []; + + result_33556943 = new Array(len_p0); for (var i = 0 ; i < len_p0 ; ++i) { result_33556943[i] = null; } + return result_33556943; + +} + +function unhandledException(e_p0) { + var buf_33556658 = [[]]; + if (!(((e_p0.message).length == 0))) { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32]);; + buf_33556658[0].push.apply(buf_33556658[0], e_p0.message);; + } + else { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110]);; + } + + buf_33556658[0].push.apply(buf_33556658[0], [32,91]);; + add__system_u1942(buf_33556658, 0, e_p0.name); + buf_33556658[0].push.apply(buf_33556658[0], [93,10]);; + var cbuf_33556659 = toJSStr(buf_33556658[0]); + if (typeof(Error) !== "undefined") { + throw new Error(cbuf_33556659); + } + else { + throw cbuf_33556659; + } + + + +} + +function raiseOverflow() { + raiseException({message: [111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119], parent: null, m_type: NTI134217743, name: null, trace: [], up: null}, "OverflowDefect"); + + +} + +function checkOverflowInt(a_p0) { + if (a_p0 > 2147483647 || a_p0 < -2147483648) raiseOverflow(); + + + +} + +function raiseRangeError() { + raiseException({message: [118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101], parent: null, m_type: NTI134217751, name: null, trace: [], up: null}, "RangeDefect"); + + +} + +function addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, start_p2, n_p3) { + var Temporary1; + + var old_301990096 = (result_p0[result_p0_Idx]).length; + if (result_p0[result_p0_Idx].length < (Temporary1 = chckRange(addInt(old_301990096, n_p3), 0, 2147483647), Temporary1)) { for (var i = result_p0[result_p0_Idx].length; i < Temporary1; ++i) result_p0[result_p0_Idx].push(0); } + else {result_p0[result_p0_Idx].length = Temporary1; }; + Label2: { + var iHEX60gensym4_301990110 = 0; + var i_536872113 = 0; + Label3: { + Label4: while (true) { + if (!(i_536872113 < n_p3)) break Label4; + iHEX60gensym4_301990110 = i_536872113; + result_p0[result_p0_Idx][chckIndx(addInt(old_301990096, iHEX60gensym4_301990110), 0, (result_p0[result_p0_Idx]).length - 1)] = x_p1.charCodeAt(chckIndx(addInt(start_p2, iHEX60gensym4_301990110), 0, (x_p1).length - 1)); + i_536872113 = addInt(i_536872113, 1); + } + }; + }; + + +} + +function addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, x_p1) { + addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, 0, ((x_p1) == null ? 0 : (x_p1).length)); + + +} + +function addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, x_p1) { + addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, ((x_p1) + "")); + + +} + +function addInt__stdZprivateZdigitsutils_u241(result_p0, result_p0_Idx, x_p1) { + addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, BigInt(x_p1)); + + +} + +function HEX24__systemZdollars_u8(x_p0) { + var result_385875978 = [[]]; + + addInt__stdZprivateZdigitsutils_u241(result_385875978, 0, x_p0); + + return result_385875978[0]; + +} + +function isFatPointer__system_u2869(ti_p0) { + var result_33557303 = false; + + BeforeRet: { + result_33557303 = !((ConstSet1[ti_p0.base.kind] != undefined)); + break BeforeRet; + }; + + return result_33557303; + +} + +function nimCopyAux(dest_p0, src_p1, n_p2) { + switch (n_p2.kind) { + case 0: + break; + case 1: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + + break; + case 2: + for (var i = 0; i < n_p2.sons.length; i++) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i]); + } + + break; + case 3: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + for (var i = 0; i < n_p2.sons.length; ++i) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i][1]); + } + + break; + } + + +} + +function raiseIndexError(i_p0, a_p1, b_p2) { + var Temporary1; + + if ((b_p2 < a_p1)) { + Temporary1 = [105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]; + } + else { + Temporary1 = ([105,110,100,101,120,32]).concat(HEX24__systemZdollars_u8(i_p0),[32,110,111,116,32,105,110,32],HEX24__systemZdollars_u8(a_p1),[32,46,46,32],HEX24__systemZdollars_u8(b_p2)); + } + + raiseException({message: nimCopy(null, Temporary1, NTI33554449), parent: null, m_type: NTI134217749, name: null, trace: [], up: null}, "IndexDefect"); + + +} + +function sysFatal__stdZassertions_u44(message_p1) { + raiseException({message: nimCopy(null, message_p1, NTI33554449), m_type: NTI134217745, parent: null, name: null, trace: [], up: null}, "AssertionDefect"); + + +} + +function raiseAssert__stdZassertions_u42(msg_p0) { + sysFatal__stdZassertions_u44(msg_p0); + + +} + +function failedAssertImpl__stdZassertions_u84(msg_p0) { + raiseAssert__stdZassertions_u42(msg_p0); + + +} + +function onDOMLoaded(e_p0) { + var Temporary4; + +function HEX3Aanonymous__dochack_u65(event_p0) { + event_p0.target.parentNode.style.display = "none"; + event_p0.target.parentNode.nextSibling.style.display = "inline"; + + +} + + document.getElementById("theme-select").value = window.localStorage.getItem("theme"); + Label1: { + var pragmaDots_536870976 = null; + var colontmp__536872104 = []; + colontmp__536872104 = document.getElementsByClassName("pragmadots"); + var i_536872106 = 0; + var L_536872107 = (colontmp__536872104).length; + Label2: { + Label3: while (true) { + if (!(i_536872106 < L_536872107)) break Label3; + pragmaDots_536870976 = colontmp__536872104[chckIndx(i_536872106, 0, (colontmp__536872104).length - 1)]; + Temporary4 = HEX3Aanonymous__dochack_u65.bind(null); Temporary4.ClP_0 = HEX3Aanonymous__dochack_u65; Temporary4.ClE_0 = null; + pragmaDots_536870976.onclick = Temporary4; + i_536872106 += 1; + if (!(((colontmp__536872104).length == L_536872107))) { + failedAssertImpl__stdZassertions_u84(makeNimstrLit("iterators.nim(254, 11) `len(a) == L` the length of the seq changed while iterating over it")); + } + + } + }; + }; + + +} + +function isWhitespace__dochack_u408(x_p0) { + var result_536871322 = false; + + result_536871322 = (((x_p0.nodeName == "#text") && !/\S/.test(x_p0.textContent)) || (x_p0.nodeName == "#comment")); + + return result_536871322; + +} + +function toToc__dochack_u411(x_p0, father_p1) { + var Temporary5; + var Temporary6; + var Temporary7; + var Temporary8; + var Temporary15; + + if ((x_p0.nodeName == "UL")) { + var f_536871333 = {heading: null, kids: [], sortId: (father_p1.kids).length, doSort: false}; + var i_536871334 = 0; + Label1: { + Label2: while (true) { + if (!(i_536871334 < x_p0.childNodes.length)) break Label2; + var nxt_536871335 = addInt(i_536871334, 1); + Label3: { + Label4: while (true) { + if (!(nxt_536871335 < x_p0.childNodes.length)) Temporary5 = false; else { Temporary5 = isWhitespace__dochack_u408(x_p0.childNodes[nxt_536871335]); } if (!Temporary5) break Label4; + nxt_536871335 = addInt(nxt_536871335, 1); + } + }; + if (!(nxt_536871335 < x_p0.childNodes.length)) Temporary8 = false; else { Temporary8 = (x_p0.childNodes[i_536871334].nodeName == "LI"); } if (!Temporary8) Temporary7 = false; else { Temporary7 = (x_p0.childNodes[i_536871334].childNodes.length == 1); } if (!Temporary7) Temporary6 = false; else { Temporary6 = (x_p0.childNodes[nxt_536871335].nodeName == "UL"); } if (Temporary6) { + var e_536871348 = {heading: x_p0.childNodes[i_536871334].childNodes[0], kids: [], sortId: (f_536871333.kids).length, doSort: false}; + var it_536871349 = x_p0.childNodes[nxt_536871335]; + Label9: { + var j_536871354 = 0; + var colontmp__536872120 = 0; + colontmp__536872120 = it_536871349.childNodes.length; + var i_536872121 = 0; + Label10: { + Label11: while (true) { + if (!(i_536872121 < colontmp__536872120)) break Label11; + j_536871354 = i_536872121; + toToc__dochack_u411(it_536871349.childNodes[j_536871354], e_536871348); + i_536872121 = addInt(i_536872121, 1); + } + }; + }; + f_536871333.kids.push(e_536871348);; + i_536871334 = addInt(nxt_536871335, 1); + } + else { + toToc__dochack_u411(x_p0.childNodes[i_536871334], f_536871333); + i_536871334 = addInt(i_536871334, 1); + } + + } + }; + father_p1.kids.push(f_536871333);; + } + else { + if (isWhitespace__dochack_u408(x_p0)) { + } + else { + if ((x_p0.nodeName == "LI")) { + var idx_536871372 = []; + Label12: { + var i_536871377 = 0; + var colontmp__536872124 = 0; + colontmp__536872124 = x_p0.childNodes.length; + var i_536872125 = 0; + Label13: { + Label14: while (true) { + if (!(i_536872125 < colontmp__536872124)) break Label14; + i_536871377 = i_536872125; + if (!(isWhitespace__dochack_u408(x_p0.childNodes[i_536871377]))) { + idx_536871372.push(i_536871377);; + } + + i_536872125 = addInt(i_536872125, 1); + } + }; + }; + if (!((idx_536871372).length == 2)) Temporary15 = false; else { Temporary15 = (x_p0.childNodes[idx_536871372[chckIndx(1, 0, (idx_536871372).length - 1)]].nodeName == "UL"); } if (Temporary15) { + var e_536871393 = {heading: x_p0.childNodes[idx_536871372[chckIndx(0, 0, (idx_536871372).length - 1)]], kids: [], sortId: (father_p1.kids).length, doSort: false}; + var it_536871394 = x_p0.childNodes[idx_536871372[chckIndx(1, 0, (idx_536871372).length - 1)]]; + Label16: { + var j_536871399 = 0; + var colontmp__536872128 = 0; + colontmp__536872128 = it_536871394.childNodes.length; + var i_536872129 = 0; + Label17: { + Label18: while (true) { + if (!(i_536872129 < colontmp__536872128)) break Label18; + j_536871399 = i_536872129; + toToc__dochack_u411(it_536871394.childNodes[j_536871399], e_536871393); + i_536872129 = addInt(i_536872129, 1); + } + }; + }; + father_p1.kids.push(e_536871393);; + } + else { + Label19: { + var i_536871408 = 0; + var colontmp__536872132 = 0; + colontmp__536872132 = x_p0.childNodes.length; + var i_536872133 = 0; + Label20: { + Label21: while (true) { + if (!(i_536872133 < colontmp__536872132)) break Label21; + i_536871408 = i_536872133; + toToc__dochack_u411(x_p0.childNodes[i_536871408], father_p1); + i_536872133 = addInt(i_536872133, 1); + } + }; + }; + } + + } + else { + father_p1.kids.push({heading: x_p0, kids: [], sortId: (father_p1.kids).length, doSort: false});; + } + }} + + +} + +function extractItems__dochack_u199(x_p0, heading_p1, items_p2, items_p2_Idx) { + BeforeRet: { + if ((x_p0 == null)) { + break BeforeRet; + } + + if ((!((x_p0.heading == null)) && (x_p0.heading.textContent == heading_p1))) { + Label1: { + var i_536871131 = 0; + var colontmp__536872136 = 0; + colontmp__536872136 = (x_p0.kids).length; + var i_536872137 = 0; + Label2: { + Label3: while (true) { + if (!(i_536872137 < colontmp__536872136)) break Label3; + i_536871131 = i_536872137; + items_p2[items_p2_Idx].push(x_p0.kids[chckIndx(i_536871131, 0, (x_p0.kids).length - 1)].heading);; + i_536872137 = addInt(i_536872137, 1); + } + }; + }; + } + else { + Label4: { + var k_536871157 = null; + var i_536872141 = 0; + var L_536872142 = (x_p0.kids).length; + Label5: { + Label6: while (true) { + if (!(i_536872141 < L_536872142)) break Label6; + k_536871157 = x_p0.kids[chckIndx(i_536872141, 0, (x_p0.kids).length - 1)]; + extractItems__dochack_u199(k_536871157, heading_p1, items_p2, items_p2_Idx); + i_536872141 += 1; + if (!(((x_p0.kids).length == L_536872142))) { + failedAssertImpl__stdZassertions_u84(makeNimstrLit("iterators.nim(254, 11) `len(a) == L` the length of the seq changed while iterating over it")); + } + + } + }; + }; + } + + }; + + +} + +function tree__dochack_u130(tag_p0, kids_p1) { + var result_536871045 = null; + + result_536871045 = document.createElement(tag_p0); + Label1: { + var k_536871059 = null; + var i_536872154 = 0; + Label2: { + Label3: while (true) { + if (!(i_536872154 < (kids_p1).length)) break Label3; + k_536871059 = kids_p1[chckIndx(i_536872154, 0, (kids_p1).length - 1)]; + result_536871045.appendChild(k_536871059); + i_536872154 += 1; + } + }; + }; + + return result_536871045; + +} + +function text__dochack_u155(s_p0) { + var result_536871069 = null; + + result_536871069 = document.createTextNode(s_p0); + + return result_536871069; + +} + +function uncovered__dochack_u600(x_p0) { + var Temporary1; + + var result_536871514 = null; + + BeforeRet: { + if ((((x_p0.kids).length == 0) && !((x_p0.heading == null)))) { + if (!(x_p0.heading.hasOwnProperty('__karaxMarker__'))) { + Temporary1 = x_p0; + } + else { + Temporary1 = null; + } + + result_536871514 = Temporary1; + break BeforeRet; + } + + result_536871514 = {heading: x_p0.heading, kids: [], sortId: x_p0.sortId, doSort: x_p0.doSort}; + Label2: { + var k_536871529 = null; + var i_536872161 = 0; + var L_536872162 = (x_p0.kids).length; + Label3: { + Label4: while (true) { + if (!(i_536872161 < L_536872162)) break Label4; + k_536871529 = x_p0.kids[chckIndx(i_536872161, 0, (x_p0.kids).length - 1)]; + var y_536871530 = uncovered__dochack_u600(k_536871529); + if (!((y_536871530 == null))) { + result_536871514.kids.push(y_536871530);; + } + + i_536872161 += 1; + if (!(((x_p0.kids).length == L_536872162))) { + failedAssertImpl__stdZassertions_u84(makeNimstrLit("iterators.nim(254, 11) `len(a) == L` the length of the seq changed while iterating over it")); + } + + } + }; + }; + if (((result_536871514.kids).length == 0)) { + result_536871514 = null; + } + + }; + + return result_536871514; + +} + +function mergeTocs__dochack_u630(orig_p0, news_p1) { + var result_536871545 = null; + + result_536871545 = uncovered__dochack_u600(orig_p0); + if ((result_536871545 == null)) { + result_536871545 = news_p1; + } + else { + Label1: { + var i_536871557 = 0; + var colontmp__536872157 = 0; + colontmp__536872157 = (news_p1.kids).length; + var i_536872158 = 0; + Label2: { + Label3: while (true) { + if (!(i_536872158 < colontmp__536872157)) break Label3; + i_536871557 = i_536872158; + result_536871545.kids.push(news_p1.kids[chckIndx(i_536871557, 0, (news_p1.kids).length - 1)]);; + i_536872158 = addInt(i_536872158, 1); + } + }; + }; + } + + + return result_536871545; + +} + +function buildToc__dochack_u650(orig_p0, types_p1, procs_p2) { + var result_536871566 = null; + + var newStuff_536871571 = {heading: null, kids: [], doSort: true, sortId: 0}; + Label1: { + var t_536871575 = null; + var i_536872149 = 0; + var L_536872150 = (types_p1).length; + Label2: { + Label3: while (true) { + if (!(i_536872149 < L_536872150)) break Label3; + t_536871575 = types_p1[chckIndx(i_536872149, 0, (types_p1).length - 1)]; + var c_536871580 = {heading: t_536871575.cloneNode(true), kids: [], doSort: true, sortId: 0}; + t_536871575.__karaxMarker__ = true; + Label4: { + var p_536871584 = null; + var i_536872146 = 0; + var L_536872147 = (procs_p2).length; + Label5: { + Label6: while (true) { + if (!(i_536872146 < L_536872147)) break Label6; + p_536871584 = procs_p2[chckIndx(i_536872146, 0, (procs_p2).length - 1)]; + if (!(p_536871584.hasOwnProperty('__karaxMarker__'))) { + var xx_536871585 = p_536871584.parentNode.getElementsByClassName("attachedType"); + if ((((xx_536871585).length == 1) && (xx_536871585[chckIndx(0, 0, (xx_536871585).length - 1)].textContent == t_536871575.textContent))) { + var q_536871590 = tree__dochack_u130("A", [text__dochack_u155(p_536871584.title)]); + q_536871590.setAttribute("href", p_536871584.getAttribute("href")); + c_536871580.kids.push({heading: q_536871590, kids: [], sortId: 0, doSort: false});; + p_536871584.__karaxMarker__ = true; + } + + } + + i_536872146 += 1; + if (!(((procs_p2).length == L_536872147))) { + failedAssertImpl__stdZassertions_u84(makeNimstrLit("iterators.nim(254, 11) `len(a) == L` the length of the seq changed while iterating over it")); + } + + } + }; + }; + newStuff_536871571.kids.push(c_536871580);; + i_536872149 += 1; + if (!(((types_p1).length == L_536872150))) { + failedAssertImpl__stdZassertions_u84(makeNimstrLit("iterators.nim(254, 11) `len(a) == L` the length of the seq changed while iterating over it")); + } + + } + }; + }; + result_536871566 = mergeTocs__dochack_u630(orig_p0, newStuff_536871571); + + return result_536871566; + +} + +function add__dochack_u148(parent_p0, kid_p1) { + if (((parent_p0.nodeName == "TR") && ((kid_p1.nodeName == "TD") || (kid_p1.nodeName == "TH")))) { + var k_536871063 = document.createElement("TD"); + k_536871063.appendChild(kid_p1); + parent_p0.appendChild(k_536871063); + } + else { + parent_p0.appendChild(kid_p1); + } + + + +} + +function setClass__dochack_u152(e_p0, value_p1) { + e_p0.setAttribute("class", value_p1); + + +} + +function toHtml__dochack_u278(x_p0, isRoot_p1) { + var Temporary1; + +function HEX3Aanonymous__dochack_u298(a_p0, b_p1) { + var result_536871213 = 0; + + BeforeRet: { + if ((!((a_p0.heading == null)) && !((b_p1.heading == null)))) { + var x_536871222 = a_p0.heading.textContent; + var y_536871223 = b_p1.heading.textContent; + if ((x_536871222 < y_536871223)) { + result_536871213 = (-1); + break BeforeRet; + } + + if ((y_536871223 < x_536871222)) { + result_536871213 = 1; + break BeforeRet; + } + + result_536871213 = 0; + break BeforeRet; + } + else { + result_536871213 = subInt(a_p0.sortId, b_p1.sortId); + break BeforeRet; + } + + }; + + return result_536871213; + +} + + var result_536871193 = null; + + BeforeRet: { + if ((x_p0 == null)) { + result_536871193 = null; + break BeforeRet; + } + + if (((x_p0.kids).length == 0)) { + if ((x_p0.heading == null)) { + result_536871193 = null; + break BeforeRet; + } + + result_536871193 = x_p0.heading.cloneNode(true); + break BeforeRet; + } + + result_536871193 = tree__dochack_u130("DIV", []); + if ((!((x_p0.heading == null)) && !(x_p0.heading.hasOwnProperty('__karaxMarker__')))) { + add__dochack_u148(result_536871193, x_p0.heading.cloneNode(true)); + } + + var ul_536871209 = tree__dochack_u130("UL", []); + if (isRoot_p1) { + setClass__dochack_u152(ul_536871209, "simple simple-toc"); + } + else { + setClass__dochack_u152(ul_536871209, "simple"); + } + + if (x_p0.doSort) { + Temporary1 = HEX3Aanonymous__dochack_u298.bind(null); Temporary1.ClP_0 = HEX3Aanonymous__dochack_u298; Temporary1.ClE_0 = null; + x_p0.kids.sort(Temporary1); + } + + Label2: { + var k_536871235 = null; + var i_536872165 = 0; + var L_536872166 = (x_p0.kids).length; + Label3: { + Label4: while (true) { + if (!(i_536872165 < L_536872166)) break Label4; + k_536871235 = x_p0.kids[chckIndx(i_536872165, 0, (x_p0.kids).length - 1)]; + var y_536871236 = toHtml__dochack_u278(k_536871235, false); + if (!((y_536871236 == null))) { + add__dochack_u148(ul_536871209, tree__dochack_u130("LI", [y_536871236])); + } + + i_536872165 += 1; + if (!(((x_p0.kids).length == L_536872166))) { + failedAssertImpl__stdZassertions_u84(makeNimstrLit("iterators.nim(254, 11) `len(a) == L` the length of the seq changed while iterating over it")); + } + + } + }; + }; + if (!((ul_536871209.childNodes.length == 0))) { + add__dochack_u148(result_536871193, ul_536871209); + } + + if ((result_536871193.childNodes.length == 0)) { + result_536871193 = null; + } + + }; + + return result_536871193; + +} + +function replaceById__dochack_u158(id_p0, newTree_p1) { + var x_536871073 = document.getElementById(id_p0); + x_536871073.parentNode.replaceChild(newTree_p1, x_536871073); + newTree_p1.id = id_p0; + + +} + +function togglevis__dochack_u708(d_p0) { + if ((d_p0.style.display == "none")) { + d_p0.style.display = "inline"; + } + else { + d_p0.style.display = "none"; + } + + + +} + +function groupBy(value_p0) { + var toc_536871624 = document.getElementById("toc-list"); + if ((alternative_536871619[0] == null)) { + var tt_536871632 = {heading: null, kids: [], sortId: 0, doSort: false}; + toToc__dochack_u411(toc_536871624, tt_536871632); + tt_536871632 = tt_536871632.kids[chckIndx(0, 0, (tt_536871632.kids).length - 1)]; + var types_536871637 = [[]]; + var procs_536871642 = [[]]; + extractItems__dochack_u199(tt_536871632, "Types", types_536871637, 0); + extractItems__dochack_u199(tt_536871632, "Procs", procs_536871642, 0); + extractItems__dochack_u199(tt_536871632, "Converters", procs_536871642, 0); + extractItems__dochack_u199(tt_536871632, "Methods", procs_536871642, 0); + extractItems__dochack_u199(tt_536871632, "Templates", procs_536871642, 0); + extractItems__dochack_u199(tt_536871632, "Macros", procs_536871642, 0); + extractItems__dochack_u199(tt_536871632, "Iterators", procs_536871642, 0); + var ntoc_536871643 = buildToc__dochack_u650(tt_536871632, types_536871637[0], procs_536871642[0]); + var x_536871644 = toHtml__dochack_u278(ntoc_536871643, true); + alternative_536871619[0] = tree__dochack_u130("DIV", [x_536871644]); + } + + if ((value_p0 == "type")) { + replaceById__dochack_u158("tocRoot", alternative_536871619[0]); + } + else { + replaceById__dochack_u158("tocRoot", tree__dochack_u130("DIV", [])); + } + + togglevis__dochack_u708(document.getElementById("toc-list")); + + +} + +function HEX5BHEX5D__pureZstrutils_u1307(s_p0, x_p1) { + var result_704644384 = []; + + var a_704644386 = x_p1.a; + var L_704644388 = addInt(subInt(subInt((s_p0).length, x_p1.b), a_704644386), 1); + result_704644384 = nimCopy(null, mnewString(chckRange(L_704644388, 0, 2147483647)), NTI33554449); + Label1: { + var i_704644393 = 0; + var i_536872175 = 0; + Label2: { + Label3: while (true) { + if (!(i_536872175 < L_704644388)) break Label3; + i_704644393 = i_536872175; + result_704644384[chckIndx(i_704644393, 0, (result_704644384).length - 1)] = s_p0[chckIndx(addInt(i_704644393, a_704644386), 0, (s_p0).length - 1)]; + i_536872175 = addInt(i_536872175, 1); + } + }; + }; + + return result_704644384; + +} + +function HEX2EHEX2E__stdZenumutils_u105(a_p0, b_p1) { + var result_922746992 = ({a: 0, b: 0}); + + result_922746992 = nimCopy(result_922746992, {a: a_p0, b: b_p1}, NTI922746967); + + return result_922746992; + +} +async function loadIndex__dochack_u928() { + var result_536871842 = null; + + BeforeRet: { + var indexURL_536871848 = document.getElementById("indexLink").getAttribute("href"); + var rootURL_536871874 = HEX5BHEX5D__pureZstrutils_u1307(cstrToNimstr(indexURL_536871848), HEX2EHEX2E__stdZenumutils_u105(0, 14)); + var resp_536871886 = (await (await fetch(indexURL_536871848)).text()); + var indexElem_536871887 = document.createElement("div"); + indexElem_536871887.innerHTML = resp_536871886; + Label1: { + var href_536871909 = null; + var colontmp__536872169 = []; + colontmp__536872169 = indexElem_536871887.getElementsByClassName("reference"); + var i_536872171 = 0; + var L_536872172 = (colontmp__536872169).length; + Label2: { + Label3: while (true) { + if (!(i_536872171 < L_536872172)) break Label3; + href_536871909 = colontmp__536872169[chckIndx(i_536872171, 0, (colontmp__536872169).length - 1)]; + href_536871909.setAttribute("href", toJSStr((rootURL_536871874).concat(cstrToNimstr(href_536871909.getAttribute("href"))))); + db_536871661[0].push(href_536871909);; + contents_536871662[0].push(href_536871909.getAttribute("data-doc-search-tag"));; + i_536872171 += 1; + if (!(((colontmp__536872169).length == L_536872172))) { + failedAssertImpl__stdZassertions_u84(makeNimstrLit("iterators.nim(254, 11) `len(a) == L` the length of the seq changed while iterating over it")); + } + + } + }; + }; + result_536871842 = undefined; + break BeforeRet; + }; + + return result_536871842; + +} + +function then__dochack_u1106(future_p0, onSuccess_p1, onReject_p2) { + var result_536872024 = null; + + BeforeRet: { + var ret_536872034 = null; + ret_536872034 = future_p0.then(onSuccess_p1, onReject_p2); + result_536872024 = ret_536872034; + break BeforeRet; + }; + + return result_536872024; + +} + +function nsuToLowerAsciiChar(c_p0) { + var result_704643158 = 0; + + if ((ConstSet2[c_p0] != undefined)) { + result_704643158 = (c_p0 ^ 32); + } + else { + result_704643158 = c_p0; + } + + + return result_704643158; + +} + +function fuzzyMatch__fuzzysearch_u16(pattern_p0, str_p1) { + var Temporary4; + var Temporary5; + var Temporary6; + var Temporary7; + var Temporary8; + + var result_687865877 = {Field0: 0, Field1: false}; + + var scoreState_687865878 = (-100); + var headerMatched_687865879 = false; + var unmatchedLeadingCharCount_687865880 = 0; + var consecutiveMatchCount_687865881 = 0; + var strIndex_687865882 = 0; + var patIndex_687865883 = 0; + var score_687865884 = 0; + Label1: { + Label2: while (true) { + if (!((strIndex_687865882 < ((str_p1) == null ? 0 : (str_p1).length)) && (patIndex_687865883 < ((pattern_p0) == null ? 0 : (pattern_p0).length)))) break Label2; + Label3: { + var patternChar_687865887 = nsuToLowerAsciiChar(pattern_p0.charCodeAt(chckIndx(patIndex_687865883, 0, (pattern_p0).length - 1))); + var strChar_687865888 = nsuToLowerAsciiChar(str_p1.charCodeAt(chckIndx(strIndex_687865882, 0, (str_p1).length - 1))); + if ((ConstSet3[patternChar_687865887] != undefined)) { + patIndex_687865883 = addInt(patIndex_687865883, 1); + break Label3; + } + + if ((ConstSet4[strChar_687865888] != undefined)) { + strIndex_687865882 = addInt(strIndex_687865882, 1); + break Label3; + } + + if ((!(headerMatched_687865879) && (strChar_687865888 == 58))) { + headerMatched_687865879 = true; + scoreState_687865878 = (-100); + score_687865884 = ((Math.floor((0.5 * score_687865884))) | 0); + patIndex_687865883 = 0; + strIndex_687865882 = addInt(strIndex_687865882, 1); + break Label3; + } + + if ((strChar_687865888 == patternChar_687865887)) { + switch (scoreState_687865878) { + case (-100): + case 20: + scoreState_687865878 = 10; + break; + case 0: + scoreState_687865878 = 5; + score_687865884 = addInt(score_687865884, scoreState_687865878); + break; + case 10: + case 5: + consecutiveMatchCount_687865881 = addInt(consecutiveMatchCount_687865881, 1); + scoreState_687865878 = 5; + score_687865884 = addInt(score_687865884, mulInt(5, consecutiveMatchCount_687865881)); + if ((scoreState_687865878 == 10)) { + score_687865884 = addInt(score_687865884, 10); + } + + var onBoundary_687865940 = (patIndex_687865883 == ((pattern_p0) == null ? -1 : (pattern_p0).length - 1)); + if ((!(onBoundary_687865940) && (strIndex_687865882 < ((str_p1) == null ? -1 : (str_p1).length - 1)))) { + var nextPatternChar_687865941 = nsuToLowerAsciiChar(pattern_p0.charCodeAt(chckIndx(addInt(patIndex_687865883, 1), 0, (pattern_p0).length - 1))); + var nextStrChar_687865942 = nsuToLowerAsciiChar(str_p1.charCodeAt(chckIndx(addInt(strIndex_687865882, 1), 0, (str_p1).length - 1))); + if (!!((ConstSet5[nextStrChar_687865942] != undefined))) Temporary4 = false; else { Temporary4 = !((nextStrChar_687865942 == nextPatternChar_687865941)); } onBoundary_687865940 = Temporary4; + } + + if (onBoundary_687865940) { + scoreState_687865878 = 20; + score_687865884 = addInt(score_687865884, scoreState_687865878); + } + + break; + case (-1): + case (-3): + if (!((ConstSet6[str_p1.charCodeAt(chckIndx(subInt(strIndex_687865882, 1), 0, (str_p1).length - 1))] != undefined))) Temporary5 = true; else { if (!(ConstSet7[str_p1.charCodeAt(chckIndx(subInt(strIndex_687865882, 1), 0, (str_p1).length - 1))] != undefined)) Temporary6 = false; else { Temporary6 = (ConstSet8[str_p1.charCodeAt(chckIndx(strIndex_687865882, 0, (str_p1).length - 1))] != undefined); } Temporary5 = Temporary6; } var isLeadingChar_687865966 = Temporary5; + if (isLeadingChar_687865966) { + scoreState_687865878 = 10; + } + else { + scoreState_687865878 = 0; + score_687865884 = addInt(score_687865884, scoreState_687865878); + } + + break; + } + patIndex_687865883 = addInt(patIndex_687865883, 1); + } + else { + switch (scoreState_687865878) { + case (-100): + scoreState_687865878 = (-3); + score_687865884 = addInt(score_687865884, scoreState_687865878); + break; + case 5: + scoreState_687865878 = (-1); + score_687865884 = addInt(score_687865884, scoreState_687865878); + consecutiveMatchCount_687865881 = 0; + break; + case (-3): + if ((unmatchedLeadingCharCount_687865880 < 3)) { + scoreState_687865878 = (-3); + score_687865884 = addInt(score_687865884, scoreState_687865878); + } + + unmatchedLeadingCharCount_687865880 = addInt(unmatchedLeadingCharCount_687865880, 1); + break; + default: + scoreState_687865878 = (-1); + score_687865884 = addInt(score_687865884, scoreState_687865878); + break; + } + } + + strIndex_687865882 = addInt(strIndex_687865882, 1); + }; + } + }; + if (!(patIndex_687865883 == ((pattern_p0) == null ? 0 : (pattern_p0).length))) Temporary7 = false; else { if ((strIndex_687865882 == ((str_p1) == null ? 0 : (str_p1).length))) Temporary8 = true; else { Temporary8 = !((ConstSet9[str_p1.charCodeAt(chckIndx(strIndex_687865882, 0, (str_p1).length - 1))] != undefined)); } Temporary7 = Temporary8; } if (Temporary7) { + score_687865884 = addInt(score_687865884, 10); + } + + var colontmp__536872188 = nimMax(0, score_687865884); + var colontmp__536872189 = (0 < score_687865884); + result_687865877 = nimCopy(result_687865877, {Field0: colontmp__536872188, Field1: colontmp__536872189}, NTI687865870); + + return result_687865877; + +} + +function escapeCString__dochack_u751(x_p0, x_p0_Idx) { + var s_536871665 = []; + Label1: { + var c_536871666 = 0; + var iHEX60gensym13_536872192 = 0; + var nHEX60gensym13_536872193 = ((x_p0[x_p0_Idx]) == null ? 0 : (x_p0[x_p0_Idx]).length); + Label2: { + Label3: while (true) { + if (!(iHEX60gensym13_536872192 < nHEX60gensym13_536872193)) break Label3; + c_536871666 = x_p0[x_p0_Idx].charCodeAt(chckIndx(iHEX60gensym13_536872192, 0, (x_p0[x_p0_Idx]).length - 1)); + switch (c_536871666) { + case 60: + s_536871665.push.apply(s_536871665, [38,108,116,59]);; + break; + case 62: + s_536871665.push.apply(s_536871665, [38,103,116,59]);; + break; + default: + addChar(s_536871665, c_536871666);; + break; + } + iHEX60gensym13_536872192 += 1; + } + }; + }; + x_p0[x_p0_Idx] = toJSStr(s_536871665); + + +} + +function dosearch__dochack_u755(value_p0) { + var Temporary5; + +function HEX3Aanonymous__dochack_u783(a_p0, b_p1) { + var result_536871708 = 0; + + result_536871708 = subInt(b_p1["Field1"], a_p0["Field1"]); + + return result_536871708; + +} + + var result_536871669 = null; + + BeforeRet: { + if (((db_536871661[0]).length == 0)) { + break BeforeRet; + } + + var ul_536871673 = tree__dochack_u130("UL", []); + result_536871669 = tree__dochack_u130("DIV", []); + setClass__dochack_u152(result_536871669, "search_results"); + var matches_536871678 = []; + Label1: { + var i_536871686 = 0; + var colontmp__536872179 = 0; + colontmp__536872179 = (db_536871661[0]).length; + var i_536872180 = 0; + Label2: { + Label3: while (true) { + if (!(i_536872180 < colontmp__536872179)) break Label3; + i_536871686 = i_536872180; + Label4: { + var c_536871687 = contents_536871662[0][chckIndx(i_536871686, 0, (contents_536871662[0]).length - 1)]; + if (((c_536871687 == "Examples") || (c_536871687 == "PEG construction"))) { + break Label4; + } + + var tmpTuple_536871688 = fuzzyMatch__fuzzysearch_u16(value_p0, c_536871687); + var score_536871689 = tmpTuple_536871688["Field0"]; + var matched_536871690 = tmpTuple_536871688["Field1"]; + if (matched_536871690) { + matches_536871678.push({Field0: db_536871661[0][chckIndx(i_536871686, 0, (db_536871661[0]).length - 1)], Field1: score_536871689});; + } + + }; + i_536872180 = addInt(i_536872180, 1); + } + }; + }; + Temporary5 = HEX3Aanonymous__dochack_u783.bind(null); Temporary5.ClP_0 = HEX3Aanonymous__dochack_u783; Temporary5.ClE_0 = null; + matches_536871678.sort(Temporary5); + Label6: { + var i_536871725 = 0; + var colontmp__536872183 = 0; + colontmp__536872183 = nimMin((matches_536871678).length, 29); + var i_536872184 = 0; + Label7: { + Label8: while (true) { + if (!(i_536872184 < colontmp__536872183)) break Label8; + i_536871725 = i_536872184; + matches_536871678[chckIndx(i_536871725, 0, (matches_536871678).length - 1)]["Field0"].innerHTML = matches_536871678[chckIndx(i_536871725, 0, (matches_536871678).length - 1)]["Field0"].getAttribute("data-doc-search-tag"); + escapeCString__dochack_u751(matches_536871678[chckIndx(i_536871725, 0, (matches_536871678).length - 1)]["Field0"], "innerHTML"); + add__dochack_u148(ul_536871673, tree__dochack_u130("LI", [matches_536871678[chckIndx(i_536871725, 0, (matches_536871678).length - 1)]["Field0"]])); + i_536872184 = addInt(i_536872184, 1); + } + }; + }; + if ((ul_536871673.childNodes.length == 0)) { + add__dochack_u148(result_536871669, tree__dochack_u130("B", [text__dochack_u155("no search results")])); + } + else { + add__dochack_u148(result_536871669, tree__dochack_u130("B", [text__dochack_u155("search results")])); + add__dochack_u148(result_536871669, ul_536871673); + } + + }; + + return result_536871669; + +} + +function wrapper__dochack_u1091() { + var elem_536872004 = document.getElementById("searchInput"); + var value_536872005 = elem_536872004.value; + if (!((((value_536872005) == null ? 0 : (value_536872005).length) == 0))) { + if ((oldtoc_536871998[0] == null)) { + oldtoc_536871998[0] = document.getElementById("tocRoot"); + } + + var results_536872009 = dosearch__dochack_u755(value_536872005); + replaceById__dochack_u158("tocRoot", results_536872009); + } + else { + if (!((oldtoc_536871998[0] == null))) { + replaceById__dochack_u158("tocRoot", oldtoc_536871998[0]); + } + } + + +} + +function search() { + var Temporary1; + + if ((loadIndexFut_536872001[0] == null)) { + loadIndexFut_536872001[0] = loadIndex__dochack_u928(); + (then__dochack_u1106(loadIndexFut_536872001[0], wrapper__dochack_u1091, null)); + } + + if (!((timer_536871999[0] == null))) { + clearTimeout(timer_536871999[0]); + } + + Temporary1 = wrapper__dochack_u1091.bind(null); Temporary1.ClP_0 = wrapper__dochack_u1091; Temporary1.ClE_0 = null; + timer_536871999[0] = setTimeout(Temporary1, 400); + + +} + +function copyToClipboard() { + + function updatePreTags() { + + const allPreTags = document.querySelectorAll("pre:not(.line-nums)") + + allPreTags.forEach((e) => { + + const div = document.createElement("div") + div.classList.add("copyToClipBoard") + + const preTag = document.createElement("pre") + preTag.innerHTML = e.innerHTML + + const button = document.createElement("button") + button.value = e.textContent.replace('...', '') + button.classList.add("copyToClipBoardBtn") + button.style.cursor = "pointer" + + div.appendChild(preTag) + div.appendChild(button) + + e.outerHTML = div.outerHTML + + }) + } + + + function copyTextToClipboard(e) { + const clipBoardContent = e.target.value + navigator.clipboard.writeText(clipBoardContent).then(function() { + e.target.style.setProperty("--clipboard-image", "var(--clipboard-image-selected)") + }, function(err) { + console.error("Could not copy text: ", err); + }); + } + + window.addEventListener("click", (e) => { + if (e.target.classList.contains("copyToClipBoardBtn")) { + copyTextToClipboard(e) + } + }) + + window.addEventListener("mouseover", (e) => { + if (e.target.nodeName === "PRE") { + e.target.nextElementSibling.style.setProperty("--clipboard-image", "var(--clipboard-image-normal)") + } + }) + + window.addEventListener("DOMContentLoaded", updatePreTags) + + + + +} +var Temporary1; +var Temporary2; +var t_536870951 = window.localStorage.getItem("theme"); +if ((t_536870951 == null)) { +Temporary1 = "auto"; +} +else { +Temporary1 = t_536870951; +} + +setTheme(Temporary1); +var alternative_536871619 = [null]; +var db_536871661 = [[]]; +var contents_536871662 = [[]]; +var oldtoc_536871998 = [null]; +var timer_536871999 = [null]; +var loadIndexFut_536872001 = [null]; +copyToClipboard(); +Temporary2 = onDOMLoaded.bind(null); Temporary2.ClP_0 = onDOMLoaded; Temporary2.ClE_0 = null; +window.addEventListener("DOMContentLoaded", Temporary2, false); diff --git a/dochelpers.html b/dochelpers.html new file mode 100644 index 0000000000000..86e5a5be2b58c --- /dev/null +++ b/dochelpers.html @@ -0,0 +1,252 @@ + + + + + + + +packages/docutils/dochelpers + + + + + + + + + + + + + + + + +
+
+

packages/docutils/dochelpers

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Integration helpers between docgen.nim and rst.nim.

+

Function toLangSymbol(linkText) produces a signature docLink of type LangSymbol in rst.nim, while match(generated, docLink) matches it with generated, produced from PNode by docgen.rst.

+

+ +
+

Types

+
+
+
LangSymbol = object
+  symKind*: string           ## "proc", "const", "type", etc
+  symTypeKind*: string       ## ""|enum|object|tuple -
+                             ## valid only when `symKind == "type"`
+  name*: string              ## plain symbol name without any parameters
+  generics*: string          ## generic parameters (without brackets)
+  isGroup*: bool             ## is LangSymbol a group with overloads?
+  parametersProvided*: bool  ## to disambiguate `proc f`_ and `proc f()`_
+  parameters*: seq[tuple[name: string, `type`: string]] ## name-type seq, e.g. for proc
+  outType*: string           ## result type, e.g. for proc
+
+ + symbol signature in Nim + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(s: LangSymbol): string {....raises: [ValueError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc langSymbolGroup(kind: string; name: string): LangSymbol {.
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc match(generated: LangSymbol; docLink: LangSymbol): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ + Returns true if generated can be a target for docLink. If generated is an overload group then only symKind and name are compared for success. + Source   +Edit   + +
+
+ +
+
+
+
func nimIdentBackticksNormalize(s: string): string {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Normalizes the string s as a Nim identifier.

+

Unlike nimIdentNormalize removes spaces and backticks.

+
Warning: +No checking (e.g. that identifiers cannot start from digits or '_', or that number of backticks is even) is performed.
+ +

Example:

+
doAssert nimIdentBackticksNormalize("Foo_bar") == "Foobar"
+doAssert nimIdentBackticksNormalize("FoO BAr") == "Foobar"
+doAssert nimIdentBackticksNormalize("`Foo BAR`") == "Foobar"
+doAssert nimIdentBackticksNormalize("` Foo BAR `") == "Foobar"
+# not a valid identifier:
+doAssert nimIdentBackticksNormalize("`_x_y`") == "_xy"
+ Source   +Edit   + +
+
+ +
+
+
+
proc toLangSymbol(linkText: PRstNode): LangSymbol {....raises: [ValueError],
+    tags: [], forbids: [].}
+
+ +

Parses linkText into a more structured form using a state machine.

+

This proc is designed to allow link syntax with operators even without escaped backticks inside:

+
`proc *`_
+`proc []`_
+

This proc should be kept in sync with the renderTypes proc from compiler/typesrenderer.nim.

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/dochelpers.idx b/dochelpers.idx new file mode 100644 index 0000000000000..3941839df9352 --- /dev/null +++ b/dochelpers.idx @@ -0,0 +1,7 @@ +nimTitle dochelpers dochelpers.html module packages/docutils/dochelpers 0 +nim LangSymbol dochelpers.html#LangSymbol object LangSymbol 24 +nim `$` dochelpers.html#$,LangSymbol proc `$`(s: LangSymbol): string 39 +nim nimIdentBackticksNormalize dochelpers.html#nimIdentBackticksNormalize,string proc nimIdentBackticksNormalize(s: string): string 45 +nim langSymbolGroup dochelpers.html#langSymbolGroup,string,string proc langSymbolGroup(kind: string; name: string): LangSymbol 81 +nim toLangSymbol dochelpers.html#toLangSymbol,PRstNode proc toLangSymbol(linkText: PRstNode): LangSymbol 87 +nim match dochelpers.html#match,LangSymbol,LangSymbol proc match(generated: LangSymbol; docLink: LangSymbol): bool 257 diff --git a/dollars.html b/dollars.html new file mode 100644 index 0000000000000..8dd0c9f5d1942 --- /dev/null +++ b/dollars.html @@ -0,0 +1,340 @@ + + + + + + + +system/dollars + + + + + + + + + + + + + + + + +
+
+

system/dollars

+
+ +
+ Source   +Edit   + +
+ +

$ is Nim's general way of spelling toString. +

Example:

+
import system/dollars
+assert $0.1 == "0.1"
+assert $(-2*3) == "-6"

+ +
+

Procs

+
+
+
+
proc `$`(t: typedesc): string {.magic: "TypeTrait", ...raises: [], tags: [],
+                                forbids: [].}
+
+ +

Returns the name of the given type.

+

For more procedures dealing with typedesc, see typetraits module.

+

doAssert $(typeof(42)) == "int"
+doAssert $(typeof("Foo")) == "string"
+static: doAssert $(typeof(@['A', 'B'])) == "seq[char]"

+ + Source   +Edit   + +
+
+
+
proc `$`(x: bool): string {.magic: "BoolToStr", noSideEffect, ...raises: [],
+                            tags: [], forbids: [].}
+
+ + The stringify operator for a boolean argument. Returns x converted to the string "false" or "true". + Source   +Edit   + +
+
+
+
proc `$`(x: char): string {.magic: "CharToStr", noSideEffect, ...raises: [],
+                            tags: [], forbids: [].}
+
+ +

The stringify operator for a character argument. Returns x converted to a string.

+

assert $'c' == "c"

+ + Source   +Edit   + +
+
+
+
proc `$`(x: cstring): string {.magic: "CStrToStr", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + The stringify operator for a CString argument. Returns x converted to a string. + Source   +Edit   + +
+
+
+
proc `$`(x: int): string {....raises: [], tags: [], forbids: [].}
+
+ + Outplace version of addInt. + Source   +Edit   + +
+
+
+
proc `$`(x: int64): string {....raises: [], tags: [], forbids: [].}
+
+ + Outplace version of addInt. + Source   +Edit   + +
+
+
+
proc `$`(x: string): string {.magic: "StrToStr", noSideEffect, ...raises: [],
+                              tags: [], forbids: [].}
+
+ + The stringify operator for a string argument. Returns x as it is. This operator is useful for generic code, so that $expr also works if expr is already a string. + Source   +Edit   + +
+
+
+
proc `$`(x: uint64): string {....raises: [], tags: [], forbids: [].}
+
+ + Outplace version of addInt. + Source   +Edit   + +
+
+
+
func `$`(x`gensym0: `{}`(int, lit)): string {.compileTime, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `$`(x`gensym1: `{}`(uint64, lit)): string {.compileTime, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `$`(x`gensym2: `{}`(int64, lit)): string {.compileTime, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `$`[Enum: enum](x: Enum): string {.magic: "EnumToStr", noSideEffect,
+                                        ...raises: [], tags: [], forbids: [].}
+
+ +

The stringify operator for an enumeration argument. This works for any enumeration type thanks to compiler magic.

+

If a $ operator for a concrete enumeration is provided, this is used instead. (In other words: Overwriting is possible.)

+ + Source   +Edit   + +
+
+
+
proc `$`[T, IDX](x: array[IDX, T]): string
+
+ + Generic $ operator for arrays that is lifted from the components. + Source   +Edit   + +
+
+
+
proc `$`[T, U](x: HSlice[T, U]): string
+
+ +

Generic $ operator for slices that is lifted from the components of x. Example:

+

$(1 .. 5) == "1 .. 5"

+ + Source   +Edit   + +
+
+
+
proc `$`[T: tuple](x: T): string
+
+ +

Generic $ operator for tuples that is lifted from the components of x. Example:

+

$(23, 45) == "(23, 45)"
+$(a: 23, b: 45) == "(a: 23, b: 45)"
+$() == "()"

+ + Source   +Edit   + +
+
+
+
proc `$`[T](x: openArray[T]): string
+
+ +

Generic $ operator for openarrays that is lifted from the components of x. Example:

+

$(@[23, 45].toOpenArray(0, 1)) == "[23, 45]"

+ + Source   +Edit   + +
+
+
+
proc `$`[T](x: seq[T]): string
+
+ +

Generic $ operator for seqs that is lifted from the components of x. Example:

+

$(@[23, 45]) == "@[23, 45]"

+ + Source   +Edit   + +
+
+
+
proc `$`[T](x: set[T]): string
+
+ +

Generic $ operator for sets that is lifted from the components of x. Example:

+

${23, 45} == "{23, 45}"

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/dollars.idx b/dollars.idx new file mode 100644 index 0000000000000..63ec910e4fd06 --- /dev/null +++ b/dollars.idx @@ -0,0 +1,21 @@ +nimTitle dollars dollars.html module system/dollars 0 +nim `$` dollars.html#$,int proc `$`(x: int): string 16 +nim `$` dollars.html#$,int64 proc `$`(x: int64): string 20 +nim `$` dollars.html#$,uint64 proc `$`(x: uint64): string 24 +nim `$` dollars.html#$ proc `$`(x`gensym0: `{}`(int, lit)): string 32 +nim `$` dollars.html#$_2 proc `$`(x`gensym1: `{}`(uint64, lit)): string 33 +nim `$` dollars.html#$_3 proc `$`(x`gensym2: `{}`(int64, lit)): string 34 +nim `$` dollars.html#$,bool proc `$`(x: bool): string 37 +nim `$` dollars.html#$,char proc `$`(x: char): string 41 +nim `$` dollars.html#$,cstring proc `$`(x: cstring): string 48 +nim `$` dollars.html#$,string proc `$`(x: string): string 52 +nim `$` dollars.html#$,Enum proc `$`[Enum: enum](x: Enum): string 57 +nim `$` dollars.html#$,typedesc proc `$`(t: typedesc): string 64 +nim `$` dollars.html#$,T proc `$`[T: tuple](x: T): string 76 +nim `$` dollars.html#$,set[T] proc `$`[T](x: set[T]): string 109 +nim `$` dollars.html#$,seq[T] proc `$`[T](x: seq[T]): string 117 +nim `$` dollars.html#$,HSlice[T,U] proc `$`[T, U](x: HSlice[T, U]): string 125 +nim `$` dollars.html#$,array[IDX,T] proc `$`[T, IDX](x: array[IDX, T]): string 137 +nim `$` dollars.html#$,openArray[T] proc `$`[T](x: openArray[T]): string 141 +idx toString dollars.html#tostring_1 Module dollars 0 +nimgrp $ dollars.html#$-procs-all proc 16 diff --git a/dom.html b/dom.html new file mode 100644 index 0000000000000..ff8eddf58cccc --- /dev/null +++ b/dom.html @@ -0,0 +1,6583 @@ + + + + + + + +std/dom + + + + + + + + + + + + + + + + +
+
+

std/dom

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Declaration of the Document Object Model for the JavaScript backend. +

Document Ready

  • Basic example of a document ready:
  • +
+ +

Example: cmd: -b:js -r:off

+
import std/dom
+proc example(e: Event) = echo "Document is ready"
+document.addEventListener("DOMContentLoaded", example)  # You can also use "load" event.
  • This example runs 5 seconds after the document ready:
  • +
+ +

Example: cmd: -b:js -r:off

+
import std/dom
+proc example() = echo "5 seconds after document ready"
+proc domReady(e: Event) = discard setTimeout(example, 5_000) # Document is ready.
+document.addEventListener("DOMContentLoaded", domReady)
+

Document onUnload

  • Simple example of how to implement code that runs when the page unloads:
  • +
+ +

Example: cmd: -b:js -r:off

+
import std/dom
+proc example(e: Event) = echo "Document is unloaded"
+document.addEventListener("unload", example)  # You can also use "beforeunload".
+

Document Autorefresh

  • Minimal example of a document autorefresh:
  • +
+ +

Example: cmd: -b:js -r:off

+
import std/dom
+proc example() = window.location.reload()
+discard setTimeout(example, 5_000)
+

+
+

Imports

+
+ since +
+
+
+

Types

+
+
+
AddEventListenerOptions = object
+  capture*: bool
+  once*: bool
+  passive*: bool
+
+ + + Source   +Edit   + +
+
+
+
AnchorElement {.importc.} = ref object of Element
+  text*: cstring
+  x*, y*: int
+
+ + + Source   +Edit   + +
+
+
+
Blob {.importc.} = ref object of RootObj
+  size*: int
+
+ + see docs + Source   +Edit   + +
+
+
+
BoundingRect {.importc.} = object
+  top*, bottom*, left*, right*, x*, y*, width*, height*: float
+
+ + + Source   +Edit   + +
+
+
+
ClassList {.importc.} = ref object of RootObj
+
+ + + Source   +Edit   + +
+
+
+
ClipboardEvent {.importc.} = object of Event
+  clipboardData*: DataTransfer
+
+ + see docs + Source   +Edit   + +
+
+
+
DataTransfer {.importc.} = ref object of RootObj
+  dropEffect*: cstring
+  effectAllowed*: cstring
+  files*: seq[Element]
+  items*: seq[DataTransferItem]
+  types*: seq[cstring]
+
+ + see docs + Source   +Edit   + +
+
+
+
DataTransferDropEffect {.pure.} = enum
+  None = "none", Copy = "copy", Link = "link", Move = "move"
+
+ + + Source   +Edit   + +
+
+
+
DataTransferEffectAllowed {.pure.} = enum
+  None = "none", Copy = "copy", CopyLink = "copyLink", CopyMove = "copyMove",
+  Link = "link", LinkMove = "linkMove", Move = "move", All = "all",
+  Uninitialized = "uninitialized"
+
+ + + Source   +Edit   + +
+
+
+
DataTransferItem {.importc.} = ref object of RootObj
+  kind*: cstring
+
+ + see docs + Source   +Edit   + +
+
+
+
DataTransferItemKind {.pure.} = enum
+  File = "file", String = "string"
+
+ + + Source   +Edit   + +
+
+
+
Document {.importc.} = ref object of Node
+  activeElement*: Element
+  documentElement*: Element
+  alinkColor*: cstring
+  bgColor*: cstring
+  body*: Element
+  charset*: cstring
+  cookie*: cstring
+  defaultCharset*: cstring
+  fgColor*: cstring
+  head*: Element
+  hidden*: bool
+  lastModified*: cstring
+  linkColor*: cstring
+  referrer*: cstring
+  title*: cstring
+  URL*: cstring
+  visibilityState*: cstring
+  vlinkColor*: cstring
+  anchors*: seq[AnchorElement]
+  forms*: seq[FormElement]
+  images*: seq[ImageElement]
+  applets*: seq[Element]
+  embeds*: seq[EmbedElement]
+  links*: seq[LinkElement]
+  fonts*: FontFaceSet
+
+ + + Source   +Edit   + +
+
+
+
DocumentOrShadowRoot {.importc.} = object of RootObj
+  activeElement*: Element
+
+ + + Source   +Edit   + +
+
+
+
DomEvent {.pure.} = enum
+  Abort = "abort", BeforeInput = "beforeinput", Blur = "blur", Click = "click",
+  CompositionEnd = "compositionend", CompositionStart = "compositionstart",
+  CompositionUpdate = "compositionupdate", DblClick = "dblclick",
+  Error = "error", Focus = "focus", FocusIn = "focusin", FocusOut = "focusout",
+  Input = "input", KeyDown = "keydown", KeyPress = "keypress", KeyUp = "keyup",
+  Load = "load", MouseDown = "mousedown", MouseEnter = "mouseenter",
+  MouseLeave = "mouseleave", MouseMove = "mousemove", MouseOut = "mouseout",
+  MouseOver = "mouseover", MouseUp = "mouseup", Resize = "resize",
+  Scroll = "scroll", Select = "select", Storage = "storage", Unload = "unload",
+  Wheel = "wheel"
+
+ + see docs + Source   +Edit   + +
+
+
+
DomException {.importc.} = ref object
+
+ + The DOMException interface represents an abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. Each exception has a name, which is a short "CamelCase" style string identifying the error or abnormal condition. https://developer.mozilla.org/en-US/docs/Web/API/DOMException + Source   +Edit   + +
+
+
+
DomParser = ref object
+
+ + DOM Parser object (defined on browser only, may not be on NodeJS). + + Source   +Edit   + +
+
+
+
DragEvent {.importc.} = object of MouseEvent
+  dataTransfer*: DataTransfer
+
+ + see docs + Source   +Edit   + +
+
+
+
DragEventTypes = enum
+  Drag = "drag", DragEnd = "dragend", DragEnter = "dragenter",
+  DragExit = "dragexit", DragLeave = "dragleave", DragOver = "dragover",
+  DragStart = "dragstart", Drop = "drop"
+
+ + + Source   +Edit   + +
+
+
+
Element {.importc.} = ref object of Node
+  className*: cstring
+  classList*: ClassList
+  checked*: bool
+  defaultChecked*: bool
+  defaultValue*: cstring
+  disabled*: bool
+  form*: FormElement
+  name*: cstring
+  readOnly*: bool
+  options*: seq[OptionElement]
+  selectedOptions*: seq[OptionElement]
+  clientWidth*, clientHeight*: int
+  contentEditable*: cstring
+  isContentEditable*: bool
+  dir*: cstring
+  offsetHeight*: int
+  offsetWidth*: int
+  offsetLeft*: int
+  offsetTop*: int
+
+ + + Source   +Edit   + +
+
+
+
EmbedElement {.importc.} = ref object of Element
+  height*: int
+  hspace*: int
+  src*: cstring
+  width*: int
+  vspace*: int
+
+ + + Source   +Edit   + +
+
+
+
Event {.importc.} = ref object of RootObj
+  bubbles*: bool
+  cancelBubble*: bool
+  cancelable*: bool
+  composed*: bool
+  currentTarget*: Node
+  defaultPrevented*: bool
+  eventPhase*: int
+  target*: Node
+  isTrusted*: bool
+
+ + see docs + Source   +Edit   + +
+
+
+
EventPhase = enum
+  None = 0, CapturingPhase, AtTarget, BubblingPhase
+
+ + + Source   +Edit   + +
+
+
+
EventTarget {.importc.} = ref object of RootObj
+  onabort*: proc (event: Event) {.closure.}
+  onblur*: proc (event: Event) {.closure.}
+  onchange*: proc (event: Event) {.closure.}
+  onclick*: proc (event: Event) {.closure.}
+  ondblclick*: proc (event: Event) {.closure.}
+  onerror*: proc (event: Event) {.closure.}
+  onfocus*: proc (event: Event) {.closure.}
+  onkeydown*: proc (event: Event) {.closure.}
+  onkeypress*: proc (event: Event) {.closure.}
+  onkeyup*: proc (event: Event) {.closure.}
+  onload*: proc (event: Event) {.closure.}
+  onmousedown*: proc (event: Event) {.closure.}
+  onmousemove*: proc (event: Event) {.closure.}
+  onmouseout*: proc (event: Event) {.closure.}
+  onmouseover*: proc (event: Event) {.closure.}
+  onmouseup*: proc (event: Event) {.closure.}
+  onreset*: proc (event: Event) {.closure.}
+  onselect*: proc (event: Event) {.closure.}
+  onstorage*: proc (event: Event) {.closure.}
+  onsubmit*: proc (event: Event) {.closure.}
+  onunload*: proc (event: Event) {.closure.}
+  onloadstart*: proc (event: Event) {.closure.}
+  onprogress*: proc (event: Event) {.closure.}
+  onloadend*: proc (event: Event) {.closure.}
+
+ + + Source   +Edit   + +
+
+
+
File {.importc.} = ref object of Blob
+  lastModified*: int
+  name*: cstring
+
+ + see docs + Source   +Edit   + +
+
+
+
FileReader {.importc.} = ref object of EventTarget
+
+ + The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. https://developer.mozilla.org/en-US/docs/Web/API/FileReader + Source   +Edit   + +
+
+
+
FileReaderState = distinct range[0'u16 .. 2'u16]
+
+ + + Source   +Edit   + +
+
+
+
FontFaceSet {.importc.} = ref object
+  ready*: FontFaceSetReady
+  onloadingdone*: proc (event: Event)
+
+ + see: docs + Source   +Edit   + +
+
+
+
FontFaceSetReady {.importc.} = ref object
+  then*: proc (cb: proc ())
+
+ + see: docs + Source   +Edit   + +
+
+
+
FormElement {.importc.} = ref object of Element
+  acceptCharset*: cstring
+  action*: cstring
+  autocomplete*: cstring
+  elements*: seq[Element]
+  encoding*: cstring
+  enctype*: cstring
+  length*: int
+  noValidate*: bool
+  target*: cstring
+
+ + see docs + Source   +Edit   + +
+
+
+
Frame {.importc.} = ref object of Window
+
+ + + Source   +Edit   + +
+
+
+
History {.importc.} = ref object of RootObj
+  length*: int
+
+ + + Source   +Edit   + +
+
+
+
HTMLSlotElement {.importc.} = ref object of RootObj
+  name*: cstring
+
+ + + Source   +Edit   + +
+
+
+
ImageElement {.importc.} = ref object of Element
+  border*: int
+  complete*: bool
+  height*: int
+  hspace*: int
+  lowsrc*: cstring
+  src*: cstring
+  vspace*: int
+  width*: int
+
+ + + Source   +Edit   + +
+
+
+
InputElement {.importc.} = ref object of Element
+  formAction*: cstring
+  formEncType*: cstring
+  formMethod*: cstring
+  formNoValidate*: bool
+  formTarget*: cstring
+  autofocus*: bool
+  required*: bool
+  value*: cstring
+  validity*: ValidityState
+  validationMessage*: cstring
+  willValidate*: bool
+  indeterminate*: bool
+  alt*: cstring
+  height*: cstring
+  src*: cstring
+  width*: cstring
+  accept*: cstring
+  files*: seq[Blob]
+  autocomplete*: cstring
+  maxLength*: int
+  size*: int
+  pattern*: cstring
+  placeholder*: cstring
+  min*: cstring
+  max*: cstring
+  selectionStart*: int
+  selectionEnd*: int
+  selectionDirection*: cstring
+  dirName*: cstring
+  accessKey*: cstring
+  list*: Element
+  multiple*: bool
+  labels*: seq[Element]
+  step*: cstring
+  valueAsDate*: cstring
+  valueAsNumber*: float
+
+ + see docs + Source   +Edit   + +
+
+
+
Interval {.importc.} = ref object of RootObj
+
+ + + Source   +Edit   + +
+
+
+
KeyboardEvent {.importc.} = ref object of UIEvent
+  altKey*, ctrlKey*, metaKey*, shiftKey*: bool
+  code*: cstring
+  isComposing*: bool
+  key*: cstring
+  keyCode*: int
+  location*: int
+
+ + see docs + Source   +Edit   + +
+
+
+
KeyboardEventKey {.pure.} = enum
+  Alt, AltGraph, CapsLock, Control, Fn, FnLock, Hyper, Meta, NumLock,
+  ScrollLock, Shift, Super, Symbol, SymbolLock, ArrowDown, ArrowLeft,
+  ArrowRight, ArrowUp, End, Home, PageDown, PageUp, Backspace, Clear, Copy,
+  CrSel, Cut, Delete, EraseEof, ExSel, Insert, Paste, Redo, Undo, Accept, Again,
+  Attn, Cancel, ContextMenu, Escape, Execute, Find, Finish, Help, Pause, Play,
+  Props, Select, ZoomIn, ZoomOut, BrigtnessDown, BrigtnessUp, Eject, LogOff,
+  Power, PowerOff, PrintScreen, Hibernate, Standby, WakeUp, AllCandidates,
+  Alphanumeric, CodeInput, Compose, Convert, Dead, FinalMode, GroupFirst,
+  GroupLast, GroupNext, GroupPrevious, ModeChange, NextCandidate, NonConvert,
+  PreviousCandidate, Process, SingleCandidate, HangulMode, HanjaMode, JunjaMode,
+  Eisu, Hankaku, Hiragana, HiraganaKatakana, KanaMode, KanjiMode, Katakana,
+  Romaji, Zenkaku, ZenkakuHanaku, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11,
+  F12, F13, F14, F15, F16, F17, F18, F19, F20, Soft1, Soft2, Soft3, Soft4,
+  AppSwitch, Call, Camera, CameraFocus, EndCall, GoBack, GoHome, HeadsetHook,
+  LastNumberRedial, Notification, MannerMode, VoiceDial, ChannelDown, ChannelUp,
+  MediaFastForward, MediaPause, MediaPlay, MediaPlayPause, MediaRecord,
+  MediaRewind, MediaStop, MediaTrackNext, MediaTrackPrevious, AudioBalanceLeft,
+  AudioBalanceRight, AudioBassDown, AudioBassBoostDown, AudioBassBoostToggle,
+  AudioBassBoostUp, AudioBassUp, AudioFaderFront, AudioFaderRear,
+  AudioSurroundModeNext, AudioTrebleDown, AudioTrebleUp, AudioVolumeDown,
+  AUdioVolumeMute, AudioVolumeUp, MicrophoneToggle, MicrophoneVolumeDown,
+  MicrophoneVolumeMute, MicrophoneVolumeUp, TV, TV3DMode, TVAntennaCable,
+  TVAudioDescription, TVAudioDescriptionMixDown, TVAudioDescriptionMixUp,
+  TVContentsMenu, TVDataService, TVInput, TVInputComponent1, TVInputComponent2,
+  TVInputComposite1, TVInputComposite2, TVInputHDMI1, TVInputHDMI2,
+  TVInputHDMI3, TVInputHDMI4, TVInputVGA1, TVMediaContext, TVNetwork,
+  TVNumberEntry, TVPower, TVRadioService, TVSatellite, TVSatelliteBS,
+  TVSatelliteCS, TVSatelliteToggle, TVTerrestrialAnalog, TVTerrestrialDigital,
+  TVTimer, AVRInput, AVRPower, ColorF0Red, ColorF1Green, ColorF2Yellow,
+  ColorF3Blue, ColorF4Grey, ColorF5Brown, ClosedCaptionToggle, Dimmer,
+  DisplaySwap, DVR, Exit, FavoriteClear0, FavoriteClear1, FavoriteClear2,
+  FavoriteClear3, FavoriteRecall0, FavoriteRecall1, FavoriteRecall2,
+  FavoriteRecall3, FavoriteStore0, FavoriteStore1, FavoriteStore2,
+  FavoriteStore3, Guide, GuideNextDay, GuidePreviousDay, Info, InstantReplay,
+  Link, ListProgram, LiveContent, Lock, MediaApps, MediaAudioTrack, MediaLast,
+  MediaSkipBackward, MediaSkipForward, MediaStepBackward, MediaStepForward,
+  MediaTopMenu, NavigateIn, NavigateNext, NavigateOut, NavigatePrevious,
+  NextFavoriteChannel, NextUserProfile, OnDemand, Pairing, PinPDown, PinPMove,
+  PinPUp, PlaySpeedDown, PlaySpeedReset, PlaySpeedUp, RandomToggle,
+  RcLowBattery, RecordSpeedNext, RfBypass, ScanChannelsToggle, ScreenModeNext,
+  Settings, SplitScreenToggle, STBInput, STBPower, Subtitle, Teletext,
+  VideoModeNext, Wink, ZoomToggle, SpeechCorrectionList, SpeechInputToggle,
+  Close, New, Open, Print, Save, SpellCheck, MailForward, MailReply, MailSend,
+  LaunchCalculator, LaunchCalendar, LaunchContacts, LaunchMail,
+  LaunchMediaPlayer, LaunchMusicPlayer, LaunchMyComputer, LaunchPhone,
+  LaunchScreenSaver, LaunchSpreadsheet, LaunchWebBrowser, LaunchWebCam,
+  LaunchWordProcessor, LaunchApplication1, LaunchApplication2,
+  LaunchApplication3, LaunchApplication4, LaunchApplication5,
+  LaunchApplication6, LaunchApplication7, LaunchApplication8,
+  LaunchApplication9, LaunchApplication10, LaunchApplication11,
+  LaunchApplication12, LaunchApplication13, LaunchApplication14,
+  LaunchApplication15, LaunchApplication16, BrowserBack, BrowserFavorites,
+  BrowserForward, BrowserHome, BrowserRefresh, BrowserSearch, BrowserStop,
+  Key11, Key12, Separator
+
+ + see docs + Source   +Edit   + +
+
+
+
LinkElement {.importc.} = ref object of Element
+  target*: cstring
+  text*: cstring
+  x*: int
+  y*: int
+
+ + + Source   +Edit   + +
+
+
+
Location {.importc.} = ref object of RootObj
+  hash*: cstring
+  host*: cstring
+  hostname*: cstring
+  href*: cstring
+  pathname*: cstring
+  port*: cstring
+  protocol*: cstring
+  search*: cstring
+  origin*: cstring
+
+ + + Source   +Edit   + +
+
+
+
LocationBar {.importc.} = object of RootObj
+  visible*: bool
+
+ + + Source   +Edit   + +
+
+
+
MediaQueryList {.importc.} = ref object of EventTarget
+  matches*: bool
+  media*: cstring
+
+ + + Source   +Edit   + +
+
+ +
+
MimeType {.importc.} = object of RootObj
+  description*: cstring
+  enabledPlugin*: ref Plugin
+  suffixes*: seq[cstring]
+
+ + + Source   +Edit   + +
+
+
+
MouseButtons = enum
+  NoButton = 0, PrimaryButton = 1, SecondaryButton = 2, AuxilaryButton = 4,
+  FourthButton = 8, FifthButton = 16
+
+ + + Source   +Edit   + +
+
+
+
MouseEvent {.importc.} = ref object of UIEvent
+  altKey*, ctrlKey*, metaKey*, shiftKey*: bool
+  button*: int
+  buttons*: int
+  clientX*, clientY*: int
+  movementX*, movementY*: int
+  offsetX*, offsetY*: int
+  pageX*, pageY*: int
+  relatedTarget*: EventTarget
+  screenX*, screenY*: int
+  x*, y*: int
+
+ + see docs + Source   +Edit   + +
+
+ +
+
Node {.importc.} = ref object of EventTarget
+  attributes*: seq[Node]
+  childNodes*: seq[Node]
+  children*: seq[Node]
+  data*: cstring
+  firstChild*: Node
+  lastChild*: Node
+  nextSibling*: Node
+  nodeName*: cstring
+  nodeType*: NodeType
+  nodeValue*: cstring
+  parentNode*: Node
+  content*: Node
+  previousSibling*: Node
+  ownerDocument*: Document
+  innerHTML*: cstring
+  outerHTML*: cstring
+  innerText*: cstring
+  textContent*: cstring
+  style*: Style
+  baseURI*: cstring
+  parentElement*: Element
+  isConnected*: bool
+
+ + + Source   +Edit   + +
+
+
+
NodeType = enum
+  ElementNode = 1, AttributeNode, TextNode, CDATANode, EntityRefNode,
+  EntityNode, ProcessingInstructionNode, CommentNode, DocumentNode,
+  DocumentTypeNode, DocumentFragmentNode, NotationNode
+
+ + + Source   +Edit   + +
+
+
+
OptionElement {.importc.} = ref object of Element
+  defaultSelected*: bool
+  selected*: bool
+  selectedIndex*: int
+  text*: cstring
+  value*: cstring
+
+ + + Source   +Edit   + +
+
+
+
Performance {.importc.} = ref object
+  memory*: PerformanceMemory
+  timing*: PerformanceTiming
+
+ + + Source   +Edit   + +
+
+
+
PerformanceMemory {.importc.} = ref object
+  jsHeapSizeLimit*: float
+  totalJSHeapSize*: float
+  usedJSHeapSize*: float
+
+ + + Source   +Edit   + +
+
+
+
PerformanceTiming {.importc.} = ref object
+  connectStart*: float
+  domComplete*: float
+  domContentLoadedEventEnd*: float
+  domContentLoadedEventStart*: float
+  domInteractive*: float
+  domLoading*: float
+  domainLookupEnd*: float
+  domainLookupStart*: float
+  fetchStart*: float
+  loadEventEnd*: float
+  loadEventStart*: float
+  navigationStart*: float
+  redirectEnd*: float
+  redirectStart*: float
+  requestStart*: float
+  responseEnd*: float
+  responseStart*: float
+  secureConnectionStart*: float
+  unloadEventEnd*: float
+  unloadEventStart*: float
+
+ + + Source   +Edit   + +
+
+
+
PersonalBar = LocationBar
+
+ + + Source   +Edit   + +
+
+
+
Plugin {.importc.} = object of RootObj
+  description*: cstring
+  filename*: cstring
+  name*: cstring
+
+ + + Source   +Edit   + +
+
+
+
Range {.importc.} = ref object
+  collapsed*: bool
+  commonAncestorContainer*: Node
+  endContainer*: Node
+  endOffset*: int
+  startContainer*: Node
+  startOffset*: int
+
+ + see docs + Source   +Edit   + +
+
+
+
RootNodeOptions = object of RootObj
+  composed*: bool
+
+ + + Source   +Edit   + +
+
+
+
Screen {.importc.} = ref object of RootObj
+  availHeight*: int
+  availWidth*: int
+  colorDepth*: int
+  height*: int
+  pixelDepth*: int
+  width*: int
+
+ + + Source   +Edit   + +
+
+
+
ScrollBars = LocationBar
+
+ + + Source   +Edit   + +
+
+
+
ScrollIntoViewOptions = object
+  behavior*: cstring
+  inline*: cstring
+
+ + + Source   +Edit   + +
+
+
+
Selection {.importc.} = ref object
+  anchorNode*: Node
+  anchorOffset*: int
+  focusNode*: Node
+  focusOffset*: int
+  isCollapsed*: bool
+  rangeCount*: int
+
+ + see docs + Source   +Edit   + +
+
+
+
ShadowRoot {.importc.} = ref object of DocumentOrShadowRoot
+  delegatesFocus*: bool
+  host*: Element
+  innerHTML*: cstring
+  mode*: cstring
+
+ + + Source   +Edit   + +
+
+
+
ShadowRootInit = object of RootObj
+  mode*: cstring
+  delegatesFocus*: bool
+
+ + + Source   +Edit   + +
+
+
+
SlotOptions = object of RootObj
+  flatten*: bool
+
+ + + Source   +Edit   + +
+
+
+
StatusBar = LocationBar
+
+ + + Source   +Edit   + +
+
+
+
Storage {.importc.} = ref object
+
+ + + Source   +Edit   + +
+
+
+
StorageEvent {.importc.} = ref object of Event
+  key*: cstring
+  newValue*, oldValue*: cstring
+  storageArea*: Storage
+  url*: cstring
+
+ + see docs + Source   +Edit   + +
+
+
+
Style {.importc.} = ref object of RootObj
+  alignContent*: cstring
+  alignItems*: cstring
+  alignSelf*: cstring
+  all*: cstring
+  animation*: cstring
+  animationDelay*: cstring
+  animationDirection*: cstring
+  animationDuration*: cstring
+  animationFillMode*: cstring
+  animationIterationCount*: cstring
+  animationName*: cstring
+  animationPlayState*: cstring
+  animationTimingFunction*: cstring
+  backdropFilter*: cstring
+  backfaceVisibility*: cstring
+  background*: cstring
+  backgroundAttachment*: cstring
+  backgroundBlendMode*: cstring
+  backgroundClip*: cstring
+  backgroundColor*: cstring
+  backgroundImage*: cstring
+  backgroundOrigin*: cstring
+  backgroundPosition*: cstring
+  backgroundRepeat*: cstring
+  backgroundSize*: cstring
+  blockSize*: cstring
+  border*: cstring
+  borderBlock*: cstring
+  borderBlockColor*: cstring
+  borderBlockEnd*: cstring
+  borderBlockEndColor*: cstring
+  borderBlockEndStyle*: cstring
+  borderBlockEndWidth*: cstring
+  borderBlockStart*: cstring
+  borderBlockStartColor*: cstring
+  borderBlockStartStyle*: cstring
+  borderBlockStartWidth*: cstring
+  borderBlockStyle*: cstring
+  borderBlockWidth*: cstring
+  borderBottom*: cstring
+  borderBottomColor*: cstring
+  borderBottomLeftRadius*: cstring
+  borderBottomRightRadius*: cstring
+  borderBottomStyle*: cstring
+  borderBottomWidth*: cstring
+  borderCollapse*: cstring
+  borderColor*: cstring
+  borderEndEndRadius*: cstring
+  borderEndStartRadius*: cstring
+  borderImage*: cstring
+  borderImageOutset*: cstring
+  borderImageRepeat*: cstring
+  borderImageSlice*: cstring
+  borderImageSource*: cstring
+  borderImageWidth*: cstring
+  borderInline*: cstring
+  borderInlineColor*: cstring
+  borderInlineEnd*: cstring
+  borderInlineEndColor*: cstring
+  borderInlineEndStyle*: cstring
+  borderInlineEndWidth*: cstring
+  borderInlineStart*: cstring
+  borderInlineStartColor*: cstring
+  borderInlineStartStyle*: cstring
+  borderInlineStartWidth*: cstring
+  borderInlineStyle*: cstring
+  borderInlineWidth*: cstring
+  borderLeft*: cstring
+  borderLeftColor*: cstring
+  borderLeftStyle*: cstring
+  borderLeftWidth*: cstring
+  borderRadius*: cstring
+  borderRight*: cstring
+  borderRightColor*: cstring
+  borderRightStyle*: cstring
+  borderRightWidth*: cstring
+  borderSpacing*: cstring
+  borderStartEndRadius*: cstring
+  borderStartStartRadius*: cstring
+  borderStyle*: cstring
+  borderTop*: cstring
+  borderTopColor*: cstring
+  borderTopLeftRadius*: cstring
+  borderTopRightRadius*: cstring
+  borderTopStyle*: cstring
+  borderTopWidth*: cstring
+  borderWidth*: cstring
+  bottom*: cstring
+  boxDecorationBreak*: cstring
+  boxShadow*: cstring
+  boxSizing*: cstring
+  breakAfter*: cstring
+  breakBefore*: cstring
+  breakInside*: cstring
+  captionSide*: cstring
+  caretColor*: cstring
+  clear*: cstring
+  clip*: cstring
+  clipPath*: cstring
+  color*: cstring
+  colorAdjust*: cstring
+  columnCount*: cstring
+  columnFill*: cstring
+  columnGap*: cstring
+  columnRule*: cstring
+  columnRuleColor*: cstring
+  columnRuleStyle*: cstring
+  columnRuleWidth*: cstring
+  columnSpan*: cstring
+  columnWidth*: cstring
+  columns*: cstring
+  contain*: cstring
+  content*: cstring
+  counterIncrement*: cstring
+  counterReset*: cstring
+  counterSet*: cstring
+  cursor*: cstring
+  direction*: cstring
+  display*: cstring
+  emptyCells*: cstring
+  filter*: cstring
+  flex*: cstring
+  flexBasis*: cstring
+  flexDirection*: cstring
+  flexFlow*: cstring
+  flexGrow*: cstring
+  flexShrink*: cstring
+  flexWrap*: cstring
+  cssFloat*: cstring
+  font*: cstring
+  fontFamily*: cstring
+  fontFeatureSettings*: cstring
+  fontKerning*: cstring
+  fontLanguageOverride*: cstring
+  fontOpticalSizing*: cstring
+  fontSize*: cstring
+  fontSizeAdjust*: cstring
+  fontStretch*: cstring
+  fontStyle*: cstring
+  fontSynthesis*: cstring
+  fontVariant*: cstring
+  fontVariantAlternates*: cstring
+  fontVariantCaps*: cstring
+  fontVariantEastAsian*: cstring
+  fontVariantLigatures*: cstring
+  fontVariantNumeric*: cstring
+  fontVariantPosition*: cstring
+  fontVariationSettings*: cstring
+  fontWeight*: cstring
+  gap*: cstring
+  grid*: cstring
+  gridArea*: cstring
+  gridAutoColumns*: cstring
+  gridAutoFlow*: cstring
+  gridAutoRows*: cstring
+  gridColumn*: cstring
+  gridColumnEnd*: cstring
+  gridColumnStart*: cstring
+  gridRow*: cstring
+  gridRowEnd*: cstring
+  gridRowStart*: cstring
+  gridTemplate*: cstring
+  gridTemplateAreas*: cstring
+  gridTemplateColumns*: cstring
+  gridTemplateRows*: cstring
+  hangingPunctuation*: cstring
+  height*: cstring
+  hyphens*: cstring
+  imageOrientation*: cstring
+  imageRendering*: cstring
+  inlineSize*: cstring
+  inset*: cstring
+  insetBlock*: cstring
+  insetBlockEnd*: cstring
+  insetBlockStart*: cstring
+  insetInline*: cstring
+  insetInlineEnd*: cstring
+  insetInlineStart*: cstring
+  isolation*: cstring
+  justifyContent*: cstring
+  justifyItems*: cstring
+  justifySelf*: cstring
+  left*: cstring
+  letterSpacing*: cstring
+  lineBreak*: cstring
+  lineHeight*: cstring
+  listStyle*: cstring
+  listStyleImage*: cstring
+  listStylePosition*: cstring
+  listStyleType*: cstring
+  margin*: cstring
+  marginBlock*: cstring
+  marginBlockEnd*: cstring
+  marginBlockStart*: cstring
+  marginBottom*: cstring
+  marginInline*: cstring
+  marginInlineEnd*: cstring
+  marginInlineStart*: cstring
+  marginLeft*: cstring
+  marginRight*: cstring
+  marginTop*: cstring
+  mask*: cstring
+  maskBorder*: cstring
+  maskBorderMode*: cstring
+  maskBorderOutset*: cstring
+  maskBorderRepeat*: cstring
+  maskBorderSlice*: cstring
+  maskBorderSource*: cstring
+  maskBorderWidth*: cstring
+  maskClip*: cstring
+  maskComposite*: cstring
+  maskImage*: cstring
+  maskMode*: cstring
+  maskOrigin*: cstring
+  maskPosition*: cstring
+  maskRepeat*: cstring
+  maskSize*: cstring
+  maskType*: cstring
+  maxBlockSize*: cstring
+  maxHeight*: cstring
+  maxInlineSize*: cstring
+  maxWidth*: cstring
+  minBlockSize*: cstring
+  minHeight*: cstring
+  minInlineSize*: cstring
+  minWidth*: cstring
+  mixBlendMode*: cstring
+  objectFit*: cstring
+  objectPosition*: cstring
+  offset*: cstring
+  offsetAnchor*: cstring
+  offsetDistance*: cstring
+  offsetPath*: cstring
+  offsetRotate*: cstring
+  opacity*: cstring
+  order*: cstring
+  orphans*: cstring
+  outline*: cstring
+  outlineColor*: cstring
+  outlineOffset*: cstring
+  outlineStyle*: cstring
+  outlineWidth*: cstring
+  overflow*: cstring
+  overflowAnchor*: cstring
+  overflowBlock*: cstring
+  overflowInline*: cstring
+  overflowWrap*: cstring
+  overflowX*: cstring
+  overflowY*: cstring
+  overscrollBehavior*: cstring
+  overscrollBehaviorBlock*: cstring
+  overscrollBehaviorInline*: cstring
+  overscrollBehaviorX*: cstring
+  overscrollBehaviorY*: cstring
+  padding*: cstring
+  paddingBlock*: cstring
+  paddingBlockEnd*: cstring
+  paddingBlockStart*: cstring
+  paddingBottom*: cstring
+  paddingInline*: cstring
+  paddingInlineEnd*: cstring
+  paddingInlineStart*: cstring
+  paddingLeft*: cstring
+  paddingRight*: cstring
+  paddingTop*: cstring
+  pageBreakAfter*: cstring
+  pageBreakBefore*: cstring
+  pageBreakInside*: cstring
+  paintOrder*: cstring
+  perspective*: cstring
+  perspectiveOrigin*: cstring
+  placeContent*: cstring
+  placeItems*: cstring
+  placeSelf*: cstring
+  pointerEvents*: cstring
+  position*: cstring
+  quotes*: cstring
+  resize*: cstring
+  right*: cstring
+  rotate*: cstring
+  rowGap*: cstring
+  scale*: cstring
+  scrollBehavior*: cstring
+  scrollMargin*: cstring
+  scrollMarginBlock*: cstring
+  scrollMarginBlockEnd*: cstring
+  scrollMarginBlockStart*: cstring
+  scrollMarginBottom*: cstring
+  scrollMarginInline*: cstring
+  scrollMarginInlineEnd*: cstring
+  scrollMarginInlineStart*: cstring
+  scrollMarginLeft*: cstring
+  scrollMarginRight*: cstring
+  scrollMarginTop*: cstring
+  scrollPadding*: cstring
+  scrollPaddingBlock*: cstring
+  scrollPaddingBlockEnd*: cstring
+  scrollPaddingBlockStart*: cstring
+  scrollPaddingBottom*: cstring
+  scrollPaddingInline*: cstring
+  scrollPaddingInlineEnd*: cstring
+  scrollPaddingInlineStart*: cstring
+  scrollPaddingLeft*: cstring
+  scrollPaddingRight*: cstring
+  scrollPaddingTop*: cstring
+  scrollSnapAlign*: cstring
+  scrollSnapStop*: cstring
+  scrollSnapType*: cstring
+  scrollbar3dLightColor*: cstring
+  scrollbarArrowColor*: cstring
+  scrollbarBaseColor*: cstring
+  scrollbarColor*: cstring
+  scrollbarDarkshadowColor*: cstring
+  scrollbarFaceColor*: cstring
+  scrollbarHighlightColor*: cstring
+  scrollbarShadowColor*: cstring
+  scrollbarTrackColor*: cstring
+  scrollbarWidth*: cstring
+  shapeImageThreshold*: cstring
+  shapeMargin*: cstring
+  shapeOutside*: cstring
+  tabSize*: cstring
+  tableLayout*: cstring
+  textAlign*: cstring
+  textAlignLast*: cstring
+  textCombineUpright*: cstring
+  textDecoration*: cstring
+  textDecorationColor*: cstring
+  textDecorationLine*: cstring
+  textDecorationSkipInk*: cstring
+  textDecorationStyle*: cstring
+  textDecorationThickness*: cstring
+  textEmphasis*: cstring
+  textEmphasisColor*: cstring
+  textEmphasisPosition*: cstring
+  textEmphasisStyle*: cstring
+  textIndent*: cstring
+  textJustify*: cstring
+  textOrientation*: cstring
+  textOverflow*: cstring
+  textRendering*: cstring
+  textShadow*: cstring
+  textTransform*: cstring
+  textUnderlineOffset*: cstring
+  textUnderlinePosition*: cstring
+  top*: cstring
+  touchAction*: cstring
+  transform*: cstring
+  transformBox*: cstring
+  transformOrigin*: cstring
+  transformStyle*: cstring
+  transition*: cstring
+  transitionDelay*: cstring
+  transitionDuration*: cstring
+  transitionProperty*: cstring
+  transitionTimingFunction*: cstring
+  translate*: cstring
+  unicodeBidi*: cstring
+  verticalAlign*: cstring
+  visibility*: cstring
+  whiteSpace*: cstring
+  widows*: cstring
+  width*: cstring
+  willChange*: cstring
+  wordBreak*: cstring
+  wordSpacing*: cstring
+  writingMode*: cstring
+  zIndex*: cstring
+
+ + + Source   +Edit   + +
+
+
+
TextAreaElement {.importc.} = ref object of Element
+  value*: cstring
+  selectionStart*, selectionEnd*: int
+  selectionDirection*: cstring
+  rows*, cols*: int
+
+ + see docs + Source   +Edit   + +
+
+
+
TimeOut {.importc.} = ref object of RootObj
+
+ + + Source   +Edit   + +
+
+
+
ToolBar = LocationBar
+
+ + + Source   +Edit   + +
+
+
+
Touch {.importc.} = ref object of RootObj
+  identifier*: int
+  screenX*, screenY*, clientX*, clientY*, pageX*, pageY*: int
+  target*: Element
+  radiusX*, radiusY*: int
+  rotationAngle*: int
+  force*: float
+
+ + + Source   +Edit   + +
+
+
+
TouchEvent {.importc.} = ref object of UIEvent
+  changedTouches*, targetTouches*, touches*: seq[Touch]
+
+ + + Source   +Edit   + +
+
+
+
TouchList {.importc.} = ref object of RootObj
+  length*: int
+
+ + + Source   +Edit   + +
+
+
+
UIEvent {.importc.} = ref object of Event
+  detail*: int64
+  view*: Window
+
+ + see docs + Source   +Edit   + +
+
+
+
ValidityState {.importc.} = ref object
+  badInput*: bool
+  customError*: bool
+  patternMismatch*: bool
+  rangeOverflow*: bool
+  rangeUnderflow*: bool
+  stepMismatch*: bool
+  tooLong*: bool
+  tooShort*: bool
+  typeMismatch*: bool
+  valid*: bool
+  valueMissing*: bool
+
+ + see docs + Source   +Edit   + +
+
+
+
VisualViewport {.importc.} = ref object of EventTarget
+  offsetLeft*, offsetTop*, pageLeft*, pageTop*, width*, height*, scale*: float
+  onResize*, onScroll*: proc (event: Event) {.closure.}
+
+ + + Source   +Edit   + +
+
+
+
Window {.importc.} = ref object of EventTarget
+  document*: Document
+  event*: Event
+  history*: History
+  location*: Location
+  closed*: bool
+  defaultStatus*: cstring
+  devicePixelRatio*: float
+  innerHeight*, innerWidth*: int
+  locationbar*: ref LocationBar
+  menubar*: ref MenuBar
+  name*: cstring
+  outerHeight*, outerWidth*: int
+  pageXOffset*, pageYOffset*: int
+  scrollX*: float
+  scrollY*: float
+  personalbar*: ref PersonalBar
+  scrollbars*: ref ScrollBars
+  statusbar*: ref StatusBar
+  status*: cstring
+  toolbar*: ref ToolBar
+  frames*: seq[Frame]
+  screen*: Screen
+  performance*: Performance
+  onpopstate*: proc (event: Event)
+  localStorage*: Storage
+  sessionStorage*: Storage
+  parent*: Window
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
document {.importc, nodecl.}: Document
+
+ + + Source   +Edit   + +
+
+ +
+
screen {.importc, nodecl.}: Screen
+
+ + + Source   +Edit   + +
+
+
+
window {.importc, nodecl.}: Window
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
DomApiVersion = 3
+
+ + the version of DOM API we try to follow. No guarantees though. + Source   +Edit   + +
+
+
+
fileReaderDone = 2'u
+
+ + + Source   +Edit   + +
+
+
+
fileReaderEmpty = 0'u
+
+ + + Source   +Edit   + +
+
+
+
fileReaderLoading = 1'u
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(s: Selection): string {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `[]`(x: Node; idx: int): Element {.importcpp: "#.childNodes[#]",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc abort(f: FileReader) {.importcpp: "#.abort()", ...raises: [], tags: [],
+                            forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FileReader/abort + Source   +Edit   + +
+
+ +
+
+
+
proc add(c: ClassList; class: cstring) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addEventListener(et: EventTarget; ev: cstring; cb: proc (ev: Event);
+                      options: AddEventListenerOptions) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc addEventListener(et: EventTarget; ev: cstring; cb: proc (ev: Event);
+                      useCapture: bool = false) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc after(self: Node; element: Node): Node {.importjs: "#.$1(@)", varargs,
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/after + Source   +Edit   + +
+
+ +
+
+
+
proc alert(w: Window; msg: cstring) {.importcpp, ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc append(self: Node; element: Node): Node {.importjs: "#.$1(@)", varargs,
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/append + Source   +Edit   + +
+
+ +
+
+
+
proc appendChild(n, child: Node) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc appendData(n: Node; data: cstring) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc assignedElements(n: HTMLSlotElement; options: SlotOptions): seq[Element] {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc assignedNodes(n: HTMLSlotElement; options: SlotOptions): seq[Node] {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc attachShadow(n: Element): ShadowRoot {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc back(h: History) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc back(w: Window) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc before(self: Node; element: Node): Node {.importjs: "#.$1(@)", varargs,
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/before + Source   +Edit   + +
+
+ +
+
+
+
proc blur(e: Element) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc blur(w: Window) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cancelAnimationFrame(w: Window; id: int) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc canShare(self: Navigator; data: cstring): bool {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Navigator/canShare + Source   +Edit   + +
+
+ +
+
+
+
proc checked(n: Node): bool {.importcpp: "#.checked", nodecl, ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc checked=(n: Node; v: bool) {.importcpp: "#.checked = #", nodecl,
+                                  ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc checkValidity(e: FormElement): bool {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc checkValidity(e: InputElement): bool {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc class(n: Node): cstring {.importcpp: "#.className", nodecl, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc class=(n: Node; v: cstring) {.importcpp: "#.className = #", nodecl,
+                                   ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clear(s: Storage) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clearData(dt: DataTransfer; format: cstring) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clearInterval(i: Interval) {.importc, nodecl, ...raises: [], tags: [],
+                                  forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc clearInterval(w: Window; interval: Interval) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clearTimeout(t: TimeOut) {.importc, nodecl, ...raises: [], tags: [],
+                                forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc clearTimeout(w: Window; timeout: TimeOut) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc click(e: Element) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clientHeight(): int {.importcpp: "(window.innerHeight || document.documentElement.clientHeight)@",
+                           nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clientWidth(): int {.importcpp: "(window.innerWidth || document.documentElement.clientWidth)@",
+                          nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cloneNode(n: Node; copyContent: bool): Node {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc close(w: Window) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc closest(self: Node; cssSelector: cstring): Node {.importjs: "#.$1(#)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/closest + Source   +Edit   + +
+
+ +
+
+
+
proc compareDocumentPosition(n: Node; otherNode: Node): int {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc confirm(w: Window; msg: cstring): bool {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc contains(c: ClassList; class: cstring): bool {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc contains(n: Node): bool {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createAttribute(d: Document; identifier: cstring): Node {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createComment(d: Document; data: cstring): Node {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createElement(d: Document; identifier: cstring): Element {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createElementNS(d: Document; namespaceURI, qualifiedIdentifier: cstring): Element {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createTextNode(d: Document; identifier: cstring): Node {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc decodeURI(uri: cstring): cstring {.importc, nodecl, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc decodeURIComponent(uri: cstring): cstring {.importc, nodecl, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc deleteData(n: Node; start, len: int) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc deleteFromDocument(s: Selection) {.importcpp, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc disabled=(n: Node; v: bool) {.importcpp: "#.disabled = #", nodecl,
+                                   ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc disableExternalCapture(w: Window) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc dispatchEvent(et: EventTarget; ev: Event) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc elementFromPoint(n: DocumentOrShadowRoot; x, y: float): Element {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc elementsFromPoint(n: DocumentOrShadowRoot; x, y: float): seq[Element] {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc enableExternalCapture(w: Window) {.importcpp, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc encodeURI(uri: cstring): cstring {.importc, nodecl, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc encodeURIComponent(uri: cstring): cstring {.importc, nodecl, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc error(f: FileReader): DomException {.importcpp: "#.error", nodecl,
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FileReader/error + Source   +Edit   + +
+
+ +
+
+
+
proc escape(uri: cstring): cstring {.importc, nodecl, ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc find(w: Window; text: cstring; caseSensitive = false; backwards = false): bool {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc focus(e: Element) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc focus(e: Node) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc focus(w: Window) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc forward(h: History) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc forward(w: Window) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getAsFile(dti: DataTransferItem): File {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getAttribute(n: Node; attr: cstring): cstring {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getAttributeNode(n: Node; attr: cstring): Node {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getBoundingClientRect(e: Node): BoundingRect {.
+    importcpp: "getBoundingClientRect", nodecl, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getComputedStyle(w: Window; e: Node; pe: Node = nil): Style {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ +
Warning: +The returned Style may or may not be read-only at run-time in the browser. getComputedStyle is performance costly.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc getData(dt: DataTransfer; format: cstring): cstring {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getElementById(d: Document; id: cstring): Element {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc getElementById(id: cstring): Element {.importc: "document.getElementById",
+    nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getElementsByClass(n: Node; name: cstring): seq[Node] {.
+    importcpp: "#.getElementsByClassName(#)", nodecl, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getElementsByClassName(d: Document; name: cstring): seq[Element] {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc getElementsByClassName(e: Element; name: cstring): seq[Element] {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getElementsByName(d: Document; name: cstring): seq[Element] {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getElementsByTagName(d: Document; name: cstring): seq[Element] {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc getElementsByTagName(e: Element; name: cstring): seq[Element] {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getItem(s: Storage; key: cstring): cstring {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getModifierState(ev: KeyboardEvent; keyArg: cstring): bool {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc getModifierState(ev: MouseEvent; keyArg: cstring): bool {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getPropertyPriority(s: Style; property: cstring): cstring {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getPropertyValue(s: Style; property: cstring): cstring {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getRangeAt(s: Selection; index: int): Range {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getRootNode(n: Node; options: RootNodeOptions): Node {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getSelection(d: Document): Selection {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc getSelection(n: DocumentOrShadowRoot): Selection {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc go(h: History; pagesToJump: int) {.importcpp, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc handleEvent(d: Document; event: Event) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc handleEvent(e: Element; event: Event) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc handleEvent(w: Window; e: Event) {.importcpp, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasAttribute(n: Node; attr: cstring): bool {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasAttributeNS(self: Node; namespace, localName: cstring): bool {.
+    importjs: "(#.$1(#, #) || false)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttributeNS + Source   +Edit   + +
+
+ +
+
+
+
proc hasChildNodes(n: Node): bool {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasPointerCapture(self: Node; pointerId: SomeNumber): bool {.
+    importjs: "(#.$1(#) || false)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/hasPointerCapture + Source   +Edit   + +
+
+ +
+
+
+
proc home(w: Window) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc id(n: Node): cstring {.importcpp: "#.id", nodecl, ...raises: [], tags: [],
+                            forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc id=(n: Node; x: cstring) {.importcpp: "#.id = #", nodecl, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc identifiedTouch(list: TouchList): Touch {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc insertAdjacentElement(self: Node; position: cstring; element: Node) {.
+    importjs: "#.$1(#, #)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement + Source   +Edit   + +
+
+ +
+
+
+
proc insertAdjacentHTML(self: Node; position, html: cstring) {.
+    importjs: "#.$1(#, #)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML + Source   +Edit   + +
+
+ +
+
+
+
proc insertAdjacentText(self: Node; position, data: cstring) {.
+    importjs: "#.$1(#, #)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentText + Source   +Edit   + +
+
+ +
+
+
+
proc insertBefore(n, newNode, before: Node) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc insertData(n: Node; position: int; data: cstring) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc insertNode(range: Range; node: Node) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inViewport(el: Node): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isDefaultNamespace(n: Node): bool {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isEqualNode(n: Node): bool {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isFinite(x: BiggestFloat): bool {.importc, nodecl, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isNaN(x: BiggestFloat): bool {.importc, nodecl, ...raises: [], tags: [],
+                                    forbids: [].}
+
+ + see also math.isNaN. + Source   +Edit   + +
+
+ +
+
+
+
proc isSameNode(n: Node): bool {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc item(list: TouchList; i: int): Touch {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc javaEnabled(h: Navigator): bool {.importcpp, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc len(x: Node): int {.importcpp: "#.childNodes.length", ...raises: [], tags: [],
+                         forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lookupNamespaceURI(n: Node): cstring {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lookupPrefix(n: Node): cstring {.importcpp, ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc matches(self: Node; cssSelector: cstring): bool {.
+    importjs: "(#.$1(#) || false)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/matches + Source   +Edit   + +
+
+ +
+
+
+
proc matchMedia(w: Window; mediaQueryString: cstring): MediaQueryList {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc message(ex: DomException): cstring {.importcpp: "#.message", nodecl,
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/DOMException/message + Source   +Edit   + +
+
+ +
+
+
+
proc moveBy(w: Window; x, y: int) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc moveTo(w: Window; x, y: int) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc name(ex: DomException): cstring {.importcpp: "#.name", nodecl, ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/DOMException/name + Source   +Edit   + +
+
+ +
+
+
+
proc newDomException(): DomException {.importcpp: "new DomException()",
+                                       constructor, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + DOM Exception constructor + Source   +Edit   + +
+
+ +
+
+
+
func newDomParser(): DomParser {.importcpp: "new DOMParser()", ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + DOM Parser constructor. + Source   +Edit   + +
+
+ +
+
+
+
proc newEvent(name: cstring): Event {.importcpp: "new Event(@)", constructor,
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newFileReader(): FileReader {.importcpp: "new FileReader()", constructor,
+                                   ...raises: [], tags: [], forbids: [].}
+
+ + File Reader constructor + Source   +Edit   + +
+
+ +
+
+
+
proc normalize(n: Node) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc now(p: Performance): float {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc offsetHeight(e: Node): int {.importcpp: "#.offsetHeight", nodecl,
+                                  ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc offsetLeft(e: Node): int {.importcpp: "#.offsetLeft", nodecl, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc offsetTop(e: Node): int {.importcpp: "#.offsetTop", nodecl, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc offsetWidth(e: Node): int {.importcpp: "#.offsetWidth", nodecl, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc open(d: Document) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc open(w: Window; uri, windowname: cstring; properties: cstring = nil): Window {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func parseFromString(this: DomParser; str: cstring; mimeType: cstring): Document {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + Parse from string to Document. + Source   +Edit   + +
+
+ +
+
+
+
proc play(e: EmbedElement) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc preventDefault(ev: Event) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
proc prompt(w: Window; text, default: cstring): cstring {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pushState[T](h: History; stateObject: T; title, url: cstring) {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc querySelector(d: Document; selectors: cstring): Element {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc querySelector(n: Node; selectors: cstring): Element {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc querySelectorAll(d: Document; selectors: cstring): seq[Element] {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc querySelectorAll(n: Node; selectors: cstring): seq[Element] {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc readAsBinaryString(f: FileReader; b: Blob) {.
+    importcpp: "#.readAsBinaryString(#)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsBinaryString + Source   +Edit   + +
+
+ +
+
+
+
proc readAsDataURL(f: FileReader; b: Blob) {.importcpp: "#.readAsDataURL(#)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL + Source   +Edit   + +
+
+ +
+
+
+
proc readAsText(f: FileReader; b: Blob | File; encoding = cstring"UTF-8") {.
+    importcpp: "#.readAsText(#, #)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsText + Source   +Edit   + +
+
+ +
+
+
+
proc readyState(f: FileReader): FileReaderState {.importcpp: "#.readyState",
+    nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readyState + Source   +Edit   + +
+
+ +
+
+
+
proc registerProtocolHandler(self: Navigator; scheme, url, title: cstring) {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Navigator/registerProtocolHandler + Source   +Edit   + +
+
+ +
+
+
+
proc releasePointerCapture(self: Node; pointerId: SomeNumber) {.
+    importjs: "#.$1(#)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/releasePointerCapture + Source   +Edit   + +
+
+ +
+
+
+
proc reload(loc: Location) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc remove(c: ClassList; class: cstring) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc remove(child: Node) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc removeAllRanges(s: Selection) {.importcpp, ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc removeAttribute(n: Node; attr: cstring) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc removeAttributeNode(n, attr: Node) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc removeAttributeNS(self: Node; namespace, attributeName: cstring) {.
+    importjs: "#.$1(#, #)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttributeNS + Source   +Edit   + +
+
+ +
+
+
+
proc removeChild(n, child: Node) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc removeEventListener(et: EventTarget; ev: cstring; cb: proc (ev: Event)) {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc removeItem(s: Storage; key: cstring) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc removeProperty(s: Style; property: cstring) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc replace(loc: Location; s: cstring) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc replaceChild(n, newNode, oldNode: Node) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc replaceChildren(self: Node; replacements: Node) {.importjs: "#.$1(@)",
+    varargs, ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/replaceChildren + Source   +Edit   + +
+
+ +
+
+
+
proc replaceData(n: Node; start, len: int; text: cstring) {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc replaceWith(self: Node; replacements: Node) {.importjs: "#.$1(@)", varargs,
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/replaceWith + Source   +Edit   + +
+
+ +
+
+
+
proc reportValidity(e: FormElement): bool {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc requestAnimationFrame(w: Window; function: proc (time: float)): int {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc requestPointerLock(self: Node) {.importjs: "#.$1()", ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock + Source   +Edit   + +
+
+ +
+
+
+
proc reset(f: FormElement) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc resizeBy(w: Window; x, y: int) {.importcpp, ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc resizeTo(w: Window; x, y: int) {.importcpp, ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc resultAsString(f: FileReader): cstring {.importcpp: "#.result", nodecl,
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FileReader/result + Source   +Edit   + +
+
+ +
+
+
+
proc routeEvent(d: Document; event: Event) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc routeEvent(w: Window; event: Event) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc scrollBy(w: Window; x, y: int) {.importcpp, ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc scrollHeight(e: Node): int {.importcpp: "#.scrollHeight", nodecl,
+                                  ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc scrollIntoView(n: Node) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc scrollIntoView(n: Node; options: ScrollIntoViewOptions) {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc scrollIntoViewIfNeeded(self: Node; centerIfNeeded: bool) {.
+    importjs: "#.$1(#)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoViewIfNeeded + Source   +Edit   + +
+
+ +
+
+
+
proc scrollLeft(e: Node): int {.importcpp: "#.scrollLeft", nodecl, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc scrollTo(w: Window; x, y: int) {.importcpp, ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc scrollTop(e: Node): int {.importcpp: "#.scrollTop", nodecl, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc scrollTop=(e: Node; value: int) {.importcpp: "#.scrollTop = #", nodecl,
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc scrollWidth(e: Node): int {.importcpp: "#.scrollWidth", nodecl, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc select(e: Element) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sendBeacon(self: Navigator; url, data: cstring): bool {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon + Source   +Edit   + +
+
+ +
+
+
+
proc setAttr(n: Node; key, val: cstring) {.importcpp: "#.setAttribute(@)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setAttribute(n: Node; name, value: cstring) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setAttributeNode(n: Node; attr: Node) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setCustomValidity(e: InputElement; error: cstring) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setData(dt: DataTransfer; format: cstring; data: cstring) {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setDragImage(dt: DataTransfer; img: Element; xOffset: int; yOffset: int) {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setHTML(self: Node; html: cstring) {.importjs: "#.$1(#)", ...raises: [],
+    tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/setHTML + Source   +Edit   + +
+
+ +
+
+
+
proc setInterval(action: proc (); ms: int): Interval {.importc, nodecl,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc setInterval(w: Window; code: cstring; pause: int): Interval {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc setInterval(w: Window; function: proc (); pause: int): Interval {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setItem(s: Storage; key, value: cstring) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setProperty(s: Style; property, value: cstring; priority = "") {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setRangeText(e: InputElement; replacement: cstring; startindex: int = 0;
+                  endindex: int = 0; selectionMode: cstring = "preserve") {.
+    importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setSelectionRange(e: InputElement; selectionStart: int; selectionEnd: int;
+                       selectionDirection: cstring = "none") {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setTimeout(action: proc (); ms: int): TimeOut {.importc, nodecl,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc setTimeout(w: Window; code: cstring; pause: int): TimeOut {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc setTimeout(w: Window; function: proc (); pause: int): Interval {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc slice(e: Blob; startindex: int = 0; endindex: int = e.size;
+           contentType: cstring = "") {.importcpp, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc stop(e: EmbedElement) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc stop(w: Window) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc stopImmediatePropagation(ev: Event) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc stopPropagation(ev: Event) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc submit(f: FormElement) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toggle(c: ClassList; class: cstring) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toggleAttribute(self: Node; name: cstring; force = false): bool {.
+    importjs: "(#.$1(#, #) || false)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Element/toggleAttribute + Source   +Edit   + +
+
+ +
+
+
+
proc unescape(uri: cstring): cstring {.importc, nodecl, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc value(n: Node): cstring {.importcpp: "#.value", nodecl, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc value=(n: Node; v: cstring) {.importcpp: "#.value = #", nodecl, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc vibrate(self: Navigator; pattern: cint): bool {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Navigator/vibrate + Source   +Edit   + +
+
+
+
proc vibrate(self: Navigator; pattern: openArray[cint]): bool {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Navigator/vibrate + Source   +Edit   + +
+
+ +
+
+
+
func visualViewport(self: Window): VisualViewport {.importjs: "#.$1", nodecl,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc write(d: Document; text: cstring) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc writeln(d: Document; text: cstring) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Converters

+
+
+
+
converter toString(s: Selection): cstring {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/dom.idx b/dom.idx new file mode 100644 index 0000000000000..ef667ec25e021 --- /dev/null +++ b/dom.idx @@ -0,0 +1,369 @@ +nimTitle dom dom.html module std/dom 0 +nim DomApiVersion dom.html#DomApiVersion const DomApiVersion 48 +nim EventTarget dom.html#EventTarget type EventTarget 51 +nim DomEvent dom.html#DomEvent enum DomEvent 77 +nim PerformanceMemory dom.html#PerformanceMemory type PerformanceMemory 110 +nim PerformanceTiming dom.html#PerformanceTiming type PerformanceTiming 115 +nim Performance dom.html#Performance type Performance 137 +nim Range dom.html#Range type Range 141 +nim Selection dom.html#Selection type Selection 150 +nim Storage dom.html#Storage type Storage 160 +nim Window dom.html#Window type Window 162 +nim Frame dom.html#Frame type Frame 191 +nim ClassList dom.html#ClassList type ClassList 193 +nim ElementNode dom.html#ElementNode NodeType.ElementNode 195 +nim AttributeNode dom.html#AttributeNode NodeType.AttributeNode 195 +nim TextNode dom.html#TextNode NodeType.TextNode 195 +nim CDATANode dom.html#CDATANode NodeType.CDATANode 195 +nim EntityRefNode dom.html#EntityRefNode NodeType.EntityRefNode 195 +nim EntityNode dom.html#EntityNode NodeType.EntityNode 195 +nim ProcessingInstructionNode dom.html#ProcessingInstructionNode NodeType.ProcessingInstructionNode 195 +nim CommentNode dom.html#CommentNode NodeType.CommentNode 195 +nim DocumentNode dom.html#DocumentNode NodeType.DocumentNode 195 +nim DocumentTypeNode dom.html#DocumentTypeNode NodeType.DocumentTypeNode 195 +nim DocumentFragmentNode dom.html#DocumentFragmentNode NodeType.DocumentFragmentNode 195 +nim NotationNode dom.html#NotationNode NodeType.NotationNode 195 +nim NodeType dom.html#NodeType enum NodeType 195 +nim Node dom.html#Node type Node 209 +nim Document dom.html#Document type Document 233 +nim Element dom.html#Element type Element 260 +nim ValidityState dom.html#ValidityState type ValidityState 281 +nim Blob dom.html#Blob type Blob 294 +nim File dom.html#File type File 298 +nim TextAreaElement dom.html#TextAreaElement type TextAreaElement 302 +nim InputElement dom.html#InputElement type InputElement 308 +nim LinkElement dom.html#LinkElement type LinkElement 360 +nim EmbedElement dom.html#EmbedElement type EmbedElement 366 +nim AnchorElement dom.html#AnchorElement type AnchorElement 374 +nim OptionElement dom.html#OptionElement type OptionElement 378 +nim FormElement dom.html#FormElement type FormElement 385 +nim ImageElement dom.html#ImageElement type ImageElement 397 +nim Style dom.html#Style type Style 407 +nim None dom.html#None EventPhase.None 777 +nim CapturingPhase dom.html#CapturingPhase EventPhase.CapturingPhase 777 +nim AtTarget dom.html#AtTarget EventPhase.AtTarget 777 +nim BubblingPhase dom.html#BubblingPhase EventPhase.BubblingPhase 777 +nim EventPhase dom.html#EventPhase enum EventPhase 777 +nim Event dom.html#Event type Event 783 +nim UIEvent dom.html#UIEvent type UIEvent 795 +nim KeyboardEvent dom.html#KeyboardEvent type KeyboardEvent 799 +nim KeyboardEventKey dom.html#KeyboardEventKey enum KeyboardEventKey 807 +nim NoButton dom.html#NoButton MouseButtons.NoButton 1153 +nim PrimaryButton dom.html#PrimaryButton MouseButtons.PrimaryButton 1153 +nim SecondaryButton dom.html#SecondaryButton MouseButtons.SecondaryButton 1153 +nim AuxilaryButton dom.html#AuxilaryButton MouseButtons.AuxilaryButton 1153 +nim FourthButton dom.html#FourthButton MouseButtons.FourthButton 1153 +nim FifthButton dom.html#FifthButton MouseButtons.FifthButton 1153 +nim MouseButtons dom.html#MouseButtons enum MouseButtons 1153 +nim MouseEvent dom.html#MouseEvent type MouseEvent 1161 +nim DataTransferItemKind dom.html#DataTransferItemKind enum DataTransferItemKind 1174 +nim DataTransferItem dom.html#DataTransferItem type DataTransferItem 1178 +nim DataTransfer dom.html#DataTransfer type DataTransfer 1182 +nim DataTransferDropEffect dom.html#DataTransferDropEffect enum DataTransferDropEffect 1189 +nim DataTransferEffectAllowed dom.html#DataTransferEffectAllowed enum DataTransferEffectAllowed 1195 +nim Drag dom.html#Drag DragEventTypes.Drag 1206 +nim DragEnd dom.html#DragEnd DragEventTypes.DragEnd 1206 +nim DragEnter dom.html#DragEnter DragEventTypes.DragEnter 1206 +nim DragExit dom.html#DragExit DragEventTypes.DragExit 1206 +nim DragLeave dom.html#DragLeave DragEventTypes.DragLeave 1206 +nim DragOver dom.html#DragOver DragEventTypes.DragOver 1206 +nim DragStart dom.html#DragStart DragEventTypes.DragStart 1206 +nim Drop dom.html#Drop DragEventTypes.Drop 1206 +nim DragEventTypes dom.html#DragEventTypes enum DragEventTypes 1206 +nim DragEvent dom.html#DragEvent object DragEvent 1216 +nim ClipboardEvent dom.html#ClipboardEvent object ClipboardEvent 1220 +nim StorageEvent dom.html#StorageEvent type StorageEvent 1224 +nim TouchList dom.html#TouchList type TouchList 1230 +nim Touch dom.html#Touch type Touch 1233 +nim TouchEvent dom.html#TouchEvent type TouchEvent 1241 +nim Location dom.html#Location type Location 1244 +nim History dom.html#History type History 1255 +nim Navigator dom.html#Navigator type Navigator 1258 +nim Plugin dom.html#Plugin object Plugin 1277 +nim MimeType dom.html#MimeType object MimeType 1282 +nim LocationBar dom.html#LocationBar object LocationBar 1288 +nim MenuBar dom.html#MenuBar type MenuBar 1290 +nim PersonalBar dom.html#PersonalBar type PersonalBar 1291 +nim ScrollBars dom.html#ScrollBars type ScrollBars 1292 +nim ToolBar dom.html#ToolBar type ToolBar 1293 +nim StatusBar dom.html#StatusBar type StatusBar 1294 +nim Screen dom.html#Screen type Screen 1296 +nim TimeOut dom.html#TimeOut type TimeOut 1304 +nim Interval dom.html#Interval type Interval 1305 +nim AddEventListenerOptions dom.html#AddEventListenerOptions object AddEventListenerOptions 1307 +nim FontFaceSetReady dom.html#FontFaceSetReady type FontFaceSetReady 1312 +nim FontFaceSet dom.html#FontFaceSet type FontFaceSet 1316 +nim ScrollIntoViewOptions dom.html#ScrollIntoViewOptions object ScrollIntoViewOptions 1321 +nim MediaQueryList dom.html#MediaQueryList type MediaQueryList 1326 +nim DomParser dom.html#DomParser type DomParser 1332 +nim DomException dom.html#DomException type DomException 1341 +nim FileReader dom.html#FileReader type FileReader 1348 +nim FileReaderState dom.html#FileReaderState type FileReaderState 1354 +nim RootNodeOptions dom.html#RootNodeOptions object RootNodeOptions 1355 +nim DocumentOrShadowRoot dom.html#DocumentOrShadowRoot object DocumentOrShadowRoot 1357 +nim ShadowRoot dom.html#ShadowRoot type ShadowRoot 1360 +nim ShadowRootInit dom.html#ShadowRootInit object ShadowRootInit 1365 +nim HTMLSlotElement dom.html#HTMLSlotElement type HTMLSlotElement 1369 +nim SlotOptions dom.html#SlotOptions object SlotOptions 1371 +nim fileReaderEmpty dom.html#fileReaderEmpty const fileReaderEmpty 1375 +nim fileReaderLoading dom.html#fileReaderLoading const fileReaderLoading 1376 +nim fileReaderDone dom.html#fileReaderDone const fileReaderDone 1377 +nim id dom.html#id,Node proc id(n: Node): cstring 1379 +nim id= dom.html#id=,Node,cstring proc id=(n: Node; x: cstring) 1380 +nim class dom.html#class,Node proc class(n: Node): cstring 1381 +nim class= dom.html#class=,Node,cstring proc class=(n: Node; v: cstring) 1382 +nim value dom.html#value,Node proc value(n: Node): cstring 1384 +nim value= dom.html#value=,Node,cstring proc value=(n: Node; v: cstring) 1385 +nim checked dom.html#checked,Node proc checked(n: Node): bool 1387 +nim checked= dom.html#checked=,Node,bool proc checked=(n: Node; v: bool) 1388 +nim disabled= dom.html#disabled=,Node,bool proc disabled=(n: Node; v: bool) 1390 +nim len dom.html#len,Node proc len(x: Node): int 1468 +nim `[]` dom.html#[],Node,int proc `[]`(x: Node; idx: int): Element 1469 +nim getElementById dom.html#getElementById,cstring proc getElementById(id: cstring): Element 1470 +nim appendChild dom.html#appendChild,Node,Node proc appendChild(n, child: Node) 1471 +nim removeChild dom.html#removeChild,Node,Node proc removeChild(n, child: Node) 1472 +nim remove dom.html#remove,Node proc remove(child: Node) 1473 +nim replaceChild dom.html#replaceChild,Node,Node,Node proc replaceChild(n, newNode, oldNode: Node) 1474 +nim insertBefore dom.html#insertBefore,Node,Node,Node proc insertBefore(n, newNode, before: Node) 1475 +nim getElementById dom.html#getElementById,Document,cstring proc getElementById(d: Document; id: cstring): Element 1476 +nim createElement dom.html#createElement,Document,cstring proc createElement(d: Document; identifier: cstring): Element 1477 +nim createElementNS dom.html#createElementNS,Document,cstring,cstring proc createElementNS(d: Document; namespaceURI, qualifiedIdentifier: cstring): Element 1478 +nim createTextNode dom.html#createTextNode,Document,cstring proc createTextNode(d: Document; identifier: cstring): Node 1479 +nim createComment dom.html#createComment,Document,cstring proc createComment(d: Document; data: cstring): Node 1480 +nim setTimeout dom.html#setTimeout,proc),int proc setTimeout(action: proc (); ms: int): TimeOut 1482 +nim clearTimeout dom.html#clearTimeout,TimeOut proc clearTimeout(t: TimeOut) 1483 +nim setInterval dom.html#setInterval,proc),int proc setInterval(action: proc (); ms: int): Interval 1484 +nim clearInterval dom.html#clearInterval,Interval proc clearInterval(i: Interval) 1485 +nim addEventListener dom.html#addEventListener,EventTarget,cstring,proc(Event),bool proc addEventListener(et: EventTarget; ev: cstring; cb: proc (ev: Event);\n useCapture: bool = false) 1490 +nim addEventListener dom.html#addEventListener,EventTarget,cstring,proc(Event),AddEventListenerOptions proc addEventListener(et: EventTarget; ev: cstring; cb: proc (ev: Event);\n options: AddEventListenerOptions) 1491 +nim dispatchEvent dom.html#dispatchEvent,EventTarget,Event proc dispatchEvent(et: EventTarget; ev: Event) 1492 +nim removeEventListener dom.html#removeEventListener,EventTarget,cstring,proc(Event) proc removeEventListener(et: EventTarget; ev: cstring; cb: proc (ev: Event)) 1493 +nim alert dom.html#alert,Window,cstring proc alert(w: Window; msg: cstring) 1496 +nim back dom.html#back,Window proc back(w: Window) 1497 +nim blur dom.html#blur,Window proc blur(w: Window) 1498 +nim clearInterval dom.html#clearInterval,Window,Interval proc clearInterval(w: Window; interval: Interval) 1499 +nim clearTimeout dom.html#clearTimeout,Window,TimeOut proc clearTimeout(w: Window; timeout: TimeOut) 1500 +nim close dom.html#close,Window proc close(w: Window) 1501 +nim confirm dom.html#confirm,Window,cstring proc confirm(w: Window; msg: cstring): bool 1502 +nim disableExternalCapture dom.html#disableExternalCapture,Window proc disableExternalCapture(w: Window) 1503 +nim enableExternalCapture dom.html#enableExternalCapture,Window proc enableExternalCapture(w: Window) 1504 +nim find dom.html#find,Window,cstring proc find(w: Window; text: cstring; caseSensitive = false; backwards = false): bool 1505 +nim focus dom.html#focus,Window proc focus(w: Window) 1507 +nim forward dom.html#forward,Window proc forward(w: Window) 1508 +nim getComputedStyle dom.html#getComputedStyle,Window,Node,Node proc getComputedStyle(w: Window; e: Node; pe: Node = nil): Style 1509 +nim handleEvent dom.html#handleEvent,Window,Event proc handleEvent(w: Window; e: Event) 1512 +nim home dom.html#home,Window proc home(w: Window) 1513 +nim moveBy dom.html#moveBy,Window,int,int proc moveBy(w: Window; x, y: int) 1514 +nim moveTo dom.html#moveTo,Window,int,int proc moveTo(w: Window; x, y: int) 1515 +nim open dom.html#open,Window,cstring,cstring,cstring proc open(w: Window; uri, windowname: cstring; properties: cstring = nil): Window 1516 +nim print dom.html#print,Window proc print(w: Window) 1518 +nim prompt dom.html#prompt,Window,cstring,cstring proc prompt(w: Window; text, default: cstring): cstring 1519 +nim resizeBy dom.html#resizeBy,Window,int,int proc resizeBy(w: Window; x, y: int) 1520 +nim resizeTo dom.html#resizeTo,Window,int,int proc resizeTo(w: Window; x, y: int) 1521 +nim routeEvent dom.html#routeEvent,Window,Event proc routeEvent(w: Window; event: Event) 1522 +nim scrollBy dom.html#scrollBy,Window,int,int proc scrollBy(w: Window; x, y: int) 1523 +nim scrollTo dom.html#scrollTo,Window,int,int proc scrollTo(w: Window; x, y: int) 1524 +nim setInterval dom.html#setInterval,Window,cstring,int proc setInterval(w: Window; code: cstring; pause: int): Interval 1525 +nim setInterval dom.html#setInterval,Window,proc),int proc setInterval(w: Window; function: proc (); pause: int): Interval 1526 +nim setTimeout dom.html#setTimeout,Window,cstring,int proc setTimeout(w: Window; code: cstring; pause: int): TimeOut 1527 +nim setTimeout dom.html#setTimeout,Window,proc),int proc setTimeout(w: Window; function: proc (); pause: int): Interval 1528 +nim stop dom.html#stop,Window proc stop(w: Window) 1529 +nim requestAnimationFrame dom.html#requestAnimationFrame,Window,proc(float) proc requestAnimationFrame(w: Window; function: proc (time: float)): int 1530 +nim cancelAnimationFrame dom.html#cancelAnimationFrame,Window,int proc cancelAnimationFrame(w: Window; id: int) 1531 +nim matchMedia dom.html#matchMedia,Window,cstring proc matchMedia(w: Window; mediaQueryString: cstring): MediaQueryList 1532 +nim appendData dom.html#appendData,Node,cstring proc appendData(n: Node; data: cstring) 1535 +nim cloneNode dom.html#cloneNode,Node,bool proc cloneNode(n: Node; copyContent: bool): Node 1536 +nim deleteData dom.html#deleteData,Node,int,int proc deleteData(n: Node; start, len: int) 1537 +nim focus dom.html#focus,Node proc focus(e: Node) 1538 +nim getAttribute dom.html#getAttribute,Node,cstring proc getAttribute(n: Node; attr: cstring): cstring 1539 +nim getAttributeNode dom.html#getAttributeNode,Node,cstring proc getAttributeNode(n: Node; attr: cstring): Node 1540 +nim hasAttribute dom.html#hasAttribute,Node,cstring proc hasAttribute(n: Node; attr: cstring): bool 1541 +nim hasChildNodes dom.html#hasChildNodes,Node proc hasChildNodes(n: Node): bool 1542 +nim normalize dom.html#normalize,Node proc normalize(n: Node) 1543 +nim insertData dom.html#insertData,Node,int,cstring proc insertData(n: Node; position: int; data: cstring) 1544 +nim removeAttribute dom.html#removeAttribute,Node,cstring proc removeAttribute(n: Node; attr: cstring) 1545 +nim removeAttributeNode dom.html#removeAttributeNode,Node,Node proc removeAttributeNode(n, attr: Node) 1546 +nim replaceData dom.html#replaceData,Node,int,int,cstring proc replaceData(n: Node; start, len: int; text: cstring) 1547 +nim scrollIntoView dom.html#scrollIntoView,Node proc scrollIntoView(n: Node) 1548 +nim scrollIntoView dom.html#scrollIntoView,Node,ScrollIntoViewOptions proc scrollIntoView(n: Node; options: ScrollIntoViewOptions) 1549 +nim setAttribute dom.html#setAttribute,Node,cstring,cstring proc setAttribute(n: Node; name, value: cstring) 1550 +nim setAttributeNode dom.html#setAttributeNode,Node,Node proc setAttributeNode(n: Node; attr: Node) 1551 +nim querySelector dom.html#querySelector,Node,cstring proc querySelector(n: Node; selectors: cstring): Element 1552 +nim querySelectorAll dom.html#querySelectorAll,Node,cstring proc querySelectorAll(n: Node; selectors: cstring): seq[Element] 1553 +nim compareDocumentPosition dom.html#compareDocumentPosition,Node,Node proc compareDocumentPosition(n: Node; otherNode: Node): int 1554 +nim lookupPrefix dom.html#lookupPrefix,Node proc lookupPrefix(n: Node): cstring 1555 +nim lookupNamespaceURI dom.html#lookupNamespaceURI,Node proc lookupNamespaceURI(n: Node): cstring 1556 +nim isDefaultNamespace dom.html#isDefaultNamespace,Node proc isDefaultNamespace(n: Node): bool 1557 +nim contains dom.html#contains,Node proc contains(n: Node): bool 1558 +nim isEqualNode dom.html#isEqualNode,Node proc isEqualNode(n: Node): bool 1559 +nim isSameNode dom.html#isSameNode,Node proc isSameNode(n: Node): bool 1560 +nim getRootNode dom.html#getRootNode,Node,RootNodeOptions proc getRootNode(n: Node; options: RootNodeOptions): Node 1563 +nim getSelection dom.html#getSelection,DocumentOrShadowRoot proc getSelection(n: DocumentOrShadowRoot): Selection 1566 +nim elementFromPoint dom.html#elementFromPoint,DocumentOrShadowRoot,float,float proc elementFromPoint(n: DocumentOrShadowRoot; x, y: float): Element 1567 +nim attachShadow dom.html#attachShadow,Element proc attachShadow(n: Element): ShadowRoot 1570 +nim assignedNodes dom.html#assignedNodes,HTMLSlotElement,SlotOptions proc assignedNodes(n: HTMLSlotElement; options: SlotOptions): seq[Node] 1571 +nim assignedElements dom.html#assignedElements,HTMLSlotElement,SlotOptions proc assignedElements(n: HTMLSlotElement; options: SlotOptions): seq[Element] 1572 +nim createAttribute dom.html#createAttribute,Document,cstring proc createAttribute(d: Document; identifier: cstring): Node 1575 +nim getElementsByName dom.html#getElementsByName,Document,cstring proc getElementsByName(d: Document; name: cstring): seq[Element] 1576 +nim getElementsByTagName dom.html#getElementsByTagName,Document,cstring proc getElementsByTagName(d: Document; name: cstring): seq[Element] 1577 +nim getElementsByClassName dom.html#getElementsByClassName,Document,cstring proc getElementsByClassName(d: Document; name: cstring): seq[Element] 1578 +nim insertNode dom.html#insertNode,Range,Node proc insertNode(range: Range; node: Node) 1579 +nim getSelection dom.html#getSelection,Document proc getSelection(d: Document): Selection 1580 +nim handleEvent dom.html#handleEvent,Document,Event proc handleEvent(d: Document; event: Event) 1581 +nim open dom.html#open,Document proc open(d: Document) 1582 +nim routeEvent dom.html#routeEvent,Document,Event proc routeEvent(d: Document; event: Event) 1583 +nim write dom.html#write,Document,cstring proc write(d: Document; text: cstring) 1584 +nim writeln dom.html#writeln,Document,cstring proc writeln(d: Document; text: cstring) 1585 +nim querySelector dom.html#querySelector,Document,cstring proc querySelector(d: Document; selectors: cstring): Element 1586 +nim querySelectorAll dom.html#querySelectorAll,Document,cstring proc querySelectorAll(d: Document; selectors: cstring): seq[Element] 1587 +nim blur dom.html#blur,Element proc blur(e: Element) 1590 +nim click dom.html#click,Element proc click(e: Element) 1591 +nim focus dom.html#focus,Element proc focus(e: Element) 1592 +nim handleEvent dom.html#handleEvent,Element,Event proc handleEvent(e: Element; event: Event) 1593 +nim select dom.html#select,Element proc select(e: Element) 1594 +nim getElementsByTagName dom.html#getElementsByTagName,Element,cstring proc getElementsByTagName(e: Element; name: cstring): seq[Element] 1595 +nim getElementsByClassName dom.html#getElementsByClassName,Element,cstring proc getElementsByClassName(e: Element; name: cstring): seq[Element] 1596 +nim reset dom.html#reset,FormElement proc reset(f: FormElement) 1599 +nim submit dom.html#submit,FormElement proc submit(f: FormElement) 1600 +nim checkValidity dom.html#checkValidity,FormElement proc checkValidity(e: FormElement): bool 1601 +nim reportValidity dom.html#reportValidity,FormElement proc reportValidity(e: FormElement): bool 1602 +nim play dom.html#play,EmbedElement proc play(e: EmbedElement) 1605 +nim stop dom.html#stop,EmbedElement proc stop(e: EmbedElement) 1606 +nim reload dom.html#reload,Location proc reload(loc: Location) 1609 +nim replace dom.html#replace,Location,cstring proc replace(loc: Location; s: cstring) 1610 +nim back dom.html#back,History proc back(h: History) 1613 +nim forward dom.html#forward,History proc forward(h: History) 1614 +nim go dom.html#go,History,int proc go(h: History; pagesToJump: int) 1615 +nim pushState dom.html#pushState,History,T,cstring,cstring proc pushState[T](h: History; stateObject: T; title, url: cstring) 1616 +nim javaEnabled dom.html#javaEnabled,Navigator proc javaEnabled(h: Navigator): bool 1619 +nim canShare dom.html#canShare,Navigator,cstring proc canShare(self: Navigator; data: cstring): bool 1621 +nim sendBeacon dom.html#sendBeacon,Navigator,cstring,cstring proc sendBeacon(self: Navigator; url, data: cstring): bool 1622 +nim vibrate dom.html#vibrate,Navigator,cint proc vibrate(self: Navigator; pattern: cint): bool 1623 +nim vibrate dom.html#vibrate,Navigator,openArray[cint] proc vibrate(self: Navigator; pattern: openArray[cint]): bool 1624 +nim registerProtocolHandler dom.html#registerProtocolHandler,Navigator,cstring,cstring,cstring proc registerProtocolHandler(self: Navigator; scheme, url, title: cstring) 1625 +nim add dom.html#add,ClassList,cstring proc add(c: ClassList; class: cstring) 1628 +nim remove dom.html#remove,ClassList,cstring proc remove(c: ClassList; class: cstring) 1629 +nim contains dom.html#contains,ClassList,cstring proc contains(c: ClassList; class: cstring): bool 1630 +nim toggle dom.html#toggle,ClassList,cstring proc toggle(c: ClassList; class: cstring) 1631 +nim getPropertyValue dom.html#getPropertyValue,Style,cstring proc getPropertyValue(s: Style; property: cstring): cstring 1634 +nim removeProperty dom.html#removeProperty,Style,cstring proc removeProperty(s: Style; property: cstring) 1635 +nim setProperty dom.html#setProperty,Style,cstring,cstring,string proc setProperty(s: Style; property, value: cstring; priority = "") 1636 +nim getPropertyPriority dom.html#getPropertyPriority,Style,cstring proc getPropertyPriority(s: Style; property: cstring): cstring 1637 +nim preventDefault dom.html#preventDefault,Event proc preventDefault(ev: Event) 1640 +nim stopImmediatePropagation dom.html#stopImmediatePropagation,Event proc stopImmediatePropagation(ev: Event) 1641 +nim stopPropagation dom.html#stopPropagation,Event proc stopPropagation(ev: Event) 1642 +nim getModifierState dom.html#getModifierState,KeyboardEvent,cstring proc getModifierState(ev: KeyboardEvent; keyArg: cstring): bool 1645 +nim getModifierState dom.html#getModifierState,MouseEvent,cstring proc getModifierState(ev: MouseEvent; keyArg: cstring): bool 1648 +nim identifiedTouch dom.html#identifiedTouch,TouchList proc identifiedTouch(list: TouchList): Touch 1651 +nim item dom.html#item,TouchList,int proc item(list: TouchList; i: int): Touch 1652 +nim clearData dom.html#clearData,DataTransfer,cstring proc clearData(dt: DataTransfer; format: cstring) 1655 +nim getData dom.html#getData,DataTransfer,cstring proc getData(dt: DataTransfer; format: cstring): cstring 1656 +nim setData dom.html#setData,DataTransfer,cstring,cstring proc setData(dt: DataTransfer; format: cstring; data: cstring) 1657 +nim setDragImage dom.html#setDragImage,DataTransfer,Element,int,int proc setDragImage(dt: DataTransfer; img: Element; xOffset: int; yOffset: int) 1658 +nim getAsFile dom.html#getAsFile,DataTransferItem proc getAsFile(dti: DataTransferItem): File 1661 +nim setSelectionRange dom.html#setSelectionRange,InputElement,int,int,cstring proc setSelectionRange(e: InputElement; selectionStart: int; selectionEnd: int;\n selectionDirection: cstring = "none") 1664 +nim setRangeText dom.html#setRangeText,InputElement,cstring,int,int,cstring proc setRangeText(e: InputElement; replacement: cstring; startindex: int = 0;\n endindex: int = 0; selectionMode: cstring = "preserve") 1665 +nim setCustomValidity dom.html#setCustomValidity,InputElement,cstring proc setCustomValidity(e: InputElement; error: cstring) 1666 +nim checkValidity dom.html#checkValidity,InputElement proc checkValidity(e: InputElement): bool 1667 +nim slice dom.html#slice,Blob,int,int,cstring proc slice(e: Blob; startindex: int = 0; endindex: int = e.size;\n contentType: cstring = "") 1670 +nim now dom.html#now,Performance proc now(p: Performance): float 1673 +nim removeAllRanges dom.html#removeAllRanges,Selection proc removeAllRanges(s: Selection) 1676 +nim deleteFromDocument dom.html#deleteFromDocument,Selection proc deleteFromDocument(s: Selection) 1677 +nim getRangeAt dom.html#getRangeAt,Selection,int proc getRangeAt(s: Selection; index: int): Range 1678 +nim toString dom.html#toString.c,Selection converter toString(s: Selection): cstring 1679 +nim `$` dom.html#$,Selection proc `$`(s: Selection): string 1680 +nim getItem dom.html#getItem,Storage,cstring proc getItem(s: Storage; key: cstring): cstring 1683 +nim setItem dom.html#setItem,Storage,cstring,cstring proc setItem(s: Storage; key, value: cstring) 1684 +nim clear dom.html#clear,Storage proc clear(s: Storage) 1685 +nim removeItem dom.html#removeItem,Storage,cstring proc removeItem(s: Storage; key: cstring) 1686 +nim setAttr dom.html#setAttr,Node,cstring,cstring proc setAttr(n: Node; key, val: cstring) 1690 +nim window dom.html#window_2 var window 1693 +nim navigator dom.html#navigator_2 var navigator 1694 +nim screen dom.html#screen_2 var screen 1695 +nim document dom.html#document_2 var document 1698 +nim decodeURI dom.html#decodeURI,cstring proc decodeURI(uri: cstring): cstring 1700 +nim encodeURI dom.html#encodeURI,cstring proc encodeURI(uri: cstring): cstring 1701 +nim escape dom.html#escape,cstring proc escape(uri: cstring): cstring 1703 +nim unescape dom.html#unescape,cstring proc unescape(uri: cstring): cstring 1704 +nim decodeURIComponent dom.html#decodeURIComponent,cstring proc decodeURIComponent(uri: cstring): cstring 1706 +nim encodeURIComponent dom.html#encodeURIComponent,cstring proc encodeURIComponent(uri: cstring): cstring 1707 +nim isFinite dom.html#isFinite,BiggestFloat proc isFinite(x: BiggestFloat): bool 1708 +nim isNaN dom.html#isNaN,BiggestFloat proc isNaN(x: BiggestFloat): bool 1709 +nim newEvent dom.html#newEvent,cstring proc newEvent(name: cstring): Event 1712 +nim getElementsByClass dom.html#getElementsByClass,Node,cstring proc getElementsByClass(n: Node; name: cstring): seq[Node] 1714 +nim BoundingRect dom.html#BoundingRect object BoundingRect 1719 +nim getBoundingClientRect dom.html#getBoundingClientRect,Node proc getBoundingClientRect(e: Node): BoundingRect 1722 +nim clientHeight dom.html#clientHeight proc clientHeight(): int 1724 +nim clientWidth dom.html#clientWidth proc clientWidth(): int 1726 +nim inViewport dom.html#inViewport,Node proc inViewport(el: Node): bool 1729 +nim scrollTop dom.html#scrollTop,Node proc scrollTop(e: Node): int 1735 +nim scrollTop= dom.html#scrollTop=,Node,int proc scrollTop=(e: Node; value: int) 1736 +nim scrollLeft dom.html#scrollLeft,Node proc scrollLeft(e: Node): int 1737 +nim scrollHeight dom.html#scrollHeight,Node proc scrollHeight(e: Node): int 1738 +nim scrollWidth dom.html#scrollWidth,Node proc scrollWidth(e: Node): int 1739 +nim offsetHeight dom.html#offsetHeight,Node proc offsetHeight(e: Node): int 1740 +nim offsetWidth dom.html#offsetWidth,Node proc offsetWidth(e: Node): int 1741 +nim offsetTop dom.html#offsetTop,Node proc offsetTop(e: Node): int 1742 +nim offsetLeft dom.html#offsetLeft,Node proc offsetLeft(e: Node): int 1743 +nim newDomParser dom.html#newDomParser proc newDomParser(): DomParser 1746 +nim parseFromString dom.html#parseFromString,DomParser,cstring,cstring proc parseFromString(this: DomParser; str: cstring; mimeType: cstring): Document 1748 +nim newDomException dom.html#newDomException proc newDomException(): DomException 1751 +nim message dom.html#message,DomException proc message(ex: DomException): cstring 1753 +nim name dom.html#name,DomException proc name(ex: DomException): cstring 1755 +nim newFileReader dom.html#newFileReader proc newFileReader(): FileReader 1758 +nim error dom.html#error,FileReader proc error(f: FileReader): DomException 1760 +nim readyState dom.html#readyState,FileReader proc readyState(f: FileReader): FileReaderState 1762 +nim resultAsString dom.html#resultAsString,FileReader proc resultAsString(f: FileReader): cstring 1764 +nim abort dom.html#abort,FileReader proc abort(f: FileReader) 1766 +nim readAsBinaryString dom.html#readAsBinaryString,FileReader,Blob proc readAsBinaryString(f: FileReader; b: Blob) 1768 +nim readAsDataURL dom.html#readAsDataURL,FileReader,Blob proc readAsDataURL(f: FileReader; b: Blob) 1770 +nim readAsText dom.html#readAsText,FileReader, proc readAsText(f: FileReader; b: Blob | File; encoding = cstring"UTF-8") 1772 +nim elementsFromPoint dom.html#elementsFromPoint,DocumentOrShadowRoot,float,float proc elementsFromPoint(n: DocumentOrShadowRoot; x, y: float): seq[Element] 1776 +nim insertAdjacentText dom.html#insertAdjacentText,Node,cstring,cstring proc insertAdjacentText(self: Node; position, data: cstring) 1781 +nim insertAdjacentElement dom.html#insertAdjacentElement,Node,cstring,Node proc insertAdjacentElement(self: Node; position: cstring; element: Node) 1784 +nim insertAdjacentHTML dom.html#insertAdjacentHTML,Node,cstring,cstring proc insertAdjacentHTML(self: Node; position, html: cstring) 1787 +nim after dom.html#after,Node,Node proc after(self: Node; element: Node): Node 1790 +nim before dom.html#before,Node,Node proc before(self: Node; element: Node): Node 1793 +nim append dom.html#append,Node,Node proc append(self: Node; element: Node): Node 1796 +nim closest dom.html#closest,Node,cstring proc closest(self: Node; cssSelector: cstring): Node 1799 +nim hasAttributeNS dom.html#hasAttributeNS,Node,cstring,cstring proc hasAttributeNS(self: Node; namespace, localName: cstring): bool 1802 +nim removeAttributeNS dom.html#removeAttributeNS,Node,cstring,cstring proc removeAttributeNS(self: Node; namespace, attributeName: cstring) 1805 +nim hasPointerCapture dom.html#hasPointerCapture,Node,SomeNumber proc hasPointerCapture(self: Node; pointerId: SomeNumber): bool 1808 +nim releasePointerCapture dom.html#releasePointerCapture,Node,SomeNumber proc releasePointerCapture(self: Node; pointerId: SomeNumber) 1811 +nim requestPointerLock dom.html#requestPointerLock,Node proc requestPointerLock(self: Node) 1814 +nim replaceChildren dom.html#replaceChildren,Node,Node proc replaceChildren(self: Node; replacements: Node) 1817 +nim replaceWith dom.html#replaceWith,Node,Node proc replaceWith(self: Node; replacements: Node) 1820 +nim scrollIntoViewIfNeeded dom.html#scrollIntoViewIfNeeded,Node,bool proc scrollIntoViewIfNeeded(self: Node; centerIfNeeded: bool) 1823 +nim setHTML dom.html#setHTML,Node,cstring proc setHTML(self: Node; html: cstring) 1826 +nim toggleAttribute dom.html#toggleAttribute,Node,cstring proc toggleAttribute(self: Node; name: cstring; force = false): bool 1829 +nim matches dom.html#matches,Node,cstring proc matches(self: Node; cssSelector: cstring): bool 1832 +nim VisualViewport dom.html#VisualViewport type VisualViewport 1837 +nim visualViewport dom.html#visualViewport,Window proc visualViewport(self: Window): VisualViewport 1841 +heading Document Ready dom.html#document-ready Document Ready 0 +heading Document onUnload dom.html#document-onunload Document onUnload 0 +heading Document Autorefresh dom.html#document-autorefresh Document Autorefresh 0 +nimgrp getselection dom.html#getSelection-procs-all proc 1566 +nimgrp cleartimeout dom.html#clearTimeout-procs-all proc 1483 +nimgrp queryselector dom.html#querySelector-procs-all proc 1552 +nimgrp scrollintoview dom.html#scrollIntoView-procs-all proc 1548 +nimgrp vibrate dom.html#vibrate-procs-all proc 1623 +nimgrp queryselectorall dom.html#querySelectorAll-procs-all proc 1553 +nimgrp addeventlistener dom.html#addEventListener-procs-all proc 1490 +nimgrp settimeout dom.html#setTimeout-procs-all proc 1482 +nimgrp focus dom.html#focus-procs-all proc 1507 +nimgrp stop dom.html#stop-procs-all proc 1529 +nimgrp getelementsbyclassname dom.html#getElementsByClassName-procs-all proc 1578 +nimgrp back dom.html#back-procs-all proc 1497 +nimgrp getelementbyid dom.html#getElementById-procs-all proc 1470 +nimgrp blur dom.html#blur-procs-all proc 1498 +nimgrp contains dom.html#contains-procs-all proc 1558 +nimgrp setinterval dom.html#setInterval-procs-all proc 1484 +nimgrp getelementsbytagname dom.html#getElementsByTagName-procs-all proc 1577 +nimgrp handleevent dom.html#handleEvent-procs-all proc 1512 +nimgrp remove dom.html#remove-procs-all proc 1473 +nimgrp routeevent dom.html#routeEvent-procs-all proc 1522 +nimgrp open dom.html#open-procs-all proc 1516 +nimgrp clearinterval dom.html#clearInterval-procs-all proc 1485 +nimgrp getmodifierstate dom.html#getModifierState-procs-all proc 1645 +nimgrp forward dom.html#forward-procs-all proc 1508 +nimgrp checkvalidity dom.html#checkValidity-procs-all proc 1601 diff --git a/dragonbox.html b/dragonbox.html new file mode 100644 index 0000000000000..cefc0e7295418 --- /dev/null +++ b/dragonbox.html @@ -0,0 +1,879 @@ + + + + + + + +std/private/dragonbox + + + + + + + + + + + + + + + + +
+
+

std/private/dragonbox

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Copyright 2020 Junekey Jeon Copyright 2020 Alexander Bolz

+

Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)

+

char* output_end = Dtoa(buffer, value);

+

Converts the given double-precision number into decimal form and stores the result in the given buffer.

+

The buffer must be large enough, i.e. >= DtoaMinBufferLength. The output format is similar to printf("%g"). The output is _not null-terminted.

+

The output is optimal, i.e. the output string

+
  1. rounds back to the input number when read in (using round-to-nearest-even)
  2. +
  3. is as short as possible,
  4. +
  5. is as close to the input number as possible.
  6. +
+

Note: This function may temporarily write up to DtoaMinBufferLength characters into the buffer.

+

This file contains an implementation of Junekey Jeon's Dragonbox algorithm.

+

It is a simplified version of the reference implementation found here: https://github.com/jk-jeon/dragonbox

+

The reference implementation also works with single-precision floating-point numbers and has options to configure the rounding mode.

+

namespace Returns floor(x / 2^n).

+

Technically, right-shift of negative integers is implementation defined... Should easily be optimized into SAR (or equivalent) instruction.

+Returns whether value is divisible by 2^e2Returns whether value is divisible by 5^e5Returns (x * y) / 2^128

+ +
+

Types

+
+
+
BitsType = uint64
+
+ + + Source   +Edit   + +
+
+
+
Double = object
+  bits*: BitsType
+
+ + + Source   +Edit   + +
+
+
+
FloatingDecimal64 {.bycopy.} = object
+  significand*: uint64
+  exponent*: int32
+
+ + + Source   +Edit   + +
+
+
+
uint64x2 {.bycopy.} = object
+  hi*: uint64
+  lo*: uint64
+
+ + + Source   +Edit   + +
+
+
+
ValueType = float
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
dtoaMinBufferLength: cint = 64
+
+ + + Source   +Edit   + +
+
+
+
exponentBias: int32 = 1075'i32
+
+ + + Source   +Edit   + +
+
+
+
exponentMask: BitsType = 9218868437227405312'u64
+
+ + + Source   +Edit   + +
+
+
+
hiddenBit: BitsType = 4503599627370496'u64
+
+ + + Source   +Edit   + +
+
+
+
maxIeeeExponent: BitsType = 2047'u
+
+ + + Source   +Edit   + +
+
+
+
significandMask: BitsType = 4503599627370495'u64
+
+ + + Source   +Edit   + +
+
+
+
significandSize: int32 = 53
+
+ + + Source   +Edit   + +
+
+
+
signMask: BitsType = 9223372036854775808'u64
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc computeDelta(pow10: uint64x2; betaMinus1: int32): uint32 {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc computePow10(k: int32): uint64x2 {.inline, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc constructDouble(bits: BitsType): Double {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc constructDouble(value: ValueType): Double {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc decimalLength(v: uint64): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc floorDivPow2(x: int32; n: int32): int32 {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc floorLog2Pow10(e: int32): int32 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc floorLog10Pow2(e: int32): int32 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc floorLog10ThreeQuartersPow2(e: int32): int32 {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc formatDigits[T: Ordinal](buffer: var openArray[char]; pos: T;
+                              digits: uint64; decimalExponent: int;
+                              forceTrailingDotZero = false): int {.inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hi32(x: uint64): uint32 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isFinite(this: Double): bool {.noSideEffect, ...raises: [], tags: [],
+                                    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isInf(this: Double): bool {.noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isIntegralEndpoint(twoF: uint64; e2: int32; minusK: int32): bool {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isIntegralMidpoint(twoF: uint64; e2: int32; minusK: int32): bool {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isNaN(this: Double): bool {.noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isZero(this: Double): bool {.noSideEffect, ...raises: [], tags: [],
+                                  forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lo32(x: uint64): uint32 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mul128(a: uint64; b: uint64): uint64x2 {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mulParity(twoF: uint64; pow10: uint64x2; betaMinus1: int32): bool {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + 1 mulx, 1 mul + Source   +Edit   + +
+
+ +
+
+
+
proc mulShift(x: uint64; y: uint64x2): uint64 {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + 2 mulx + Source   +Edit   + +
+
+ +
+
+
+
proc multipleOfPow2(value: uint64; e2: int32): bool {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc multipleOfPow5(value: uint64; e5: int32): bool {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc physicalExponent(this: Double): BitsType {.noSideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc physicalSignificand(this: Double): BitsType {.noSideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc printDecimalDigitsBackwards(buf: var openArray[char]; pos: int;
+                                 output64: uint64): int {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc signBit(this: Double): int {.noSideEffect, ...raises: [], tags: [],
+                                  forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toChars(buffer: var openArray[char]; v: float; forceTrailingDotZero = false): int {.
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toDecimal64(ieeeSignificand: uint64; ieeeExponent: uint64): FloatingDecimal64 {.
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toDecimal64AsymmetricInterval(e2: int32): FloatingDecimal64 {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + NB: accept_lower_endpoint = true accept_upper_endpoint = true + Source   +Edit   + +
+
+ +
+
+
+
proc utoa8DigitsSkipTrailingZeros(buf: var openArray[char]; pos: int;
+                                  digits: uint32): int {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template dragonbox_Assert(x: untyped): untyped
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/dragonbox.idx b/dragonbox.idx new file mode 100644 index 0000000000000..6e43be4e19670 --- /dev/null +++ b/dragonbox.idx @@ -0,0 +1,47 @@ +nimTitle dragonbox dragonbox.html module std/private/dragonbox 0 +nim dtoaMinBufferLength dragonbox.html#dtoaMinBufferLength const dtoaMinBufferLength 31 +nim dragonbox_Assert dragonbox.html#dragonbox_Assert.t,untyped template dragonbox_Assert(x: untyped): untyped 41 +nim ValueType dragonbox.html#ValueType type ValueType 49 +nim BitsType dragonbox.html#BitsType type BitsType 50 +nim Double dragonbox.html#Double object Double 53 +nim significandSize dragonbox.html#significandSize const significandSize 57 +nim exponentBias dragonbox.html#exponentBias const exponentBias 61 +nim maxIeeeExponent dragonbox.html#maxIeeeExponent const maxIeeeExponent 64 +nim hiddenBit dragonbox.html#hiddenBit const hiddenBit 67 +nim significandMask dragonbox.html#significandMask const significandMask 70 +nim exponentMask dragonbox.html#exponentMask const exponentMask 73 +nim signMask dragonbox.html#signMask const signMask 76 +nim constructDouble dragonbox.html#constructDouble,BitsType proc constructDouble(bits: BitsType): Double 78 +nim constructDouble dragonbox.html#constructDouble,ValueType proc constructDouble(value: ValueType): Double 81 +nim physicalSignificand dragonbox.html#physicalSignificand,Double proc physicalSignificand(this: Double): BitsType 84 +nim physicalExponent dragonbox.html#physicalExponent,Double proc physicalExponent(this: Double): BitsType 87 +nim isFinite dragonbox.html#isFinite,Double proc isFinite(this: Double): bool 90 +nim isInf dragonbox.html#isInf,Double proc isInf(this: Double): bool 93 +nim isNaN dragonbox.html#isNaN,Double proc isNaN(this: Double): bool 97 +nim isZero dragonbox.html#isZero,Double proc isZero(this: Double): bool 101 +nim signBit dragonbox.html#signBit,Double proc signBit(this: Double): int 104 +nim floorDivPow2 dragonbox.html#floorDivPow2,int32,int32 proc floorDivPow2(x: int32; n: int32): int32 117 +nim floorLog2Pow10 dragonbox.html#floorLog2Pow10,int32 proc floorLog2Pow10(e: int32): int32 120 +nim floorLog10Pow2 dragonbox.html#floorLog10Pow2,int32 proc floorLog10Pow2(e: int32): int32 125 +nim floorLog10ThreeQuartersPow2 dragonbox.html#floorLog10ThreeQuartersPow2,int32 proc floorLog10ThreeQuartersPow2(e: int32): int32 130 +nim uint64x2 dragonbox.html#uint64x2 object uint64x2 140 +nim computePow10 dragonbox.html#computePow10,int32 proc computePow10(k: int32): uint64x2 145 +nim multipleOfPow2 dragonbox.html#multipleOfPow2,uint64,int32 proc multipleOfPow2(value: uint64; e2: int32): bool 777 +nim multipleOfPow5 dragonbox.html#multipleOfPow5,uint64,int32 proc multipleOfPow5(value: uint64; e5: int32): bool 783 +nim FloatingDecimal64 dragonbox.html#FloatingDecimal64 object FloatingDecimal64 821 +nim toDecimal64AsymmetricInterval dragonbox.html#toDecimal64AsymmetricInterval,int32 proc toDecimal64AsymmetricInterval(e2: int32): FloatingDecimal64 826 +nim computeDelta dragonbox.html#computeDelta,uint64x2,int32 proc computeDelta(pow10: uint64x2; betaMinus1: int32): uint32 859 +nim lo32 dragonbox.html#lo32,uint64 proc lo32(x: uint64): uint32 882 +nim hi32 dragonbox.html#hi32,uint64 proc hi32(x: uint64): uint32 885 +nim mul128 dragonbox.html#mul128,uint64,uint64 proc mul128(a: uint64; b: uint64): uint64x2 888 +nim mulShift dragonbox.html#mulShift,uint64,uint64x2 proc mulShift(x: uint64; y: uint64x2): uint64 901 +nim mulParity dragonbox.html#mulParity,uint64,uint64x2,int32 proc mulParity(twoF: uint64; pow10: uint64x2; betaMinus1: int32): bool 909 +nim isIntegralEndpoint dragonbox.html#isIntegralEndpoint,uint64,int32,int32 proc isIntegralEndpoint(twoF: uint64; e2: int32; minusK: int32): bool 918 +nim isIntegralMidpoint dragonbox.html#isIntegralMidpoint,uint64,int32,int32 proc isIntegralMidpoint(twoF: uint64; e2: int32; minusK: int32): bool 927 +nim toDecimal64 dragonbox.html#toDecimal64,uint64,uint64 proc toDecimal64(ieeeSignificand: uint64; ieeeExponent: uint64): FloatingDecimal64 936 +nim utoa8DigitsSkipTrailingZeros dragonbox.html#utoa8DigitsSkipTrailingZeros,openArray[char],int,uint32 proc utoa8DigitsSkipTrailingZeros(buf: var openArray[char]; pos: int; digits: uint32): int 1055 +nim printDecimalDigitsBackwards dragonbox.html#printDecimalDigitsBackwards,openArray[char],int,uint64 proc printDecimalDigitsBackwards(buf: var openArray[char]; pos: int; output64: uint64): int 1073 +nim decimalLength dragonbox.html#decimalLength,uint64 proc decimalLength(v: uint64): int 1149 +nim formatDigits dragonbox.html#formatDigits,openArray[char],T,uint64,int proc formatDigits[T: Ordinal](buffer: var openArray[char]; pos: T; digits: uint64;\n decimalExponent: int; forceTrailingDotZero = false): int 1189 +nim toChars dragonbox.html#toChars,openArray[char],float proc toChars(buffer: var openArray[char]; v: float; forceTrailingDotZero = false): int 1282 +nimgrp constructdouble dragonbox.html#constructDouble-procs-all proc 78 diff --git a/drnim.html b/drnim.html new file mode 100644 index 0000000000000..12ffb623b4985 --- /dev/null +++ b/drnim.html @@ -0,0 +1,185 @@ + + + + + + + +DrNim User Guide + + + + + + + + + + + + + + + + +
+
+

DrNim User Guide

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + + +
+
+ Source   +Edit   + +
+ +

+ +
Author:Andreas Rumpf
Version:2.2.1
+

Introduction

This document describes the usage of the DrNim tool. DrNim combines the Nim frontend with the Z3 proof engine, in order to allow verify/validate software written in Nim. DrNim's command-line options are the same as the Nim compiler's.

+

DrNim currently only checks the sections of your code that are marked via staticBoundChecks: on:

+

{.push staticBoundChecks: on.}
+# <--- code section here ---->
+{.pop.}

+

DrNim currently only tries to prove array indexing or subrange checks, overflow errors are not prevented. Overflows will be checked for in the future.

+

Later versions of the Nim compiler will assume that the checks inside the staticBoundChecks: on environment have been proven correct and so it will omit the runtime checks. If you do not want this behavior, use instead {.push staticBoundChecks: defined(nimDrNim).}. This way the Nim compiler remains unaware of the performed proofs but DrNim will prove your code.

+ +

Installation

Run koch drnim, the executable will afterwards be in $nim/bin/drnim.

+ +

Motivating Example

The follow example highlights what DrNim can easily do, even without additional annotations:

+

{.push staticBoundChecks: on.}
+
+proc sum(a: openArray[int]): int =
+  for i in 0..a.len:
+    result += a[i]
+
+{.pop.}
+
+echo sum([1, 2, 3])

+

This program contains a famous "index out of bounds" bug. DrNim detects it and produces the following error message:

+
cannot prove: i <= len(a) + -1; counter example: i -> 0 a.len -> 0 [IndexCheck]
+

In other words for i == 0 and a.len == 0 (for example!) there would be an index out of bounds error.

+ +

Pre-, postconditions and invariants

DrNim adds 4 additional annotations (pragmas) to Nim:

+
  • requires
  • +
  • ensures
  • +
  • invariant
  • +
  • assume
  • +
+

These pragmas are ignored by the Nim compiler so that they don't have to be disabled via when defined(nimDrNim).

+ +

Invariant

An invariant is a proposition that must be true after every loop iteration, it's tied to the loop body it's part of.

+ +

Requires

A requires annotation describes what the function expects to be true before it's called so that it can perform its operation. A requires annotation is also called a precondition.

+ +

Ensures

An ensures annotation describes what will be true after the function call. An ensures annotation is also called a postcondition.

+ +

Assume

An assume annotation describes what DrNim should assume to be true in this section of the program. It is an unsafe escape mechanism comparable to Nim's cast statement. Use it only when you really know better than DrNim. You should add a comment to a paper that proves the proposition you assume.

+ +

Example: insertionSort

Note: This example does not yet work with DrNim.

+

import std / logic
+
+proc insertionSort(a: var openArray[int]) {.
+    ensures: forall(i in 1..<a.len, a[i-1] <= a[i]).} =
+  
+  for k in 1 ..< a.len:
+    {.invariant: 1 <= k and k <= a.len.}
+    {.invariant: forall(j in 1..<k, i in 0..<j, a[i] <= a[j]).}
+    var t = k
+    while t > 0 and a[t-1] > a[t]:
+      {.invariant: k < a.len.}
+      {.invariant: 0 <= t and t <= k.}
+      {.invariant: forall(j in 1..k, i in 0..<j, j == t or a[i] <= a[j]).}
+      swap a[t], a[t-1]
+      dec t

+

Unfortunately, the invariants required to prove that this code is correct take more code than the imperative instructions. However, this effort can be compensated by the fact that the result needs very little testing. Be aware though that DrNim only proves that after insertionSort this condition holds:

+
forall(i in 1..<a.len, a[i-1] <= a[i])
+

This is required, but not sufficient to describe that a sort operation was performed. For example, the same postcondition is true for this proc which doesn't sort at all:

+

import std / logic
+
+proc insertionSort(a: var openArray[int]) {.
+    ensures: forall(i in 1..<a.len, a[i-1] <= a[i]).} =
+  # does not sort, overwrites `a`'s contents!
+  for i in 0..<a.len: a[i] = i

+ +

Syntax of propositions

The basic syntax is ensures|requires|invariant: <prop>. A prop is either a comparison or a compound:

+
prop = nim_bool_expression
+     | prop 'and' prop
+     | prop 'or' prop
+     | prop '->' prop # implication
+     | prop '<->' prop
+     | 'not' prop
+     | '(' prop ')' # you can group props via ()
+     | forallProp
+     | existsProp
+
+forallProp = 'forall' '(' quantifierList ',' prop ')'
+existsProp = 'exists' '(' quantifierList ',' prop ')'
+
+quantifierList = quantifier (',' quantifier)*
+quantifier = <new identifier> 'in' nim_iteration_expression
+

nim_iteration_expression here is an ordinary expression of Nim code that describes an iteration space, for example 1..4 or 1..<a.len.

+

nim_bool_expression here is an ordinary expression of Nim code of type bool like a == 3 or 23 > a.len.

+

The supported subset of Nim code that can be used in these expressions is currently underspecified but let variables, function parameters and result (which represents the function's final result) are amenable for verification. The expressions must not have any side-effects and must terminate.

+

The operators forall, exists, ->, <-> have to imported from std / logic.

+

+ +
+
+ + +
+
+ + + + diff --git a/drnim.idx b/drnim.idx new file mode 100644 index 0000000000000..deee23d00793c --- /dev/null +++ b/drnim.idx @@ -0,0 +1,17 @@ +markupTitle DrNim User Guide drnim.html DrNim User Guide 0 +heading Introduction drnim.html#introduction Introduction 0 +heading Installation drnim.html#installation Installation 0 +heading Motivating Example drnim.html#motivating-example Motivating Example 0 +heading Pre-, postconditions and invariants drnim.html#preminus-postconditions-and-invariants Pre-, postconditions and invariants 0 +idx requires drnim.html#requires_1 Pre-, postconditions and invariants 0 +idx ensures drnim.html#ensures_1 Pre-, postconditions and invariants 0 +idx invariant drnim.html#invariant_1 Pre-, postconditions and invariants 0 +idx assume drnim.html#assume_1 Pre-, postconditions and invariants 0 +heading Invariant drnim.html#preminus-postconditions-and-invariants-invariant Invariant 0 +heading Requires drnim.html#preminus-postconditions-and-invariants-requires Requires 0 +idx precondition drnim.html#precondition_1 Requires 0 +heading Ensures drnim.html#preminus-postconditions-and-invariants-ensures Ensures 0 +idx postcondition drnim.html#postcondition_1 Ensures 0 +heading Assume drnim.html#preminus-postconditions-and-invariants-assume Assume 0 +heading Example: insertionSort drnim.html#examplecolon-insertionsort Example: insertionSort 0 +heading Syntax of propositions drnim.html#syntax-of-propositions Syntax of propositions 0 diff --git a/dynlib.html b/dynlib.html new file mode 100644 index 0000000000000..a34170fc858b7 --- /dev/null +++ b/dynlib.html @@ -0,0 +1,290 @@ + + + + + + + +std/dynlib + + + + + + + + + + + + + + + + +
+
+

std/dynlib

+
+ +
+ Source   +Edit   + +
+ +

This module implements the ability to access symbols from shared libraries. On POSIX this uses the dlsym mechanism, on Windows LoadLibrary. +

Examples

+

Loading a simple C function

The following example demonstrates loading a function called greet from a library that is determined at runtime based upon a language choice. If the library fails to load or the function greet is not found, it quits with a failure error code.

+ +

Example:

+
import std/dynlib
+type
+  GreetFunction = proc (): cstring {.gcsafe, stdcall.}
+
+proc loadGreet(lang: string) =
+  let lib =
+    case lang
+    of "french":
+      loadLib("french.dll")
+    else:
+      loadLib("english.dll")
+  assert lib != nil, "Error loading library"
+
+  let greet = cast[GreetFunction](lib.symAddr("greet"))
+  assert greet != nil, "Error loading 'greet' function from library"
+
+  echo greet()
+
+  unloadLib(lib)

+
+

Imports

+
+ strutils, posix +
+
+
+

Types

+
+
+
LibHandle = pointer
+
+ + A handle to a dynamically loaded library. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc checkedSymAddr(lib: LibHandle; name: cstring): pointer {.
+    ...raises: [Exception, LibraryError], tags: [RootEffect], forbids: [].}
+
+ + Retrieves the address of a procedure/variable from lib. Raises LibraryError if the symbol could not be found. + Source   +Edit   + +
+
+ +
+
+
+
proc libCandidates(s: string; dest: var seq[string]) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Given a library name pattern s, write possible library names to dest. + Source   +Edit   + +
+
+ +
+
+
+
proc loadLib(): LibHandle {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ + Gets the handle from the current executable. Returns nil if the library could not be loaded. + Source   +Edit   + +
+
+
+
proc loadLib(path: string; globalSymbols = false): LibHandle {....gcsafe,
+    raises: [], tags: [], forbids: [].}
+
+ + Loads a library from path. Returns nil if the library could not be loaded. + Source   +Edit   + +
+
+ +
+
+
+
proc loadLibPattern(pattern: string; globalSymbols = false): LibHandle {.
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + Loads a library with name matching pattern, similar to what the dynlib pragma does. Returns nil if the library could not be loaded.
Warning: +this proc uses the GC and so cannot be used to load the GC.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc raiseInvalidLibrary(name: cstring) {.noinline, noreturn,
+    ...raises: [LibraryError], tags: [], forbids: [].}
+
+ + Raises a LibraryError exception. + Source   +Edit   + +
+
+ +
+
+
+
proc symAddr(lib: LibHandle; name: cstring): pointer {....gcsafe, raises: [],
+    tags: [], forbids: [].}
+
+ + Retrieves the address of a procedure/variable from lib. Returns nil if the symbol could not be found. + Source   +Edit   + +
+
+ +
+
+
+
proc unloadLib(lib: LibHandle) {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ + Unloads the library lib. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/dynlib.idx b/dynlib.idx new file mode 100644 index 0000000000000..cad8c825740ee --- /dev/null +++ b/dynlib.idx @@ -0,0 +1,13 @@ +nimTitle dynlib dynlib.html module std/dynlib 0 +nim LibHandle dynlib.html#LibHandle type LibHandle 49 +nim loadLib dynlib.html#loadLib,string proc loadLib(path: string; globalSymbols = false): LibHandle 51 +nim loadLib dynlib.html#loadLib proc loadLib(): LibHandle 55 +nim unloadLib dynlib.html#unloadLib,LibHandle proc unloadLib(lib: LibHandle) 59 +nim raiseInvalidLibrary dynlib.html#raiseInvalidLibrary,cstring proc raiseInvalidLibrary(name: cstring) 62 +nim symAddr dynlib.html#symAddr,LibHandle,cstring proc symAddr(lib: LibHandle; name: cstring): pointer 66 +nim checkedSymAddr dynlib.html#checkedSymAddr,LibHandle,cstring proc checkedSymAddr(lib: LibHandle; name: cstring): pointer 70 +nim libCandidates dynlib.html#libCandidates,string,seq[string] proc libCandidates(s: string; dest: var seq[string]) 76 +nim loadLibPattern dynlib.html#loadLibPattern,string proc loadLibPattern(pattern: string; globalSymbols = false): LibHandle 88 +heading Examples dynlib.html#examples Examples 0 +heading Loading a simple C function dynlib.html#examples-loading-a-simple-c-function Loading a simple C function 0 +nimgrp loadlib dynlib.html#loadLib-procs-all proc 51 diff --git a/editdistance.html b/editdistance.html new file mode 100644 index 0000000000000..622fe65a38175 --- /dev/null +++ b/editdistance.html @@ -0,0 +1,146 @@ + + + + + + + +std/editdistance + + + + + + + + + + + + + + + + +
+
+

std/editdistance

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements an algorithm to compute the edit distance between two Unicode strings.

+
+

Imports

+
+ unicode +
+
+
+

Procs

+
+
+
+
proc editDistance(a, b: string): int {.noSideEffect, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ +

Returns the unicode-rune edit distance between a and b.

+

This uses the Levenshtein distance algorithm with only a linear memory overhead.

+ +

Example:

+
static: doAssert editdistance("Kitten", "Bitten") == 1
+ Source   +Edit   + +
+
+ +
+
+
+
proc editDistanceAscii(a, b: string): int {.noSideEffect, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Returns the edit distance between a and b.

+

This uses the Levenshtein distance algorithm with only a linear memory overhead.

+ +

Example:

+
static: doAssert editDistanceAscii("Kitten", "Bitten") == 1
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/editdistance.idx b/editdistance.idx new file mode 100644 index 0000000000000..33696f10cc101 --- /dev/null +++ b/editdistance.idx @@ -0,0 +1,6 @@ +nimTitle editdistance editdistance.html module std/editdistance 0 +nim editDistance editdistance.html#editDistance,string,string proc editDistance(a, b: string): int 15 +nim editDistanceAscii editdistance.html#editDistanceAscii,string,string proc editDistanceAscii(a, b: string): int 180 +idx edit distance editdistance.html#edit-distance_1 Module editdistance 0 +idx Levenshtein editdistance.html#levenshtein_1 Module editdistance 0 +idx Levenshtein editdistance.html#levenshtein_2 Module editdistance 0 diff --git a/effecttraits.html b/effecttraits.html new file mode 100644 index 0000000000000..0517cb2a6abaf --- /dev/null +++ b/effecttraits.html @@ -0,0 +1,189 @@ + + + + + + + +std/effecttraits + + + + + + + + + + + + + + + + +
+
+

std/effecttraits

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module provides access to the inferred .raises effects for Nim's macro system. Since: Version 1.4.

+

One can test for the existence of this standard module via defined(nimHasEffectTraitsModule).

+

+
+

Imports

+
+ macros +
+
+
+

Procs

+
+
+
+
proc getForbidsList(fn: NimNode): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Extracts the .forbids list of the func/proc/etc fn. fn has to be a resolved symbol of kind nnkSym. This implies that the macro that calls this proc should accept typed arguments and not untyped arguments. + Source   +Edit   + +
+
+ +
+
+
+
proc getRaisesList(fn: NimNode): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Extracts the .raises list of the func/proc/etc fn. fn has to be a resolved symbol of kind nnkSym. This implies that the macro that calls this proc should accept typed arguments and not untyped arguments. + Source   +Edit   + +
+
+ +
+
+
+
proc getTagsList(fn: NimNode): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Extracts the .tags list of the func/proc/etc fn. fn has to be a resolved symbol of kind nnkSym. This implies that the macro that calls this proc should accept typed arguments and not untyped arguments. + Source   +Edit   + +
+
+ +
+
+
+
proc hasNoSideEffects(fn: NimNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + Return true if the func/proc/etc fn has noSideEffect. fn has to be a resolved symbol of kind nnkSym. This implies that the macro that calls this proc should accept typed arguments and not untyped arguments. + Source   +Edit   + +
+
+ +
+
+
+
proc isGcSafe(fn: NimNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + Return true if the func/proc/etc fn is gcsafe. fn has to be a resolved symbol of kind nnkSym. This implies that the macro that calls this proc should accept typed arguments and not untyped arguments. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/effecttraits.idx b/effecttraits.idx new file mode 100644 index 0000000000000..14cbcacdd0442 --- /dev/null +++ b/effecttraits.idx @@ -0,0 +1,6 @@ +nimTitle effecttraits effecttraits.html module std/effecttraits 0 +nim getRaisesList effecttraits.html#getRaisesList,NimNode proc getRaisesList(fn: NimNode): NimNode 25 +nim getTagsList effecttraits.html#getTagsList,NimNode proc getTagsList(fn: NimNode): NimNode 33 +nim getForbidsList effecttraits.html#getForbidsList,NimNode proc getForbidsList(fn: NimNode): NimNode 41 +nim isGcSafe effecttraits.html#isGcSafe,NimNode proc isGcSafe(fn: NimNode): bool 49 +nim hasNoSideEffects effecttraits.html#hasNoSideEffects,NimNode proc hasNoSideEffects(fn: NimNode): bool 57 diff --git a/encodings.html b/encodings.html new file mode 100644 index 0000000000000..13a9ea3aa7529 --- /dev/null +++ b/encodings.html @@ -0,0 +1,251 @@ + + + + + + + +std/encodings + + + + + + + + + + + + + + + + +
+
+

std/encodings

+
+ +
+ Source   +Edit   + +
+ +

Routines for converting between different character encodings. On UNIX, this uses the iconv library, on Windows the Windows API.

+

The following example shows how to change character encodings.

+ +

Example:

+
import std/encodings
+when defined(windows):
+  let
+    orig = "öäüß"
+    # convert `orig` from "UTF-8" to "CP1252"
+    cp1252 = convert(orig, "CP1252", "UTF-8")
+    # convert `cp1252` from "CP1252" to "ibm850"
+    ibm850 = convert(cp1252, "ibm850", "CP1252")
+    current = getCurrentEncoding()
+  assert orig == "\195\182\195\164\195\188\195\159"
+  assert ibm850 == "\148\132\129\225"
+  assert convert(ibm850, current, "ibm850") == orig
The example below uses a reuseable EncodingConverter object which is created by open with destEncoding and srcEncoding specified. You can use convert on this object multiple times. +

Example:

+
import std/encodings
+when defined(windows):
+  var fromGB2312 = open("utf-8", "gb2312")
+  let first = "\203\173\197\194\163\191\210\187" &
+      "\203\242\209\204\211\234\200\206\198\189\201\250"
+  assert fromGB2312.convert(first) == "谁怕?一蓑烟雨任平生"
+
+  let second = "\211\208\176\215\205\183\200\231" &
+      "\208\194\163\172\199\227\184\199\200\231\185\202"
+  assert fromGB2312.convert(second) == "有白头如新,倾盖如故"

+
+

Imports

+
+ os, assertions +
+
+
+

Types

+
+
+
EncodingConverter = ptr ConverterObj
+
+ + Can convert between two character sets. + Source   +Edit   + +
+
+
+
EncodingError = object of ValueError
+
+ + Exception that is raised for encoding errors. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc close(c: EncodingConverter) {....raises: [], tags: [], forbids: [].}
+
+ + Frees the resources the converter c holds. + Source   +Edit   + +
+
+ +
+
+
+
proc convert(c: EncodingConverter; s: string): string {....raises: [OSError],
+    tags: [], forbids: [].}
+
+ + Converts s to destEncoding that was given to the converter c. It assumes that s is in srcEncoding.
Warning: +UTF-16BE and UTF-32 conversions are not supported on Windows.
+ + Source   +Edit   + +
+
+
+
proc convert(s: string; destEncoding = "UTF-8"; srcEncoding = "CP1252"): string {.
+    ...raises: [EncodingError, OSError], tags: [], forbids: [].}
+
+ + Converts s to destEncoding. It assumed that s is in srcEncoding. This opens a converter, uses it and closes it again and is thus more convenient but also likely less efficient than re-using a converter.
Warning: +UTF-16BE and UTF-32 conversions are not supported on Windows.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc getCurrentEncoding(uiApp = false): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + Retrieves the current encoding. On Unix, "UTF-8" is always returned. The uiApp parameter is Windows specific. If true, the UI's code-page is returned, if false, the Console's code-page is returned. + Source   +Edit   + +
+
+ +
+
+
+
proc open(destEncoding = "UTF-8"; srcEncoding = "CP1252"): EncodingConverter {.
+    ...raises: [EncodingError], tags: [], forbids: [].}
+
+ + Opens a converter that can convert from srcEncoding to destEncoding. Raises EncodingError if it cannot fulfill the request. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/encodings.idx b/encodings.idx new file mode 100644 index 0000000000000..3c595a9b4c31d --- /dev/null +++ b/encodings.idx @@ -0,0 +1,10 @@ +nimTitle encodings encodings.html module std/encodings 0 +nim EncodingConverter encodings.html#EncodingConverter type EncodingConverter 49 +nim EncodingError encodings.html#EncodingError object EncodingError 58 +nim getCurrentEncoding encodings.html#getCurrentEncoding proc getCurrentEncoding(uiApp = false): string 331 +nim open encodings.html#open,string,string proc open(destEncoding = "UTF-8"; srcEncoding = "CP1252"): EncodingConverter 340 +nim close encodings.html#close,EncodingConverter proc close(c: EncodingConverter) 359 +nim convert encodings.html#convert,EncodingConverter,string proc convert(c: EncodingConverter; s: string): string 457 +nim convert encodings.html#convert,string,string,string proc convert(s: string; destEncoding = "UTF-8"; srcEncoding = "CP1252"): string 500 +idx iconv encodings.html#iconv_1 Module encodings 0 +nimgrp convert encodings.html#convert-procs-all proc 457 diff --git a/endians.html b/endians.html new file mode 100644 index 0000000000000..ecf26f50ccf3b --- /dev/null +++ b/endians.html @@ -0,0 +1,270 @@ + + + + + + + +std/endians + + + + + + + + + + + + + + + + +
+
+

std/endians

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module contains helpers that deal with different byte orders (endian).

+

Endianness is the order of bytes of a value in memory. Big-endian means that the most significant byte is stored at the smallest memory address, while little endian means that the least-significant byte is stored at the smallest address. See also https://en.wikipedia.org/wiki/Endianness.

+

Unstable API.

+

+
+

Procs

+
+
+
+
proc bigEndian16(outp, inp: pointer) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Copies inp to outp, storing it in 16-bit big-endian order. Both buffers are supposed to contain at least 2 bytes. + Source   +Edit   + +
+
+ +
+
+
+
proc bigEndian32(outp, inp: pointer) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Copies inp to outp, storing it in 32-bit big-endian order. Both buffers are supposed to contain at least 4 bytes. + Source   +Edit   + +
+
+ +
+
+
+
proc bigEndian64(outp, inp: pointer) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Copies inp to outp, storing it in 64-bit big-endian order. Both buffers are supposed to contain at least 8 bytes. + Source   +Edit   + +
+
+ +
+
+
+
proc littleEndian16(outp, inp: pointer) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Copies inp to outp, storing it in 16-bit little-endian order. Both buffers are supposed to contain at least 2 bytes. + Source   +Edit   + +
+
+ +
+
+
+
proc littleEndian32(outp, inp: pointer) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Copies inp to outp, storing it in 32-bit little-endian order. Both buffers are supposed to contain at least 4 bytes. + Source   +Edit   + +
+
+ +
+
+
+
proc littleEndian64(outp, inp: pointer) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Copies inp to outp, storing it in 64-bit little-endian order. Both buffers are supposed to contain at least 8 bytes. + Source   +Edit   + +
+
+ +
+
+
+
proc swapEndian16(outp, inp: pointer) {.inline, noSideEffect, ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + Copies inp to outp, reversing the byte order. Both buffers are supposed to contain at least 2 bytes. +

Example:

+
var a = [1'u8, 2]
+var b: array[2, uint8]
+swapEndian16(addr b, addr a)
+assert b == [2'u8, 1]
+ Source   +Edit   + +
+
+ +
+
+
+
proc swapEndian32(outp, inp: pointer) {.inline, noSideEffect, ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + Copies inp to outp, reversing the byte order. Both buffers are supposed to contain at least 4 bytes. +

Example:

+
var a = [1'u8, 2, 3, 4]
+var b: array[4, uint8]
+swapEndian32(addr b, addr a)
+assert b == [4'u8, 3, 2, 1]
+ Source   +Edit   + +
+
+ +
+
+
+
proc swapEndian64(outp, inp: pointer) {.inline, noSideEffect, ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + Copies inp to outp, reversing the byte order. Both buffers are supposed to contain at least 8 bytes. +

Example:

+
var a = [1'u8, 2, 3, 4, 5, 6, 7, 8]
+var b: array[8, uint8]
+swapEndian64(addr b, addr a)
+assert b == [8'u8, 7, 6, 5, 4, 3, 2, 1]
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/endians.idx b/endians.idx new file mode 100644 index 0000000000000..2b2866b377d4c --- /dev/null +++ b/endians.idx @@ -0,0 +1,11 @@ +nimTitle endians endians.html module std/endians 0 +nim swapEndian64 endians.html#swapEndian64,pointer,pointer proc swapEndian64(outp, inp: pointer) 63 +nim swapEndian32 endians.html#swapEndian32,pointer,pointer proc swapEndian32(outp, inp: pointer) 74 +nim swapEndian16 endians.html#swapEndian16,pointer,pointer proc swapEndian16(outp, inp: pointer) 85 +nim littleEndian64 endians.html#littleEndian64,pointer,pointer proc littleEndian64(outp, inp: pointer) 131 +nim littleEndian32 endians.html#littleEndian32,pointer,pointer proc littleEndian32(outp, inp: pointer) 134 +nim littleEndian16 endians.html#littleEndian16,pointer,pointer proc littleEndian16(outp, inp: pointer) 137 +nim bigEndian64 endians.html#bigEndian64,pointer,pointer proc bigEndian64(outp, inp: pointer) 140 +nim bigEndian32 endians.html#bigEndian32,pointer,pointer proc bigEndian32(outp, inp: pointer) 143 +nim bigEndian16 endians.html#bigEndian16,pointer,pointer proc bigEndian16(outp, inp: pointer) 146 +idx endian endians.html#endian_1 Module endians 0 diff --git a/enumerate.html b/enumerate.html new file mode 100644 index 0000000000000..6c8891718f359 --- /dev/null +++ b/enumerate.html @@ -0,0 +1,133 @@ + + + + + + + +std/enumerate + + + + + + + + + + + + + + + + +
+
+

std/enumerate

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements enumerate syntactic sugar based on Nim's macro system.

+
+

Imports

+
+ since, macros +
+
+
+

Macros

+
+
+
+
macro enumerate(x: ForLoopStmt): untyped
+
+ +

Enumerating iterator for collections.

+

It yields (count, value) tuples (which must be immediately unpacked). The default starting count 0 can be manually overridden if needed.

+ +

Example:

+
let a = [10, 20, 30]
+var b: seq[(int, int)] = @[]
+for i, x in enumerate(a):
+  b.add((i, x))
+assert b == @[(0, 10), (1, 20), (2, 30)]
+
+let c = "abcd"
+var d: seq[(int, char)]
+for (i, x) in enumerate(97, c):
+  d.add((i, x))
+assert d == @[(97, 'a'), (98, 'b'), (99, 'c'), (100, 'd')]
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/enumerate.idx b/enumerate.idx new file mode 100644 index 0000000000000..1ffa20d9e4787 --- /dev/null +++ b/enumerate.idx @@ -0,0 +1,2 @@ +nimTitle enumerate enumerate.html module std/enumerate 0 +nim enumerate enumerate.html#enumerate.m,ForLoopStmt macro enumerate(x: ForLoopStmt): untyped 17 diff --git a/enumutils.html b/enumutils.html new file mode 100644 index 0000000000000..7491817279575 --- /dev/null +++ b/enumutils.html @@ -0,0 +1,270 @@ + + + + + + + +std/enumutils + + + + + + + + + + + + + + + + +
+
+

std/enumutils

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
func symbolName[T: enum](a: T): string
+
+ +

Returns the symbol name of an enum.

+

This uses symbolRank.

+ +

Example:

+
type B = enum
+  b0 = (10, "kb0")
+  b1 = "kb1"
+  b2
+let b = B.low
+assert b.symbolName == "b0"
+assert $b == "kb0"
+static: assert B.high.symbolName == "b2"
+type C = enum # HoleyEnum
+  c0 = -3
+  c1 = 4
+  c2 = 20
+assert c1.symbolName == "c1"
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator items[T: HoleyEnum](E: typedesc[T]): T
+
+ + Iterates over an enum with holes. +

Example:

+
type
+  A = enum
+    a0 = 2
+    a1 = 4
+    a2
+  B[T] = enum
+    b0 = 2
+    b1 = 4
+from std/sequtils import toSeq
+assert A.toSeq == [a0, a1, a2]
+assert B[float].toSeq == [B[float].b0, B[float].b1]
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro genEnumCaseStmt(typ: typedesc; argSym: typed; default: typed;
+                      userMin, userMax: static[int];
+                      normalizer: static[proc (s: string): string]): untyped
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template symbolRank[T: enum](a: T): int
+
+ +

Returns the index in which a is listed in T.

+

The cost for a HoleyEnum is implementation defined, currently optimized for small enums, otherwise is O(T.enumLen).

+ +

Example:

+
type
+  A = enum # HoleyEnum
+    a0 = -3
+    a1 = 10
+    a2
+    a3 = (20, "f3Alt")
+  B = enum # OrdinalEnum
+    b0
+    b1
+    b2
+  C = enum # OrdinalEnum
+    c0 = 10
+    c1
+    c2
+assert a2.symbolRank == 2
+assert b2.symbolRank == 2
+assert c2.symbolRank == 2
+assert c2.ord == 12
+assert a2.ord == 11
+var invalid = 7.A
+doAssertRaises(IndexDefect): discard invalid.symbolRank
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/enumutils.idx b/enumutils.idx new file mode 100644 index 0000000000000..e63a75dfdcf31 --- /dev/null +++ b/enumutils.idx @@ -0,0 +1,5 @@ +nimTitle enumutils enumutils.html module std/enumutils 0 +nim genEnumCaseStmt enumutils.html#genEnumCaseStmt.m,typedesc,typed,typed,static[int],static[int],static[proc(string)] macro genEnumCaseStmt(typ: typedesc; argSym: typed; default: typed;\n userMin, userMax: static[int];\n normalizer: static[proc (s: string): string]): untyped 19 +nim items enumutils.html#items.i,typedesc[T] iterator items[T: HoleyEnum](E: typedesc[T]): T 94 +nim symbolRank enumutils.html#symbolRank.t,T template symbolRank[T: enum](a: T): int 147 +nim symbolName enumutils.html#symbolName,T proc symbolName[T: enum](a: T): string 180 diff --git a/envvars.html b/envvars.html new file mode 100644 index 0000000000000..dfa4e1a36d95b --- /dev/null +++ b/envvars.html @@ -0,0 +1,284 @@ + + + + + + + +std/envvars + + + + + + + + + + + + + + + + +
+
+

std/envvars

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

The std/envvars module implements environment variable handling.

+
+

Imports

+
+ oserrors +
+
+
+

Types

+
+
+
ReadEnvEffect = object of ReadIOEffect
+
+ + Effect that denotes a read from an environment variable. + Source   +Edit   + +
+
+
+
WriteEnvEffect = object of WriteIOEffect
+
+ + Effect that denotes a write to an environment variable. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc delEnv(key: string) {....tags: [WriteEnvEffect], raises: [OSError],
+                           forbids: [].}
+
+ +

Deletes the environment variable named key. If an error occurs, OSError is raised.

+

See also:ven

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc existsEnv(key: string): bool {....tags: [ReadEnvEffect], raises: [],
+                                    forbids: [].}
+
+ +

Checks whether the environment variable named key exists. Returns true if it exists, false otherwise.

+

See also:

+ + +

Example:

+
assert not existsEnv("unknownEnv")
+ Source   +Edit   + +
+
+ +
+
+
+
proc getEnv(key: string; default = ""): string {....tags: [ReadEnvEffect],
+    raises: [], forbids: [].}
+
+ +

Returns the value of the environment variable named key.

+

If the variable does not exist, "" is returned. To distinguish whether a variable exists or it's value is just "", call existsEnv(key) proc.

+

See also:

+ + +

Example:

+
assert getEnv("unknownEnv") == ""
+assert getEnv("unknownEnv", "doesn't exist") == "doesn't exist"
+ Source   +Edit   + +
+
+ +
+
+
+
proc putEnv(key, val: string) {....tags: [WriteEnvEffect], raises: [OSError],
+                                forbids: [].}
+
+ +

Sets the value of the environment variable named key to val. If an error occurs, OSError is raised.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator envPairs(): tuple[key, value: string] {....tags: [ReadEnvEffect],
+    raises: [], forbids: [].}
+
+ +

Iterate over all environments variables.

+

In the first component of the tuple is the name of the current variable stored, in the second its value.

+

Works in native backends, nodejs and vm, like the following APIs:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/envvars.idx b/envvars.idx new file mode 100644 index 0000000000000..b7e445245e97b --- /dev/null +++ b/envvars.idx @@ -0,0 +1,12 @@ +nimTitle envvars envvars.html module std/envvars 0 +nim ReadEnvEffect envvars.html#ReadEnvEffect object ReadEnvEffect 15 +nim WriteEnvEffect envvars.html#WriteEnvEffect object WriteEnvEffect 17 +nim getEnv envvars.html#getEnv,string,string proc getEnv(key: string; default = ""): string 80 +nim existsEnv envvars.html#existsEnv,string proc existsEnv(key: string): bool 102 +nim putEnv envvars.html#putEnv,string,string proc putEnv(key, val: string) 116 +nim delEnv envvars.html#delEnv,string proc delEnv(key: string) 134 +nim envPairs envvars.html#envPairs.i iterator envPairs(): tuple[key, value: string] 205 +idx environment variable envvars.html#environment-variable_1 Module envvars 0 +idx environment variable envvars.html#environment-variable_2 Module envvars 0 +idx environment variable envvars.html#environment-variable_3 Module envvars 0 +idx environments variables envvars.html#environments-variables_1 Module envvars 0 diff --git a/epoll.html b/epoll.html new file mode 100644 index 0000000000000..a051df15105da --- /dev/null +++ b/epoll.html @@ -0,0 +1,445 @@ + + + + + + + +std/epoll + + + + + + + + + + + + + + + + +
+
+

std/epoll

+
+ +
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ posix +
+
+
+

Types

+
+
+
EpollData {.importc: "epoll_data_t", header: "<sys/epoll.h>", pure, final, union.} = object
+  fd* {.importc: "fd".}: cint
+  u32* {.importc: "u32".}: uint32
+  u64* {.importc: "u64".}: uint64
+
+ + + Source   +Edit   + +
+
+
+
EpollEvent {.importc: "struct epoll_event", header: "<sys/epoll.h>", pure,
+             final, packed.} = object
+  events*: uint32
+  data*: EpollData
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
EPOLL_CTL_ADD = 1
+
+ + + Source   +Edit   + +
+
+
+
EPOLL_CTL_DEL = 2
+
+ + + Source   +Edit   + +
+
+
+
EPOLL_CTL_MOD = 3
+
+ + + Source   +Edit   + +
+
+
+
EPOLLERR = 0x00000008
+
+ + + Source   +Edit   + +
+
+
+
EPOLLET = 2147483648
+
+ + + Source   +Edit   + +
+
+
+
EPOLLEXCLUSIVE = 268435456
+
+ + + Source   +Edit   + +
+
+
+
EPOLLHUP = 0x00000010
+
+ + + Source   +Edit   + +
+
+
+
EPOLLIN = 0x00000001
+
+ + + Source   +Edit   + +
+
+
+
EPOLLMSG = 0x00000400
+
+ + + Source   +Edit   + +
+
+
+
EPOLLONESHOT = 1073741824
+
+ + + Source   +Edit   + +
+
+
+
EPOLLOUT = 0x00000004
+
+ + + Source   +Edit   + +
+
+
+
EPOLLPRI = 0x00000002
+
+ + + Source   +Edit   + +
+
+
+
EPOLLRDBAND = 0x00000080
+
+ + + Source   +Edit   + +
+
+
+
EPOLLRDHUP = 0x00002000
+
+ + + Source   +Edit   + +
+
+
+
EPOLLRDNORM = 0x00000040
+
+ + + Source   +Edit   + +
+
+
+
EPOLLWAKEUP = 536870912
+
+ + + Source   +Edit   + +
+
+
+
EPOLLWRBAND = 0x00000200
+
+ + + Source   +Edit   + +
+
+
+
EPOLLWRNORM = 0x00000100
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc epoll_create(size: cint): cint {.importc: "epoll_create",
+                                      header: "<sys/epoll.h>", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ +

Creates an epoll instance. Returns an fd for the new instance.

+

The "size" parameter is a hint specifying the number of file descriptors to be associated with the new instance. The fd returned by epoll_create() should be closed with close().

+ + Source   +Edit   + +
+
+ +
+
+
+
proc epoll_create1(flags: cint): cint {.importc: "epoll_create1",
+                                        header: "<sys/epoll.h>", ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + Same as epoll_create but with an FLAGS parameter. The unused SIZE parameter has been dropped. + Source   +Edit   + +
+
+ +
+
+
+
proc epoll_ctl(epfd: cint; op: cint; fd: cint | SocketHandle;
+               event: ptr EpollEvent): cint {.importc: "epoll_ctl",
+    header: "<sys/epoll.h>", ...raises: [], tags: [], forbids: [].}
+
+ +

Manipulate an epoll instance "epfd". Returns 0 in case of success, -1 in case of error (the "errno" variable will contain the specific error code).

+

The "op" parameter is one of the EPOLL_CTL_* constants defined above. The "fd" parameter is the target of the operation. The "event" parameter describes which events the caller is interested in and any associated user data.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc epoll_wait(epfd: cint; events: ptr EpollEvent; maxevents: cint;
+                timeout: cint): cint {.importc: "epoll_wait",
+                                       header: "<sys/epoll.h>", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ +

Wait for events on an epoll instance "epfd". Returns the number of triggered events returned in "events" buffer. Or -1 in case of error with the "errno" variable set to the specific error code. The "events" parameter is a buffer that will contain triggered events. The "maxevents" is the maximum number of events to be returned ( usually size of "events" ). The "timeout" parameter specifies the maximum wait time in milliseconds (-1 == infinite).

+

This function is a cancellation point and therefore not marked with __THROW.

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/epoll.idx b/epoll.idx new file mode 100644 index 0000000000000..4302f1ffdaaa9 --- /dev/null +++ b/epoll.idx @@ -0,0 +1,25 @@ +nimTitle epoll epoll.html module std/epoll 0 +nim EPOLLIN epoll.html#EPOLLIN const EPOLLIN 13 +nim EPOLLPRI epoll.html#EPOLLPRI const EPOLLPRI 14 +nim EPOLLOUT epoll.html#EPOLLOUT const EPOLLOUT 15 +nim EPOLLERR epoll.html#EPOLLERR const EPOLLERR 16 +nim EPOLLHUP epoll.html#EPOLLHUP const EPOLLHUP 17 +nim EPOLLRDNORM epoll.html#EPOLLRDNORM const EPOLLRDNORM 18 +nim EPOLLRDBAND epoll.html#EPOLLRDBAND const EPOLLRDBAND 19 +nim EPOLLWRNORM epoll.html#EPOLLWRNORM const EPOLLWRNORM 20 +nim EPOLLWRBAND epoll.html#EPOLLWRBAND const EPOLLWRBAND 21 +nim EPOLLMSG epoll.html#EPOLLMSG const EPOLLMSG 22 +nim EPOLLRDHUP epoll.html#EPOLLRDHUP const EPOLLRDHUP 23 +nim EPOLLEXCLUSIVE epoll.html#EPOLLEXCLUSIVE const EPOLLEXCLUSIVE 24 +nim EPOLLWAKEUP epoll.html#EPOLLWAKEUP const EPOLLWAKEUP 25 +nim EPOLLONESHOT epoll.html#EPOLLONESHOT const EPOLLONESHOT 26 +nim EPOLLET epoll.html#EPOLLET const EPOLLET 27 +nim EPOLL_CTL_ADD epoll.html#EPOLL_CTL_ADD const EPOLL_CTL_ADD 32 +nim EPOLL_CTL_DEL epoll.html#EPOLL_CTL_DEL const EPOLL_CTL_DEL 33 +nim EPOLL_CTL_MOD epoll.html#EPOLL_CTL_MOD const EPOLL_CTL_MOD 34 +nim EpollData epoll.html#EpollData object EpollData 44 +nim EpollEvent epoll.html#EpollEvent object EpollEvent 50 +nim epoll_create epoll.html#epoll_create,cint proc epoll_create(size: cint): cint 54 +nim epoll_create1 epoll.html#epoll_create1,cint proc epoll_create1(flags: cint): cint 62 +nim epoll_ctl epoll.html#epoll_ctl,cint,cint,,ptr.EpollEvent proc epoll_ctl(epfd: cint; op: cint; fd: cint | SocketHandle; event: ptr EpollEvent): cint 67 +nim epoll_wait epoll.html#epoll_wait,cint,ptr.EpollEvent,cint,cint proc epoll_wait(epfd: cint; events: ptr EpollEvent; maxevents: cint; timeout: cint): cint 77 diff --git a/estp.html b/estp.html new file mode 100644 index 0000000000000..cbc3f322fb609 --- /dev/null +++ b/estp.html @@ -0,0 +1,199 @@ + + + + + + + +Embedded Stack Trace Profiler (ESTP) User Guide + + + + + + + + + + + + + + + + +
+
+

Embedded Stack Trace Profiler (ESTP) User Guide

+ + +
Author:Andreas Rumpf
Version:2.2.1

Nim comes with a platform independent profiler - the Embedded Stack Trace Profiler (ESTP). The profiler is embedded into your executable. To activate the profiler you need to do:

+
  • compile your program with the --profiler:on --stackTrace:on command line options
  • +
  • import the nimprof module
  • +
  • run your program as usual.
  • +
+

You can in fact look at nimprof's source code to see how to implement your own profiler.

+

The setting --profiler:on defines the conditional symbol profiler. You can use when compileOption("profiler") to make the switch seamless. If profiler is off, your program runs normally. Otherwise your program is profiled.

+

when compileOption("profiler"):
+  import std/nimprof

+

After your program has finished the profiler will create a file profile_results.txt containing the profiling results.

+

Since the profiler works by examining stack traces, it's essential that the option --stackTrace:on is active! Unfortunately this means that a profiling build is much slower than a release build.

+ +

Memory profiler

You can also use ESTP as a memory profiler to see which stack traces allocate the most memory and thus create the most GC pressure. It may also help to find memory leaks. To activate the memory profiler you need to do:

+
  • compile your program with the --profiler:off --stackTrace:on -d:memProfiler command line options. Yes it's --profiler:off.
  • +
  • import the nimprof module
  • +
  • run your program as usual.
  • +
+

Define the symbol ignoreAllocationSize so that only the number of allocations is counted and the sizes of the memory allocations do not matter.

+ +

Example results file

The results file lists stack traces ordered by significance.

+

The following example file has been generated by profiling the Nim compiler itself: It shows that in total 5.4% of the runtime has been spent in crcFromRope or its children.

+

In general the stack traces show you immediately where the problem is because the trace acts like an explanation; in traditional profilers you can only find expensive leaf functions easily but the reason why they are invoked often remains mysterious.

+
total executions of each stack trace:
+Entry: 0/3391 Calls: 84/4160 = 2.0% [sum: 84; 84/4160 = 2.0%]
+  newCrcFromRopeAux
+  crcFromRope
+  writeRopeIfNotEqual
+  shouldRecompile
+  writeModule
+  myClose
+  closePasses
+  processModule
+  CompileModule
+  CompileProject
+  CommandCompileToC
+  MainCommand
+  HandleCmdLine
+  nim
+Entry: 1/3391 Calls: 46/4160 = 1.1% [sum: 130; 130/4160 = 3.1%]
+  updateCrc32
+  newCrcFromRopeAux
+  crcFromRope
+  writeRopeIfNotEqual
+  shouldRecompile
+  writeModule
+  myClose
+  closePasses
+  processModule
+  CompileModule
+  CompileProject
+  CommandCompileToC
+  MainCommand
+  HandleCmdLine
+  nim
+Entry: 2/3391 Calls: 41/4160 = 0.99% [sum: 171; 171/4160 = 4.1%]
+  updateCrc32
+  updateCrc32
+  newCrcFromRopeAux
+  crcFromRope
+  writeRopeIfNotEqual
+  shouldRecompile
+  writeModule
+  myClose
+  closePasses
+  processModule
+  CompileModule
+  CompileProject
+  CommandCompileToC
+  MainCommand
+  HandleCmdLine
+  nim
+Entry: 3/3391 Calls: 41/4160 = 0.99% [sum: 212; 212/4160 = 5.1%]
+  crcFromFile
+  writeRopeIfNotEqual
+  shouldRecompile
+  writeModule
+  myClose
+  closePasses
+  processModule
+  CompileModule
+  CompileProject
+  CommandCompileToC
+  MainCommand
+  HandleCmdLine
+  nim
+Entry: 4/3391 Calls: 41/4160 = 0.99% [sum: 253; 253/4160 = 6.1%]
+  updateCrc32
+  crcFromFile
+  writeRopeIfNotEqual
+  shouldRecompile
+  writeModule
+  myClose
+  closePasses
+  processModule
+  CompileModule
+  CompileProject
+  CommandCompileToC
+  MainCommand
+  HandleCmdLine
+  nim
+Entry: 5/3391 Calls: 32/4160 = 0.77% [sum: 285; 285/4160 = 6.9%]
+  pop
+  newCrcFromRopeAux
+  crcFromRope
+  writeRopeIfNotEqual
+  shouldRecompile
+  writeModule
+  myClose
+  closePasses
+  processModule
+  CompileModule
+  CompileProject
+  CommandCompileToC
+  MainCommand
+  HandleCmdLine
+  nim
+Entry: 6/3391 Calls: 17/4160 = 0.41% [sum: 302; 302/4160 = 7.3%]
+  doOperation
+  forAllChildrenAux
+  pop
+  newCrcFromRopeAux
+  crcFromRope
+  writeRopeIfNotEqual
+  shouldRecompile
+  writeModule
+  myClose
+  closePasses
+  processModule
+  CompileModule
+  CompileProject
+  CommandCompileToC
+  MainCommand
+  HandleCmdLine
+  ...
+  nim
+Entry: 7/3391 Calls: 14/4160 = 0.34% [sum: 316; 316/4160 = 7.6%]
+  Contains
+  isAccessible
+  interiorAllocatedPtr
+  gcMark
+  markStackAndRegisters
+  collectCTBody
+  collectCT
+  rawNewObj
+  newObj
+  newNode
+  copyTree
+  matchesAux
+  matches
+  resolveOverloads
+  semOverloadedCall
+  semOverloadedCallAnalyseEffects
+  ...
+  CommandCompileToC
+  MainCommand
+  HandleCmdLine
+ + + + +
+
+ + + + diff --git a/estp.idx b/estp.idx new file mode 100644 index 0000000000000..537781f90717f --- /dev/null +++ b/estp.idx @@ -0,0 +1,3 @@ +markupTitle Embedded Stack Trace Profiler (ESTP) User Guide estp.html Embedded Stack Trace Profiler (ESTP) User Guide 0 +heading Memory profiler estp.html#memory-profiler Memory profiler 0 +heading Example results file estp.html#example-results-file Example results file 0 diff --git a/exceptions.html b/exceptions.html new file mode 100644 index 0000000000000..9e515551ddd15 --- /dev/null +++ b/exceptions.html @@ -0,0 +1,505 @@ + + + + + + + +system/exceptions + + + + + + + + + + + + + + + + +
+
+

system/exceptions

+
+ +
+ Source   +Edit   + +
+ +

Exception and effect types used in Nim code.

+
+

Types

+
+
+
AccessViolationDefect = object of Defect
+
+ + +Raised for invalid memory access errors + Source   +Edit   + +
+
+
+
ArithmeticDefect = object of Defect
+
+ + +Raised if any kind of arithmetic error occurred. + Source   +Edit   + +
+
+
+
AssertionDefect = object of Defect
+
+ +

+Raised when assertion is proved wrong.

+

Usually the result of using the assert() template.

+ + Source   +Edit   + +
+
+
+
DeadThreadDefect = object of Defect
+
+ + +Raised if it is attempted to send a message to a dead thread. + Source   +Edit   + +
+
+
+
DivByZeroDefect = object of ArithmeticDefect
+
+ + +Raised for runtime integer divide-by-zero errors. + Source   +Edit   + +
+
+
+
EOFError = object of IOError
+
+ + +Raised if an IO "end of file" error occurred. + Source   +Edit   + +
+
+
+
ExecIOEffect = object of IOEffect
+
+ + Effect describing an executing IO operation. + Source   +Edit   + +
+
+
+
FieldDefect = object of Defect
+
+ + +Raised if a record field is not accessible because its discriminant's value does not fit. + Source   +Edit   + +
+
+
+
FloatDivByZeroDefect = object of FloatingPointDefect
+
+ +

+Raised by division by zero.

+

Divisor is zero and dividend is a finite nonzero number.

+ + Source   +Edit   + +
+
+
+
FloatInexactDefect = object of FloatingPointDefect
+
+ +

+Raised for inexact results.

+

The operation produced a result that cannot be represented with infinite precision -- for example: 2.0 / 3.0, log(1.1)

+

Note: Nim currently does not detect these!

+ + Source   +Edit   + +
+
+
+
FloatingPointDefect = object of Defect
+
+ + +Base class for floating point exceptions. + Source   +Edit   + +
+
+
+
FloatInvalidOpDefect = object of FloatingPointDefect
+
+ +

+Raised by invalid operations according to IEEE.

+

Raised by 0.0/0.0, for example.

+ + Source   +Edit   + +
+
+
+
FloatOverflowDefect = object of FloatingPointDefect
+
+ +

+Raised for overflows.

+

The operation produced a result that exceeds the range of the exponent.

+ + Source   +Edit   + +
+
+
+
FloatUnderflowDefect = object of FloatingPointDefect
+
+ +

+Raised for underflows.

+

The operation produced a result that is too small to be represented as a normal number.

+ + Source   +Edit   + +
+
+
+
IndexDefect = object of Defect
+
+ + +Raised if an array index is out of bounds. + Source   +Edit   + +
+
+
+
IOEffect = object of RootEffect
+
+ + IO effect. + Source   +Edit   + +
+
+
+
IOError = object of CatchableError
+
+ + +Raised if an IO error occurred. + Source   +Edit   + +
+
+
+
KeyError = object of ValueError
+
+ +

+Raised if a key cannot be found in a table.

+

Mostly used by the tables module, it can also be raised by other collection modules like sets or strtabs.

+ + Source   +Edit   + +
+
+
+
LibraryError = object of OSError
+
+ + +Raised if a dynamic library could not be loaded. + Source   +Edit   + +
+
+
+
NilAccessDefect = object of Defect
+
+ +

+Raised on dereferences of nil pointers.

+

This is only raised if the segfaults module was imported!

+ + Source   +Edit   + +
+
+
+
ObjectAssignmentDefect = object of Defect
+
+ + +Raised if an object gets assigned to its parent's object. + Source   +Edit   + +
+
+
+
ObjectConversionDefect = object of Defect
+
+ + +Raised if an object is converted to an incompatible object type. You can use of operator to check if conversion will succeed. + Source   +Edit   + +
+
+
+
OSError = object of CatchableError
+  errorCode*: int32          ## OS-defined error code describing this error.
+
+ + +Raised if an operating system service failed. + Source   +Edit   + +
+
+
+
OutOfMemDefect = object of Defect
+
+ + +Raised for unsuccessful attempts to allocate memory. + Source   +Edit   + +
+
+
+
OverflowDefect = object of ArithmeticDefect
+
+ +

+Raised for runtime integer overflows.

+

This happens for calculations whose results are too large to fit in the provided bits.

+ + Source   +Edit   + +
+
+
+
RangeDefect = object of Defect
+
+ + +Raised if a range check error occurred. + Source   +Edit   + +
+
+
+
ReadIOEffect = object of IOEffect
+
+ + Effect describing a read IO operation. + Source   +Edit   + +
+
+
+
ReraiseDefect = object of Defect
+
+ + +Raised if there is no exception to reraise. + Source   +Edit   + +
+
+
+
ResourceExhaustedError = object of CatchableError
+
+ + +Raised if a resource request could not be fulfilled. + Source   +Edit   + +
+
+
+
StackOverflowDefect = object of Defect
+
+ + +Raised if the hardware stack used for subroutine calls overflowed. + Source   +Edit   + +
+
+
+
TimeEffect = object of RootEffect
+
+ + Time effect. + Source   +Edit   + +
+
+
+
ValueError = object of CatchableError
+
+ + +Raised for string and object conversion errors. + Source   +Edit   + +
+
+
+
WriteIOEffect = object of IOEffect
+
+ + Effect describing a write IO operation. + Source   +Edit   + +
+
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/exceptions.idx b/exceptions.idx new file mode 100644 index 0000000000000..c3cd72fb6c56b --- /dev/null +++ b/exceptions.idx @@ -0,0 +1,34 @@ +nimTitle exceptions exceptions.html module system/exceptions 0 +nim TimeEffect exceptions.html#TimeEffect object TimeEffect 4 +nim IOEffect exceptions.html#IOEffect object IOEffect 5 +nim ReadIOEffect exceptions.html#ReadIOEffect object ReadIOEffect 6 +nim WriteIOEffect exceptions.html#WriteIOEffect object WriteIOEffect 7 +nim ExecIOEffect exceptions.html#ExecIOEffect object ExecIOEffect 8 +nim IOError exceptions.html#IOError object IOError 11 +nim EOFError exceptions.html#EOFError object EOFError 13 +nim OSError exceptions.html#OSError object OSError 15 +nim LibraryError exceptions.html#LibraryError object LibraryError 18 +nim ResourceExhaustedError exceptions.html#ResourceExhaustedError object ResourceExhaustedError 20 +nim ArithmeticDefect exceptions.html#ArithmeticDefect object ArithmeticDefect 22 +nim DivByZeroDefect exceptions.html#DivByZeroDefect object DivByZeroDefect 24 +nim OverflowDefect exceptions.html#OverflowDefect object OverflowDefect 27 +nim AccessViolationDefect exceptions.html#AccessViolationDefect object AccessViolationDefect 32 +nim AssertionDefect exceptions.html#AssertionDefect object AssertionDefect 34 +nim ValueError exceptions.html#ValueError object ValueError 39 +nim KeyError exceptions.html#KeyError object KeyError 41 +nim OutOfMemDefect exceptions.html#OutOfMemDefect object OutOfMemDefect 47 +nim IndexDefect exceptions.html#IndexDefect object IndexDefect 49 +nim FieldDefect exceptions.html#FieldDefect object FieldDefect 52 +nim RangeDefect exceptions.html#RangeDefect object RangeDefect 55 +nim StackOverflowDefect exceptions.html#StackOverflowDefect object StackOverflowDefect 57 +nim ReraiseDefect exceptions.html#ReraiseDefect object ReraiseDefect 59 +nim ObjectAssignmentDefect exceptions.html#ObjectAssignmentDefect object ObjectAssignmentDefect 61 +nim ObjectConversionDefect exceptions.html#ObjectConversionDefect object ObjectConversionDefect 63 +nim FloatingPointDefect exceptions.html#FloatingPointDefect object FloatingPointDefect 66 +nim FloatInvalidOpDefect exceptions.html#FloatInvalidOpDefect object FloatInvalidOpDefect 68 +nim FloatDivByZeroDefect exceptions.html#FloatDivByZeroDefect object FloatDivByZeroDefect 72 +nim FloatOverflowDefect exceptions.html#FloatOverflowDefect object FloatOverflowDefect 76 +nim FloatUnderflowDefect exceptions.html#FloatUnderflowDefect object FloatUnderflowDefect 80 +nim FloatInexactDefect exceptions.html#FloatInexactDefect object FloatInexactDefect 85 +nim DeadThreadDefect exceptions.html#DeadThreadDefect object DeadThreadDefect 92 +nim NilAccessDefect exceptions.html#NilAccessDefect object NilAccessDefect 94 diff --git a/exitprocs.html b/exitprocs.html new file mode 100644 index 0000000000000..0c28fc742b960 --- /dev/null +++ b/exitprocs.html @@ -0,0 +1,164 @@ + + + + + + + +std/exitprocs + + + + + + + + + + + + + + + + +
+
+

std/exitprocs

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module allows adding hooks to program exit.

+
+

Imports

+
+ locks +
+
+
+

Procs

+
+
+
+
proc addExitProc(cl: proc () {.closure.}) {....raises: [], tags: [], forbids: [].}
+
+ + Adds/registers a quit procedure. Each call to addExitProc registers another quit procedure. They are executed on a last-in, first-out basis. + Source   +Edit   + +
+
+
+
proc addExitProc(cl: proc () {.noconv.}) {....raises: [], tags: [], forbids: [].}
+
+ + overload for noconv procs. + Source   +Edit   + +
+
+ +
+
+
+
proc getProgramResult(): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setProgramResult(a: int) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/exitprocs.idx b/exitprocs.idx new file mode 100644 index 0000000000000..1322c9b18752c --- /dev/null +++ b/exitprocs.idx @@ -0,0 +1,6 @@ +nimTitle exitprocs exitprocs.html module std/exitprocs 0 +nim addExitProc exitprocs.html#addExitProc,proc) proc addExitProc(cl: proc () {.closure.}) 56 +nim addExitProc exitprocs.html#addExitProc,proc)_2 proc addExitProc(cl: proc () {.noconv.}) 66 +nim getProgramResult exitprocs.html#getProgramResult proc getProgramResult(): int 73 +nim setProgramResult exitprocs.html#setProgramResult,int proc setProgramResult(a: int) 81 +nimgrp addexitproc exitprocs.html#addExitProc-procs-all proc 56 diff --git a/fenv.html b/fenv.html new file mode 100644 index 0000000000000..ce4018f61a034 --- /dev/null +++ b/fenv.html @@ -0,0 +1,745 @@ + + + + + + + +std/fenv + + + + + + + + + + + + + + + + +
+
+

std/fenv

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Floating-point environment. Handling of floating-point rounding and exceptions (overflow, division by zero, etc.). The types, vars and procs are bindings for the C standard library <fenv.h> header.

+
+

Types

+
+
+
Tfenv {.importc: "fenv_t", header: "<fenv.h>", final, pure.} = object
+
+ + Represents the entire floating-point environment. The floating-point environment refers collectively to any floating-point status flags and control modes supported by the implementation. + Source   +Edit   + +
+
+
+
Tfexcept {.importc: "fexcept_t", header: "<fenv.h>", final, pure.} = object
+
+ + Represents the floating-point status flags collectively, including any status the implementation associates with the flags. A floating-point status flag is a system variable whose value is set (but never cleared) when a floating-point exception is raised, which occurs as a side effect of exceptional floating-point arithmetic to provide auxiliary information. A floating-point control mode is a system variable whose value may be set by the user to affect the subsequent behavior of floating-point arithmetic. + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
FE_ALL_EXCEPT {.importc, header: "<fenv.h>".}: cint
+
+ + bitwise OR of all supported exceptions + Source   +Edit   + +
+
+
+
FE_DFL_ENV {.importc, header: "<fenv.h>".}: cint
+
+ + macro of type pointer to fenv_t to be used as the argument to functions taking an argument of type fenv_t; in this case the default environment will be used + Source   +Edit   + +
+
+
+
FE_DIVBYZERO {.importc, header: "<fenv.h>".}: cint
+
+ + division by zero + Source   +Edit   + +
+
+
+
FE_DOWNWARD {.importc, header: "<fenv.h>".}: cint
+
+ + round toward -Inf + Source   +Edit   + +
+
+
+
FE_INEXACT {.importc, header: "<fenv.h>".}: cint
+
+ + inexact result + Source   +Edit   + +
+
+
+
FE_INVALID {.importc, header: "<fenv.h>".}: cint
+
+ + invalid operation + Source   +Edit   + +
+
+
+
FE_OVERFLOW {.importc, header: "<fenv.h>".}: cint
+
+ + result not representable due to overflow + Source   +Edit   + +
+
+
+
FE_TONEAREST {.importc, header: "<fenv.h>".}: cint
+
+ + round to nearest + Source   +Edit   + +
+
+
+
FE_TOWARDZERO {.importc, header: "<fenv.h>".}: cint
+
+ + round toward 0 + Source   +Edit   + +
+
+
+
FE_UNDERFLOW {.importc, header: "<fenv.h>".}: cint
+
+ + result not representable due to underflow + Source   +Edit   + +
+
+
+
FE_UPWARD {.importc, header: "<fenv.h>".}: cint
+
+ + round toward +Inf + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc feclearexcept(excepts: cint): cint {.importc, header: "<fenv.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Clear the supported exceptions represented by excepts. + Source   +Edit   + +
+
+ +
+
+
+
proc fegetenv(envp: ptr Tfenv): cint {.importc, header: "<fenv.h>", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + Store the current floating-point environment in the object pointed to by envp. + Source   +Edit   + +
+
+ +
+
+
+
proc fegetexceptflag(flagp: ptr Tfexcept; excepts: cint): cint {.importc,
+    header: "<fenv.h>", ...raises: [], tags: [], forbids: [].}
+
+ + Store implementation-defined representation of the exception flags indicated by excepts in the object pointed to by flagp. + Source   +Edit   + +
+
+ +
+
+
+
proc fegetround(): cint {.importc, header: "<fenv.h>", ...raises: [], tags: [],
+                          forbids: [].}
+
+ + Get current rounding direction. + Source   +Edit   + +
+
+ +
+
+
+
proc feholdexcept(envp: ptr Tfenv): cint {.importc, header: "<fenv.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Save the current environment in the object pointed to by envp, clear exception flags and install a non-stop mode (if available) for all exceptions. + Source   +Edit   + +
+
+ +
+
+
+
proc feraiseexcept(excepts: cint): cint {.importc, header: "<fenv.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Raise the supported exceptions represented by excepts. + Source   +Edit   + +
+
+ +
+
+
+
proc fesetenv(a1: ptr Tfenv): cint {.importc, header: "<fenv.h>", ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + Establish the floating-point environment represented by the object pointed to by envp. + Source   +Edit   + +
+
+ +
+
+
+
proc fesetexceptflag(flagp: ptr Tfexcept; excepts: cint): cint {.importc,
+    header: "<fenv.h>", ...raises: [], tags: [], forbids: [].}
+
+ + Set complete status for exceptions indicated by excepts according to the representation in the object pointed to by flagp. + Source   +Edit   + +
+
+ +
+
+
+
proc fesetround(roundingDirection: cint): cint {.importc, header: "<fenv.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Establish the rounding direction represented by roundingDirection. + Source   +Edit   + +
+
+ +
+
+
+
proc fetestexcept(excepts: cint): cint {.importc, header: "<fenv.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Determine which of subset of the exceptions specified by excepts are currently set. + Source   +Edit   + +
+
+ +
+
+
+
proc feupdateenv(envp: ptr Tfenv): cint {.importc, header: "<fenv.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Save current exceptions in temporary storage, install environment represented by object pointed to by envp and raise exceptions according to saved exceptions. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template digits(T: typedesc[float32]): int
+
+ + Number of decimal digits that can be represented in a 32-bit floating-point type without losing precision. + Source   +Edit   + +
+
+
+
template digits(T: typedesc[float64]): int
+
+ + Number of decimal digits that can be represented in a 64-bit floating-point type without losing precision. + Source   +Edit   + +
+
+ +
+
+
+
template epsilon(T: typedesc[float32]): float32
+
+ + The difference between 1.0 and the smallest number greater than 1.0 that can be represented in a 32-bit floating-point type. + Source   +Edit   + +
+
+
+
template epsilon(T: typedesc[float64]): float64
+
+ + The difference between 1.0 and the smallest number greater than 1.0 that can be represented in a 64-bit floating-point type. + Source   +Edit   + +
+
+ +
+
+
+
template fpRadix(): int
+
+ + The (integer) value of the radix used to represent any floating point type on the architecture used to build the program. + Source   +Edit   + +
+
+ +
+
+
+
template mantissaDigits(T: typedesc[float32]): int
+
+ + Number of digits (in base floatingPointRadix) in the mantissa of 32-bit floating-point numbers. + Source   +Edit   + +
+
+
+
template mantissaDigits(T: typedesc[float64]): int
+
+ + Number of digits (in base floatingPointRadix) in the mantissa of 64-bit floating-point numbers. + Source   +Edit   + +
+
+ +
+
+
+
template max10Exponent(T: typedesc[float32]): int
+
+ + Maximum (positive) exponent in base 10 for 32-bit floating-point numbers. + Source   +Edit   + +
+
+
+
template max10Exponent(T: typedesc[float64]): int
+
+ + Maximum (positive) exponent in base 10 for 64-bit floating-point numbers. + Source   +Edit   + +
+
+ +
+
+
+
template maxExponent(T: typedesc[float32]): int
+
+ + Maximum (positive) exponent for 32-bit floating-point numbers. + Source   +Edit   + +
+
+
+
template maxExponent(T: typedesc[float64]): int
+
+ + Maximum (positive) exponent for 64-bit floating-point numbers. + Source   +Edit   + +
+
+ +
+
+
+
template maximumPositiveValue(T: typedesc[float32]): float32
+
+ + The largest positive number that can be represented in a 32-bit floating-point type. + Source   +Edit   + +
+
+
+
template maximumPositiveValue(T: typedesc[float64]): float64
+
+ + The largest positive number that can be represented in a 64-bit floating-point type. + Source   +Edit   + +
+
+ +
+
+
+
template min10Exponent(T: typedesc[float32]): int
+
+ + Minimum (negative) exponent in base 10 for 32-bit floating-point numbers. + Source   +Edit   + +
+
+
+
template min10Exponent(T: typedesc[float64]): int
+
+ + Minimum (negative) exponent in base 10 for 64-bit floating-point numbers. + Source   +Edit   + +
+
+ +
+
+
+
template minExponent(T: typedesc[float32]): int
+
+ + Minimum (negative) exponent for 32-bit floating-point numbers. + Source   +Edit   + +
+
+
+
template minExponent(T: typedesc[float64]): int
+
+ + Minimum (negative) exponent for 64-bit floating-point numbers. + Source   +Edit   + +
+
+ +
+
+
+
template minimumPositiveValue(T: typedesc[float32]): float32
+
+ + The smallest positive (nonzero) number that can be represented in a 32-bit floating-point type. + Source   +Edit   + +
+
+
+
template minimumPositiveValue(T: typedesc[float64]): float64
+
+ + The smallest positive (nonzero) number that can be represented in a 64-bit floating-point type. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/fenv.idx b/fenv.idx new file mode 100644 index 0000000000000..b8907ac9f2484 --- /dev/null +++ b/fenv.idx @@ -0,0 +1,53 @@ +nimTitle fenv fenv.html module std/fenv 0 +nim FE_DIVBYZERO fenv.html#FE_DIVBYZERO var FE_DIVBYZERO 19 +nim FE_INEXACT fenv.html#FE_INEXACT var FE_INEXACT 21 +nim FE_INVALID fenv.html#FE_INVALID var FE_INVALID 23 +nim FE_OVERFLOW fenv.html#FE_OVERFLOW var FE_OVERFLOW 25 +nim FE_UNDERFLOW fenv.html#FE_UNDERFLOW var FE_UNDERFLOW 27 +nim FE_ALL_EXCEPT fenv.html#FE_ALL_EXCEPT var FE_ALL_EXCEPT 29 +nim FE_DOWNWARD fenv.html#FE_DOWNWARD var FE_DOWNWARD 31 +nim FE_TONEAREST fenv.html#FE_TONEAREST var FE_TONEAREST 33 +nim FE_TOWARDZERO fenv.html#FE_TOWARDZERO var FE_TOWARDZERO 35 +nim FE_UPWARD fenv.html#FE_UPWARD var FE_UPWARD 37 +nim FE_DFL_ENV fenv.html#FE_DFL_ENV var FE_DFL_ENV 39 +nim Tfenv fenv.html#Tfenv object Tfenv 45 +nim Tfexcept fenv.html#Tfexcept object Tfexcept 50 +nim feclearexcept fenv.html#feclearexcept,cint proc feclearexcept(excepts: cint): cint 61 +nim fegetexceptflag fenv.html#fegetexceptflag,ptr.Tfexcept,cint proc fegetexceptflag(flagp: ptr Tfexcept; excepts: cint): cint 64 +nim feraiseexcept fenv.html#feraiseexcept,cint proc feraiseexcept(excepts: cint): cint 69 +nim fesetexceptflag fenv.html#fesetexceptflag,ptr.Tfexcept,cint proc fesetexceptflag(flagp: ptr Tfexcept; excepts: cint): cint 72 +nim fetestexcept fenv.html#fetestexcept,cint proc fetestexcept(excepts: cint): cint 77 +nim fegetround fenv.html#fegetround proc fegetround(): cint 81 +nim fesetround fenv.html#fesetround,cint proc fesetround(roundingDirection: cint): cint 84 +nim fegetenv fenv.html#fegetenv,ptr.Tfenv proc fegetenv(envp: ptr Tfenv): cint 87 +nim feholdexcept fenv.html#feholdexcept,ptr.Tfenv proc feholdexcept(envp: ptr Tfenv): cint 91 +nim fesetenv fenv.html#fesetenv,ptr.Tfenv proc fesetenv(a1: ptr Tfenv): cint 96 +nim feupdateenv fenv.html#feupdateenv,ptr.Tfenv proc feupdateenv(envp: ptr Tfenv): cint 100 +nim fpRadix fenv.html#fpRadix.t template fpRadix(): int 128 +nim mantissaDigits fenv.html#mantissaDigits.t,typedesc[float32] template mantissaDigits(T: typedesc[float32]): int 132 +nim digits fenv.html#digits.t,typedesc[float32] template digits(T: typedesc[float32]): int 135 +nim minExponent fenv.html#minExponent.t,typedesc[float32] template minExponent(T: typedesc[float32]): int 138 +nim maxExponent fenv.html#maxExponent.t,typedesc[float32] template maxExponent(T: typedesc[float32]): int 140 +nim min10Exponent fenv.html#min10Exponent.t,typedesc[float32] template min10Exponent(T: typedesc[float32]): int 142 +nim max10Exponent fenv.html#max10Exponent.t,typedesc[float32] template max10Exponent(T: typedesc[float32]): int 145 +nim minimumPositiveValue fenv.html#minimumPositiveValue.t,typedesc[float32] template minimumPositiveValue(T: typedesc[float32]): float32 148 +nim maximumPositiveValue fenv.html#maximumPositiveValue.t,typedesc[float32] template maximumPositiveValue(T: typedesc[float32]): float32 151 +nim epsilon fenv.html#epsilon.t,typedesc[float32] template epsilon(T: typedesc[float32]): float32 154 +nim mantissaDigits fenv.html#mantissaDigits.t,typedesc[float64] template mantissaDigits(T: typedesc[float64]): int 158 +nim digits fenv.html#digits.t,typedesc[float64] template digits(T: typedesc[float64]): int 161 +nim minExponent fenv.html#minExponent.t,typedesc[float64] template minExponent(T: typedesc[float64]): int 164 +nim maxExponent fenv.html#maxExponent.t,typedesc[float64] template maxExponent(T: typedesc[float64]): int 166 +nim min10Exponent fenv.html#min10Exponent.t,typedesc[float64] template min10Exponent(T: typedesc[float64]): int 168 +nim max10Exponent fenv.html#max10Exponent.t,typedesc[float64] template max10Exponent(T: typedesc[float64]): int 171 +nim minimumPositiveValue fenv.html#minimumPositiveValue.t,typedesc[float64] template minimumPositiveValue(T: typedesc[float64]): float64 174 +nim maximumPositiveValue fenv.html#maximumPositiveValue.t,typedesc[float64] template maximumPositiveValue(T: typedesc[float64]): float64 177 +nim epsilon fenv.html#epsilon.t,typedesc[float64] template epsilon(T: typedesc[float64]): float64 180 +nimgrp minimumpositivevalue fenv.html#minimumPositiveValue-templates-all template 148 +nimgrp digits fenv.html#digits-templates-all template 135 +nimgrp maximumpositivevalue fenv.html#maximumPositiveValue-templates-all template 151 +nimgrp min10exponent fenv.html#min10Exponent-templates-all template 142 +nimgrp mantissadigits fenv.html#mantissaDigits-templates-all template 132 +nimgrp minexponent fenv.html#minExponent-templates-all template 138 +nimgrp max10exponent fenv.html#max10Exponent-templates-all template 145 +nimgrp epsilon fenv.html#epsilon-templates-all template 154 +nimgrp maxexponent fenv.html#maxExponent-templates-all template 140 diff --git a/files.html b/files.html new file mode 100644 index 0000000000000..567df3844a7b5 --- /dev/null +++ b/files.html @@ -0,0 +1,177 @@ + + + + + + + +std/files + + + + + + + + + + + + + + + + +
+
+

std/files

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements file handling.

+

See also:

+ +

+
+

Imports

+
+ paths, osfiles +
+
+
+

Procs

+
+
+
+
proc fileExists(filename: Path): bool {.inline, ...tags: [ReadDirEffect],
+                                        sideEffect, ...raises: [], forbids: [].}
+
+ +

Returns true if filename exists and is a regular file or symlink.

+

Directories, device files, named pipes and sockets return false.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc moveFile(source, dest: Path) {.inline, ...tags: [ReadDirEffect, ReadIOEffect,
+    WriteIOEffect], raises: [OSError, IOError, Exception], forbids: [].}
+
+ +

Moves a file from source to dest.

+

Symlinks are not followed: if source is a symlink, it is itself moved, not its target.

+

If this fails, OSError is raised. If dest already exists, it will be overwritten.

+

Can be used to rename files.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc removeFile(file: Path) {.inline, ...tags: [WriteDirEffect], raises: [OSError],
+                              forbids: [].}
+
+ +

Removes the file.

+

If this fails, OSError is raised. This does not fail if the file never existed in the first place.

+

On Windows, ignores the read-only attribute.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/files.idx b/files.idx new file mode 100644 index 0000000000000..e0583202a9180 --- /dev/null +++ b/files.idx @@ -0,0 +1,5 @@ +nimTitle files files.html module std/files 0 +nim fileExists files.html#fileExists,Path proc fileExists(filename: Path): bool 12 +nim removeFile files.html#removeFile,Path proc removeFile(file: Path) 18 +nim moveFile files.html#moveFile,Path,Path proc moveFile(source, dest: Path) 31 +idx rename files files.html#rename-files_1 Module files 0 diff --git a/filters.html b/filters.html new file mode 100644 index 0000000000000..80daa626a0370 --- /dev/null +++ b/filters.html @@ -0,0 +1,246 @@ + + + + + + + +Source Code Filters + + + + + + + + + + + + + + + + +
+
+

Source Code Filters

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + + +
+
+ Source   +Edit   + +
+ +

A Source Code Filter (SCF) transforms the input character stream to an in-memory output stream before parsing. A filter can be used to provide templating systems or preprocessors.

+

To use a filter for a source file the #? notation is used:

+
#? stdtmpl(subsChar = '$', metaChar = '#')
+#proc generateXML(name, age: string): string =
+#  result = ""
+<xml>
+  <name>$name</name>
+  <age>$age</age>
+</xml>
+

As the example shows, passing arguments to a filter can be done just like an ordinary procedure call with named or positional arguments. The available parameters depend on the invoked filter. Before version 0.12.0 of the language #! was used instead of #?.

+

Hint: With --hint:codeBegin:on or --verbosity:2 (or higher) while compiling or nim check, Nim lists the processed code after each filter application.

+ +

Usage

First, put your SCF code in a separate file with filters specified in the first line. Note: You can name your SCF file with any file extension you want, but the conventional extension is .nimf (it used to be .tmpl but that was too generic, for example preventing github to recognize it as Nim source file).

+

If we use generateXML code shown above and call the SCF file xmlGen.nimf In your main.nim:

+

include "xmlGen.nimf"
+
+echo generateXML("John Smith","42")

+ +

Pipe operator

Filters can be combined with the | pipe operator:

+
#? strip(startswith="<") | stdtmpl
+#proc generateXML(name, age: string): string =
+#  result = ""
+<xml>
+  <name>$name</name>
+  <age>$age</age>
+</xml>
+ +

Available filters

+

Replace filter

The replace filter replaces substrings in each line.

+

Parameters and their defaults:

+
  • sub: string = ""
    +
    the substring that is searched for
    +
    +
  • +
  • by: string = ""
    +
    the string the substring is replaced with
    +
    +
  • +
+ +

Strip filter

The strip filter simply removes leading and trailing whitespace from each line.

+

Parameters and their defaults:

+
  • startswith: string = ""
    +
    strip only the lines that start with startswith (ignoring leading whitespace). If empty every line is stripped.
    +
    +
  • +
  • leading: bool = true
    +
    strip leading whitespace
    +
    +
  • +
  • trailing: bool = true
    +
    strip trailing whitespace
    +
    +
  • +
+ +

StdTmpl filter

The stdtmpl filter provides a simple templating engine for Nim. The filter uses a line based parser: Lines prefixed with a meta character (default: #) contain Nim code, other lines are verbatim. Because indentation-based parsing is not suited for a templating engine, control flow statements need end X delimiters.

+

Parameters and their defaults:

+
  • metaChar: char = '#'
    +
    prefix for a line that contains Nim code
    +
    +
  • +
  • subsChar: char = '$'
    +
    prefix for a Nim expression within a template line
    +
    +
  • +
  • conc: string = " & "
    +
    the operation for concatenation
    +
    +
  • +
  • emit: string = "result.add"
    +
    the operation to emit a string literal
    +
    +
  • +
  • toString: string = "$"
    +
    the operation that is applied to each expression
    +
    +
  • +
+

Example:

+
#? stdtmpl | standard
+#proc generateHTMLPage(title, currentTab, content: string,
+#                      tabs: openArray[string]): string =
+#  result = ""
+<head><title>$title</title></head>
+<body>
+  <div id="menu">
+    <ul>
+  #for tab in items(tabs):
+    #if currentTab == tab:
+    <li><a id="selected"
+    #else:
+    <li><a
+    #end if
+    href="${tab}.html">$tab</a></li>
+  #end for
+    </ul>
+  </div>
+  <div id="content">
+    $content
+    A dollar: $$.
+  </div>
+</body>
+

The filter transforms this into:

+

proc generateHTMLPage(title, currentTab, content: string,
+                      tabs: openArray[string]): string =
+  result = ""
+  result.add("<head><title>" & $(title) & "</title></head>\n" &
+    "<body>\n" &
+    "  <div id=\"menu\">\n" &
+    "    <ul>\n")
+  for tab in items(tabs):
+    if currentTab == tab:
+      result.add("    <li><a id=\"selected\" \n")
+    else:
+      result.add("    <li><a\n")
+    #end
+    result.add("    href=\"" & $(tab) & ".html\">" & $(tab) & "</a></li>\n")
+  #end
+  result.add("    </ul>\n" &
+    "  </div>\n" &
+    "  <div id=\"content\">\n" &
+    "    " & $(content) & "\n" &
+    "    A dollar: $.\n" &
+    "  </div>\n" &
+    "</body>\n")

+

Each line that does not start with the meta character (ignoring leading whitespace) is converted to a string literal that is added to result.

+

The substitution character introduces a Nim expression e within the string literal. e is converted to a string with the toString operation which defaults to $. For strong type checking, set toString to the empty string. e must match this PEG pattern:

+
e <- [a-zA-Z\128-\255][a-zA-Z0-9\128-\255_.]* / '{' x '}'
+x <- '{' x+ '}' / [^}]*
+

To produce a single substitution character it has to be doubled: $$ produces $.

+

The template engine is quite flexible. It is easy to produce a procedure that writes the template code directly to a file:

+
#? stdtmpl(emit="f.write") | standard
+#proc writeHTMLPage(f: File, title, currentTab, content: string,
+#                   tabs: openArray[string]) =
+<head><title>$title</title></head>
+<body>
+  <div id="menu">
+    <ul>
+  #for tab in items(tabs):
+    #if currentTab == tab:
+    <li><a id="selected"
+    #else:
+    <li><a
+    #end if
+    href="${tab}.html" title = "$title - $tab">$tab</a></li>
+  #end for
+    </ul>
+  </div>
+  <div id="content">
+    $content
+    A dollar: $$.
+  </div>
+</body>
+

+ +
+
+ + +
+
+ + + + diff --git a/filters.idx b/filters.idx new file mode 100644 index 0000000000000..0b00c6e8a6fd4 --- /dev/null +++ b/filters.idx @@ -0,0 +1,7 @@ +markupTitle Source Code Filters filters.html Source Code Filters 0 +heading Usage filters.html#usage Usage 0 +heading Pipe operator filters.html#pipe-operator Pipe operator 0 +heading Available filters filters.html#available-filters Available filters 0 +heading Replace filter filters.html#available-filters-replace-filter Replace filter 0 +heading Strip filter filters.html#available-filters-strip-filter Strip filter 0 +heading StdTmpl filter filters.html#available-filters-stdtmpl-filter StdTmpl filter 0 diff --git a/formatfloat.html b/formatfloat.html new file mode 100644 index 0000000000000..31aac7b1d4808 --- /dev/null +++ b/formatfloat.html @@ -0,0 +1,247 @@ + + + + + + + +std/formatfloat + + + + + + + + + + + + + + + + +
+
+

std/formatfloat

+
+ +
+ Source   +Edit   + +
+ +

This module implements formatting floats as strings.

+ +
+

Procs

+
+
+
+
func `$`(x: float | float32): string
+
+ + Outplace version of addFloat. + Source   +Edit   + +
+
+ +
+
+
+
proc addFloat(result: var string; x: float | float32) {.inline.}
+
+ + Converts float to its string representation and appends it to result. +

Example:

+
var
+  s = "foo:"
+  b = 45.67
+s.addFloat(45.67)
+assert s == "foo:45.67"
+ Source   +Edit   + +
+
+ +
+
+
+
proc addFloatRoundtrip(result: var string; x: float | float32)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addFloatSprintf(result: var string; x: float) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc writeFloatToBuffer(buf: var array[65, char]; value: BiggestFloat | float32): int {.
+    inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc writeFloatToBufferRoundtrip(buf: var array[65, char]; value: BiggestFloat): int {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

This is the implementation to format floats.

+

returns the amount of bytes written to buf not counting the terminating '0' character.

+ + Source   +Edit   + +
+
+
+
proc writeFloatToBufferRoundtrip(buf: var array[65, char]; value: float32): int {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc writeFloatToBufferSprintf(buf: var array[65, char]; value: BiggestFloat): int {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

This is the implementation to format floats.

+

returns the amount of bytes written to buf not counting the terminating '0' character.

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/formatfloat.idx b/formatfloat.idx new file mode 100644 index 0000000000000..153d036687fe4 --- /dev/null +++ b/formatfloat.idx @@ -0,0 +1,10 @@ +nimTitle formatfloat formatfloat.html module std/formatfloat 0 +nim writeFloatToBufferRoundtrip formatfloat.html#writeFloatToBufferRoundtrip,array[,char],BiggestFloat proc writeFloatToBufferRoundtrip(buf: var array[65, char]; value: BiggestFloat): int 26 +nim writeFloatToBufferRoundtrip formatfloat.html#writeFloatToBufferRoundtrip,array[,char],float32 proc writeFloatToBufferRoundtrip(buf: var array[65, char]; value: float32): int 34 +nim writeFloatToBufferSprintf formatfloat.html#writeFloatToBufferSprintf,array[,char],BiggestFloat proc writeFloatToBufferSprintf(buf: var array[65, char]; value: BiggestFloat): int 47 +nim writeFloatToBuffer formatfloat.html#writeFloatToBuffer,array[,char], proc writeFloatToBuffer(buf: var array[65, char]; value: BiggestFloat | float32): int 81 +nim addFloatRoundtrip formatfloat.html#addFloatRoundtrip,string, proc addFloatRoundtrip(result: var string; x: float | float32) 87 +nim addFloatSprintf formatfloat.html#addFloatSprintf,string,float proc addFloatSprintf(result: var string; x: float) 95 +nim addFloat formatfloat.html#addFloat,string, proc addFloat(result: var string; x: float | float32) 121 +nim `$` formatfloat.html#$ proc `$`(x: float | float32): string 141 +nimgrp writefloattobufferroundtrip formatfloat.html#writeFloatToBufferRoundtrip-procs-all proc 26 diff --git a/genasts.html b/genasts.html new file mode 100644 index 0000000000000..3f267955d6125 --- /dev/null +++ b/genasts.html @@ -0,0 +1,201 @@ + + + + + + + +std/genasts + + + + + + + + + + + + + + + + +
+
+

std/genasts

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements AST generation using captured variables for macros.

+
+

Imports

+
+ macros +
+
+
+

Types

+
+
+
GenAstOpt = enum
+  kDirtyTemplate, kNoNewLit
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Macros

+
+
+
+
macro genAstOpt(options: static set[GenAstOpt]; args: varargs[untyped]): untyped
+
+ + Accepts a list of captured variables a=b or a and a block and returns the AST that represents it. Local {.inject.} symbols (e.g. procs) are captured unless kDirtyTemplate in options. +

Example:

+
# This example shows how one could write a simplified version of `unittest.check`.
+import std/[macros, strutils]
+macro check2(cond: bool): untyped =
+  assert cond.kind == nnkInfix, "$# not implemented" % $cond.kind
+  result = genAst(cond, s = repr(cond), lhs = cond[1], rhs = cond[2]):
+    # each local symbol we access must be explicitly captured
+    if not cond:
+      raiseAssert "'$#'' failed: lhs: '$#', rhs: '$#'" % [s, $lhs, $rhs]
+let a = 3
+check2 a*2 == a+3
+if false: check2 a*2 < a+1 # would error with: 'a * 2 < a + 1'' failed: lhs: '6', rhs: '4'
+

Example:

+
# This example goes in more details about the capture semantics.
+macro fun(a: string, b: static bool): untyped =
+  let c = 'z'
+  var d = 11 # implicitly {.gensym.} and needs to be captured for use in `genAst`.
+  proc localFun(): auto = 12 # implicitly {.inject.}, doesn't need to be captured.
+  genAst(a, b, c = true):
+    # `a`, `b` are captured explicitly, `c` is a local definition masking `c = 'z'`.
+    const b2 = b # macro static param `b` is forwarded here as a static param.
+    # `echo d` would give: `var not init` because `d` is not captured.
+    (a & a, b, c, localFun()) # localFun can be called without capture.
+assert fun("ab", false) == ("abab", false, true, 12)
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template genAst(args: varargs[untyped]): untyped
+
+ + Convenience wrapper around genAstOpt. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/genasts.idx b/genasts.idx new file mode 100644 index 0000000000000..7940d317b05fe --- /dev/null +++ b/genasts.idx @@ -0,0 +1,6 @@ +nimTitle genasts genasts.html module std/genasts 0 +nim kDirtyTemplate genasts.html#kDirtyTemplate GenAstOpt.kDirtyTemplate 5 +nim kNoNewLit genasts.html#kNoNewLit GenAstOpt.kNoNewLit 5 +nim GenAstOpt genasts.html#GenAstOpt enum GenAstOpt 5 +nim genAstOpt genasts.html#genAstOpt.m,staticset[GenAstOpt],varargs[untyped] macro genAstOpt(options: static set[GenAstOpt]; args: varargs[untyped]): untyped 15 +nim genAst genasts.html#genAst.t,varargs[untyped] template genAst(args: varargs[untyped]): untyped 87 diff --git a/gitutils.html b/gitutils.html new file mode 100644 index 0000000000000..fe700a43e375e --- /dev/null +++ b/gitutils.html @@ -0,0 +1,230 @@ + + + + + + + +std/private/gitutils + + + + + + + + + + + + + + + + +
+
+

std/private/gitutils

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

internal API for now, API subject to change

+ +
+

Consts

+
+
+
commitHead = "HEAD"
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc diffFiles(path1, path2: string): tuple[output: string, same: bool] {.
+    ...raises: [OSError, IOError, ValueError],
+    tags: [ExecIOEffect, ReadIOEffect, RootEffect], forbids: [].}
+
+ + Returns a human readable diff of files path1, path2, the exact form of which is implementation defined. + Source   +Edit   + +
+
+ +
+
+
+
proc diffStrings(a, b: string): tuple[output: string, same: bool] {.
+    ...raises: [IOError, OSError, ValueError], tags: [ReadEnvEffect, ReadIOEffect,
+    WriteIOEffect, WriteDirEffect, ExecIOEffect, RootEffect], forbids: [].}
+
+ + Returns a human readable diff of a, b, the exact form of which is implementation defined. See also experimental.diff. +

Example:

+
let a = "ok1\nok2\nok3\n"
+let b = "ok1\nok2 alt\nok3\nok4\n"
+let (c, same) = diffStrings(a, b)
+doAssert not same
+let (c2, same2) = diffStrings(a, a)
+doAssert same2
+

Example: cmd: -r:off

+
let a = "ok1\nok2\nok3\n"
+let b = "ok1\nok2 alt\nok3\nok4\n"
+echo diffStrings(a, b).output
+ Source   +Edit   + +
+
+ +
+
+
+
proc isGitRepo(dir: string): bool {....raises: [], tags: [ReadDirEffect],
+                                    forbids: [].}
+
+ + Avoid calling git since it depends on /bin/sh existing and fails in Nix. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template retryCall(maxRetry = 3; backoffDuration = 1.0; call: untyped): bool
+
+ + Retry call up to maxRetry times with exponential backoff and initial duraton of backoffDuration seconds. This is in particular useful for network commands that can fail. +

Example:

+
doAssert not retryCall(maxRetry = 2, backoffDuration = 0.1, false)
+var i = 0
+doAssert: retryCall(maxRetry = 3, backoffDuration = 0.1, (i.inc; i >= 3))
+doAssert retryCall(call = true)
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/gitutils.idx b/gitutils.idx new file mode 100644 index 0000000000000..c1c19e4bf4ab1 --- /dev/null +++ b/gitutils.idx @@ -0,0 +1,6 @@ +nimTitle gitutils gitutils.html module std/private/gitutils 0 +nim commitHead gitutils.html#commitHead const commitHead 12 +nim retryCall gitutils.html#retryCall.t,int,float,untyped template retryCall(maxRetry = 3; backoffDuration = 1.0; call: untyped): bool 14 +nim isGitRepo gitutils.html#isGitRepo,string proc isGitRepo(dir: string): bool 34 +nim diffFiles gitutils.html#diffFiles,string,string proc diffFiles(path1, path2: string): tuple[output: string, same: bool] 38 +nim diffStrings gitutils.html#diffStrings,string,string proc diffStrings(a, b: string): tuple[output: string, same: bool] 49 diff --git a/globs.html b/globs.html new file mode 100644 index 0000000000000..7e1db84534e65 --- /dev/null +++ b/globs.html @@ -0,0 +1,184 @@ + + + + + + + +std/private/globs + + + + + + + + + + + + + + + + +
+
+

std/private/globs

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

unstable API, internal use only for now. this can eventually be moved to std/os and walkDirRec can be implemented in terms of this to avoid duplication

+ +
+

Types

+
+
+
PathEntry = object
+  kind*: PathComponent
+  path*: string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc nativeToUnixPath(path: string): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator walkDirRecFilter(dir: string;
+                          follow: proc (entry: PathEntry): bool = nil;
+                          relative = false; checkDir = true): PathEntry {.
+    ...tags: [ReadDirEffect], effectsOf: follow, ...raises: [OSError], forbids: [].}
+
+ + Improved os.walkDirRec. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/globs.idx b/globs.idx new file mode 100644 index 0000000000000..ccf2d93a9114d --- /dev/null +++ b/globs.idx @@ -0,0 +1,4 @@ +nimTitle globs globs.html module std/private/globs 0 +nim PathEntry globs.html#PathEntry object PathEntry 21 +nim walkDirRecFilter globs.html#walkDirRecFilter.i,string,proc(PathEntry) iterator walkDirRecFilter(dir: string; follow: proc (entry: PathEntry): bool = nil;\n relative = false; checkDir = true): PathEntry 25 +nim nativeToUnixPath globs.html#nativeToUnixPath,string proc nativeToUnixPath(path: string): string 55 diff --git a/hashes.html b/hashes.html new file mode 100644 index 0000000000000..16318c2e5c17f --- /dev/null +++ b/hashes.html @@ -0,0 +1,560 @@ + + + + + + + +std/hashes + + + + + + + + + + + + + + + + +
+
+

std/hashes

+
+ +
+ Source   +Edit   + +
+ +

This module implements efficient computations of hash values for diverse Nim types. All the procs are based on these two building blocks:

  • !& proc used to start or mix a hash value, and
  • +
  • !$ proc used to finish the hash value.
  • +
+

If you want to implement hash procs for your custom types, you will end up writing the following kind of skeleton of code:

+ +

Example:

+
import std/hashes
+type
+  Something = object
+    foo: int
+    bar: string
+
+iterator items(x: Something): Hash =
+  yield hash(x.foo)
+  yield hash(x.bar)
+
+proc hash(x: Something): Hash =
+  ## Computes a Hash from `x`.
+  var h: Hash = 0
+  # Iterate over parts of `x`.
+  for xAtom in x:
+    # Mix the atom with the partial hash.
+    h = h !& xAtom
+  # Finish the hash.
+  result = !$h
If your custom types contain fields for which there already is a hash proc, you can simply hash together the hash values of the individual fields: +

Example:

+
import std/hashes
+type
+  Something = object
+    foo: int
+    bar: string
+
+proc hash(x: Something): Hash =
+  ## Computes a Hash from `x`.
+  var h: Hash = 0
+  h = h !& hash(x.foo)
+  h = h !& hash(x.bar)
+  result = !$h
Important: +Use -d:nimPreviewHashRef to enable hashing refs. It is expected that this behavior becomes the new default in upcoming versions.
+
Note: +If the type has a == operator, the following must hold: If two values compare equal, their hashes must also be equal.
+ +

See also

+

+ +
+

Types

+
+
+
Hash = int
+
+ + A hash value. Hash tables using these values should always have a size of a power of two so they can use the and operator instead of mod for truncation of the hash value. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `!$`(h: Hash): Hash {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Finishes the computation of the hash value.

+

This is only needed if you need to implement a hash proc for a new datatype.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `!&`(h: Hash; val: int): Hash {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Mixes a hash value h with val to produce a new hash value.

+

This is only needed if you need to implement a hash proc for a new datatype.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc hash(sBuf: string; sPos, ePos: int): Hash {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Efficient hashing of a string buffer, from starting position sPos to ending position ePos (included).

+

hash(myStr, 0, myStr.high) is equivalent to hash(myStr).

+ +

Example:

+
var a = "abracadabra"
+doAssert hash(a, 0, 3) == hash(a, 7, 10)
+ Source   +Edit   + +
+
+
+
proc hash(x: cstring): Hash {....raises: [], tags: [], forbids: [].}
+
+ + Efficient hashing of null-terminated strings. +

Example:

+
doAssert hash(cstring"abracadabra") == hash("abracadabra")
+doAssert hash(cstring"AbracadabrA") == hash("AbracadabrA")
+doAssert hash(cstring"abracadabra") != hash(cstring"AbracadabrA")
+ Source   +Edit   + +
+
+
+
proc hash(x: float): Hash {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Efficient hashing of floats. + Source   +Edit   + +
+
+
+
proc hash(x: pointer): Hash {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Efficient hash overload. + Source   +Edit   + +
+
+
+
proc hash(x: string): Hash {....raises: [], tags: [], forbids: [].}
+
+ +

Efficient hashing of strings.

+

See also:

+ + +

Example:

+
doAssert hash("abracadabra") != hash("AbracadabrA")
+ Source   +Edit   + +
+
+
+
proc hash[A](aBuf: openArray[A]; sPos, ePos: int): Hash
+
+ +

Efficient hashing of portions of arrays and sequences, from starting position sPos to ending position ePos (included). There must be a hash proc defined for the element type A.

+

hash(myBuf, 0, myBuf.high) is equivalent to hash(myBuf).

+ +

Example:

+
let a = [1, 2, 5, 1, 2, 6]
+doAssert hash(a, 0, 1) == hash(a, 3, 4)
+ Source   +Edit   + +
+
+
+
proc hash[A](x: openArray[A]): Hash
+
+ + + Source   +Edit   + +
+
+
+
proc hash[A](x: set[A]): Hash
+
+ + + Source   +Edit   + +
+
+
+
proc hash[T: Ordinal | enum](x: T): Hash {.inline.}
+
+ + Efficient hashing of integers. + Source   +Edit   + +
+
+
+
proc hash[T: tuple | object | proc | iterator {.closure.}](x: T): Hash
+
+ + Efficient hash overload. +

Example:

+
# for `tuple|object`, `hash` must be defined for each component of `x`.
+type Obj = object
+  x: int
+  y: string
+type Obj2[T] = object
+  x: int
+  y: string
+assert hash(Obj(x: 520, y: "Nim")) != hash(Obj(x: 520, y: "Nim2"))
+# you can define custom hashes for objects (even if they're generic):
+proc hash(a: Obj2): Hash = hash((a.x))
+assert hash(Obj2[float](x: 520, y: "Nim")) == hash(Obj2[float](x: 520, y: "Nim2"))
+

Example:

+
# proc
+proc fn1() = discard
+const fn1b = fn1
+assert hash(fn1b) == hash(fn1)
+
+# closure
+proc outer =
+  var a = 0
+  proc fn2() = a.inc
+  assert fn2 is "closure"
+  let fn2b = fn2
+  assert hash(fn2b) == hash(fn2)
+  assert hash(fn2) != hash(fn1)
+outer()
+ Source   +Edit   + +
+
+
+
proc hash[T](x: ptr [T]): Hash {.inline.}
+
+ + Efficient hash overload. +

Example:

+
var a: array[10, uint8]
+assert a[0].addr.hash != a[1].addr.hash
+assert cast[pointer](a[0].addr).hash == a[0].addr.hash
+ Source   +Edit   + +
+
+
+
proc hash[T](x: ref [T]): Hash {.inline.}
+
+ + Efficient hash overload.
Important: +Use -d:nimPreviewHashRef to enable hashing refs. It is expected that this behavior becomes the new default in upcoming versions.
+ +

Example: cmd: -d:nimPreviewHashRef

+
type A = ref object
+  x: int
+let a = A(x: 3)
+let ha = a.hash
+assert ha != A(x: 3).hash # A(x: 3) is a different ref object from `a`.
+a.x = 4
+assert ha == a.hash # the hash only depends on the address
+

Example: cmd: -d:nimPreviewHashRef

+
# you can overload `hash` if you want to customize semantics
+type A[T] = ref object
+  x, y: T
+proc hash(a: A): Hash = hash(a.x)
+assert A[int](x: 3, y: 4).hash == A[int](x: 3, y: 5).hash
+ Source   +Edit   + +
+
+ +
+
+
+
proc hashData(data: pointer; size: int): Hash {....raises: [], tags: [],
+    forbids: [].}
+
+ + Hashes an array of bytes of size size. + Source   +Edit   + +
+
+ +
+
+
+
proc hashIdentity[T: Ordinal | enum](x: T): Hash {.inline.}
+
+ + The identity hash, i.e. hashIdentity(x) = x. + Source   +Edit   + +
+
+ +
+
+
+
proc hashIgnoreCase(sBuf: string; sPos, ePos: int): Hash {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Efficient hashing of a string buffer, from starting position sPos to ending position ePos (included); case is ignored.

+

Note: This uses a different hashing algorithm than hash(string).

+

hashIgnoreCase(myBuf, 0, myBuf.high) is equivalent to hashIgnoreCase(myBuf).

+ +

Example:

+
var a = "ABracadabRA"
+doAssert hashIgnoreCase(a, 0, 3) == hashIgnoreCase(a, 7, 10)
+ Source   +Edit   + +
+
+
+
proc hashIgnoreCase(x: string): Hash {....raises: [], tags: [], forbids: [].}
+
+ +

Efficient hashing of strings; case is ignored.

+

Note: This uses a different hashing algorithm than hash(string).

+

See also:

+ + +

Example:

+
doAssert hashIgnoreCase("ABRAcaDABRA") == hashIgnoreCase("abRACAdabra")
+doAssert hashIgnoreCase("abcdefghi") != hash("abcdefghi")
+ Source   +Edit   + +
+
+ +
+
+
+
proc hashIgnoreStyle(sBuf: string; sPos, ePos: int): Hash {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Efficient hashing of a string buffer, from starting position sPos to ending position ePos (included); style is ignored.

+

Note: This uses a different hashing algorithm than hash(string).

+

hashIgnoreStyle(myBuf, 0, myBuf.high) is equivalent to hashIgnoreStyle(myBuf).

+ +

Example:

+
var a = "ABracada_b_r_a"
+doAssert hashIgnoreStyle(a, 0, 3) == hashIgnoreStyle(a, 7, a.high)
+ Source   +Edit   + +
+
+
+
proc hashIgnoreStyle(x: string): Hash {....raises: [], tags: [], forbids: [].}
+
+ +

Efficient hashing of strings; style is ignored.

+

Note: This uses a different hashing algorithm than hash(string).

+

See also:

+ + +

Example:

+
doAssert hashIgnoreStyle("aBr_aCa_dAB_ra") == hashIgnoreStyle("abracadabra")
+doAssert hashIgnoreStyle("abcdefghi") != hash("abcdefghi")
+ Source   +Edit   + +
+
+ +
+
+
+
proc hashWangYi1(x: int64 | uint64 | Hash): Hash {.inline.}
+
+ +

Wang Yi's hash_v1 for 64-bit ints (see https://github.com/rurban/smhasher for more details). This passed all scrambling tests in Spring 2019 and is simple.

+

Note: It's ok to define proc(x: int16): Hash = hashWangYi1(Hash(x)).

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/hashes.idx b/hashes.idx new file mode 100644 index 0000000000000..49a8ad1680949 --- /dev/null +++ b/hashes.idx @@ -0,0 +1,27 @@ +nimTitle hashes hashes.html module std/hashes 0 +nim Hash hashes.html#Hash type Hash 75 +nim `!&` hashes.html#!&,Hash,int proc `!&`(h: Hash; val: int): Hash 79 +nim `!$` hashes.html#!$,Hash proc `!$`(h: Hash): Hash 90 +nim hashWangYi1 hashes.html#hashWangYi1 proc hashWangYi1(x: int64 | uint64 | Hash): Hash 165 +nim hashData hashes.html#hashData,pointer,int proc hashData(data: pointer; size: int): Hash 188 +nim hashIdentity hashes.html#hashIdentity,T proc hashIdentity[T: Ordinal | enum](x: T): Hash 204 +nim hash hashes.html#hash,T proc hash[T: Ordinal | enum](x: T): Hash 213 +nim hash hashes.html#hash,pointer proc hash(x: pointer): Hash 231 +nim hash hashes.html#hash,ptr. proc hash[T](x: ptr [T]): Hash 239 +nim hash hashes.html#hash,ref. proc hash[T](x: ref [T]): Hash 248 +nim hash hashes.html#hash,float proc hash(x: float): Hash 272 +nim hash hashes.html#hash,openArray[A] proc hash[A](x: openArray[A]): Hash 286 +nim hash hashes.html#hash,set[A] proc hash[A](x: set[A]): Hash 287 +nim hash hashes.html#hash,string proc hash(x: string): Hash 527 +nim hash hashes.html#hash,cstring proc hash(x: cstring): Hash 544 +nim hash hashes.html#hash,string,int,int proc hash(sBuf: string; sPos, ePos: int): Hash 568 +nim hashIgnoreStyle hashes.html#hashIgnoreStyle,string proc hashIgnoreStyle(x: string): Hash 583 +nim hashIgnoreStyle hashes.html#hashIgnoreStyle,string,int,int proc hashIgnoreStyle(sBuf: string; sPos, ePos: int): Hash 608 +nim hashIgnoreCase hashes.html#hashIgnoreCase,string proc hashIgnoreCase(x: string): Hash 633 +nim hashIgnoreCase hashes.html#hashIgnoreCase,string,int,int proc hashIgnoreCase(sBuf: string; sPos, ePos: int): Hash 652 +nim hash hashes.html#hash,T_2 proc hash[T: tuple | object | proc | iterator {.closure.}](x: T): Hash 672 +nim hash hashes.html#hash,openArray[A],int,int proc hash[A](aBuf: openArray[A]; sPos, ePos: int): Hash 734 +heading See also hashes.html#see-also See also 0 +nimgrp hashignorecase hashes.html#hashIgnoreCase-procs-all proc 633 +nimgrp hashignorestyle hashes.html#hashIgnoreStyle-procs-all proc 583 +nimgrp hash hashes.html#hash-procs-all proc 213 diff --git a/hcr.html b/hcr.html new file mode 100644 index 0000000000000..3b342f079f192 --- /dev/null +++ b/hcr.html @@ -0,0 +1,168 @@ + + + + + + + +Hot code reloading + + + + + + + + + + + + + + + + +
+
+

Hot code reloading

+

The hotCodeReloading option enables special compilation mode where changes in the code can be applied automatically to a running program. The code reloading happens at the granularity of an individual module. When a module is reloaded, any newly added global variables will be initialized, but all other top-level code appearing in the module won't be re-executed and the state of all existing global variables will be preserved.

+ +

Basic workflow

Currently, hot code reloading does not work for the main module itself, so we have to use a helper module where the major logic we want to change during development resides.

+

In this example, we use SDL2 to create a window and we reload the logic code when F9 is pressed. The important lines are marked with #***. To install SDL2 you can use nimble install sdl2.

+

# logic.nim
+import sdl2
+
+#*** import the hotcodereloading stdlib module ***
+import std/hotcodereloading
+
+var runGame*: bool = true
+var window: WindowPtr
+var renderer: RendererPtr
+var evt = sdl2.defaultEvent
+
+proc init*() =
+  discard sdl2.init(INIT_EVERYTHING)
+  window = createWindow("testing", SDL_WINDOWPOS_UNDEFINED.cint, SDL_WINDOWPOS_UNDEFINED.cint, 640, 480, 0'u32)
+  assert(window != nil, $sdl2.getError())
+  renderer = createRenderer(window, -1, RENDERER_SOFTWARE)
+  assert(renderer != nil, $sdl2.getError())
+
+proc destroy*() =
+  destroyRenderer(renderer)
+  destroyWindow(window)
+
+var posX: cint = 1
+var posY: cint = 0
+var dX: cint = 1
+var dY: cint = 1
+
+proc update*() =
+  while pollEvent(evt):
+    if evt.kind == QuitEvent:
+      runGame = false
+      break
+    if evt.kind == KeyDown:
+      if evt.key.keysym.scancode == SDL_SCANCODE_ESCAPE: runGame = false
+      elif evt.key.keysym.scancode == SDL_SCANCODE_F9:
+        #*** reload this logic.nim module on the F9 keypress ***
+        performCodeReload()
+  
+  # draw a bouncing rectangle:
+  posX += dX
+  posY += dY
+  
+  if posX >= 640: dX = -2
+  if posX <= 0: dX = +2
+  if posY >= 480: dY = -2
+  if posY <= 0: dY = +2
+  
+  discard renderer.setDrawColor(0, 0, 255, 255)
+  discard renderer.clear()
+  discard renderer.setDrawColor(255, 128, 128, 0)
+  
+  var rect: Rect = (x: posX - 25, y: posY - 25, w: 50.cint, h: 50.cint)
+  discard renderer.fillRect(rect)
+  delay(16)
+  renderer.present()

+

# mymain.nim
+import logic
+
+proc main() =
+  init()
+  while runGame:
+    update()
+  destroy()
+
+main()

+

Compile this example via:

+

nim c --hotcodereloading:on mymain.nim

+

Now start the program and KEEP it running!

+

# Unix:
+mymain &
+# or Windows (click on the .exe)
+mymain.exe
+# edit

+

For example, change the line:

+

discard renderer.setDrawColor(255, 128, 128, 0)

+

into:

+

discard renderer.setDrawColor(255, 255, 128, 0)

+

(This will change the color of the rectangle.)

+

Then recompile the project, but do not restart or quit the mymain.exe program!

+

nim c --hotcodereloading:on mymain.nim

+

Now give the mymain SDL window the focus, press F9, and watch the updated version of the program.

+ +

Reloading API

One can use the special event handlers beforeCodeReload and afterCodeReload to reset the state of a particular variable or to force the execution of certain statements:

+

var
+ settings = initTable[string, string]()
+ lastReload: Time
+
+for k, v in loadSettings():
+  settings[k] = v
+
+initProgram()
+
+afterCodeReload:
+  lastReload = now()
+  resetProgramState()

+

On each code reload, Nim will first execute all beforeCodeReload handlers registered in the previous version of the program and then all afterCodeReload handlers appearing in the newly loaded code. Please note that any handlers appearing in modules that weren't reloaded will also be executed. To prevent this behavior, one can guard the code with the hasModuleChanged() API:

+

import mydb
+
+var myCache = initTable[Key, Value]()
+
+afterCodeReload:
+  if hasModuleChanged(mydb):
+    resetCache(myCache)

+

The hot code reloading is based on dynamic library hot swapping in the native targets and direct manipulation of the global namespace in the JavaScript target. The Nim compiler does not specify the mechanism for detecting the conditions when the code must be reloaded. Instead, the program code is expected to call performCodeReload() every time it wishes to reload its code.

+

It's expected that most projects will implement the reloading with a suitable build-system triggered IPC notification mechanism, but a polling solution is also possible through the provided hasAnyModuleChanged() API.

+

In order to access beforeCodeReload, afterCodeReload, hasModuleChanged or hasAnyModuleChanged one must import the hotcodereloading module.

+ +

Native code targets

Native projects using the hot code reloading option will be implicitly compiled with the -d:useNimRtl option and they will depend on both the nimrtl library and the nimhcr library which implements the hot code reloading run-time. Both libraries can be found in the lib folder of Nim and can be compiled into dynamic libraries to satisfy runtime demands of the example code above. An example of compiling nimhcr.nim and nimrtl.nim when the source dir of Nim is installed with choosenim follows.

+

# Unix/MacOS
+# Make sure you are in the directory containing your .nim files
+$ cd your-source-directory
+
+# Compile two required files and set their output directory to current dir
+$ nim c --outdir:$PWD ~/.choosenim/toolchains/nim-#devel/lib/nimhcr.nim
+$ nim c --outdir:$PWD ~/.choosenim/toolchains/nim-#devel/lib/nimrtl.nim
+
+# verify that you have two files named libnimhcr and libnimrtl in your
+# source directory (.dll for Windows, .so for Unix, .dylib for MacOS)

+

All modules of the project will be compiled to separate dynamic link libraries placed in the nimcache directory. Please note that during the execution of the program, the hot code reloading run-time will load only copies of these libraries in order to not interfere with any newly issued build commands.

+

The main module of the program is considered non-reloadable. Please note that procs from reloadable modules should not appear in the call stack of program while performCodeReload is being called. Thus, the main module is a suitable place for implementing a program loop capable of calling performCodeReload.

+

Please note that reloading won't be possible when any of the type definitions in the program has been changed. When closure iterators are used (directly or through async code), the reloaded definitions will affect only newly created instances. Existing iterator instances will execute their original code to completion.

+ +

JavaScript target

Once your code is compiled for hot reloading, a convenient solution for implementing the actual reloading in the browser using a framework such as LiveReload or BrowserSync.

+ + + + +
+
+ + + + diff --git a/hcr.idx b/hcr.idx new file mode 100644 index 0000000000000..2b02edb0fab23 --- /dev/null +++ b/hcr.idx @@ -0,0 +1,12 @@ +markupTitle Hot code reloading hcr.html Hot code reloading 0 +idx hotCodeReloading hcr.html#hotcodereloading_1 Hot code reloading 0 +heading Basic workflow hcr.html#basic-workflow Basic workflow 0 +heading Reloading API hcr.html#reloading-api Reloading API 0 +idx beforeCodeReload hcr.html#beforecodereload_1 Reloading API 0 +idx afterCodeReload hcr.html#aftercodereload_1 Reloading API 0 +idx hasModuleChanged() hcr.html#hasmodulechanged_1 Reloading API 0 +idx performCodeReload() hcr.html#performcodereload_1 Reloading API 0 +idx hasAnyModuleChanged() hcr.html#hasanymodulechanged_1 Reloading API 0 +idx hotcodereloading hcr.html#hotcodereloading_2 Reloading API 0 +heading Native code targets hcr.html#native-code-targets Native code targets 0 +heading JavaScript target hcr.html#javascript-target JavaScript target 0 diff --git a/heapqueue.html b/heapqueue.html new file mode 100644 index 0000000000000..5b01ce7f298a3 --- /dev/null +++ b/heapqueue.html @@ -0,0 +1,462 @@ + + + + + + + +std/heapqueue + + + + + + + + + + + + + + + + +
+
+

std/heapqueue

+
+ +
+ Source   +Edit   + +
+ +

The heapqueue module implements a binary heap data structure that can be used as a priority queue. They are represented as arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for all indices k (counting elements from 0). The interesting property of a heap is that a[0] is always its smallest element. +

Basic usage

+

Example:

+
import std/heapqueue
+var heap = [8, 2].toHeapQueue
+heap.push(5)
+# the first element is the lowest element
+assert heap[0] == 2
+# remove and return the lowest element
+assert heap.pop() == 2
+# the lowest element remaining is 5
+assert heap[0] == 5
+

Usage with custom objects

To use a HeapQueue with a custom object, the < operator must be implemented.

+ +

Example:

+
import std/heapqueue
+type Job = object
+  priority: int
+
+proc `<`(a, b: Job): bool = a.priority < b.priority
+
+var jobs = initHeapQueue[Job]()
+jobs.push(Job(priority: 1))
+jobs.push(Job(priority: 2))
+
+assert jobs[0].priority == 1

+ +
+

Types

+
+
+
HeapQueue[T] = object
+
+ + A heap queue, commonly known as a priority queue. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`[T](heap: HeapQueue[T]): string
+
+ + Turns a heap into its string representation. +

Example:

+
let heap = [1, 2].toHeapQueue
+assert $heap == "[1, 2]"
+ Source   +Edit   + +
+
+ +
+
+
+
proc `[]`[T](heap: HeapQueue[T]; i: Natural): lent T {.inline.}
+
+ + Accesses the i-th element of heap. + Source   +Edit   + +
+
+ +
+
+
+
proc clear[T](heap: var HeapQueue[T])
+
+ + Removes all elements from heap, making it empty. +

Example:

+
var heap = [9, 5, 8].toHeapQueue
+heap.clear()
+assert heap.len == 0
+ Source   +Edit   + +
+
+ +
+
+
+
proc contains[T](heap: HeapQueue[T]; x: T): bool
+
+ + Returns true if x is in heap or false if not found. This is a shortcut for find(heap, x) >= 0. + Source   +Edit   + +
+
+ +
+
+
+
proc del[T](heap: var HeapQueue[T]; index: Natural)
+
+ + Removes the element at index from heap, maintaining the heap invariant. +

Example:

+
var heap = [9, 5, 8].toHeapQueue
+heap.del(1)
+assert heap[0] == 5
+assert heap[1] == 8
+ Source   +Edit   + +
+
+ +
+
+
+
proc find[T](heap: HeapQueue[T]; x: T): int
+
+ + Linear scan to find the index of the item x or -1 if not found. +

Example:

+
let heap = [9, 5, 8].toHeapQueue
+assert heap.find(5) == 0
+assert heap.find(9) == 1
+assert heap.find(777) == -1
+ Source   +Edit   + +
+
+ +
+
+
+
proc initHeapQueue[T](): HeapQueue[T]
+
+ +

Creates a new empty heap.

+

Heaps are initialized by default, so it is not necessary to call this function explicitly.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc len[T](heap: HeapQueue[T]): int {.inline.}
+
+ + Returns the number of elements of heap. +

Example:

+
let heap = [9, 5, 8].toHeapQueue
+assert heap.len == 3
+ Source   +Edit   + +
+
+ +
+
+
+
proc pop[T](heap: var HeapQueue[T]): T
+
+ + Pops and returns the smallest item from heap, maintaining the heap invariant. +

Example:

+
var heap = [9, 5, 8].toHeapQueue
+assert heap.pop() == 5
+ Source   +Edit   + +
+
+ +
+
+
+
proc push[T](heap: var HeapQueue[T]; item: sink T)
+
+ + Pushes item onto heap, maintaining the heap invariant. + Source   +Edit   + +
+
+ +
+
+
+
proc pushpop[T](heap: var HeapQueue[T]; item: sink T): T
+
+ +

Fast version of a push() followed by a pop().

+

See also:

+ + +

Example:

+
var heap = [5, 12].toHeapQueue
+assert heap.pushpop(6) == 5
+assert heap.len == 2
+assert heap[0] == 6
+assert heap.pushpop(4) == 4
+ Source   +Edit   + +
+
+ +
+
+
+
proc replace[T](heap: var HeapQueue[T]; item: sink T): T
+
+ +

Pops and returns the current smallest value, and add the new item. This is more efficient than pop() followed by push(), and can be more appropriate when using a fixed-size heap. Note that the value returned may be larger than item! That constrains reasonable uses of this routine unless written as part of a conditional replacement.

+

See also:

+ + +

Example:

+
var heap = [5, 12].toHeapQueue
+assert heap.replace(6) == 5
+assert heap.len == 2
+assert heap[0] == 6
+assert heap.replace(4) == 6
+ Source   +Edit   + +
+
+ +
+
+
+
proc toHeapQueue[T](x: openArray[T]): HeapQueue[T]
+
+ +

Creates a new HeapQueue that contains the elements of x.

+

See also:

+ + +

Example:

+
var heap = [9, 5, 8].toHeapQueue
+assert heap.pop() == 5
+assert heap[0] == 8
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator items[T](heap: HeapQueue[T]): lent T {.inline.}
+
+ + Iterates over each item of heap. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/heapqueue.idx b/heapqueue.idx new file mode 100644 index 0000000000000..fc7cb6732862f --- /dev/null +++ b/heapqueue.idx @@ -0,0 +1,18 @@ +nimTitle heapqueue heapqueue.html module std/heapqueue 0 +nim HeapQueue heapqueue.html#HeapQueue object HeapQueue 53 +nim initHeapQueue heapqueue.html#initHeapQueue proc initHeapQueue[T](): HeapQueue[T] 57 +nim len heapqueue.html#len,HeapQueue[T] proc len[T](heap: HeapQueue[T]): int 67 +nim `[]` heapqueue.html#[],HeapQueue[T],Natural proc `[]`[T](heap: HeapQueue[T]; i: Natural): lent T 75 +nim items heapqueue.html#items.i,HeapQueue[T] iterator items[T](heap: HeapQueue[T]): lent T 79 +nim push heapqueue.html#push,HeapQueue[T],sinkT proc push[T](heap: var HeapQueue[T]; item: sink T) 144 +nim toHeapQueue heapqueue.html#toHeapQueue,openArray[T] proc toHeapQueue[T](x: openArray[T]): HeapQueue[T] 149 +nim pop heapqueue.html#pop,HeapQueue[T] proc pop[T](heap: var HeapQueue[T]): T 164 +nim find heapqueue.html#find,HeapQueue[T],T proc find[T](heap: HeapQueue[T]; x: T): int 179 +nim contains heapqueue.html#contains,HeapQueue[T],T proc contains[T](heap: HeapQueue[T]; x: T): bool 191 +nim del heapqueue.html#del,HeapQueue[T],Natural proc del[T](heap: var HeapQueue[T]; index: Natural) 196 +nim replace heapqueue.html#replace,HeapQueue[T],sinkT proc replace[T](heap: var HeapQueue[T]; item: sink T): T 210 +nim pushpop heapqueue.html#pushpop,HeapQueue[T],sinkT proc pushpop[T](heap: var HeapQueue[T]; item: sink T): T 230 +nim clear heapqueue.html#clear,HeapQueue[T] proc clear[T](heap: var HeapQueue[T]) 247 +nim `$` heapqueue.html#$,HeapQueue[T] proc `$`[T](heap: HeapQueue[T]): string 256 +heading Basic usage heapqueue.html#basic-usage Basic usage 0 +heading Usage with custom objects heapqueue.html#usage-with-custom-objects Usage with custom objects 0 diff --git a/highlite.html b/highlite.html new file mode 100644 index 0000000000000..911fc4526060a --- /dev/null +++ b/highlite.html @@ -0,0 +1,363 @@ + + + + + + + +packages/docutils/highlite + + + + + + + + + + + + + + + + +
+
+

packages/docutils/highlite

+
+ +
+ Source   +Edit   + +
+ +

Source highlighter for programming or markup languages. Currently only few languages are supported, other languages may be added. The interface supports one language nested in another.

+

You can use this to build your own syntax highlighting, check this example:

+

let code = """for x in $int.high: echo x.ord mod 2 == 0"""
+var toknizr: GeneralTokenizer
+initGeneralTokenizer(toknizr, code)
+while true:
+  getNextToken(toknizr, langNim)
+  case toknizr.kind
+  of gtEof: break  # End Of File (or string)
+  of gtWhitespace:
+    echo gtWhitespace # Maybe you want "visible" whitespaces?.
+    echo substr(code, toknizr.start, toknizr.length + toknizr.start - 1)
+  of gtOperator:
+    echo gtOperator # Maybe you want Operators to use a specific color?.
+    echo substr(code, toknizr.start, toknizr.length + toknizr.start - 1)
+  # of gtSomeSymbol: syntaxHighlight("Comic Sans", "bold", "99px", "pink")
+  else:
+    echo toknizr.kind # All the kinds of tokens can be processed here.
+    echo substr(code, toknizr.start, toknizr.length + toknizr.start - 1)

+

The proc getSourceLanguage can get the language enum from a string:

+

for l in ["C", "c++", "jAvA", "Nim", "c#"]: echo getSourceLanguage(l)

+

There is also a Cmd pseudo-language supported, which is a simple generic shell/cmdline tokenizer (UNIX shell/Powershell/Windows Command): no escaping, no programming language constructs besides variable definition at the beginning of line. It supports these operators:

+

&  &&  |  ||  (  )  ''  ""  ;  # for comments

+

Instead of escaping always use quotes like here nimgrep --ext:'nim|nims' file.name shows how to input |. Any argument that contains . or / or \ will be treated as a file or directory.

+

In addition to Cmd there is also Console language for displaying interactive sessions. Lines with a command should start with $, other lines are considered as program output.

+

+ +
+

Types

+
+
+
GeneralTokenizer = object of RootObj
+  kind*: TokenClass
+  start*, length*: int
+
+ + + Source   +Edit   + +
+
+
+
SourceLanguage = enum
+  langNone, langNim, langCpp, langCsharp, langC, langJava, langYaml, langPython,
+  langCmd, langConsole
+
+ + + Source   +Edit   + +
+
+
+
TokenClass = enum
+  gtEof, gtNone, gtWhitespace, gtDecNumber, gtBinNumber, gtHexNumber,
+  gtOctNumber, gtFloatNumber, gtIdentifier, gtKeyword, gtStringLit,
+  gtLongStringLit, gtCharLit, gtEscapeSequence, gtOperator, gtPunctuation,
+  gtComment, gtLongComment, gtRegularExpression, gtTagStart, gtTagEnd, gtKey,
+  gtValue, gtRawData, gtAssembler, gtPreprocessor, gtDirective, gtCommand,
+  gtRule, gtHyperlink, gtLabel, gtReference, gtPrompt, gtProgramOutput,
+  gtProgram, gtOption, gtOther
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
sourceLanguageToAlpha: array[SourceLanguage, string] = ["none", "Nim", "cpp",
+    "csharp", "C", "Java", "Yaml", "Python", "Cmd", "Console"]
+
+ + list of languages spelled with alpabetic characters + Source   +Edit   + +
+
+
+
sourceLanguageToStr: array[SourceLanguage, string] = ["none", "Nim", "C++",
+    "C#", "C", "Java", "Yaml", "Python", "Cmd", "Console"]
+
+ + + Source   +Edit   + +
+
+
+
tokenClassToStr: array[TokenClass, string] = ["Eof", "None", "Whitespace",
+    "DecNumber", "BinNumber", "HexNumber", "OctNumber", "FloatNumber",
+    "Identifier", "Keyword", "StringLit", "LongStringLit", "CharLit",
+    "EscapeSequence", "Operator", "Punctuation", "Comment", "LongComment",
+    "RegularExpression", "TagStart", "TagEnd", "Key", "Value", "RawData",
+    "Assembler", "Preprocessor", "Directive", "Command", "Rule", "Hyperlink",
+    "Label", "Reference", "Prompt", "ProgramOutput", "program", "option",
+    "Other"]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc deinitGeneralTokenizer(g: var GeneralTokenizer) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getNextToken(g: var GeneralTokenizer; lang: SourceLanguage) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getSourceLanguage(name: string): SourceLanguage {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initGeneralTokenizer(g: var GeneralTokenizer; buf: cstring) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc initGeneralTokenizer(g: var GeneralTokenizer; buf: string) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc tokenize(text: string; lang: SourceLanguage): seq[(string, TokenClass)] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/highlite.idx b/highlite.idx new file mode 100644 index 0000000000000..8aa28f36af472 --- /dev/null +++ b/highlite.idx @@ -0,0 +1,61 @@ +nimTitle highlite highlite.html module packages/docutils/highlite 0 +nim langNone highlite.html#langNone SourceLanguage.langNone 68 +nim langNim highlite.html#langNim SourceLanguage.langNim 68 +nim langCpp highlite.html#langCpp SourceLanguage.langCpp 68 +nim langCsharp highlite.html#langCsharp SourceLanguage.langCsharp 68 +nim langC highlite.html#langC SourceLanguage.langC 68 +nim langJava highlite.html#langJava SourceLanguage.langJava 68 +nim langYaml highlite.html#langYaml SourceLanguage.langYaml 68 +nim langPython highlite.html#langPython SourceLanguage.langPython 68 +nim langCmd highlite.html#langCmd SourceLanguage.langCmd 68 +nim langConsole highlite.html#langConsole SourceLanguage.langConsole 68 +nim SourceLanguage highlite.html#SourceLanguage enum SourceLanguage 68 +nim gtEof highlite.html#gtEof TokenClass.gtEof 71 +nim gtNone highlite.html#gtNone TokenClass.gtNone 71 +nim gtWhitespace highlite.html#gtWhitespace TokenClass.gtWhitespace 71 +nim gtDecNumber highlite.html#gtDecNumber TokenClass.gtDecNumber 71 +nim gtBinNumber highlite.html#gtBinNumber TokenClass.gtBinNumber 71 +nim gtHexNumber highlite.html#gtHexNumber TokenClass.gtHexNumber 71 +nim gtOctNumber highlite.html#gtOctNumber TokenClass.gtOctNumber 71 +nim gtFloatNumber highlite.html#gtFloatNumber TokenClass.gtFloatNumber 71 +nim gtIdentifier highlite.html#gtIdentifier TokenClass.gtIdentifier 71 +nim gtKeyword highlite.html#gtKeyword TokenClass.gtKeyword 71 +nim gtStringLit highlite.html#gtStringLit TokenClass.gtStringLit 71 +nim gtLongStringLit highlite.html#gtLongStringLit TokenClass.gtLongStringLit 71 +nim gtCharLit highlite.html#gtCharLit TokenClass.gtCharLit 71 +nim gtEscapeSequence highlite.html#gtEscapeSequence TokenClass.gtEscapeSequence 71 +nim gtOperator highlite.html#gtOperator TokenClass.gtOperator 71 +nim gtPunctuation highlite.html#gtPunctuation TokenClass.gtPunctuation 71 +nim gtComment highlite.html#gtComment TokenClass.gtComment 71 +nim gtLongComment highlite.html#gtLongComment TokenClass.gtLongComment 71 +nim gtRegularExpression highlite.html#gtRegularExpression TokenClass.gtRegularExpression 71 +nim gtTagStart highlite.html#gtTagStart TokenClass.gtTagStart 71 +nim gtTagEnd highlite.html#gtTagEnd TokenClass.gtTagEnd 71 +nim gtKey highlite.html#gtKey TokenClass.gtKey 71 +nim gtValue highlite.html#gtValue TokenClass.gtValue 71 +nim gtRawData highlite.html#gtRawData TokenClass.gtRawData 71 +nim gtAssembler highlite.html#gtAssembler TokenClass.gtAssembler 71 +nim gtPreprocessor highlite.html#gtPreprocessor TokenClass.gtPreprocessor 71 +nim gtDirective highlite.html#gtDirective TokenClass.gtDirective 71 +nim gtCommand highlite.html#gtCommand TokenClass.gtCommand 71 +nim gtRule highlite.html#gtRule TokenClass.gtRule 71 +nim gtHyperlink highlite.html#gtHyperlink TokenClass.gtHyperlink 71 +nim gtLabel highlite.html#gtLabel TokenClass.gtLabel 71 +nim gtReference highlite.html#gtReference TokenClass.gtReference 71 +nim gtPrompt highlite.html#gtPrompt TokenClass.gtPrompt 71 +nim gtProgramOutput highlite.html#gtProgramOutput TokenClass.gtProgramOutput 71 +nim gtProgram highlite.html#gtProgram TokenClass.gtProgram 71 +nim gtOption highlite.html#gtOption TokenClass.gtOption 71 +nim gtOther highlite.html#gtOther TokenClass.gtOther 71 +nim TokenClass highlite.html#TokenClass enum TokenClass 71 +nim GeneralTokenizer highlite.html#GeneralTokenizer object GeneralTokenizer 79 +nim sourceLanguageToStr highlite.html#sourceLanguageToStr const sourceLanguageToStr 88 +nim sourceLanguageToAlpha highlite.html#sourceLanguageToAlpha const sourceLanguageToAlpha 90 +nim tokenClassToStr highlite.html#tokenClassToStr const tokenClassToStr 93 +nim getSourceLanguage highlite.html#getSourceLanguage,string proc getSourceLanguage(name: string): SourceLanguage 118 +nim initGeneralTokenizer highlite.html#initGeneralTokenizer,GeneralTokenizer,cstring proc initGeneralTokenizer(g: var GeneralTokenizer; buf: cstring) 126 +nim initGeneralTokenizer highlite.html#initGeneralTokenizer,GeneralTokenizer,string proc initGeneralTokenizer(g: var GeneralTokenizer; buf: string) 135 +nim deinitGeneralTokenizer highlite.html#deinitGeneralTokenizer,GeneralTokenizer proc deinitGeneralTokenizer(g: var GeneralTokenizer) 138 +nim getNextToken highlite.html#getNextToken,GeneralTokenizer,SourceLanguage proc getNextToken(g: var GeneralTokenizer; lang: SourceLanguage) 1000 +nim tokenize highlite.html#tokenize,string,SourceLanguage proc tokenize(text: string; lang: SourceLanguage): seq[(string, TokenClass)] 1014 +nimgrp initgeneraltokenizer highlite.html#initGeneralTokenizer-procs-all proc 126 diff --git a/hotcodereloading.html b/hotcodereloading.html new file mode 100644 index 0000000000000..4152de4415428 --- /dev/null +++ b/hotcodereloading.html @@ -0,0 +1,192 @@ + + + + + + + +std/hotcodereloading + + + + + + + + + + + + + + + + +
+
+

std/hotcodereloading

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Unstable API.

+
+

Procs

+
+
+
+
proc hasAnyModuleChanged(): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template afterCodeReload(body: untyped)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template beforeCodeReload(body: untyped)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template hasModuleChanged(module: typed): bool
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template performCodeReload()
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/hotcodereloading.idx b/hotcodereloading.idx new file mode 100644 index 0000000000000..4c0b6c38d6719 --- /dev/null +++ b/hotcodereloading.idx @@ -0,0 +1,6 @@ +nimTitle hotcodereloading hotcodereloading.html module std/hotcodereloading 0 +nim beforeCodeReload hotcodereloading.html#beforeCodeReload.t,untyped template beforeCodeReload(body: untyped) 37 +nim afterCodeReload hotcodereloading.html#afterCodeReload.t,untyped template afterCodeReload(body: untyped) 38 +nim hasModuleChanged hotcodereloading.html#hasModuleChanged.t,typed template hasModuleChanged(module: typed): bool 39 +nim hasAnyModuleChanged hotcodereloading.html#hasAnyModuleChanged proc hasAnyModuleChanged(): bool 40 +nim performCodeReload hotcodereloading.html#performCodeReload.t template performCodeReload() 41 diff --git a/htmlgen.html b/htmlgen.html new file mode 100644 index 0000000000000..cc278498e71cf --- /dev/null +++ b/htmlgen.html @@ -0,0 +1,2781 @@ + + + + + + + +std/htmlgen + + + + + + + + + + + + + + + + +
+
+

std/htmlgen

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Do yourself a favor and import the module as from std/htmlgen import nil and then fully qualify the macros.

+

Note: The Karax project (nimble install karax) has a better way to achieve the same, see https://github.com/pragmagic/karax/blob/master/tests/nativehtmlgen.nim for an example.

+

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.

+ +

MathML

MathML is supported, MathML is part of HTML5. MathML is an Standard ISO/IEC 40314 from year 2015. MathML allows you to draw advanced math on the web, visually similar to Latex math.

+ +

Examples

var nim = "Nim"
+echo h1(a(href="https://nim-lang.org", nim))

+

Writes the string:

+
<h1><a href="https://nim-lang.org">Nim</a></h1>
+ +

Example:

+
import std/htmlgen
+let nim = "Nim"
+assert h1(a(href = "https://nim-lang.org", nim)) ==
+  """<h1><a href="https://nim-lang.org">Nim</a></h1>"""
+assert form(action = "test", `accept-charset` = "Content-Type") ==
+  """<form action="test" accept-charset="Content-Type"></form>"""
+
+
+assert math(
+  semantics(
+    mrow(
+      msup(
+        mi("x"),
+        mn("42")
+      )
+    )
+  )
+) == "<math><semantics><mrow><msup><mi>x</mi><mn>42</mn></msup></mrow></semantics></math>"
+
+assert math(
+  semantics(
+    annotation(encoding = "application/x-tex", title = "Latex on Web", r"x^{2} + y")
+  )
+) == """<math><semantics><annotation encoding="application/x-tex" title="Latex on Web">x^{2} + y</annotation></semantics></math>"""

+
+

Imports

+
+ macros, strutils +
+
+
+

Consts

+
+
+
ariaAttr = " role "
+
+ + HTML DOM Aria Attributes + Source   +Edit   + +
+
+
+
commonAttr = " accesskey class contenteditable dir hidden id lang spellcheck style tabindex title translate onabort onblur oncancel oncanplay oncanplaythrough onchange onclick oncuechange ondblclick ondurationchange onemptied onended onerror onfocus oninput oninvalid onkeydown onkeypress onkeyup onload onloadeddata onloadedmetadata onloadstart onmousedown onmouseenter onmouseleave onmousemove onmouseout onmouseover onmouseup onmousewheel onpause onplay onplaying onprogress onratechange onreset onresize onscroll onseeked onseeking onselect onshow onstalled onsubmit onsuspend ontimeupdate ontoggle onvolumechange onwaiting  role "
+
+ + HTML DOM Common Attributes + Source   +Edit   + +
+
+
+
coreAttr = " accesskey class contenteditable dir hidden id lang spellcheck style tabindex title translate "
+
+ + HTML DOM Core Attributes + Source   +Edit   + +
+
+
+
eventAttr = "onabort onblur oncancel oncanplay oncanplaythrough onchange onclick oncuechange ondblclick ondurationchange onemptied onended onerror onfocus oninput oninvalid onkeydown onkeypress onkeyup onload onloadeddata onloadedmetadata onloadstart onmousedown onmouseenter onmouseleave onmousemove onmouseout onmouseover onmouseup onmousewheel onpause onplay onplaying onprogress onratechange onreset onresize onscroll onseeked onseeking onselect onshow onstalled onsubmit onsuspend ontimeupdate ontoggle onvolumechange onwaiting "
+
+ + HTML DOM Event Attributes + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc xmlCheckedTag(argsList: NimNode; tag: string; optAttr = ""; reqAttr = "";
+                   isLeaf = false): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + use this procedure to define a new XML tag + Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro a(e: varargs[untyped]): untyped
+
+ + Generates the HTML a element. + Source   +Edit   + +
+
+ +
+
+
+
macro abbr(e: varargs[untyped]): untyped
+
+ + Generates the HTML abbr element. + Source   +Edit   + +
+
+ +
+
+
+
macro address(e: varargs[untyped]): untyped
+
+ + Generates the HTML address element. + Source   +Edit   + +
+
+ +
+
+ + +
+
+ + +
+
+
+
macro area(e: varargs[untyped]): untyped
+
+ + Generates the HTML area element. + Source   +Edit   + +
+
+ +
+
+
+
macro article(e: varargs[untyped]): untyped
+
+ + Generates the HTML article element. + Source   +Edit   + +
+
+ +
+
+
+
macro aside(e: varargs[untyped]): untyped
+
+ + Generates the HTML aside element. + Source   +Edit   + +
+
+ +
+
+
+
macro audio(e: varargs[untyped]): untyped
+
+ + Generates the HTML audio element. + Source   +Edit   + +
+
+ +
+
+
+
macro b(e: varargs[untyped]): untyped
+
+ + Generates the HTML b element. + Source   +Edit   + +
+
+ +
+
+
+
macro base(e: varargs[untyped]): untyped
+
+ + Generates the HTML base element. + Source   +Edit   + +
+
+ +
+
+
+
macro bdi(e: varargs[untyped]): untyped
+
+ + Generates the HTML bdi element. + Source   +Edit   + +
+
+ +
+
+
+
macro bdo(e: varargs[untyped]): untyped
+
+ + Generates the HTML bdo element. + Source   +Edit   + +
+
+ +
+
+
+
macro big(e: varargs[untyped]): untyped
+
+ + Generates the HTML big element. + Source   +Edit   + +
+
+ +
+
+
+
macro blockquote(e: varargs[untyped]): untyped
+
+ + Generates the HTML blockquote element. + Source   +Edit   + +
+
+ +
+
+
+
macro body(e: varargs[untyped]): untyped
+
+ + Generates the HTML body element. + Source   +Edit   + +
+
+ +
+
+
+
macro br(e: varargs[untyped]): untyped
+
+ + Generates the HTML br element. + Source   +Edit   + +
+
+ +
+
+
+
macro button(e: varargs[untyped]): untyped
+
+ + Generates the HTML button element. + Source   +Edit   + +
+
+ +
+
+
+
macro canvas(e: varargs[untyped]): untyped
+
+ + Generates the HTML canvas element. + Source   +Edit   + +
+
+ +
+
+
+
macro caption(e: varargs[untyped]): untyped
+
+ + Generates the HTML caption element. + Source   +Edit   + +
+
+ +
+
+
+
macro center(e: varargs[untyped]): untyped
+
+ + Generates the HTML center element. + Source   +Edit   + +
+
+ +
+
+
+
macro cite(e: varargs[untyped]): untyped
+
+ + Generates the HTML cite element. + Source   +Edit   + +
+
+ +
+
+
+
macro code(e: varargs[untyped]): untyped
+
+ + Generates the HTML code element. + Source   +Edit   + +
+
+ +
+
+
+
macro col(e: varargs[untyped]): untyped
+
+ + Generates the HTML col element. + Source   +Edit   + +
+
+ +
+
+
+
macro colgroup(e: varargs[untyped]): untyped
+
+ + Generates the HTML colgroup element. + Source   +Edit   + +
+
+ +
+
+
+
macro data(e: varargs[untyped]): untyped
+
+ + Generates the HTML data element. + Source   +Edit   + +
+
+ +
+
+
+
macro datalist(e: varargs[untyped]): untyped
+
+ + Generates the HTML datalist element. + Source   +Edit   + +
+
+ +
+
+
+
macro dd(e: varargs[untyped]): untyped
+
+ + Generates the HTML dd element. + Source   +Edit   + +
+
+ +
+
+
+
macro del(e: varargs[untyped]): untyped
+
+ + Generates the HTML del element. + Source   +Edit   + +
+
+ +
+
+
+
macro details(e: varargs[untyped]): untyped
+
+ + Generates the HTML details element. + Source   +Edit   + +
+
+ +
+
+
+
macro dfn(e: varargs[untyped]): untyped
+
+ + Generates the HTML dfn element. + Source   +Edit   + +
+
+ +
+
+
+
macro dialog(e: varargs[untyped]): untyped
+
+ + Generates the HTML dialog element. + Source   +Edit   + +
+
+ +
+
+
+
macro `div`(e: varargs[untyped]): untyped
+
+ + Generates the HTML div element. + Source   +Edit   + +
+
+ +
+
+
+
macro dl(e: varargs[untyped]): untyped
+
+ + Generates the HTML dl element. + Source   +Edit   + +
+
+ +
+
+
+
macro dt(e: varargs[untyped]): untyped
+
+ + Generates the HTML dt element. + Source   +Edit   + +
+
+ +
+
+
+
macro em(e: varargs[untyped]): untyped
+
+ + Generates the HTML em element. + Source   +Edit   + +
+
+ +
+
+
+
macro embed(e: varargs[untyped]): untyped
+
+ + Generates the HTML embed element. + Source   +Edit   + +
+
+ +
+
+
+
macro fieldset(e: varargs[untyped]): untyped
+
+ + Generates the HTML fieldset element. + Source   +Edit   + +
+
+ +
+
+
+
macro figcaption(e: varargs[untyped]): untyped
+
+ + Generates the HTML figcaption element. + Source   +Edit   + +
+
+ +
+
+
+
macro figure(e: varargs[untyped]): untyped
+
+ + Generates the HTML figure element. + Source   +Edit   + +
+
+ +
+ +
+
+
macro form(e: varargs[untyped]): untyped
+
+ + Generates the HTML form element. + Source   +Edit   + +
+
+ +
+
+
+
macro h1(e: varargs[untyped]): untyped
+
+ + Generates the HTML h1 element. + Source   +Edit   + +
+
+ +
+
+
+
macro h2(e: varargs[untyped]): untyped
+
+ + Generates the HTML h2 element. + Source   +Edit   + +
+
+ +
+
+
+
macro h3(e: varargs[untyped]): untyped
+
+ + Generates the HTML h3 element. + Source   +Edit   + +
+
+ +
+
+
+
macro h4(e: varargs[untyped]): untyped
+
+ + Generates the HTML h4 element. + Source   +Edit   + +
+
+ +
+
+
+
macro h5(e: varargs[untyped]): untyped
+
+ + Generates the HTML h5 element. + Source   +Edit   + +
+
+ +
+
+
+
macro h6(e: varargs[untyped]): untyped
+
+ + Generates the HTML h6 element. + Source   +Edit   + +
+
+ +
+
+
+
macro head(e: varargs[untyped]): untyped
+
+ + Generates the HTML head element. + Source   +Edit   + +
+
+ +
+
+
+
macro header(e: varargs[untyped]): untyped
+
+ + Generates the HTML header element. + Source   +Edit   + +
+
+ +
+
+
+
macro hr(): untyped
+
+ + Generates the HTML hr element. + Source   +Edit   + +
+
+ +
+
+
+
macro html(e: varargs[untyped]): untyped
+
+ + Generates the HTML html element. + Source   +Edit   + +
+
+ +
+
+
+
macro i(e: varargs[untyped]): untyped
+
+ + Generates the HTML i element. + Source   +Edit   + +
+
+ +
+
+
+
macro iframe(e: varargs[untyped]): untyped
+
+ + Generates the HTML iframe element. + Source   +Edit   + +
+
+ +
+
+
+
macro img(e: varargs[untyped]): untyped
+
+ + Generates the HTML img element. + Source   +Edit   + +
+
+ +
+
+
+
macro input(e: varargs[untyped]): untyped
+
+ + Generates the HTML input element. + Source   +Edit   + +
+
+ +
+
+
+
macro ins(e: varargs[untyped]): untyped
+
+ + Generates the HTML ins element. + Source   +Edit   + +
+
+ +
+
+
+
macro kbd(e: varargs[untyped]): untyped
+
+ + Generates the HTML kbd element. + Source   +Edit   + +
+
+ +
+
+
+
macro keygen(e: varargs[untyped]): untyped
+
+ + Generates the HTML keygen element. + Source   +Edit   + +
+
+ +
+
+
+
macro label(e: varargs[untyped]): untyped
+
+ + Generates the HTML label element. + Source   +Edit   + +
+
+ +
+
+
+
macro legend(e: varargs[untyped]): untyped
+
+ + Generates the HTML legend element. + Source   +Edit   + +
+
+ +
+
+
+
macro li(e: varargs[untyped]): untyped
+
+ + Generates the HTML li element. + Source   +Edit   + +
+
+ +
+ +
+ + +
+
+
+
macro main(e: varargs[untyped]): untyped
+
+ + Generates the HTML main element. + Source   +Edit   + +
+
+ +
+
+
+
macro map(e: varargs[untyped]): untyped
+
+ + Generates the HTML map element. + Source   +Edit   + +
+
+ +
+
+
+
macro mark(e: varargs[untyped]): untyped
+
+ + Generates the HTML mark element. + Source   +Edit   + +
+
+ +
+
+
+
macro marquee(e: varargs[untyped]): untyped
+
+ + Generates the HTML marquee element. + Source   +Edit   + +
+
+ +
+ +
+ + +
+
+ + +
+
+
+
macro meta(e: varargs[untyped]): untyped
+
+ + Generates the HTML meta element. + Source   +Edit   + +
+
+ +
+
+
+
macro meter(e: varargs[untyped]): untyped
+
+ + Generates the HTML meter element. + Source   +Edit   + +
+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+
+
macro noscript(e: varargs[untyped]): untyped
+
+ + Generates the HTML noscript element. + Source   +Edit   + +
+
+ +
+
+
+
macro `object`(e: varargs[untyped]): untyped
+
+ + Generates the HTML object element. + Source   +Edit   + +
+
+ +
+
+
+
macro ol(e: varargs[untyped]): untyped
+
+ + Generates the HTML ol element. + Source   +Edit   + +
+
+ +
+
+
+
macro optgroup(e: varargs[untyped]): untyped
+
+ + Generates the HTML optgroup element. + Source   +Edit   + +
+
+ +
+
+
+
macro option(e: varargs[untyped]): untyped
+
+ + Generates the HTML option element. + Source   +Edit   + +
+
+ +
+
+
+
macro output(e: varargs[untyped]): untyped
+
+ + Generates the HTML output element. + Source   +Edit   + +
+
+ +
+
+
+
macro p(e: varargs[untyped]): untyped
+
+ + Generates the HTML p element. + Source   +Edit   + +
+
+ +
+
+
+
macro param(e: varargs[untyped]): untyped
+
+ + Generates the HTML param element. + Source   +Edit   + +
+
+ +
+
+
+
macro picture(e: varargs[untyped]): untyped
+
+ + Generates the HTML picture element. + Source   +Edit   + +
+
+ +
+
+
+
macro portal(e: varargs[untyped]): untyped
+
+ + Generates the HTML portal element. + Source   +Edit   + +
+
+ +
+
+
+
macro pre(e: varargs[untyped]): untyped
+
+ + Generates the HTML pre element. + Source   +Edit   + +
+
+ +
+
+
+
macro progress(e: varargs[untyped]): untyped
+
+ + Generates the HTML progress element. + Source   +Edit   + +
+
+ +
+
+
+
macro q(e: varargs[untyped]): untyped
+
+ + Generates the HTML q element. + Source   +Edit   + +
+
+ +
+
+
+
macro rb(e: varargs[untyped]): untyped
+
+ + Generates the HTML rb element. + Source   +Edit   + +
+
+ +
+
+
+
macro rp(e: varargs[untyped]): untyped
+
+ + Generates the HTML rp element. + Source   +Edit   + +
+
+ +
+
+
+
macro rt(e: varargs[untyped]): untyped
+
+ + Generates the HTML rt element. + Source   +Edit   + +
+
+ +
+
+
+
macro rtc(e: varargs[untyped]): untyped
+
+ + Generates the HTML rtc element. + Source   +Edit   + +
+
+ +
+
+
+
macro ruby(e: varargs[untyped]): untyped
+
+ + Generates the HTML ruby element. + Source   +Edit   + +
+
+ +
+
+
+
macro s(e: varargs[untyped]): untyped
+
+ + Generates the HTML s element. + Source   +Edit   + +
+
+ +
+
+
+
macro samp(e: varargs[untyped]): untyped
+
+ + Generates the HTML samp element. + Source   +Edit   + +
+
+ +
+
+
+
macro script(e: varargs[untyped]): untyped
+
+ + Generates the HTML script element. + Source   +Edit   + +
+
+ +
+
+
+
macro section(e: varargs[untyped]): untyped
+
+ + Generates the HTML section element. + Source   +Edit   + +
+
+ +
+
+
+
macro select(e: varargs[untyped]): untyped
+
+ + Generates the HTML select element. + Source   +Edit   + +
+
+ +
+
+ + +
+
+
+
macro slot(e: varargs[untyped]): untyped
+
+ + Generates the HTML slot element. + Source   +Edit   + +
+
+ +
+
+
+
macro small(e: varargs[untyped]): untyped
+
+ + Generates the HTML small element. + Source   +Edit   + +
+
+ +
+
+
+
macro source(e: varargs[untyped]): untyped
+
+ + Generates the HTML source element. + Source   +Edit   + +
+
+ +
+
+
+
macro span(e: varargs[untyped]): untyped
+
+ + Generates the HTML span element. + Source   +Edit   + +
+
+ +
+
+
+
macro strong(e: varargs[untyped]): untyped
+
+ + Generates the HTML strong element. + Source   +Edit   + +
+
+ +
+
+
+
macro style(e: varargs[untyped]): untyped
+
+ + Generates the HTML style element. + Source   +Edit   + +
+
+ +
+
+
+
macro sub(e: varargs[untyped]): untyped
+
+ + Generates the HTML sub element. + Source   +Edit   + +
+
+ +
+
+
+
macro summary(e: varargs[untyped]): untyped
+
+ + Generates the HTML summary element. + Source   +Edit   + +
+
+ +
+
+
+
macro sup(e: varargs[untyped]): untyped
+
+ + Generates the HTML sup element. + Source   +Edit   + +
+
+ +
+
+
+
macro table(e: varargs[untyped]): untyped
+
+ + Generates the HTML table element. + Source   +Edit   + +
+
+ +
+
+
+
macro tbody(e: varargs[untyped]): untyped
+
+ + Generates the HTML tbody element. + Source   +Edit   + +
+
+ +
+
+
+
macro td(e: varargs[untyped]): untyped
+
+ + Generates the HTML td element. + Source   +Edit   + +
+
+ +
+
+
+
macro `template`(e: varargs[untyped]): untyped
+
+ + Generates the HTML template element. + Source   +Edit   + +
+
+ +
+
+
+
macro textarea(e: varargs[untyped]): untyped
+
+ + Generates the HTML textarea element. + Source   +Edit   + +
+
+ +
+
+
+
macro tfoot(e: varargs[untyped]): untyped
+
+ + Generates the HTML tfoot element. + Source   +Edit   + +
+
+ +
+
+
+
macro th(e: varargs[untyped]): untyped
+
+ + Generates the HTML th element. + Source   +Edit   + +
+
+ +
+
+
+
macro thead(e: varargs[untyped]): untyped
+
+ + Generates the HTML thead element. + Source   +Edit   + +
+
+ +
+
+
+
macro time(e: varargs[untyped]): untyped
+
+ + Generates the HTML time element. + Source   +Edit   + +
+
+ +
+
+
+
macro title(e: varargs[untyped]): untyped
+
+ + Generates the HTML title element. + Source   +Edit   + +
+
+ +
+
+
+
macro tr(e: varargs[untyped]): untyped
+
+ + Generates the HTML tr element. + Source   +Edit   + +
+
+ +
+
+
+
macro track(e: varargs[untyped]): untyped
+
+ + Generates the HTML track element. + Source   +Edit   + +
+
+ +
+
+
+
macro tt(e: varargs[untyped]): untyped
+
+ + Generates the HTML tt element. + Source   +Edit   + +
+
+ +
+
+
+
macro u(e: varargs[untyped]): untyped
+
+ + Generates the HTML u element. + Source   +Edit   + +
+
+ +
+
+
+
macro ul(e: varargs[untyped]): untyped
+
+ + Generates the HTML ul element. + Source   +Edit   + +
+
+ +
+
+
+
macro `var`(e: varargs[untyped]): untyped
+
+ + Generates the HTML var element. + Source   +Edit   + +
+
+ +
+
+
+
macro video(e: varargs[untyped]): untyped
+
+ + Generates the HTML video element. + Source   +Edit   + +
+
+ +
+
+
+
macro wbr(e: varargs[untyped]): untyped
+
+ + Generates the HTML wbr element. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/htmlgen.idx b/htmlgen.idx new file mode 100644 index 0000000000000..d3825d60ff370 --- /dev/null +++ b/htmlgen.idx @@ -0,0 +1,160 @@ +nimTitle htmlgen htmlgen.html module std/htmlgen 0 +nim coreAttr htmlgen.html#coreAttr const coreAttr 47 +nim eventAttr htmlgen.html#eventAttr const eventAttr 49 +nim ariaAttr htmlgen.html#ariaAttr const ariaAttr 57 +nim commonAttr htmlgen.html#commonAttr const commonAttr 58 +nim xmlCheckedTag htmlgen.html#xmlCheckedTag,NimNode,string,string,string proc xmlCheckedTag(argsList: NimNode; tag: string; optAttr = ""; reqAttr = "";\n isLeaf = false): NimNode 78 +nim a htmlgen.html#a.m,varargs[untyped] macro a(e: varargs[untyped]): untyped 119 +nim abbr htmlgen.html#abbr.m,varargs[untyped] macro abbr(e: varargs[untyped]): untyped 124 +nim address htmlgen.html#address.m,varargs[untyped] macro address(e: varargs[untyped]): untyped 128 +nim area htmlgen.html#area.m,varargs[untyped] macro area(e: varargs[untyped]): untyped 132 +nim article htmlgen.html#article.m,varargs[untyped] macro article(e: varargs[untyped]): untyped 137 +nim aside htmlgen.html#aside.m,varargs[untyped] macro aside(e: varargs[untyped]): untyped 141 +nim audio htmlgen.html#audio.m,varargs[untyped] macro audio(e: varargs[untyped]): untyped 145 +nim b htmlgen.html#b.m,varargs[untyped] macro b(e: varargs[untyped]): untyped 150 +nim base htmlgen.html#base.m,varargs[untyped] macro base(e: varargs[untyped]): untyped 154 +nim bdi htmlgen.html#bdi.m,varargs[untyped] macro bdi(e: varargs[untyped]): untyped 158 +nim bdo htmlgen.html#bdo.m,varargs[untyped] macro bdo(e: varargs[untyped]): untyped 162 +nim big htmlgen.html#big.m,varargs[untyped] macro big(e: varargs[untyped]): untyped 166 +nim blockquote htmlgen.html#blockquote.m,varargs[untyped] macro blockquote(e: varargs[untyped]): untyped 170 +nim body htmlgen.html#body.m,varargs[untyped] macro body(e: varargs[untyped]): untyped 174 +nim br htmlgen.html#br.m,varargs[untyped] macro br(e: varargs[untyped]): untyped 180 +nim button htmlgen.html#button.m,varargs[untyped] macro button(e: varargs[untyped]): untyped 184 +nim canvas htmlgen.html#canvas.m,varargs[untyped] macro canvas(e: varargs[untyped]): untyped 190 +nim caption htmlgen.html#caption.m,varargs[untyped] macro caption(e: varargs[untyped]): untyped 194 +nim center htmlgen.html#center.m,varargs[untyped] macro center(e: varargs[untyped]): untyped 198 +nim cite htmlgen.html#cite.m,varargs[untyped] macro cite(e: varargs[untyped]): untyped 202 +nim code htmlgen.html#code.m,varargs[untyped] macro code(e: varargs[untyped]): untyped 206 +nim col htmlgen.html#col.m,varargs[untyped] macro col(e: varargs[untyped]): untyped 210 +nim colgroup htmlgen.html#colgroup.m,varargs[untyped] macro colgroup(e: varargs[untyped]): untyped 214 +nim data htmlgen.html#data.m,varargs[untyped] macro data(e: varargs[untyped]): untyped 218 +nim datalist htmlgen.html#datalist.m,varargs[untyped] macro datalist(e: varargs[untyped]): untyped 222 +nim dd htmlgen.html#dd.m,varargs[untyped] macro dd(e: varargs[untyped]): untyped 226 +nim del htmlgen.html#del.m,varargs[untyped] macro del(e: varargs[untyped]): untyped 230 +nim details htmlgen.html#details.m,varargs[untyped] macro details(e: varargs[untyped]): untyped 234 +nim dfn htmlgen.html#dfn.m,varargs[untyped] macro dfn(e: varargs[untyped]): untyped 238 +nim dialog htmlgen.html#dialog.m,varargs[untyped] macro dialog(e: varargs[untyped]): untyped 242 +nim `div` htmlgen.html#div.m,varargs[untyped] macro `div`(e: varargs[untyped]): untyped 246 +nim dl htmlgen.html#dl.m,varargs[untyped] macro dl(e: varargs[untyped]): untyped 250 +nim dt htmlgen.html#dt.m,varargs[untyped] macro dt(e: varargs[untyped]): untyped 254 +nim em htmlgen.html#em.m,varargs[untyped] macro em(e: varargs[untyped]): untyped 258 +nim embed htmlgen.html#embed.m,varargs[untyped] macro embed(e: varargs[untyped]): untyped 262 +nim fieldset htmlgen.html#fieldset.m,varargs[untyped] macro fieldset(e: varargs[untyped]): untyped 267 +nim figure htmlgen.html#figure.m,varargs[untyped] macro figure(e: varargs[untyped]): untyped 271 +nim figcaption htmlgen.html#figcaption.m,varargs[untyped] macro figcaption(e: varargs[untyped]): untyped 275 +nim footer htmlgen.html#footer.m,varargs[untyped] macro footer(e: varargs[untyped]): untyped 279 +nim form htmlgen.html#form.m,varargs[untyped] macro form(e: varargs[untyped]): untyped 283 +nim h1 htmlgen.html#h1.m,varargs[untyped] macro h1(e: varargs[untyped]): untyped 288 +nim h2 htmlgen.html#h2.m,varargs[untyped] macro h2(e: varargs[untyped]): untyped 292 +nim h3 htmlgen.html#h3.m,varargs[untyped] macro h3(e: varargs[untyped]): untyped 296 +nim h4 htmlgen.html#h4.m,varargs[untyped] macro h4(e: varargs[untyped]): untyped 300 +nim h5 htmlgen.html#h5.m,varargs[untyped] macro h5(e: varargs[untyped]): untyped 304 +nim h6 htmlgen.html#h6.m,varargs[untyped] macro h6(e: varargs[untyped]): untyped 308 +nim head htmlgen.html#head.m,varargs[untyped] macro head(e: varargs[untyped]): untyped 312 +nim header htmlgen.html#header.m,varargs[untyped] macro header(e: varargs[untyped]): untyped 316 +nim html htmlgen.html#html.m,varargs[untyped] macro html(e: varargs[untyped]): untyped 320 +nim hr htmlgen.html#hr.m macro hr(): untyped 324 +nim i htmlgen.html#i.m,varargs[untyped] macro i(e: varargs[untyped]): untyped 328 +nim iframe htmlgen.html#iframe.m,varargs[untyped] macro iframe(e: varargs[untyped]): untyped 332 +nim img htmlgen.html#img.m,varargs[untyped] macro img(e: varargs[untyped]): untyped 337 +nim input htmlgen.html#input.m,varargs[untyped] macro input(e: varargs[untyped]): untyped 342 +nim ins htmlgen.html#ins.m,varargs[untyped] macro ins(e: varargs[untyped]): untyped 350 +nim kbd htmlgen.html#kbd.m,varargs[untyped] macro kbd(e: varargs[untyped]): untyped 354 +nim keygen htmlgen.html#keygen.m,varargs[untyped] macro keygen(e: varargs[untyped]): untyped 358 +nim label htmlgen.html#label.m,varargs[untyped] macro label(e: varargs[untyped]): untyped 363 +nim legend htmlgen.html#legend.m,varargs[untyped] macro legend(e: varargs[untyped]): untyped 367 +nim li htmlgen.html#li.m,varargs[untyped] macro li(e: varargs[untyped]): untyped 371 +nim link htmlgen.html#link.m,varargs[untyped] macro link(e: varargs[untyped]): untyped 375 +nim main htmlgen.html#main.m,varargs[untyped] macro main(e: varargs[untyped]): untyped 380 +nim map htmlgen.html#map.m,varargs[untyped] macro map(e: varargs[untyped]): untyped 384 +nim mark htmlgen.html#mark.m,varargs[untyped] macro mark(e: varargs[untyped]): untyped 388 +nim marquee htmlgen.html#marquee.m,varargs[untyped] macro marquee(e: varargs[untyped]): untyped 392 +nim meta htmlgen.html#meta.m,varargs[untyped] macro meta(e: varargs[untyped]): untyped 398 +nim meter htmlgen.html#meter.m,varargs[untyped] macro meter(e: varargs[untyped]): untyped 403 +nim nav htmlgen.html#nav.m,varargs[untyped] macro nav(e: varargs[untyped]): untyped 408 +nim noscript htmlgen.html#noscript.m,varargs[untyped] macro noscript(e: varargs[untyped]): untyped 412 +nim `object` htmlgen.html#object.m,varargs[untyped] macro `object`(e: varargs[untyped]): untyped 416 +nim ol htmlgen.html#ol.m,varargs[untyped] macro ol(e: varargs[untyped]): untyped 421 +nim optgroup htmlgen.html#optgroup.m,varargs[untyped] macro optgroup(e: varargs[untyped]): untyped 425 +nim option htmlgen.html#option.m,varargs[untyped] macro option(e: varargs[untyped]): untyped 429 +nim output htmlgen.html#output.m,varargs[untyped] macro output(e: varargs[untyped]): untyped 434 +nim p htmlgen.html#p.m,varargs[untyped] macro p(e: varargs[untyped]): untyped 438 +nim param htmlgen.html#param.m,varargs[untyped] macro param(e: varargs[untyped]): untyped 442 +nim picture htmlgen.html#picture.m,varargs[untyped] macro picture(e: varargs[untyped]): untyped 446 +nim pre htmlgen.html#pre.m,varargs[untyped] macro pre(e: varargs[untyped]): untyped 450 +nim progress htmlgen.html#progress.m,varargs[untyped] macro progress(e: varargs[untyped]): untyped 454 +nim q htmlgen.html#q.m,varargs[untyped] macro q(e: varargs[untyped]): untyped 458 +nim rb htmlgen.html#rb.m,varargs[untyped] macro rb(e: varargs[untyped]): untyped 462 +nim rp htmlgen.html#rp.m,varargs[untyped] macro rp(e: varargs[untyped]): untyped 466 +nim rt htmlgen.html#rt.m,varargs[untyped] macro rt(e: varargs[untyped]): untyped 470 +nim rtc htmlgen.html#rtc.m,varargs[untyped] macro rtc(e: varargs[untyped]): untyped 474 +nim ruby htmlgen.html#ruby.m,varargs[untyped] macro ruby(e: varargs[untyped]): untyped 478 +nim s htmlgen.html#s.m,varargs[untyped] macro s(e: varargs[untyped]): untyped 482 +nim samp htmlgen.html#samp.m,varargs[untyped] macro samp(e: varargs[untyped]): untyped 486 +nim script htmlgen.html#script.m,varargs[untyped] macro script(e: varargs[untyped]): untyped 490 +nim section htmlgen.html#section.m,varargs[untyped] macro section(e: varargs[untyped]): untyped 495 +nim select htmlgen.html#select.m,varargs[untyped] macro select(e: varargs[untyped]): untyped 499 +nim slot htmlgen.html#slot.m,varargs[untyped] macro slot(e: varargs[untyped]): untyped 504 +nim small htmlgen.html#small.m,varargs[untyped] macro small(e: varargs[untyped]): untyped 508 +nim source htmlgen.html#source.m,varargs[untyped] macro source(e: varargs[untyped]): untyped 512 +nim span htmlgen.html#span.m,varargs[untyped] macro span(e: varargs[untyped]): untyped 516 +nim strong htmlgen.html#strong.m,varargs[untyped] macro strong(e: varargs[untyped]): untyped 520 +nim style htmlgen.html#style.m,varargs[untyped] macro style(e: varargs[untyped]): untyped 524 +nim sub htmlgen.html#sub.m,varargs[untyped] macro sub(e: varargs[untyped]): untyped 528 +nim summary htmlgen.html#summary.m,varargs[untyped] macro summary(e: varargs[untyped]): untyped 532 +nim sup htmlgen.html#sup.m,varargs[untyped] macro sup(e: varargs[untyped]): untyped 536 +nim table htmlgen.html#table.m,varargs[untyped] macro table(e: varargs[untyped]): untyped 540 +nim tbody htmlgen.html#tbody.m,varargs[untyped] macro tbody(e: varargs[untyped]): untyped 544 +nim td htmlgen.html#td.m,varargs[untyped] macro td(e: varargs[untyped]): untyped 548 +nim `template` htmlgen.html#template.m,varargs[untyped] macro `template`(e: varargs[untyped]): untyped 552 +nim textarea htmlgen.html#textarea.m,varargs[untyped] macro textarea(e: varargs[untyped]): untyped 556 +nim tfoot htmlgen.html#tfoot.m,varargs[untyped] macro tfoot(e: varargs[untyped]): untyped 562 +nim th htmlgen.html#th.m,varargs[untyped] macro th(e: varargs[untyped]): untyped 566 +nim thead htmlgen.html#thead.m,varargs[untyped] macro thead(e: varargs[untyped]): untyped 571 +nim time htmlgen.html#time.m,varargs[untyped] macro time(e: varargs[untyped]): untyped 575 +nim title htmlgen.html#title.m,varargs[untyped] macro title(e: varargs[untyped]): untyped 579 +nim tr htmlgen.html#tr.m,varargs[untyped] macro tr(e: varargs[untyped]): untyped 583 +nim track htmlgen.html#track.m,varargs[untyped] macro track(e: varargs[untyped]): untyped 587 +nim tt htmlgen.html#tt.m,varargs[untyped] macro tt(e: varargs[untyped]): untyped 592 +nim u htmlgen.html#u.m,varargs[untyped] macro u(e: varargs[untyped]): untyped 596 +nim ul htmlgen.html#ul.m,varargs[untyped] macro ul(e: varargs[untyped]): untyped 600 +nim `var` htmlgen.html#var.m,varargs[untyped] macro `var`(e: varargs[untyped]): untyped 604 +nim video htmlgen.html#video.m,varargs[untyped] macro video(e: varargs[untyped]): untyped 608 +nim wbr htmlgen.html#wbr.m,varargs[untyped] macro wbr(e: varargs[untyped]): untyped 613 +nim portal htmlgen.html#portal.m,varargs[untyped] macro portal(e: varargs[untyped]): untyped 617 +nim math htmlgen.html#math.m,varargs[untyped] macro math(e: varargs[untyped]): untyped 622 +nim maction htmlgen.html#maction.m,varargs[untyped] macro maction(e: varargs[untyped]): untyped 627 +nim menclose htmlgen.html#menclose.m,varargs[untyped] macro menclose(e: varargs[untyped]): untyped 632 +nim merror htmlgen.html#merror.m,varargs[untyped] macro merror(e: varargs[untyped]): untyped 637 +nim mfenced htmlgen.html#mfenced.m,varargs[untyped] macro mfenced(e: varargs[untyped]): untyped 642 +nim mfrac htmlgen.html#mfrac.m,varargs[untyped] macro mfrac(e: varargs[untyped]): untyped 647 +nim mglyph htmlgen.html#mglyph.m,varargs[untyped] macro mglyph(e: varargs[untyped]): untyped 652 +nim mi htmlgen.html#mi.m,varargs[untyped] macro mi(e: varargs[untyped]): untyped 657 +nim mlabeledtr htmlgen.html#mlabeledtr.m,varargs[untyped] macro mlabeledtr(e: varargs[untyped]): untyped 662 +nim mmultiscripts htmlgen.html#mmultiscripts.m,varargs[untyped] macro mmultiscripts(e: varargs[untyped]): untyped 667 +nim mn htmlgen.html#mn.m,varargs[untyped] macro mn(e: varargs[untyped]): untyped 672 +nim mo htmlgen.html#mo.m,varargs[untyped] macro mo(e: varargs[untyped]): untyped 677 +nim mover htmlgen.html#mover.m,varargs[untyped] macro mover(e: varargs[untyped]): untyped 683 +nim mpadded htmlgen.html#mpadded.m,varargs[untyped] macro mpadded(e: varargs[untyped]): untyped 688 +nim mphantom htmlgen.html#mphantom.m,varargs[untyped] macro mphantom(e: varargs[untyped]): untyped 693 +nim mroot htmlgen.html#mroot.m,varargs[untyped] macro mroot(e: varargs[untyped]): untyped 698 +nim mrow htmlgen.html#mrow.m,varargs[untyped] macro mrow(e: varargs[untyped]): untyped 703 +nim ms htmlgen.html#ms.m,varargs[untyped] macro ms(e: varargs[untyped]): untyped 708 +nim mspace htmlgen.html#mspace.m,varargs[untyped] macro mspace(e: varargs[untyped]): untyped 713 +nim msqrt htmlgen.html#msqrt.m,varargs[untyped] macro msqrt(e: varargs[untyped]): untyped 718 +nim mstyle htmlgen.html#mstyle.m,varargs[untyped] macro mstyle(e: varargs[untyped]): untyped 723 +nim msub htmlgen.html#msub.m,varargs[untyped] macro msub(e: varargs[untyped]): untyped 729 +nim msubsup htmlgen.html#msubsup.m,varargs[untyped] macro msubsup(e: varargs[untyped]): untyped 734 +nim msup htmlgen.html#msup.m,varargs[untyped] macro msup(e: varargs[untyped]): untyped 739 +nim mtable htmlgen.html#mtable.m,varargs[untyped] macro mtable(e: varargs[untyped]): untyped 744 +nim mtd htmlgen.html#mtd.m,varargs[untyped] macro mtd(e: varargs[untyped]): untyped 752 +nim mtext htmlgen.html#mtext.m,varargs[untyped] macro mtext(e: varargs[untyped]): untyped 758 +nim munder htmlgen.html#munder.m,varargs[untyped] macro munder(e: varargs[untyped]): untyped 763 +nim munderover htmlgen.html#munderover.m,varargs[untyped] macro munderover(e: varargs[untyped]): untyped 768 +nim semantics htmlgen.html#semantics.m,varargs[untyped] macro semantics(e: varargs[untyped]): untyped 773 +nim annotation htmlgen.html#annotation.m,varargs[untyped] macro annotation(e: varargs[untyped]): untyped 778 +nim annotation-xml htmlgen.html#annotation-xml.m,varargs[untyped] macro annotation-xml(e: varargs[untyped]): untyped 783 +idx XML htmlgen.html#xml_1 Module htmlgen 0 +idx HTML htmlgen.html#html_1 Module htmlgen 0 +heading MathML htmlgen.html#mathml MathML 0 +heading Examples htmlgen.html#examples Examples 0 diff --git a/htmlparser.html b/htmlparser.html new file mode 100644 index 0000000000000..0b3bcd3984143 --- /dev/null +++ b/htmlparser.html @@ -0,0 +1,651 @@ + + + + + + + +src/htmlparser + + + + + + + + + + + + + + + + +
+
+

src/htmlparser

+
+ +
+ +
+ +

Note: +In order to use this module, run nimble install htmlparser.
+

NOTE: The behaviour might change in future versions as it is not clear what "wild HTML the real world uses" really implies.

+

It can be used to parse a wild HTML document and output it as valid XHTML document (well, if you are lucky):

+

echo loadHtml("mydirty.html")

+

Every tag in the resulting tree is in lower case.

+

Note: The resulting XmlNode already uses the clientData field, so it cannot be used by clients of this library.

+ +

Example: Transforming hyperlinks

This code demonstrates how you can iterate over all the tags in an HTML file and write back the modified version. In this case we look for hyperlinks ending with the extension .rst and convert them to .html.

+

import std/xmltree  # To use '$' for XmlNode
+import std/strtabs  # To access XmlAttributes
+import std/os       # To use splitFile
+import std/strutils # To use cmpIgnoreCase
+
+proc transformHyperlinks() =
+  let html = loadHtml("input.html")
+  
+  for a in html.findAll("a"):
+    if a.attrs.hasKey "href":
+      let (dir, filename, ext) = splitFile(a.attrs["href"])
+      if cmpIgnoreCase(ext, ".rst") == 0:
+        a.attrs["href"] = dir / filename & ".html"
+  
+  writeFile("output.html", $html)

+

+
+

Types

+
+
+
HtmlTag = enum
+  tagUnknown,               ## unknown HTML element
+  tagA,                     ## the HTML `a` element
+  tagAbbr,                  ## the deprecated HTML `abbr` element
+  tagAcronym,               ## the HTML `acronym` element
+  tagAddress,               ## the HTML `address` element
+  tagApplet,                ## the deprecated HTML `applet` element
+  tagArea,                  ## the HTML `area` element
+  tagArticle,               ## the HTML `article` element
+  tagAside,                 ## the HTML `aside` element
+  tagAudio,                 ## the HTML `audio` element
+  tagB,                     ## the HTML `b` element
+  tagBase,                  ## the HTML `base` element
+  tagBdi,                   ## the HTML `bdi` element
+  tagBdo,                   ## the deprecated HTML `dbo` element
+  tagBasefont,              ## the deprecated HTML `basefont` element
+  tagBig,                   ## the HTML `big` element
+  tagBlockquote,            ## the HTML `blockquote` element
+  tagBody,                  ## the HTML `body` element
+  tagBr,                    ## the HTML `br` element
+  tagButton,                ## the HTML `button` element
+  tagCanvas,                ## the HTML `canvas` element
+  tagCaption,               ## the HTML `caption` element
+  tagCenter,                ## the deprecated HTML `center` element
+  tagCite,                  ## the HTML `cite` element
+  tagCode,                  ## the HTML `code` element
+  tagCol,                   ## the HTML `col` element
+  tagColgroup,              ## the HTML `colgroup` element
+  tagCommand,               ## the HTML `command` element
+  tagDatalist,              ## the HTML `datalist` element
+  tagDd,                    ## the HTML `dd` element
+  tagDel,                   ## the HTML `del` element
+  tagDetails,               ## the HTML `details` element
+  tagDfn,                   ## the HTML `dfn` element
+  tagDialog,                ## the HTML `dialog` element
+  tagDiv,                   ## the HTML `div` element
+  tagDir,                   ## the deprecated HTLM `dir` element
+  tagDl,                    ## the HTML `dl` element
+  tagDt,                    ## the HTML `dt` element
+  tagEm,                    ## the HTML `em` element
+  tagEmbed,                 ## the HTML `embed` element
+  tagFieldset,              ## the HTML `fieldset` element
+  tagFigcaption,            ## the HTML `figcaption` element
+  tagFigure,                ## the HTML `figure` element
+  tagFont,                  ## the deprecated HTML `font` element
+  tagFooter,                ## the HTML `footer` element
+  tagForm,                  ## the HTML `form` element
+  tagFrame,                 ## the HTML `frame` element
+  tagFrameset,              ## the deprecated HTML `frameset` element
+  tagH1,                    ## the HTML `h1` element
+  tagH2,                    ## the HTML `h2` element
+  tagH3,                    ## the HTML `h3` element
+  tagH4,                    ## the HTML `h4` element
+  tagH5,                    ## the HTML `h5` element
+  tagH6,                    ## the HTML `h6` element
+  tagHead,                  ## the HTML `head` element
+  tagHeader,                ## the HTML `header` element
+  tagHgroup,                ## the HTML `hgroup` element
+  tagHtml,                  ## the HTML `html` element
+  tagHr,                    ## the HTML `hr` element
+  tagI,                     ## the HTML `i` element
+  tagIframe,                ## the deprecated HTML `iframe` element
+  tagImg,                   ## the HTML `img` element
+  tagInput,                 ## the HTML `input` element
+  tagIns,                   ## the HTML `ins` element
+  tagIsindex,               ## the deprecated HTML `isindex` element
+  tagKbd,                   ## the HTML `kbd` element
+  tagKeygen,                ## the HTML `keygen` element
+  tagLabel,                 ## the HTML `label` element
+  tagLegend,                ## the HTML `legend` element
+  tagLi,                    ## the HTML `li` element
+  tagLink,                  ## the HTML `link` element
+  tagMap,                   ## the HTML `map` element
+  tagMark,                  ## the HTML `mark` element
+  tagMenu,                  ## the deprecated HTML `menu` element
+  tagMeta,                  ## the HTML `meta` element
+  tagMeter,                 ## the HTML `meter` element
+  tagNav,                   ## the HTML `nav` element
+  tagNobr,                  ## the deprecated HTML `nobr` element
+  tagNoframes,              ## the deprecated HTML `noframes` element
+  tagNoscript,              ## the HTML `noscript` element
+  tagObject,                ## the HTML `object` element
+  tagOl,                    ## the HTML `ol` element
+  tagOptgroup,              ## the HTML `optgroup` element
+  tagOption,                ## the HTML `option` element
+  tagOutput,                ## the HTML `output` element
+  tagP,                     ## the HTML `p` element
+  tagParam,                 ## the HTML `param` element
+  tagPre,                   ## the HTML `pre` element
+  tagProgress,              ## the HTML `progress` element
+  tagQ,                     ## the HTML `q` element
+  tagRp,                    ## the HTML `rp` element
+  tagRt,                    ## the HTML `rt` element
+  tagRuby,                  ## the HTML `ruby` element
+  tagS,                     ## the deprecated HTML `s` element
+  tagSamp,                  ## the HTML `samp` element
+  tagScript,                ## the HTML `script` element
+  tagSection,               ## the HTML `section` element
+  tagSelect,                ## the HTML `select` element
+  tagSmall,                 ## the HTML `small` element
+  tagSource,                ## the HTML `source` element
+  tagSpan,                  ## the HTML `span` element
+  tagStrike,                ## the deprecated HTML `strike` element
+  tagStrong,                ## the HTML `strong` element
+  tagStyle,                 ## the HTML `style` element
+  tagSub,                   ## the HTML `sub` element
+  tagSummary,               ## the HTML `summary` element
+  tagSup,                   ## the HTML `sup` element
+  tagTable,                 ## the HTML `table` element
+  tagTbody,                 ## the HTML `tbody` element
+  tagTd,                    ## the HTML `td` element
+  tagTextarea,              ## the HTML `textarea` element
+  tagTfoot,                 ## the HTML `tfoot` element
+  tagTh,                    ## the HTML `th` element
+  tagThead,                 ## the HTML `thead` element
+  tagTime,                  ## the HTML `time` element
+  tagTitle,                 ## the HTML `title` element
+  tagTr,                    ## the HTML `tr` element
+  tagTrack,                 ## the HTML `track` element
+  tagTt,                    ## the HTML `tt` element
+  tagU,                     ## the deprecated HTML `u` element
+  tagUl,                    ## the HTML `ul` element
+  tagVar,                   ## the HTML `var` element
+  tagVideo,                 ## the HTML `video` element
+  tagWbr                     ## the HTML `wbr` element
+
+ + list of all supported HTML tags; order will always be alphabetically + +
+
+ +
+
+
+

Consts

+
+
+
BlockTags = {tagAddress, tagBlockquote, tagCenter, tagDel, tagDir, tagDiv,
+             tagDl, tagFieldset, tagForm, tagH1, tagH2, tagH3, tagH4, tagH5,
+             tagH6, tagHr, tagIns, tagIsindex, tagMenu, tagNoframes,
+             tagNoscript, tagOl, tagP, tagPre, tagTable, tagUl, tagCenter,
+             tagDir, tagIsindex, tagMenu, tagNoframes}
+
+ + + +
+
+
+
InlineTags = {tagA, tagAbbr, tagAcronym, tagApplet, tagB, tagBasefont, tagBdo,
+              tagBig, tagBr, tagButton, tagCite, tagCode, tagDel, tagDfn, tagEm,
+              tagFont, tagI, tagImg, tagIns, tagInput, tagIframe, tagKbd,
+              tagLabel, tagMap, tagObject, tagQ, tagSamp, tagScript, tagSelect,
+              tagSmall, tagSpan, tagStrong, tagSub, tagSup, tagTextarea, tagTt,
+              tagVar, tagApplet, tagBasefont, tagFont, tagIframe, tagU, tagS,
+              tagStrike, tagWbr}
+
+ + + +
+
+
+
SingleTags = {tagArea, tagBase, tagBasefont, tagBr, tagCol, tagFrame, tagHr,
+              tagImg, tagIsindex, tagLink, tagMeta, tagParam, tagWbr, tagSource}
+
+ + + +
+
+
+
tagToStr = ["a", "abbr", "acronym", "address", "applet", "area", "article",
+            "aside", "audio", "b", "base", "basefont", "bdi", "bdo", "big",
+            "blockquote", "body", "br", "button", "canvas", "caption", "center",
+            "cite", "code", "col", "colgroup", "command", "datalist", "dd",
+            "del", "details", "dfn", "dialog", "div", "dir", "dl", "dt", "em",
+            "embed", "fieldset", "figcaption", "figure", "font", "footer",
+            "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6",
+            "head", "header", "hgroup", "html", "hr", "i", "iframe", "img",
+            "input", "ins", "isindex", "kbd", "keygen", "label", "legend", "li",
+            "link", "map", "mark", "menu", "meta", "meter", "nav", "nobr",
+            "noframes", "noscript", "object", "ol", "optgroup", "option",
+            "output", "p", "param", "pre", "progress", "q", "rp", "rt", "ruby",
+            "s", "samp", "script", "section", "select", "small", "source",
+            "span", "strike", "strong", "style", "sub", "summary", "sup",
+            "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "time",
+            "title", "tr", "track", "tt", "u", "ul", "var", "video", "wbr"]
+
+ + + +
+
+ +
+
+
+

Procs

+
+
+
+
proc entityToRune(entity: string): Rune {....raises: [], tags: [], forbids: [].}
+
+ + Converts an HTML entity name like &Uuml; or values like &#220; or &#x000DC; to its UTF-8 equivalent. Rune(0) is returned if the entity name is unknown. +

Example:

+
import std/unicode
+doAssert entityToRune("") == Rune(0)
+doAssert entityToRune("a") == Rune(0)
+doAssert entityToRune("gt") == ">".runeAt(0)
+doAssert entityToRune("Uuml") == "Ü".runeAt(0)
+doAssert entityToRune("quest") == "?".runeAt(0)
+doAssert entityToRune("#x0003F") == "?".runeAt(0)
+ +
+
+ +
+
+
+
proc entityToUtf8(entity: string): string {....raises: [], tags: [], forbids: [].}
+
+ + Converts an HTML entity name like &Uuml; or values like &#220; or &#x000DC; to its UTF-8 equivalent. "" is returned if the entity name is unknown. The HTML parser already converts entities to UTF-8. +

Example:

+
const sigma = "Σ"
+doAssert entityToUtf8("") == ""
+doAssert entityToUtf8("a") == ""
+doAssert entityToUtf8("gt") == ">"
+doAssert entityToUtf8("Uuml") == "Ü"
+doAssert entityToUtf8("quest") == "?"
+doAssert entityToUtf8("#63") == "?"
+doAssert entityToUtf8("Sigma") == sigma
+doAssert entityToUtf8("#931") == sigma
+doAssert entityToUtf8("#0931") == sigma
+doAssert entityToUtf8("#x3A3") == sigma
+doAssert entityToUtf8("#x03A3") == sigma
+doAssert entityToUtf8("#x3a3") == sigma
+doAssert entityToUtf8("#X3a3") == sigma
+ +
+
+ +
+
+
+
proc htmlTag(n: XmlNode): HtmlTag {....raises: [], tags: [], forbids: [].}
+
+ + Gets n's tag as a HtmlTag. + +
+
+
+
proc htmlTag(s: string): HtmlTag {....raises: [], tags: [], forbids: [].}
+
+ + Converts s to a HtmlTag. If s is no HTML tag, tagUnknown is returned. + +
+
+ +
+
+
+
proc loadHtml(path: string): XmlNode {....raises: [IOError, OSError, ValueError,
+    Exception], tags: [ReadIOEffect, RootEffect, WriteIOEffect], forbids: [].}
+
+ + Loads and parses HTML from file specified by path, and returns a XmlNode. All parsing errors are ignored. + +
+
+
+
proc loadHtml(path: string; errors: var seq[string]): XmlNode {.
+    ...raises: [IOError, OSError, ValueError, Exception],
+    tags: [ReadIOEffect, RootEffect, WriteIOEffect], forbids: [].}
+
+ + Loads and parses HTML from file specified by path, and returns a XmlNode. Every occurred parsing error is added to the errors sequence. + +
+
+ +
+
+
+
proc parseHtml(html: string): XmlNode {....raises: [IOError, OSError, ValueError,
+    Exception], tags: [ReadIOEffect, RootEffect, WriteIOEffect], forbids: [].}
+
+ + Parses the HTML from string html and returns a XmlNode. All parsing errors are ignored. + +
+
+
+
proc parseHtml(s: Stream): XmlNode {....raises: [IOError, OSError, ValueError,
+    Exception], tags: [ReadIOEffect, RootEffect, WriteIOEffect], forbids: [].}
+
+ + Parses the HTML from stream s and returns a XmlNode. All parsing errors are ignored. + +
+
+
+
proc parseHtml(s: Stream; filename: string; errors: var seq[string]): XmlNode {.
+    ...raises: [IOError, OSError, ValueError, Exception],
+    tags: [ReadIOEffect, RootEffect, WriteIOEffect], forbids: [].}
+
+ + Parses the XML from stream s and returns a XmlNode. Every occurred parsing error is added to the errors sequence. + +
+
+ +
+
+
+
proc runeToEntity(rune: Rune): string {....raises: [], tags: [], forbids: [].}
+
+ + converts a Rune to its numeric HTML entity equivalent. +

Example:

+
import std/unicode
+doAssert runeToEntity(Rune(0)) == ""
+doAssert runeToEntity(Rune(-1)) == ""
+doAssert runeToEntity("Ü".runeAt(0)) == "#220"
+doAssert runeToEntity("∈".runeAt(0)) == "#8712"
+ +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/htmlparser.idx b/htmlparser.idx new file mode 100644 index 0000000000000..5827790e5cac3 --- /dev/null +++ b/htmlparser.idx @@ -0,0 +1,144 @@ +nimTitle htmlparser htmlparser.html module src/htmlparser 0 +nim tagUnknown htmlparser.html#tagUnknown HtmlTag.tagUnknown 57 +nim tagA htmlparser.html#tagA HtmlTag.tagA 57 +nim tagAbbr htmlparser.html#tagAbbr HtmlTag.tagAbbr 57 +nim tagAcronym htmlparser.html#tagAcronym HtmlTag.tagAcronym 57 +nim tagAddress htmlparser.html#tagAddress HtmlTag.tagAddress 57 +nim tagApplet htmlparser.html#tagApplet HtmlTag.tagApplet 57 +nim tagArea htmlparser.html#tagArea HtmlTag.tagArea 57 +nim tagArticle htmlparser.html#tagArticle HtmlTag.tagArticle 57 +nim tagAside htmlparser.html#tagAside HtmlTag.tagAside 57 +nim tagAudio htmlparser.html#tagAudio HtmlTag.tagAudio 57 +nim tagB htmlparser.html#tagB HtmlTag.tagB 57 +nim tagBase htmlparser.html#tagBase HtmlTag.tagBase 57 +nim tagBdi htmlparser.html#tagBdi HtmlTag.tagBdi 57 +nim tagBdo htmlparser.html#tagBdo HtmlTag.tagBdo 57 +nim tagBasefont htmlparser.html#tagBasefont HtmlTag.tagBasefont 57 +nim tagBig htmlparser.html#tagBig HtmlTag.tagBig 57 +nim tagBlockquote htmlparser.html#tagBlockquote HtmlTag.tagBlockquote 57 +nim tagBody htmlparser.html#tagBody HtmlTag.tagBody 57 +nim tagBr htmlparser.html#tagBr HtmlTag.tagBr 57 +nim tagButton htmlparser.html#tagButton HtmlTag.tagButton 57 +nim tagCanvas htmlparser.html#tagCanvas HtmlTag.tagCanvas 57 +nim tagCaption htmlparser.html#tagCaption HtmlTag.tagCaption 57 +nim tagCenter htmlparser.html#tagCenter HtmlTag.tagCenter 57 +nim tagCite htmlparser.html#tagCite HtmlTag.tagCite 57 +nim tagCode htmlparser.html#tagCode HtmlTag.tagCode 57 +nim tagCol htmlparser.html#tagCol HtmlTag.tagCol 57 +nim tagColgroup htmlparser.html#tagColgroup HtmlTag.tagColgroup 57 +nim tagCommand htmlparser.html#tagCommand HtmlTag.tagCommand 57 +nim tagDatalist htmlparser.html#tagDatalist HtmlTag.tagDatalist 57 +nim tagDd htmlparser.html#tagDd HtmlTag.tagDd 57 +nim tagDel htmlparser.html#tagDel HtmlTag.tagDel 57 +nim tagDetails htmlparser.html#tagDetails HtmlTag.tagDetails 57 +nim tagDfn htmlparser.html#tagDfn HtmlTag.tagDfn 57 +nim tagDialog htmlparser.html#tagDialog HtmlTag.tagDialog 57 +nim tagDiv htmlparser.html#tagDiv HtmlTag.tagDiv 57 +nim tagDir htmlparser.html#tagDir HtmlTag.tagDir 57 +nim tagDl htmlparser.html#tagDl HtmlTag.tagDl 57 +nim tagDt htmlparser.html#tagDt HtmlTag.tagDt 57 +nim tagEm htmlparser.html#tagEm HtmlTag.tagEm 57 +nim tagEmbed htmlparser.html#tagEmbed HtmlTag.tagEmbed 57 +nim tagFieldset htmlparser.html#tagFieldset HtmlTag.tagFieldset 57 +nim tagFigcaption htmlparser.html#tagFigcaption HtmlTag.tagFigcaption 57 +nim tagFigure htmlparser.html#tagFigure HtmlTag.tagFigure 57 +nim tagFont htmlparser.html#tagFont HtmlTag.tagFont 57 +nim tagFooter htmlparser.html#tagFooter HtmlTag.tagFooter 57 +nim tagForm htmlparser.html#tagForm HtmlTag.tagForm 57 +nim tagFrame htmlparser.html#tagFrame HtmlTag.tagFrame 57 +nim tagFrameset htmlparser.html#tagFrameset HtmlTag.tagFrameset 57 +nim tagH1 htmlparser.html#tagH1 HtmlTag.tagH1 57 +nim tagH2 htmlparser.html#tagH2 HtmlTag.tagH2 57 +nim tagH3 htmlparser.html#tagH3 HtmlTag.tagH3 57 +nim tagH4 htmlparser.html#tagH4 HtmlTag.tagH4 57 +nim tagH5 htmlparser.html#tagH5 HtmlTag.tagH5 57 +nim tagH6 htmlparser.html#tagH6 HtmlTag.tagH6 57 +nim tagHead htmlparser.html#tagHead HtmlTag.tagHead 57 +nim tagHeader htmlparser.html#tagHeader HtmlTag.tagHeader 57 +nim tagHgroup htmlparser.html#tagHgroup HtmlTag.tagHgroup 57 +nim tagHtml htmlparser.html#tagHtml HtmlTag.tagHtml 57 +nim tagHr htmlparser.html#tagHr HtmlTag.tagHr 57 +nim tagI htmlparser.html#tagI HtmlTag.tagI 57 +nim tagIframe htmlparser.html#tagIframe HtmlTag.tagIframe 57 +nim tagImg htmlparser.html#tagImg HtmlTag.tagImg 57 +nim tagInput htmlparser.html#tagInput HtmlTag.tagInput 57 +nim tagIns htmlparser.html#tagIns HtmlTag.tagIns 57 +nim tagIsindex htmlparser.html#tagIsindex HtmlTag.tagIsindex 57 +nim tagKbd htmlparser.html#tagKbd HtmlTag.tagKbd 57 +nim tagKeygen htmlparser.html#tagKeygen HtmlTag.tagKeygen 57 +nim tagLabel htmlparser.html#tagLabel HtmlTag.tagLabel 57 +nim tagLegend htmlparser.html#tagLegend HtmlTag.tagLegend 57 +nim tagLi htmlparser.html#tagLi HtmlTag.tagLi 57 +nim tagLink htmlparser.html#tagLink HtmlTag.tagLink 57 +nim tagMap htmlparser.html#tagMap HtmlTag.tagMap 57 +nim tagMark htmlparser.html#tagMark HtmlTag.tagMark 57 +nim tagMenu htmlparser.html#tagMenu HtmlTag.tagMenu 57 +nim tagMeta htmlparser.html#tagMeta HtmlTag.tagMeta 57 +nim tagMeter htmlparser.html#tagMeter HtmlTag.tagMeter 57 +nim tagNav htmlparser.html#tagNav HtmlTag.tagNav 57 +nim tagNobr htmlparser.html#tagNobr HtmlTag.tagNobr 57 +nim tagNoframes htmlparser.html#tagNoframes HtmlTag.tagNoframes 57 +nim tagNoscript htmlparser.html#tagNoscript HtmlTag.tagNoscript 57 +nim tagObject htmlparser.html#tagObject HtmlTag.tagObject 57 +nim tagOl htmlparser.html#tagOl HtmlTag.tagOl 57 +nim tagOptgroup htmlparser.html#tagOptgroup HtmlTag.tagOptgroup 57 +nim tagOption htmlparser.html#tagOption HtmlTag.tagOption 57 +nim tagOutput htmlparser.html#tagOutput HtmlTag.tagOutput 57 +nim tagP htmlparser.html#tagP HtmlTag.tagP 57 +nim tagParam htmlparser.html#tagParam HtmlTag.tagParam 57 +nim tagPre htmlparser.html#tagPre HtmlTag.tagPre 57 +nim tagProgress htmlparser.html#tagProgress HtmlTag.tagProgress 57 +nim tagQ htmlparser.html#tagQ HtmlTag.tagQ 57 +nim tagRp htmlparser.html#tagRp HtmlTag.tagRp 57 +nim tagRt htmlparser.html#tagRt HtmlTag.tagRt 57 +nim tagRuby htmlparser.html#tagRuby HtmlTag.tagRuby 57 +nim tagS htmlparser.html#tagS HtmlTag.tagS 57 +nim tagSamp htmlparser.html#tagSamp HtmlTag.tagSamp 57 +nim tagScript htmlparser.html#tagScript HtmlTag.tagScript 57 +nim tagSection htmlparser.html#tagSection HtmlTag.tagSection 57 +nim tagSelect htmlparser.html#tagSelect HtmlTag.tagSelect 57 +nim tagSmall htmlparser.html#tagSmall HtmlTag.tagSmall 57 +nim tagSource htmlparser.html#tagSource HtmlTag.tagSource 57 +nim tagSpan htmlparser.html#tagSpan HtmlTag.tagSpan 57 +nim tagStrike htmlparser.html#tagStrike HtmlTag.tagStrike 57 +nim tagStrong htmlparser.html#tagStrong HtmlTag.tagStrong 57 +nim tagStyle htmlparser.html#tagStyle HtmlTag.tagStyle 57 +nim tagSub htmlparser.html#tagSub HtmlTag.tagSub 57 +nim tagSummary htmlparser.html#tagSummary HtmlTag.tagSummary 57 +nim tagSup htmlparser.html#tagSup HtmlTag.tagSup 57 +nim tagTable htmlparser.html#tagTable HtmlTag.tagTable 57 +nim tagTbody htmlparser.html#tagTbody HtmlTag.tagTbody 57 +nim tagTd htmlparser.html#tagTd HtmlTag.tagTd 57 +nim tagTextarea htmlparser.html#tagTextarea HtmlTag.tagTextarea 57 +nim tagTfoot htmlparser.html#tagTfoot HtmlTag.tagTfoot 57 +nim tagTh htmlparser.html#tagTh HtmlTag.tagTh 57 +nim tagThead htmlparser.html#tagThead HtmlTag.tagThead 57 +nim tagTime htmlparser.html#tagTime HtmlTag.tagTime 57 +nim tagTitle htmlparser.html#tagTitle HtmlTag.tagTitle 57 +nim tagTr htmlparser.html#tagTr HtmlTag.tagTr 57 +nim tagTrack htmlparser.html#tagTrack HtmlTag.tagTrack 57 +nim tagTt htmlparser.html#tagTt HtmlTag.tagTt 57 +nim tagU htmlparser.html#tagU HtmlTag.tagU 57 +nim tagUl htmlparser.html#tagUl HtmlTag.tagUl 57 +nim tagVar htmlparser.html#tagVar HtmlTag.tagVar 57 +nim tagVideo htmlparser.html#tagVideo HtmlTag.tagVideo 57 +nim tagWbr htmlparser.html#tagWbr HtmlTag.tagWbr 57 +nim HtmlTag htmlparser.html#HtmlTag enum HtmlTag 57 +nim tagToStr htmlparser.html#tagToStr const tagToStr 185 +nim InlineTags htmlparser.html#InlineTags const InlineTags 206 +nim BlockTags htmlparser.html#BlockTags const BlockTags 213 +nim SingleTags htmlparser.html#SingleTags const SingleTags 218 +nim htmlTag htmlparser.html#htmlTag,XmlNode proc htmlTag(n: XmlNode): HtmlTag 355 +nim htmlTag htmlparser.html#htmlTag,string proc htmlTag(s: string): HtmlTag 361 +nim runeToEntity htmlparser.html#runeToEntity,Rune proc runeToEntity(rune: Rune): string 367 +nim entityToRune htmlparser.html#entityToRune,string proc entityToRune(entity: string): Rune 378 +nim entityToUtf8 htmlparser.html#entityToUtf8,string proc entityToUtf8(entity: string): string 1871 +nim parseHtml htmlparser.html#parseHtml,Stream,string,seq[string] proc parseHtml(s: Stream; filename: string; errors: var seq[string]): XmlNode 2015 +nim parseHtml htmlparser.html#parseHtml,Stream proc parseHtml(s: Stream): XmlNode 2040 +nim parseHtml htmlparser.html#parseHtml,string proc parseHtml(html: string): XmlNode 2046 +nim loadHtml htmlparser.html#loadHtml,string,seq[string] proc loadHtml(path: string; errors: var seq[string]): XmlNode 2051 +nim loadHtml htmlparser.html#loadHtml,string proc loadHtml(path: string): XmlNode 2059 +nimgrp htmltag htmlparser.html#htmlTag-procs-all proc 355 +nimgrp loadhtml htmlparser.html#loadHtml-procs-all proc 2051 +nimgrp parsehtml htmlparser.html#parseHtml-procs-all proc 2015 +heading Example: Transforming hyperlinks htmlparser.html#examplecolon-transforming-hyperlinks Example: Transforming hyperlinks 0 diff --git a/httpclient.html b/httpclient.html new file mode 100644 index 0000000000000..7ba6a1fe0ca0c --- /dev/null +++ b/httpclient.html @@ -0,0 +1,1307 @@ + + + + + + + +std/httpclient + + + + + + + + + + + + + + + + +
+
+

std/httpclient

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a simple HTTP client that can be used to retrieve webpages and other data.

Warning: +Validate untrusted inputs: URI parsers and getters are not detecting malicious URIs.
+ +

Retrieving a website

This example uses HTTP GET to retrieve http://google.com:

+

import std/httpclient
+var client = newHttpClient()
+try:
+  echo client.getContent("http://google.com")
+finally:
+  client.close()

+

The same action can also be performed asynchronously, simply use the AsyncHttpClient:

+

import std/[asyncdispatch, httpclient]
+
+proc asyncProc(): Future[string] {.async.} =
+  var client = newAsyncHttpClient()
+  try:
+    return await client.getContent("http://google.com")
+  finally:
+    client.close()
+
+echo waitFor asyncProc()

+

The functionality implemented by HttpClient and AsyncHttpClient is the same, so you can use whichever one suits you best in the examples shown here.

+

Note: You need to run asynchronous examples in an async proc otherwise you will get an Undeclared identifier: 'await' error.

+

Note: An asynchronous client instance can only deal with one request at a time. To send multiple requests in parallel, use multiple client instances.

+ +

Using HTTP POST

This example demonstrates the usage of the W3 HTML Validator, it uses multipart/form-data as the Content-Type to send the HTML to be validated to the server.

+

import std/[httpclient]
+var client = newHttpClient()
+var data = newMultipartData()
+data["output"] = "soap12"
+data["uploaded_file"] = ("test.html", "text/html",
+  "<html><head></head><body><p>test</p></body></html>")
+try:
+  echo client.postContent("http://validator.w3.org/check", multipart=data)
+finally:
+  client.close()

+

To stream files from disk when performing the request, use addFiles.

+

Note: This will allocate a new Mimetypes database every time you call it, you can pass your own via the mimeDb parameter to avoid this.

+

import std/[httpclient, mimetypes]
+let mimes = newMimetypes()
+var client = newHttpClient()
+var data = newMultipartData()
+data.addFiles({"uploaded_file": "test.html"}, mimeDb = mimes)
+try:
+  echo client.postContent("http://validator.w3.org/check", multipart=data)
+finally:
+  client.close()

+

You can also make post requests with custom headers. This example sets Content-Type to application/json and uses a json object for the body

+

import std/[httpclient, json]
+
+let client = newHttpClient()
+client.headers = newHttpHeaders({ "Content-Type": "application/json" })
+let body = %*{
+    "data": "some text"
+}
+try:
+  let response = client.request("http://some.api", httpMethod = HttpPost, body = $body)
+  echo response.status
+finally:
+  client.close()

+ +

Progress reporting

You may specify a callback procedure to be called during an HTTP request. This callback will be executed every second with information about the progress of the HTTP request.

+

import std/[asyncdispatch, httpclient]
+
+proc onProgressChanged(total, progress, speed: BiggestInt) {.async.} =
+  echo("Downloaded ", progress, " of ", total)
+  echo("Current rate: ", speed div 1000, "kb/s")
+
+proc asyncProc() {.async.} =
+  var client = newAsyncHttpClient()
+  client.onProgressChanged = onProgressChanged
+  try:
+    discard await client.getContent("http://speedtest-ams2.digitalocean.com/100mb.test")
+  finally:
+    client.close()
+
+waitFor asyncProc()

+

If you would like to remove the callback simply set it to nil.

+

client.onProgressChanged = nil

+
Warning: +The total reported by httpclient may be 0 in some cases.
+ +

SSL/TLS support

This requires the OpenSSL library. Fortunately it's widely used and installed on many operating systems. httpclient will use SSL automatically if you give any of the functions a url with the https schema, for example: https://github.com/.

+

You will also have to compile with ssl defined like so: nim c -d:ssl ....

+

Certificate validation is performed by default.

+

A set of directories and files from the ssl_certs module are scanned to locate CA certificates.

+

Example of setting SSL verification parameters in a new client:

+

import std/[net, httpclient]
+var client = newHttpClient(sslContext=newContext(verifyMode=CVerifyPeer))

+

There are three options for verify mode:

+
  • CVerifyNone: certificates are not verified;
  • +
  • CVerifyPeer: certificates are verified;
  • +
  • CVerifyPeerUseEnvVars: certificates are verified and the optional environment variables SSL_CERT_FILE and SSL_CERT_DIR are also used to locate certificates
  • +
+

See newContext to tweak or disable certificate validation.

+ +

Timeouts

Currently only the synchronous functions support a timeout. The timeout is measured in milliseconds, once it is set any call on a socket which may block will be susceptible to this timeout.

+

It may be surprising but the function as a whole can take longer than the specified timeout, only individual internal calls on the socket are affected. In practice this means that as long as the server is sending data an exception will not be raised, if however data does not reach the client within the specified timeout a TimeoutError exception will be raised.

+

Here is how to set a timeout when creating an HttpClient instance:

+

import std/httpclient
+
+let client = newHttpClient(timeout = 42)

+ +

Proxy

A proxy can be specified as a param to any of the procedures defined in this module. To do this, use the newProxy constructor. Unfortunately, only basic authentication is supported at the moment.

+

Some examples on how to configure a Proxy for HttpClient:

+

import std/httpclient
+
+let myProxy = newProxy("http://myproxy.network")
+let client = newHttpClient(proxy = myProxy)

+

Use proxies with basic authentication:

+

import std/httpclient
+
+let myProxy = newProxy("http://myproxy.network", auth="user:password")
+let client = newHttpClient(proxy = myProxy)

+

Get Proxy URL from environment variables:

+

import std/httpclient
+
+var url = ""
+try:
+  if existsEnv("http_proxy"):
+    url = getEnv("http_proxy")
+  elif existsEnv("https_proxy"):
+    url = getEnv("https_proxy")
+except ValueError:
+  echo "Unable to parse proxy from environment variables."
+
+let myProxy = newProxy(url = url)
+let client = newHttpClient(proxy = myProxy)

+ +

Redirects

The maximum redirects can be set with the maxRedirects of int type, it specifies the maximum amount of redirects to follow, it defaults to 5, you can set it to 0 to disable redirects.

+

Here you can see an example about how to set the maxRedirects of HttpClient:

+

import std/httpclient
+
+let client = newHttpClient(maxRedirects = 0)

+

+ +
+

Types

+
+ +
+
AsyncResponse = ref object
+  version*: string
+  status*: string
+  headers*: HttpHeaders
+  bodyStream*: FutureStream[string]
+
+ + + Source   +Edit   + +
+
+
+
HttpClient = HttpClientBase[Socket]
+
+ + + Source   +Edit   + +
+
+
+
HttpClientBase[SocketType] = ref object
+  ## Where we are currently connected.
+  headers*: HttpHeaders      ## Headers to send in requests.
+  ## Maximum redirects, set to `0` to disable.
+  timeout*: int              ## Only used for blocking HttpClient for now.
+  ## `nil` or the callback to call when request progress changes.
+  when SocketType is Socket:
+    onProgressChanged*: ProgressChangedProc[void]
+  else:
+    onProgressChanged*: ProgressChangedProc[Future[void]]
+  when defined(ssl):
+  when SocketType is AsyncSocket:
+  else:
+  ## When `false`, the body is never read in requestAux.
+
+ + + Source   +Edit   + +
+
+
+
HttpRequestError = object of IOError
+
+ + Thrown in the getContent proc and postContent proc, when the server returns an error + Source   +Edit   + +
+
+
+
MultipartData = ref object
+
+ + + Source   +Edit   + +
+
+
+
MultipartEntries = openArray[tuple[name, content: string]]
+
+ + + Source   +Edit   + +
+
+
+
ProgressChangedProc[ReturnType] = proc (total, progress, speed: BiggestInt): ReturnType {.
+    closure, ...gcsafe.}
+
+ + + Source   +Edit   + +
+
+
+
ProtocolError = object of IOError
+
+ + exception that is raised when server does not conform to the implemented protocol + Source   +Edit   + +
+
+
+
Proxy = ref object
+  url*: Uri
+  auth*: string
+
+ + + Source   +Edit   + +
+
+
+
Response = ref object
+  version*: string
+  status*: string
+  headers*: HttpHeaders
+  bodyStream*: Stream
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
defUserAgent = "Nim-httpclient/2.2.1"
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(data: MultipartData): string {....raises: [], tags: [], forbids: [].}
+
+ + convert MultipartData to string so it's human readable when echo see https://github.com/nim-lang/Nim/issues/11863 + Source   +Edit   + +
+
+ +
+
+
+
proc `[]=`(p: MultipartData; name, content: string) {.inline,
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ +

Add a multipart entry to the multipart data p. The value is added without a filename and without a content type.

+

data["username"] = "NimUser"

+ + Source   +Edit   + +
+
+
+
proc `[]=`(p: MultipartData; name: string;
+           file: tuple[name, contentType, content: string]) {.inline,
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ +

Add a file to the multipart data p, specifying filename, contentType and content manually.

+

data["uploaded_file"] = ("test.html", "text/html",
+  "<html><head></head><body><p>test</p></body></html>")

+ + Source   +Edit   + +
+
+ +
+
+
+
proc add(p: MultipartData; name, content: string; filename: string = "";
+         contentType: string = ""; useStream = true) {....raises: [ValueError],
+    tags: [], forbids: [].}
+
+ +

Add a value to the multipart data.

+

When useStream is false, the file will be read into memory.

+

Raises a ValueError exception if name, filename or contentType contain newline characters.

+ + Source   +Edit   + +
+
+
+
proc add(p: MultipartData; xs: MultipartEntries): MultipartData {.discardable,
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ +

Add a list of multipart entries to the multipart data p. All values are added without a filename and without a content type.

+

data.add({"action": "login", "format": "json"})

+ + Source   +Edit   + +
+
+ +
+
+
+
proc addFiles(p: MultipartData; xs: openArray[tuple[name, file: string]];
+              mimeDb = newMimetypes(); useStream = true): MultipartData {.
+    discardable, ...raises: [IOError, ValueError], tags: [ReadIOEffect],
+    forbids: [].}
+
+ +

Add files to a multipart data object. The files will be streamed from disk when the request is being made. When stream is false, the files are instead read into memory, but beware this is very memory ineffecient even for small files. The MIME types will automatically be determined. Raises an IOError if the file cannot be opened or reading fails. To manually specify file content, filename and MIME type, use []= instead.

+

data.addFiles({"uploaded_file": "public/test.html"})

+ + Source   +Edit   + +
+
+ +
+
+
+
proc body(response: AsyncResponse): Future[string] {....stackTrace: false,
+    raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}
+
+ + Reads the response's body and caches it. The read is performed only once. + Source   +Edit   + +
+
+
+
proc body(response: Response): string {....raises: [IOError, OSError],
+                                        tags: [ReadIOEffect], forbids: [].}
+
+ +

Retrieves the specified response's body.

+

The response's body stream is read synchronously.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc close(client: HttpClient | AsyncHttpClient)
+
+ + Closes any connections held by the HTTP client. + Source   +Edit   + +
+
+ +
+
+
+
proc code(response: Response | AsyncResponse): HttpCode {.
+    ...raises: [ValueError, OverflowDefect].}
+
+ +

Retrieves the specified response's HttpCode.

+

Raises a ValueError if the response's status does not have a corresponding HttpCode.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc contentLength(response: Response | AsyncResponse): int
+
+ +

Retrieves the specified response's content length.

+

This is effectively the value of the "Content-Length" header.

+

A ValueError exception will be raised if the value is not an integer. If the Content-Length header is not set in the response, ContentLength is set to the value -1.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc contentType(response: Response | AsyncResponse): string {.inline.}
+
+ +

Retrieves the specified response's content type.

+

This is effectively the value of the "Content-Type" header.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc delete(client: AsyncHttpClient; url: Uri | string): Future[AsyncResponse] {.
+    ...stackTrace: false.}
+
+ + Connects to the hostname specified by the URL and performs a DELETE request. This procedure uses httpClient values such as client.maxRedirects. + Source   +Edit   + +
+
+
+
proc delete(client: HttpClient; url: Uri | string): Response
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc deleteContent(client: AsyncHttpClient; url: Uri | string): Future[string] {.
+    ...stackTrace: false.}
+
+ + Connects to the hostname specified by the URL and returns the content of a DELETE request. + Source   +Edit   + +
+
+
+
proc deleteContent(client: HttpClient; url: Uri | string): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc downloadFile(client: AsyncHttpClient; url: Uri | string; filename: string): Future[
+    void]
+
+ + + Source   +Edit   + +
+
+
+
proc downloadFile(client: HttpClient; url: Uri | string; filename: string)
+
+ + Downloads url and saves it to filename. + Source   +Edit   + +
+
+ +
+
+
+
proc get(client: AsyncHttpClient; url: Uri | string): Future[AsyncResponse] {.
+    ...stackTrace: false.}
+
+ +

Connects to the hostname specified by the URL and performs a GET request.

+

This procedure uses httpClient values such as client.maxRedirects.

+ + Source   +Edit   + +
+
+
+
proc get(client: HttpClient; url: Uri | string): Response
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getContent(client: AsyncHttpClient; url: Uri | string): Future[string] {.
+    ...stackTrace: false.}
+
+ + Connects to the hostname specified by the URL and returns the content of a GET request. + Source   +Edit   + +
+
+
+
proc getContent(client: HttpClient; url: Uri | string): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getSocket(client: AsyncHttpClient): AsyncSocket {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc getSocket(client: HttpClient): Socket {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Get network socket, useful if you want to find out more details about the connection.

+

This example shows info about local and remote endpoints:

+

if client.connected:
+  echo client.getSocket.getLocalAddr
+  echo client.getSocket.getPeerAddr

+ + Source   +Edit   + +
+
+ +
+
+
+
proc head(client: AsyncHttpClient; url: Uri | string): Future[AsyncResponse] {.
+    ...stackTrace: false.}
+
+ +

Connects to the hostname specified by the URL and performs a HEAD request.

+

This procedure uses httpClient values such as client.maxRedirects.

+ + Source   +Edit   + +
+
+
+
proc head(client: HttpClient; url: Uri | string): Response
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lastModified(response: Response | AsyncResponse): DateTime
+
+ +

Retrieves the specified response's last modified time.

+

This is effectively the value of the "Last-Modified" header.

+

Raises a ValueError if the parsing fails or the value is not a correctly formatted time.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newAsyncHttpClient(userAgent = defUserAgent; maxRedirects = 5;
+                        sslContext = getDefaultSSL(); proxy: Proxy = nil;
+                        headers = newHttpHeaders()): AsyncHttpClient {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new AsyncHttpClient instance.

+

userAgent specifies the user agent that will be used when making requests.

+

maxRedirects specifies the maximum amount of redirects to follow, default is 5.

+

sslContext specifies the SSL context to use for HTTPS requests.

+

proxy specifies an HTTP proxy to use for this HTTP client's connections.

+

headers specifies the HTTP Headers.

+ +

Example:

+
import std/[asyncdispatch, strutils]
+
+proc asyncProc(): Future[string] {.async.} =
+  let client = newAsyncHttpClient()
+  result = await client.getContent("http://example.com")
+
+let exampleHtml = waitFor asyncProc()
+assert "Example Domain" in exampleHtml
+assert "Pizza" notin exampleHtml
+ Source   +Edit   + +
+
+ +
+
+
+
proc newHttpClient(userAgent = defUserAgent; maxRedirects = 5;
+                   sslContext = getDefaultSSL(); proxy: Proxy = nil;
+                   timeout = -1; headers = newHttpHeaders()): HttpClient {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new HttpClient instance.

+

userAgent specifies the user agent that will be used when making requests.

+

maxRedirects specifies the maximum amount of redirects to follow, default is 5.

+

sslContext specifies the SSL context to use for HTTPS requests. See SSL/TLS support

+

proxy specifies an HTTP proxy to use for this HTTP client's connections.

+

timeout specifies the number of milliseconds to allow before a TimeoutError is raised.

+

headers specifies the HTTP Headers.

+ +

Example:

+
import std/strutils
+
+let exampleHtml = newHttpClient().getContent("http://example.com")
+assert "Example Domain" in exampleHtml
+assert "Pizza" notin exampleHtml
+ Source   +Edit   + +
+
+ +
+
+
+
proc newMultipartData(): MultipartData {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Constructs a new MultipartData object. + Source   +Edit   + +
+
+
+
proc newMultipartData(xs: MultipartEntries): MultipartData {.
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ +

Create a new multipart data object and fill it with the entries xs directly.

+

var data = newMultipartData({"action": "login", "format": "json"})

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newProxy(url: string; auth = ""): Proxy {....raises: [], tags: [], forbids: [].}
+
+ + Constructs a new TProxy object. + Source   +Edit   + +
+
+
+
proc newProxy(url: Uri; auth = ""): Proxy {....raises: [], tags: [], forbids: [].}
+
+ + Constructs a new TProxy object. + Source   +Edit   + +
+
+ +
+
+
+
proc patch(client: AsyncHttpClient; url: Uri | string; body = "";
+           multipart: MultipartData = nil): Future[AsyncResponse] {.
+    ...stackTrace: false.}
+
+ + Connects to the hostname specified by the URL and performs a PATCH request. This procedure uses httpClient values such as client.maxRedirects. + Source   +Edit   + +
+
+
+
proc patch(client: HttpClient; url: Uri | string; body = "";
+           multipart: MultipartData = nil): Response
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc patchContent(client: AsyncHttpClient; url: Uri | string; body = "";
+                  multipart: MultipartData = nil): Future[string] {.
+    ...stackTrace: false.}
+
+ + Connects to the hostname specified by the URL and returns the content of a PATCH request. + Source   +Edit   + +
+
+
+
proc patchContent(client: HttpClient; url: Uri | string; body = "";
+                  multipart: MultipartData = nil): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc post(client: AsyncHttpClient; url: Uri | string; body = "";
+          multipart: MultipartData = nil): Future[AsyncResponse] {.
+    ...stackTrace: false.}
+
+ + Connects to the hostname specified by the URL and performs a POST request. This procedure uses httpClient values such as client.maxRedirects. + Source   +Edit   + +
+
+
+
proc post(client: HttpClient; url: Uri | string; body = "";
+          multipart: MultipartData = nil): Response
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc postContent(client: AsyncHttpClient; url: Uri | string; body = "";
+                 multipart: MultipartData = nil): Future[string] {.
+    ...stackTrace: false.}
+
+ + Connects to the hostname specified by the URL and returns the content of a POST request. + Source   +Edit   + +
+
+
+
proc postContent(client: HttpClient; url: Uri | string; body = "";
+                 multipart: MultipartData = nil): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc put(client: AsyncHttpClient; url: Uri | string; body = "";
+         multipart: MultipartData = nil): Future[AsyncResponse] {.
+    ...stackTrace: false.}
+
+ + Connects to the hostname specified by the URL and performs a PUT request. This procedure uses httpClient values such as client.maxRedirects. + Source   +Edit   + +
+
+
+
proc put(client: HttpClient; url: Uri | string; body = "";
+         multipart: MultipartData = nil): Response
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc putContent(client: AsyncHttpClient; url: Uri | string; body = "";
+                multipart: MultipartData = nil): Future[string] {.
+    ...stackTrace: false.}
+
+ + Connects to the hostname specified by the URL andreturns the content of a PUT request. + Source   +Edit   + +
+
+
+
proc putContent(client: HttpClient; url: Uri | string; body = "";
+                multipart: MultipartData = nil): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc request(client: AsyncHttpClient; url: Uri | string;
+             httpMethod: HttpMethod | string = HttpGet; body = "";
+             headers: HttpHeaders = nil; multipart: MultipartData = nil): Future[
+    AsyncResponse] {....stackTrace: false.}
+
+ +

Connects to the hostname specified by the URL and performs a request using the custom method string specified by httpMethod.

+

Connection will be kept alive. Further requests on the same client to the same hostname will not require a new connection to be made. The connection can be closed by using the close procedure.

+

This procedure will follow redirects up to a maximum number of redirects specified in client.maxRedirects.

+

You need to make sure that the url doesn't contain any newline characters. Failing to do so will raise AssertionDefect.

+

headers are HTTP headers that override the client.headers for this specific request only and will not be persisted.

+

Deprecated since v1.5: use HttpMethod enum instead; string parameter httpMethod is deprecated

+ + Source   +Edit   + +
+
+
+
proc request(client: HttpClient; url: Uri | string;
+             httpMethod: HttpMethod | string = HttpGet; body = "";
+             headers: HttpHeaders = nil; multipart: MultipartData = nil): Response
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/httpclient.idx b/httpclient.idx new file mode 100644 index 0000000000000..11a90c0d7596d --- /dev/null +++ b/httpclient.idx @@ -0,0 +1,86 @@ +nimTitle httpclient httpclient.html module std/httpclient 0 +nim Response httpclient.html#Response type Response 275 +nim AsyncResponse httpclient.html#AsyncResponse type AsyncResponse 282 +nim code httpclient.html#code proc code(response: Response | AsyncResponse): HttpCode 289 +nim contentType httpclient.html#contentType proc contentType(response: Response | AsyncResponse): string 297 +nim contentLength httpclient.html#contentLength proc contentLength(response: Response | AsyncResponse): int 303 +nim lastModified httpclient.html#lastModified proc lastModified(response: Response | AsyncResponse): DateTime 313 +nim body httpclient.html#body,Response proc body(response: Response): string 323 +nim body httpclient.html#body,AsyncResponse proc body(response: AsyncResponse): Future[string] 331 +nim Proxy httpclient.html#Proxy type Proxy 339 +nim MultipartEntries httpclient.html#MultipartEntries type MultipartEntries 352 +nim MultipartData httpclient.html#MultipartData type MultipartData 353 +nim ProtocolError httpclient.html#ProtocolError object ProtocolError 356 +nim HttpRequestError httpclient.html#HttpRequestError object HttpRequestError 360 +nim defUserAgent httpclient.html#defUserAgent const defUserAgent 364 +nim newProxy httpclient.html#newProxy,string,string proc newProxy(url: string; auth = ""): Proxy 390 +nim newProxy httpclient.html#newProxy,Uri,string proc newProxy(url: Uri; auth = ""): Proxy 394 +nim newMultipartData httpclient.html#newMultipartData proc newMultipartData(): MultipartData 398 +nim `$` httpclient.html#$,MultipartData proc `$`(data: MultipartData): string 402 +nim add httpclient.html#add,MultipartData,string,string,string,string proc add(p: MultipartData; name, content: string; filename: string = "";\n contentType: string = ""; useStream = true) 414 +nim add httpclient.html#add,MultipartData,MultipartEntries proc add(p: MultipartData; xs: MultipartEntries): MultipartData 442 +nim newMultipartData httpclient.html#newMultipartData,MultipartEntries proc newMultipartData(xs: MultipartEntries): MultipartData 454 +nim addFiles httpclient.html#addFiles,MultipartData,openArray[tuple[string,string]] proc addFiles(p: MultipartData; xs: openArray[tuple[name, file: string]];\n mimeDb = newMimetypes(); useStream = true): MultipartData 465 +nim `[]=` httpclient.html#[]=,MultipartData,string,string proc `[]=`(p: MultipartData; name, content: string) 487 +nim `[]=` httpclient.html#[]=,MultipartData,string,tuple[string,string,string] proc `[]=`(p: MultipartData; name: string;\n file: tuple[name, contentType, content: string]) 496 +nim ProgressChangedProc httpclient.html#ProgressChangedProc type ProgressChangedProc 587 +nim HttpClientBase httpclient.html#HttpClientBase type HttpClientBase 591 +nim HttpClient httpclient.html#HttpClient type HttpClient 619 +nim newHttpClient httpclient.html#newHttpClient,int,Proxy,int proc newHttpClient(userAgent = defUserAgent; maxRedirects = 5;\n sslContext = getDefaultSSL(); proxy: Proxy = nil; timeout = -1;\n headers = newHttpHeaders()): HttpClient 621 +nim AsyncHttpClient httpclient.html#AsyncHttpClient type AsyncHttpClient 662 +nim newAsyncHttpClient httpclient.html#newAsyncHttpClient,int,Proxy proc newAsyncHttpClient(userAgent = defUserAgent; maxRedirects = 5;\n sslContext = getDefaultSSL(); proxy: Proxy = nil;\n headers = newHttpHeaders()): AsyncHttpClient 664 +nim close httpclient.html#close proc close(client: HttpClient | AsyncHttpClient) 704 +nim getSocket httpclient.html#getSocket,HttpClient proc getSocket(client: HttpClient): Socket 710 +nim getSocket httpclient.html#getSocket,AsyncHttpClient proc getSocket(client: AsyncHttpClient): AsyncSocket 722 +nim request httpclient.html#request,AsyncHttpClient,,string,HttpHeaders,MultipartData proc request(client: AsyncHttpClient; url: Uri | string;\n httpMethod: HttpMethod | string = HttpGet; body = "";\n headers: HttpHeaders = nil; multipart: MultipartData = nil): Future[\n AsyncResponse] 1129 +nim request httpclient.html#request,HttpClient,,string,HttpHeaders,MultipartData proc request(client: HttpClient; url: Uri | string;\n httpMethod: HttpMethod | string = HttpGet; body = "";\n headers: HttpHeaders = nil; multipart: MultipartData = nil): Response 1133 +nim head httpclient.html#head,AsyncHttpClient, proc head(client: AsyncHttpClient; url: Uri | string): Future[AsyncResponse] 1241 +nim head httpclient.html#head,HttpClient, proc head(client: HttpClient; url: Uri | string): Response 1242 +nim get httpclient.html#get,AsyncHttpClient, proc get(client: AsyncHttpClient; url: Uri | string): Future[AsyncResponse] 1248 +nim get httpclient.html#get,HttpClient, proc get(client: HttpClient; url: Uri | string): Response 1249 +nim getContent httpclient.html#getContent,AsyncHttpClient, proc getContent(client: AsyncHttpClient; url: Uri | string): Future[string] 1255 +nim getContent httpclient.html#getContent,HttpClient, proc getContent(client: HttpClient; url: Uri | string): string 1256 +nim delete httpclient.html#delete,AsyncHttpClient, proc delete(client: AsyncHttpClient; url: Uri | string): Future[AsyncResponse] 1261 +nim delete httpclient.html#delete,HttpClient, proc delete(client: HttpClient; url: Uri | string): Response 1262 +nim deleteContent httpclient.html#deleteContent,AsyncHttpClient, proc deleteContent(client: AsyncHttpClient; url: Uri | string): Future[string] 1267 +nim deleteContent httpclient.html#deleteContent,HttpClient, proc deleteContent(client: HttpClient; url: Uri | string): string 1268 +nim post httpclient.html#post,AsyncHttpClient,,string,MultipartData proc post(client: AsyncHttpClient; url: Uri | string; body = "";\n multipart: MultipartData = nil): Future[AsyncResponse] 1273 +nim post httpclient.html#post,HttpClient,,string,MultipartData proc post(client: HttpClient; url: Uri | string; body = "";\n multipart: MultipartData = nil): Response 1275 +nim postContent httpclient.html#postContent,AsyncHttpClient,,string,MultipartData proc postContent(client: AsyncHttpClient; url: Uri | string; body = "";\n multipart: MultipartData = nil): Future[string] 1280 +nim postContent httpclient.html#postContent,HttpClient,,string,MultipartData proc postContent(client: HttpClient; url: Uri | string; body = "";\n multipart: MultipartData = nil): string 1282 +nim put httpclient.html#put,AsyncHttpClient,,string,MultipartData proc put(client: AsyncHttpClient; url: Uri | string; body = "";\n multipart: MultipartData = nil): Future[AsyncResponse] 1287 +nim put httpclient.html#put,HttpClient,,string,MultipartData proc put(client: HttpClient; url: Uri | string; body = "";\n multipart: MultipartData = nil): Response 1289 +nim putContent httpclient.html#putContent,AsyncHttpClient,,string,MultipartData proc putContent(client: AsyncHttpClient; url: Uri | string; body = "";\n multipart: MultipartData = nil): Future[string] 1294 +nim putContent httpclient.html#putContent,HttpClient,,string,MultipartData proc putContent(client: HttpClient; url: Uri | string; body = "";\n multipart: MultipartData = nil): string 1295 +nim patch httpclient.html#patch,AsyncHttpClient,,string,MultipartData proc patch(client: AsyncHttpClient; url: Uri | string; body = "";\n multipart: MultipartData = nil): Future[AsyncResponse] 1300 +nim patch httpclient.html#patch,HttpClient,,string,MultipartData proc patch(client: HttpClient; url: Uri | string; body = "";\n multipart: MultipartData = nil): Response 1302 +nim patchContent httpclient.html#patchContent,AsyncHttpClient,,string,MultipartData proc patchContent(client: AsyncHttpClient; url: Uri | string; body = "";\n multipart: MultipartData = nil): Future[string] 1307 +nim patchContent httpclient.html#patchContent,HttpClient,,string,MultipartData proc patchContent(client: HttpClient; url: Uri | string; body = "";\n multipart: MultipartData = nil): string 1309 +nim downloadFile httpclient.html#downloadFile,HttpClient,,string proc downloadFile(client: HttpClient; url: Uri | string; filename: string) 1314 +nim downloadFile httpclient.html#downloadFile,AsyncHttpClient,,string proc downloadFile(client: AsyncHttpClient; url: Uri | string; filename: string): Future[\n void] 1352 +heading Retrieving a website httpclient.html#retrieving-a-website Retrieving a website 0 +heading Using HTTP POST httpclient.html#using-http-post Using HTTP POST 0 +heading Progress reporting httpclient.html#progress-reporting Progress reporting 0 +heading SSL/TLS support httpclient.html#sslslashtls-support SSL/TLS support 0 +heading Timeouts httpclient.html#timeouts Timeouts 0 +heading Proxy httpclient.html#proxy Proxy 0 +heading Redirects httpclient.html#redirects Redirects 0 +nimgrp body httpclient.html#body-procs-all proc 323 +nimgrp request httpclient.html#request-procs-all proc 1129 +nimgrp getsocket httpclient.html#getSocket-procs-all proc 710 +nimgrp postcontent httpclient.html#postContent-procs-all proc 1280 +nimgrp newmultipartdata httpclient.html#newMultipartData-procs-all proc 398 +nimgrp patchcontent httpclient.html#patchContent-procs-all proc 1307 +nimgrp []= httpclient.html#[]=-procs-all proc 487 +nimgrp putcontent httpclient.html#putContent-procs-all proc 1294 +nimgrp delete httpclient.html#delete-procs-all proc 1261 +nimgrp getcontent httpclient.html#getContent-procs-all proc 1255 +nimgrp post httpclient.html#post-procs-all proc 1273 +nimgrp get httpclient.html#get-procs-all proc 1248 +nimgrp downloadfile httpclient.html#downloadFile-procs-all proc 1314 +nimgrp add httpclient.html#add-procs-all proc 414 +nimgrp deletecontent httpclient.html#deleteContent-procs-all proc 1267 +nimgrp newproxy httpclient.html#newProxy-procs-all proc 390 +nimgrp head httpclient.html#head-procs-all proc 1241 +nimgrp put httpclient.html#put-procs-all proc 1287 +nimgrp patch httpclient.html#patch-procs-all proc 1300 diff --git a/httpcore.html b/httpcore.html new file mode 100644 index 0000000000000..6247eb1410c50 --- /dev/null +++ b/httpcore.html @@ -0,0 +1,1415 @@ + + + + + + + +std/httpcore + + + + + + + + + + + + + + + + +
+
+

std/httpcore

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Contains functionality shared between the httpclient and asynchttpserver modules.

+

Unstable API.

+

+ +
+

Types

+
+
+
HttpCode = distinct range[0 .. 599]
+
+ + + Source   +Edit   + +
+
+
+
HttpHeaders = ref object
+  table*: TableRef[string, seq[string]]
+
+ + + Source   +Edit   + +
+
+
+
HttpHeaderValues = distinct seq[string]
+
+ + + Source   +Edit   + +
+
+
+
HttpMethod = enum
+  HttpHead = "HEAD",        ## Asks for the response identical to the one that
+                             ## would correspond to a GET request, but without
+                             ## the response body.
+  HttpGet = "GET",          ## Retrieves the specified resource.
+  HttpPost = "POST",        ## Submits data to be processed to the identified
+                             ## resource. The data is included in the body of
+                             ## the request.
+  HttpPut = "PUT",          ## Uploads a representation of the specified
+                             ## resource.
+  HttpDelete = "DELETE",    ## Deletes the specified resource.
+  HttpTrace = "TRACE",      ## Echoes back the received request, so that a
+                             ## client
+                             ## can see what intermediate servers are adding or
+                             ## changing in the request.
+  HttpOptions = "OPTIONS",  ## Returns the HTTP methods that the server
+                             ## supports for specified address.
+  HttpConnect = "CONNECT",  ## Converts the request connection to a transparent
+                             ## TCP/IP tunnel, usually used for proxies.
+  HttpPatch = "PATCH"        ## Applies partial modifications to a resource.
+
+ + the requested HttpMethod + Source   +Edit   + +
+
+
+
HttpVersion = enum
+  HttpVer11, HttpVer10
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
headerLimit = 10000
+
+ + + Source   +Edit   + +
+
+
+
Http100 = 100
+
+ + + Source   +Edit   + +
+
+
+
Http101 = 101
+
+ + + Source   +Edit   + +
+
+
+
Http102 = 102
+
+ + https://tools.ietf.org/html/rfc2518.html WebDAV + Source   +Edit   + +
+
+
+
Http103 = 103
+
+ + https://tools.ietf.org/html/rfc8297.html Early hints + Source   +Edit   + +
+
+
+
Http200 = 200
+
+ + + Source   +Edit   + +
+
+
+
Http201 = 201
+
+ + + Source   +Edit   + +
+
+
+
Http202 = 202
+
+ + + Source   +Edit   + +
+
+
+
Http203 = 203
+
+ + + Source   +Edit   + +
+
+
+
Http204 = 204
+
+ + + Source   +Edit   + +
+
+
+
Http205 = 205
+
+ + + Source   +Edit   + +
+
+
+
Http206 = 206
+
+ + + Source   +Edit   + +
+
+
+
Http207 = 207
+
+ + https://tools.ietf.org/html/rfc4918.html WebDAV + Source   +Edit   + +
+
+
+
Http208 = 208
+
+ + https://tools.ietf.org/html/rfc5842.html WebDAV, Section 7.1 + Source   +Edit   + +
+
+
+
Http226 = 226
+
+ + https://tools.ietf.org/html/rfc3229.html Delta encoding, Section 10.4.1 + Source   +Edit   + +
+
+
+
Http300 = 300
+
+ + + Source   +Edit   + +
+
+
+
Http301 = 301
+
+ + + Source   +Edit   + +
+
+
+
Http302 = 302
+
+ + + Source   +Edit   + +
+
+
+
Http303 = 303
+
+ + + Source   +Edit   + +
+
+
+
Http304 = 304
+
+ + + Source   +Edit   + +
+
+
+
Http305 = 305
+
+ + + Source   +Edit   + +
+
+
+
Http307 = 307
+
+ + + Source   +Edit   + +
+
+
+
Http308 = 308
+
+ + + Source   +Edit   + +
+
+
+
Http400 = 400
+
+ + + Source   +Edit   + +
+
+
+
Http401 = 401
+
+ + + Source   +Edit   + +
+
+
+
Http402 = 402
+
+ + https://tools.ietf.org/html/rfc7231.html Payment required, Section 6.5.2 + Source   +Edit   + +
+
+
+
Http403 = 403
+
+ + + Source   +Edit   + +
+
+
+
Http404 = 404
+
+ + + Source   +Edit   + +
+
+
+
Http405 = 405
+
+ + + Source   +Edit   + +
+
+
+
Http406 = 406
+
+ + + Source   +Edit   + +
+
+
+
Http407 = 407
+
+ + + Source   +Edit   + +
+
+
+
Http408 = 408
+
+ + + Source   +Edit   + +
+
+
+
Http409 = 409
+
+ + + Source   +Edit   + +
+
+
+
Http410 = 410
+
+ + + Source   +Edit   + +
+
+
+
Http411 = 411
+
+ + + Source   +Edit   + +
+
+
+
Http412 = 412
+
+ + + Source   +Edit   + +
+
+
+
Http413 = 413
+
+ + + Source   +Edit   + +
+
+
+
Http414 = 414
+
+ + + Source   +Edit   + +
+
+
+
Http415 = 415
+
+ + + Source   +Edit   + +
+
+
+
Http416 = 416
+
+ + + Source   +Edit   + +
+
+
+
Http417 = 417
+
+ + + Source   +Edit   + +
+
+
+
Http418 = 418
+
+ + + Source   +Edit   + +
+
+
+
Http421 = 421
+
+ + + Source   +Edit   + +
+
+
+
Http422 = 422
+
+ + + Source   +Edit   + +
+
+
+
Http423 = 423
+
+ + https://tools.ietf.org/html/rfc4918.html WebDAV, Section 11.3 + Source   +Edit   + +
+
+
+
Http424 = 424
+
+ + https://tools.ietf.org/html/rfc4918.html WebDAV, Section 11.3 + Source   +Edit   + +
+
+
+
Http425 = 425
+
+ + https://tools.ietf.org/html/rfc8470.html Early data + Source   +Edit   + +
+
+
+
Http426 = 426
+
+ + + Source   +Edit   + +
+
+
+
Http428 = 428
+
+ + + Source   +Edit   + +
+
+
+
Http429 = 429
+
+ + + Source   +Edit   + +
+
+
+
Http431 = 431
+
+ + + Source   +Edit   + +
+
+
+
Http451 = 451
+
+ + + Source   +Edit   + +
+
+
+
Http500 = 500
+
+ + + Source   +Edit   + +
+
+
+
Http501 = 501
+
+ + + Source   +Edit   + +
+
+
+
Http502 = 502
+
+ + + Source   +Edit   + +
+
+
+
Http503 = 503
+
+ + + Source   +Edit   + +
+
+
+
Http504 = 504
+
+ + + Source   +Edit   + +
+
+
+
Http505 = 505
+
+ + + Source   +Edit   + +
+
+
+
Http506 = 506
+
+ + https://tools.ietf.org/html/rfc2295.html Content negotiation, Section 8.1 + Source   +Edit   + +
+
+
+
Http507 = 507
+
+ + https://tools.ietf.org/html/rfc4918.html WebDAV, Section 11.5 + Source   +Edit   + +
+
+
+
Http508 = 508
+
+ + https://tools.ietf.org/html/rfc5842.html WebDAV, Section 7.2 + Source   +Edit   + +
+
+
+
Http510 = 510
+
+ + https://tools.ietf.org/html/rfc2774.html Extension framework, Section 7 + Source   +Edit   + +
+
+
+
Http511 = 511
+
+ + https://tools.ietf.org/html/rfc6585.html Additional status code, Section 6 + Source   +Edit   + +
+
+
+
httpNewLine = "\r\n"
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `$`(code: HttpCode): string {....raises: [], tags: [], forbids: [].}
+
+ + Converts the specified HttpCode into a HTTP status. +

Example:

+
doAssert($Http404 == "404 Not Found")
+ Source   +Edit   + +
+
+
+
func `$`(headers: HttpHeaders): string {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `==`(a, b: HttpCode): bool {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `==`(protocol: tuple[orig: string, major, minor: int]; ver: HttpVersion): bool {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `[]`(headers: HttpHeaders; key: string): HttpHeaderValues {.
+    ...raises: [KeyError], tags: [], forbids: [].}
+
+ +

Returns the values associated with the given key. If the returned values are passed to a procedure expecting a string, the first value is automatically picked. If there are no values associated with the key, an exception is raised.

+

To access multiple values of a key, use the overloaded [] below or to get all of them access the table field directly.

+ + Source   +Edit   + +
+
+
+
func `[]`(headers: HttpHeaders; key: string; i: int): string {.
+    ...raises: [KeyError], tags: [], forbids: [].}
+
+ + Returns the i'th value associated with the given key. If there are no values associated with the key or the i'th value doesn't exist, an exception is raised. + Source   +Edit   + +
+
+ +
+
+
+
proc `[]=`(headers: HttpHeaders; key, value: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Sets the header entries associated with key to the specified value. Replaces any existing values. + Source   +Edit   + +
+
+
+
proc `[]=`(headers: HttpHeaders; key: string; value: seq[string]) {....raises: [],
+    tags: [], forbids: [].}
+
+ + Sets the header entries associated with key to the specified list of values. Replaces any existing values. If value is empty, deletes the header entries associated with key. + Source   +Edit   + +
+
+ +
+
+
+
proc add(headers: HttpHeaders; key, value: string) {....raises: [KeyError],
+    tags: [], forbids: [].}
+
+ + Adds the specified value to the specified key. Appends to any existing values associated with the key. + Source   +Edit   + +
+
+ +
+
+
+
proc clear(headers: HttpHeaders) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func contains(methods: set[HttpMethod]; x: string): bool {....raises: [ValueError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func contains(values: HttpHeaderValues; value: string): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ + Determines if value is one of the values inside values. Comparison is performed without case sensitivity. + Source   +Edit   + +
+
+ +
+
+
+
proc del(headers: HttpHeaders; key: string) {....raises: [], tags: [], forbids: [].}
+
+ + Deletes the header entries associated with key + Source   +Edit   + +
+
+ +
+
+
+
func getOrDefault(headers: HttpHeaders; key: string;
+                  default = @[""].HttpHeaderValues): HttpHeaderValues {.
+    ...raises: [KeyError], tags: [], forbids: [].}
+
+ + Returns the values associated with the given key. If there are no values associated with the key, then default is returned. + Source   +Edit   + +
+
+ +
+
+
+
func hasKey(headers: HttpHeaders; key: string): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func is1xx(code: HttpCode): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Determines whether code is a 1xx HTTP status code. +

Example:

+
doAssert is1xx(HttpCode(103))
+ Source   +Edit   + +
+
+ +
+
+
+
func is2xx(code: HttpCode): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Determines whether code is a 2xx HTTP status code. + Source   +Edit   + +
+
+ +
+
+
+
func is3xx(code: HttpCode): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Determines whether code is a 3xx HTTP status code. + Source   +Edit   + +
+
+ +
+
+
+
func is4xx(code: HttpCode): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Determines whether code is a 4xx HTTP status code. + Source   +Edit   + +
+
+ +
+
+
+
func is5xx(code: HttpCode): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Determines whether code is a 5xx HTTP status code. + Source   +Edit   + +
+
+ +
+
+
+
func len(headers: HttpHeaders): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func newHttpHeaders(keyValuePairs: openArray[tuple[key: string, val: string]];
+                    titleCase = false): HttpHeaders {....raises: [KeyError],
+    tags: [], forbids: [].}
+
+ + Returns a new HttpHeaders object from an array. if titleCase is set to true, headers are passed to the server in title case (e.g. "Content-Length") + Source   +Edit   + +
+
+
+
func newHttpHeaders(titleCase = false): HttpHeaders {....raises: [], tags: [],
+    forbids: [].}
+
+ + Returns a new HttpHeaders object. if titleCase is set to true, headers are passed to the server in title case (e.g. "Content-Length") + Source   +Edit   + +
+
+ +
+
+
+
func parseHeader(line: string): tuple[key: string, value: seq[string]] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Parses a single raw header HTTP line into key value pairs.

+

Used by asynchttpserver and httpclient internally and should not be used by you.

+ + Source   +Edit   + +
+
+ +
+
+
+
func toCaseInsensitive(headers: HttpHeaders; s: string): string {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + For internal usage only. Do not use. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator pairs(headers: HttpHeaders): tuple[key, value: string] {....raises: [],
+    tags: [], forbids: [].}
+
+ + Yields each key, value pair. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Converters

+
+
+
+
converter toString(values: HttpHeaderValues): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/httpcore.idx b/httpcore.idx new file mode 100644 index 0000000000000..b044777d7229b --- /dev/null +++ b/httpcore.idx @@ -0,0 +1,114 @@ +nimTitle httpcore httpcore.html module std/httpcore 0 +nim HttpHeaders httpcore.html#HttpHeaders type HttpHeaders 18 +nim HttpHeaderValues httpcore.html#HttpHeaderValues type HttpHeaderValues 22 +nim HttpCode httpcore.html#HttpCode type HttpCode 26 +nim HttpVer11 httpcore.html#HttpVer11 HttpVersion.HttpVer11 28 +nim HttpVer10 httpcore.html#HttpVer10 HttpVersion.HttpVer10 28 +nim HttpVersion httpcore.html#HttpVersion enum HttpVersion 28 +nim HttpHead httpcore.html#HttpHead HttpMethod.HttpHead 32 +nim HttpGet httpcore.html#HttpGet HttpMethod.HttpGet 32 +nim HttpPost httpcore.html#HttpPost HttpMethod.HttpPost 32 +nim HttpPut httpcore.html#HttpPut HttpMethod.HttpPut 32 +nim HttpDelete httpcore.html#HttpDelete HttpMethod.HttpDelete 32 +nim HttpTrace httpcore.html#HttpTrace HttpMethod.HttpTrace 32 +nim HttpOptions httpcore.html#HttpOptions HttpMethod.HttpOptions 32 +nim HttpConnect httpcore.html#HttpConnect HttpMethod.HttpConnect 32 +nim HttpPatch httpcore.html#HttpPatch HttpMethod.HttpPatch 32 +nim HttpMethod httpcore.html#HttpMethod enum HttpMethod 32 +nim Http100 httpcore.html#Http100 const Http100 55 +nim Http101 httpcore.html#Http101 const Http101 56 +nim Http102 httpcore.html#Http102 const Http102 57 +nim Http103 httpcore.html#Http103 const Http103 58 +nim Http200 httpcore.html#Http200 const Http200 59 +nim Http201 httpcore.html#Http201 const Http201 60 +nim Http202 httpcore.html#Http202 const Http202 61 +nim Http203 httpcore.html#Http203 const Http203 62 +nim Http204 httpcore.html#Http204 const Http204 63 +nim Http205 httpcore.html#Http205 const Http205 64 +nim Http206 httpcore.html#Http206 const Http206 65 +nim Http207 httpcore.html#Http207 const Http207 66 +nim Http208 httpcore.html#Http208 const Http208 67 +nim Http226 httpcore.html#Http226 const Http226 68 +nim Http300 httpcore.html#Http300 const Http300 69 +nim Http301 httpcore.html#Http301 const Http301 70 +nim Http302 httpcore.html#Http302 const Http302 71 +nim Http303 httpcore.html#Http303 const Http303 72 +nim Http304 httpcore.html#Http304 const Http304 73 +nim Http305 httpcore.html#Http305 const Http305 74 +nim Http307 httpcore.html#Http307 const Http307 75 +nim Http308 httpcore.html#Http308 const Http308 76 +nim Http400 httpcore.html#Http400 const Http400 77 +nim Http401 httpcore.html#Http401 const Http401 78 +nim Http402 httpcore.html#Http402 const Http402 79 +nim Http403 httpcore.html#Http403 const Http403 80 +nim Http404 httpcore.html#Http404 const Http404 81 +nim Http405 httpcore.html#Http405 const Http405 82 +nim Http406 httpcore.html#Http406 const Http406 83 +nim Http407 httpcore.html#Http407 const Http407 84 +nim Http408 httpcore.html#Http408 const Http408 85 +nim Http409 httpcore.html#Http409 const Http409 86 +nim Http410 httpcore.html#Http410 const Http410 87 +nim Http411 httpcore.html#Http411 const Http411 88 +nim Http412 httpcore.html#Http412 const Http412 89 +nim Http413 httpcore.html#Http413 const Http413 90 +nim Http414 httpcore.html#Http414 const Http414 91 +nim Http415 httpcore.html#Http415 const Http415 92 +nim Http416 httpcore.html#Http416 const Http416 93 +nim Http417 httpcore.html#Http417 const Http417 94 +nim Http418 httpcore.html#Http418 const Http418 95 +nim Http421 httpcore.html#Http421 const Http421 96 +nim Http422 httpcore.html#Http422 const Http422 97 +nim Http423 httpcore.html#Http423 const Http423 98 +nim Http424 httpcore.html#Http424 const Http424 99 +nim Http425 httpcore.html#Http425 const Http425 100 +nim Http426 httpcore.html#Http426 const Http426 101 +nim Http428 httpcore.html#Http428 const Http428 102 +nim Http429 httpcore.html#Http429 const Http429 103 +nim Http431 httpcore.html#Http431 const Http431 104 +nim Http451 httpcore.html#Http451 const Http451 105 +nim Http500 httpcore.html#Http500 const Http500 106 +nim Http501 httpcore.html#Http501 const Http501 107 +nim Http502 httpcore.html#Http502 const Http502 108 +nim Http503 httpcore.html#Http503 const Http503 109 +nim Http504 httpcore.html#Http504 const Http504 110 +nim Http505 httpcore.html#Http505 const Http505 111 +nim Http506 httpcore.html#Http506 const Http506 112 +nim Http507 httpcore.html#Http507 const Http507 113 +nim Http508 httpcore.html#Http508 const Http508 114 +nim Http510 httpcore.html#Http510 const Http510 115 +nim Http511 httpcore.html#Http511 const Http511 116 +nim httpNewLine httpcore.html#httpNewLine const httpNewLine 119 +nim headerLimit httpcore.html#headerLimit const headerLimit 120 +nim toCaseInsensitive httpcore.html#toCaseInsensitive,HttpHeaders,string proc toCaseInsensitive(headers: HttpHeaders; s: string): string 129 +nim newHttpHeaders httpcore.html#newHttpHeaders proc newHttpHeaders(titleCase = false): HttpHeaders 133 +nim newHttpHeaders httpcore.html#newHttpHeaders,openArray[tuple[string,string]] proc newHttpHeaders(keyValuePairs: openArray[tuple[key: string, val: string]];\n titleCase = false): HttpHeaders 138 +nim `$` httpcore.html#$,HttpHeaders proc `$`(headers: HttpHeaders): string 152 +nim clear httpcore.html#clear,HttpHeaders proc clear(headers: HttpHeaders) 155 +nim `[]` httpcore.html#[],HttpHeaders,string proc `[]`(headers: HttpHeaders; key: string): HttpHeaderValues 158 +nim toString httpcore.html#toString.c,HttpHeaderValues converter toString(values: HttpHeaderValues): string 170 +nim `[]` httpcore.html#[],HttpHeaders,string,int proc `[]`(headers: HttpHeaders; key: string; i: int): string 173 +nim `[]=` httpcore.html#[]=,HttpHeaders,string,string proc `[]=`(headers: HttpHeaders; key, value: string) 180 +nim `[]=` httpcore.html#[]=,HttpHeaders,string,seq[string] proc `[]=`(headers: HttpHeaders; key: string; value: seq[string]) 185 +nim add httpcore.html#add,HttpHeaders,string,string proc add(headers: HttpHeaders; key, value: string) 194 +nim del httpcore.html#del,HttpHeaders,string proc del(headers: HttpHeaders; key: string) 202 +nim pairs httpcore.html#pairs.i,HttpHeaders iterator pairs(headers: HttpHeaders): tuple[key, value: string] 206 +nim contains httpcore.html#contains,HttpHeaderValues,string proc contains(values: HttpHeaderValues; value: string): bool 212 +nim hasKey httpcore.html#hasKey,HttpHeaders,string proc hasKey(headers: HttpHeaders; key: string): bool 218 +nim getOrDefault httpcore.html#getOrDefault,HttpHeaders,string proc getOrDefault(headers: HttpHeaders; key: string;\n default = @[""].HttpHeaderValues): HttpHeaderValues 221 +nim len httpcore.html#len,HttpHeaders proc len(headers: HttpHeaders): int 230 +nim parseHeader httpcore.html#parseHeader,string proc parseHeader(line: string): tuple[key: string, value: seq[string]] 242 +nim `==` httpcore.html#==,tuple[string,int,int],HttpVersion proc `==`(protocol: tuple[orig: string, major, minor: int]; ver: HttpVersion): bool 262 +nim contains httpcore.html#contains,set[HttpMethod],string proc contains(methods: set[HttpMethod]; x: string): bool 273 +nim `$` httpcore.html#$,HttpCode proc `$`(code: HttpCode): string 276 +nim `==` httpcore.html#==,HttpCode,HttpCode proc `==`(a, b: HttpCode): bool 345 +nim is1xx httpcore.html#is1xx,HttpCode proc is1xx(code: HttpCode): bool 347 +nim is2xx httpcore.html#is2xx,HttpCode proc is2xx(code: HttpCode): bool 354 +nim is3xx httpcore.html#is3xx,HttpCode proc is3xx(code: HttpCode): bool 358 +nim is4xx httpcore.html#is4xx,HttpCode proc is4xx(code: HttpCode): bool 362 +nim is5xx httpcore.html#is5xx,HttpCode proc is5xx(code: HttpCode): bool 366 +nimgrp == httpcore.html#==-procs-all proc 262 +nimgrp $ httpcore.html#$-procs-all proc 152 +nimgrp []= httpcore.html#[]=-procs-all proc 180 +nimgrp contains httpcore.html#contains-procs-all proc 212 +nimgrp [] httpcore.html#[]-procs-all proc 158 +nimgrp newhttpheaders httpcore.html#newHttpHeaders-procs-all proc 133 diff --git a/idetools.html b/idetools.html new file mode 100644 index 0000000000000..849cb49cff9e0 --- /dev/null +++ b/idetools.html @@ -0,0 +1,330 @@ + + + + + + + +Nim IDE Integration Guide + + + + + + + + + + + + + + + + +
+
+

Nim IDE Integration Guide

+
+ +
+ Source   +Edit   + +
+ +

+ +
Author:Britney Spears
Version:2.2.1

"yes, I'm the creator" -- Araq, 2013-07-26 19:28:32.

+

Note: this is mostly outdated, see instead nimsuggest

+

Nim differs from many other compilers in that it is really fast, and being so fast makes it suited to provide external queries for text editors about the source code being written. Through the idetools command of the compiler, any IDE can query a .nim source file and obtain useful information like definition of symbols or suggestions for completion.

+

This document will guide you through the available options. If you want to look at practical examples of idetools support you can look at the test files found in the Test suite or various editor integrations already available.

+ +

Idetools invocation

+

Specifying the location of the query

All of the available idetools commands require you to specify a query location through the --track or --trackDirty switches. The general idetools invocations are:

+

nim idetools --track:FILE,LINE,COL <switches> proj.nim

+

Or:

+

nim idetools --trackDirty:DIRTY_FILE,FILE,LINE,COL <switches> proj.nim

+
proj.nim
+
This is the main project filename. Most of the time you will pass in the same as FILE, but for bigger projects this is the file which is used as main entry point for the program, the one which users compile to generate a final binary.
+
<switches>
+
This would be any of the other idetools available options, like --def or --suggest explained in the following sections.
+
COL
+
An integer with the column you are going to query. For the compiler columns start at zero, so the first column will be 0 and the last in an 80 column terminal will be 79.
+
LINE
+
An integer with the line you are going to query. For the compiler lines start at 1.
+
FILE
+
The file you want to perform the query on. Usually you will pass in the same value as proj.nim.
+
DIRTY_FILE
+

The FILE parameter is enough for static analysis, but IDEs tend to have unsaved buffers where the user may still be in the middle of typing a line. In such situations the IDE can save the current contents to a temporary file and then use the --trackDirty switch.

+

Dirty files are likely to contain errors and they are usually compiled partially only to the point needed to service the idetool request. The compiler discriminates them to ensure that a) they won't be cached and b) they won't invalidate the cached contents of the original module.

+

The other reason is that the dirty file can appear anywhere on disk (e.g. in tmpfs), but it must be treated as having a path matching the original module when it comes to usage of relative paths, etc. Queries, however, will refer to the dirty module name in their answers instead of the normal filename.

+
+
+ +

Definitions

The --def idetools switch performs a query about the definition of a specific symbol. If available, idetools will answer with the type, source file, line/column information and other accessory data if available like a docstring. With this information an IDE can provide the typical Jump to definition where a user puts the cursor on a symbol or uses the mouse to select it and is redirected to the place where the symbol is located.

+

Since Nim is implemented in Nim, one of the nice things of this feature is that any user with an IDE supporting it can quickly jump around the standard library implementation and see exactly what a proc does, learning about the language and seeing real life examples of how to write/implement specific features.

+

Idetools will always answer with a single definition or none if it can't find any valid symbol matching the position of the query.

+ +

Suggestions

The --suggest idetools switch performs a query about possible completion symbols at some point in the file. IDEs can easily provide an autocompletion feature where the IDE scans the current file (and related ones, if it knows about the language being edited and follows includes/imports) and when the user starts typing something a completion box with different options appears.

+

However such features are not context sensitive and work simply on string matching, which can be problematic in Nim especially due to the case insensitiveness of the language (plus underscores as separators!).

+

The typical usage scenario for this option is to call it after the user has typed the dot character for the object oriented call syntax. Idetools will try to return the suggestions sorted first by scope (from innermost to outermost) and then by item name.

+ +

Invocation context

The --context idetools switch is very similar to the suggestions switch, but instead of being used after the user has typed a dot character, this one is meant to be used after the user has typed an opening brace to start typing parameters.

+ +

Symbol usages

The --usages idetools switch lists all usages of the symbol at a position. IDEs can use this to find all the places in the file where the symbol is used and offer the user to rename it in all places at the same time. Again, a pure string based search and replace may catch symbols out of the scope of a function/loop.

+

For this kind of query the IDE will most likely ignore all the type/signature info provided by idetools and concentrate on the filename, line and column position of the multiple returned answers.

+ +

Expression evaluation

This feature is still under development. In the future it will allow an IDE to evaluate an expression in the context of the currently running/debugged user project.

+ +

Compiler as a service (CAAS)

The occasional use of idetools is acceptable for things like definitions, where the user puts the cursor on a symbol or double clicks it and after a second or two the IDE displays where that symbol is defined. Such latencies would be terrible for features like symbol suggestion, plus why wait at all if we can avoid it?

+

The idetools command can be run as a compiler service (CAAS), where you first launch the compiler and it will stay online as a server, accepting queries in a telnet like fashion. The advantage of staying on is that for many queries the compiler can cache the results of the compilation, and subsequent queries should be fast in the millisecond range, thus being responsive enough for IDEs.

+

If you want to start the server using stdin/stdout as communication you need to type:

+

nim serve --server.type:stdin proj.nim

+

If you want to start the server using tcp and a port, you need to type:

+

nim serve --server.type:tcp --server.port:6000 \
+    --server.address:hostname proj.nim

+

In both cases the server will start up and await further commands. The syntax of the commands you can now send to the server is practically the same as running the nim compiler on the commandline, you only need to remove the name of the compiler since you are already talking to it. The server will answer with as many lines of text it thinks necessary plus an empty line to indicate the end of the answer.

+

You can find examples of client/server communication in the idetools tests found in the Test suite.

+ +

Parsing idetools output

Idetools outputs is always returned on single lines separated by tab characters (\t). The values of each column are:

+
  1. Three characters indicating the type of returned answer (e.g. def for definition, sug for suggestion, etc).
  2. +
  3. Type of the symbol. This can be skProc, skLet, and just about any of the enums defined in the module compiler/ast.nim.
  4. +
  5. Full qualified path of the symbol. If you are querying a symbol defined in the proj.nim file, this would have the form proj.symbolName.
  6. +
  7. Type/signature. For variables and enums this will contain the type of the symbol, for procs, methods and templates this will contain the full unique signature (e.g. proc (File)).
  8. +
  9. Full path to the file containing the symbol.
  10. +
  11. Line where the symbol is located in the file. Lines start to count at 1.
  12. +
  13. Column where the symbol is located in the file. Columns start to count at 0.
  14. +
  15. Docstring for the symbol if available or the empty string. To differentiate the docstring from end of answer in server mode, the docstring is always provided enclosed in double quotes, and if the docstring spans multiple lines, all following lines of the docstring will start with a blank space to align visually with the starting quote.

    +

    Also, you won't find raw \n characters breaking the one answer per line format. Instead you will need to parse sequences in the form \xHH, where HH is a hexadecimal value (e.g. newlines generate the sequence \x0A).

    +
  16. +
+

The following sections define the expected output for each kind of symbol for which idetools returns valid output.

+ +

skConst

Third column: module + [n scope nesting] + const name.
Fourth column: the type of the const value.

Docstring: always the empty string.

+

const SOME_SEQUENCE = @[1, 2]
+--> col 2: $MODULE.SOME_SEQUENCE
+    col 3: seq[int]
+    col 7: ""

+

+

skEnumField

Third column: module + [n scope nesting] + enum type + enum field name.
Fourth column: enum type grouping other enum fields.

Docstring: always the empty string.

+

Open(filename, fmWrite)
+--> col 2: system.FileMode.fmWrite
+    col 3: FileMode
+    col 7: ""

+

+

skForVar

Third column: module + [n scope nesting] + var name.
Fourth column: type of the var.

Docstring: always the empty string.

+

proc looper(filename = "tests.nim") =
+  for letter in filename:
+    echo letter
+--> col 2: $MODULE.looper.letter
+    col 3: char
+    col 7: ""

+

+

skIterator, skClosureIterator

The fourth column will be the empty string if the iterator is being defined, since at that point in the file the parser hasn't processed the full line yet. The signature will be returned complete in posterior instances of the iterator.

+

Third column: module + [n scope nesting] + iterator name.
Fourth column: signature of the iterator including return type.

Docstring: docstring if available.

+

let
+  text = "some text"
+  letters = toSeq(runes(text))
+--> col 2: unicode.runes
+    col 3: iterator (string): Rune
+    col 7: "iterates over any unicode character of the string `s`."

+

+

skLabel

Third column: module + [n scope nesting] + name.
Fourth column: always the empty string.

Docstring: always the empty string.

+

proc test(text: string) =
+  var found = -1
+  block loops:
+--> col 2: $MODULE.test.loops
+    col 3: ""
+    col 7: ""

+

+

skLet

Third column: module + [n scope nesting] + let name.
Fourth column: the type of the let variable.

Docstring: always the empty string.

+

let
+  text = "some text"
+--> col 2: $MODULE.text
+    col 3: string
+    col 7: ""

+

+

skMacro

The fourth column will be the empty string if the macro is being defined, since at that point in the file the parser hasn't processed the full line yet. The signature will be returned complete in posterior instances of the macro.

+

Third column: module + [n scope nesting] + macro name.
Fourth column: signature of the macro including return type.

Docstring: docstring if available.

+

proc testMacro() =
+  expect(EArithmetic):
+--> col 2: idetools_api.expect
+    col 3: proc (varargs[expr], stmt): stmt
+    col 7: ""

+

+

skMethod

The fourth column will be the empty string if the method is being defined, since at that point in the file the parser hasn't processed the full line yet. The signature will be returned complete in posterior instances of the method.

+

Methods imply dynamic dispatch and idetools performs a static analysis on the code. For this reason idetools may not return the definition of the correct method you are querying because it may be impossible to know until the code is executed. It will try to return the method which covers the most possible cases (i.e. for variations of different classes in a hierarchy it will prefer methods using the base class).

+

While at the language level a method is differentiated from others by the parameters and return value, the signature of the method returned by idetools returns also the pragmas for the method.

+

Note that at the moment the word proc is returned for the signature of the found method instead of the expected method. This may change in the future.

+

Third column: module + [n scope nesting] + method name.
Fourth column: signature of the method including return type.

Docstring: docstring if available.

+

method eval(e: PExpr): int = quit "to override!"
+method eval(e: PLiteral): int = e.x
+method eval(e: PPlusExpr): int = eval(e.a) + eval(e.b)
+echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4)))
+--> col 2: $MODULE.eval
+    col 3: proc (PPlusExpr): int
+    col 7: ""

+

+

skParam

Third column: module + [n scope nesting] + param name.
Fourth column: the type of the parameter.

Docstring: always the empty string.

+

proc reader(filename = "tests.nim") =
+  let text = readFile(filename)
+--> col 2: $MODULE.reader.filename
+    col 3: string
+    col 7: ""

+

+

skProc

The fourth column will be the empty string if the proc is being defined, since at that point in the file the parser hasn't processed the full line yet. The signature will be returned complete in posterior instances of the proc.

+

While at the language level a proc is differentiated from others by the parameters and return value, the signature of the proc returned by idetools returns also the pragmas for the proc.

+

Third column: module + [n scope nesting] + proc name.
Fourth column: signature of the proc including return type.

Docstring: docstring if available.

+

open(filename, fmWrite)
+--> col 2: system.Open
+    col 3: proc (var File, string, FileMode, int): bool
+    col 7:
+"Opens a file named `filename` with given `mode`.
+ 
+ Default mode is readonly. Returns true iff the file could be opened.
+ This throws no exception if the file could not be opened."

+

+

skResult

Third column: module + [n scope nesting] + result.
Fourth column: the type of the result.

Docstring: always the empty string.

+

proc getRandomValue() : int =
+  return 4
+--> col 2: $MODULE.getRandomValue.result
+    col 3: int
+    col 7: ""

+

+

skTemplate

The fourth column will be the empty string if the template is being defined, since at that point in the file the parser hasn't processed the full line yet. The signature will be returned complete in posterior instances of the template.

+

Third column: module + [n scope nesting] + template name.
Fourth column: signature of the template including return type.

Docstring: docstring if available.

+

  let
+    text = "some text"
+    letters = toSeq(runes(text))
+  --> col 2: sequtils.toSeq
+      col 3: proc (expr): expr
+      col 7:
+  "Transforms any iterator into a sequence.
+   
+   Example:
+     
+     ```nim
+     let
+       numeric = @[1, 2, 3, 4, 5, 6, 7, 8, 9]
+       odd_numbers = toSeq(filter(numeric) do (x: int) -> bool:
+         if x mod 2 == 1:
+           result = true)
+     assert odd_numbers == @[1, 3, 5, 7, 9]"
+     ```

+

+

skType

Third column: module + [n scope nesting] + type name.
Fourth column: the type.

Docstring: always the empty string.

+

proc writeTempFile() =
+  var output: File
+--> col 2: system.File
+    col 3: File
+    col 7: ""

+

+

skVar

Third column: module + [n scope nesting] + var name.
Fourth column: the type of the var.

Docstring: always the empty string.

+

proc writeTempFile() =
+  var output: File
+  output.open("/tmp/somefile", fmWrite)
+  output.write("test")
+--> col 2: $MODULE.writeTempFile.output
+    col 3: File
+    col 7: ""

+

+

Test suite

To verify that idetools is working properly there are files in the tests/caas/ directory which provide unit testing. If you find odd idetools behaviour and are able to reproduce it, you are welcome to report it as a bug and add a test to the suite to avoid future regressions.

+ +

Running the test suite

At the moment idetools support is still in development so the test suite is not integrated with the main test suite and you have to run it manually. First you have to compile the tester:

+

$ cd my/nim/checkout/tests
+$ nim c testament/caasdriver.nim

+

Running the caasdriver without parameters will attempt to process all the test cases in all three operation modes. If a test succeeds nothing will be printed and the process will exit with zero. If any test fails, the specific line of the test preceding the failure and the failure itself will be dumped to stdout, along with a final indicator of the success state and operation mode. You can pass the parameter verbose to force all output even on successful tests.

+

The normal operation mode is called ProcRun and it involves starting a process for each command or query, similar to running manually the Nim compiler from the commandline. The CaasRun mode starts a server process to answer all queries. The SymbolProcRun mode is used by compiler developers. This means that running all tests involves processing all *.txt files three times, which can be quite time consuming.

+

If you don't want to run all the test case files you can pass any substring as a parameter to caasdriver. Only files matching the passed substring will be run. The filtering doesn't use any globbing metacharacters, it's a plain match. For example, to run only *-compile*.txt tests in verbose mode:

+

./caasdriver verbose -compile

+ +

Test case file format

All the tests/caas/*.txt files encode a session with the compiler:

+
  • The first line indicates the main project file.
  • +
  • Lines starting with > indicate a command to be sent to the compiler and the lines following a command include checks for expected or forbidden output (! for forbidden).
  • +
  • If a line starts with # it will be ignored completely, so you can use that for comments.
  • +
  • Since some cases are specific to either ProcRun or CaasRun modes, you can prefix a line with the mode and the line will be processed only in that mode.
  • +
  • The rest of the line is treated as a regular expression, so be careful escaping metacharacters like parenthesis.
  • +
+

Before the line is processed as a regular expression, some basic variables are searched for and replaced in the tests. The variables which will be replaced are:

+
  • $TESTNIM: filename specified in the first line of the script.
  • +
  • $MODULE: like $TESTNIM but without extension, useful for expected output.
  • +
+

When adding a test case to the suite it is a good idea to write a few comments about what the test is meant to verify.

+

+ +
+
+ + +
+
+ + + + diff --git a/idetools.idx b/idetools.idx new file mode 100644 index 0000000000000..63ff0c8e39f7e --- /dev/null +++ b/idetools.idx @@ -0,0 +1,27 @@ +markupTitle Nim IDE Integration Guide idetools.html Nim IDE Integration Guide 0 +heading Idetools invocation idetools.html#idetools-invocation Idetools invocation 0 +heading Specifying the location of the query idetools.html#idetools-invocation-specifying-the-location-of-the-query Specifying the location of the query 0 +heading Definitions idetools.html#idetools-invocation-definitions Definitions 0 +heading Suggestions idetools.html#idetools-invocation-suggestions Suggestions 0 +heading Invocation context idetools.html#idetools-invocation-invocation-context Invocation context 0 +heading Symbol usages idetools.html#idetools-invocation-symbol-usages Symbol usages 0 +heading Expression evaluation idetools.html#idetools-invocation-expression-evaluation Expression evaluation 0 +heading Compiler as a service (CAAS) idetools.html#compiler-as-a-service-caas Compiler as a service (CAAS) 0 +heading Parsing idetools output idetools.html#parsing-idetools-output Parsing idetools output 0 +heading skConst idetools.html#parsing-idetools-output-skconst skConst 0 +heading skEnumField idetools.html#parsing-idetools-output-skenumfield skEnumField 0 +heading skForVar idetools.html#parsing-idetools-output-skforvar skForVar 0 +heading skIterator, skClosureIterator idetools.html#parsing-idetools-output-skiterator-skclosureiterator skIterator, skClosureIterator 0 +heading skLabel idetools.html#parsing-idetools-output-sklabel skLabel 0 +heading skLet idetools.html#parsing-idetools-output-sklet skLet 0 +heading skMacro idetools.html#parsing-idetools-output-skmacro skMacro 0 +heading skMethod idetools.html#parsing-idetools-output-skmethod skMethod 0 +heading skParam idetools.html#parsing-idetools-output-skparam skParam 0 +heading skProc idetools.html#parsing-idetools-output-skproc skProc 0 +heading skResult idetools.html#parsing-idetools-output-skresult skResult 0 +heading skTemplate idetools.html#parsing-idetools-output-sktemplate skTemplate 0 +heading skType idetools.html#parsing-idetools-output-sktype skType 0 +heading skVar idetools.html#parsing-idetools-output-skvar skVar 0 +heading Test suite idetools.html#test-suite Test suite 0 +heading Running the test suite idetools.html#test-suite-running-the-test-suite Running the test suite 0 +heading Test case file format idetools.html#test-suite-test-case-file-format Test case file format 0 diff --git a/importutils.html b/importutils.html new file mode 100644 index 0000000000000..eb8ea8b1c4f21 --- /dev/null +++ b/importutils.html @@ -0,0 +1,133 @@ + + + + + + + +std/importutils + + + + + + + + + + + + + + + + +
+
+

std/importutils

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Utilities related to import and symbol resolution.

+

Experimental API, subject to change.

+

+
+

Procs

+
+
+
+
proc privateAccess(t: typedesc) {.magic: "PrivateAccess", ...raises: [], tags: [],
+                                  forbids: [].}
+
+ + Enables access to private fields of t in current scope. +

Example: cmd: -d:nimImportutilsExample

+
# here we're importing a module containing:
+# type
+#   Foo = object
+#     f0: int # private
+#   Goo*[T] = object
+#     g0: int # private
+# proc initFoo*(): auto = Foo()
+var f = initFoo()
+block:
+  assert not compiles(f.f0)
+  privateAccess(f.type)
+  f.f0 = 1 # accessible in this scope
+  block:
+    assert f.f0 == 1 # still in scope
+assert not compiles(f.f0)
+
+# this also works with generics
+privateAccess(Goo)
+assert Goo[float](g0: 1).g0 == 1
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/importutils.idx b/importutils.idx new file mode 100644 index 0000000000000..5dc4a6f4e7b62 --- /dev/null +++ b/importutils.idx @@ -0,0 +1,2 @@ +nimTitle importutils importutils.html module std/importutils 0 +nim privateAccess importutils.html#privateAccess,typedesc proc privateAccess(t: typedesc) 23 diff --git a/index.html b/index.html new file mode 100644 index 0000000000000..0cd266084ff12 --- /dev/null +++ b/index.html @@ -0,0 +1,55 @@ + + + + + + + +Nim Documentation Overview + + + + + + + + + + + + + + + + +
+
+

Nim Documentation Overview

+ + +
Author:Andreas Rumpf
Version:2.2.1
The documentation consists of several documents:
  • Tutorial (part I)
    The Nim tutorial part one deals with the basics.

  • +
  • Tutorial (part II)
    The Nim tutorial part two deals with the advanced language constructs.

  • +
  • Tutorial (part III)
    The Nim tutorial part three about Nim's macro system.

  • +
  • Language Manual
    The Nim manual is a draft that will evolve into a proper specification.

  • +
  • Library documentation
    This document describes Nim's standard library.

  • +
  • Compiler user guide
    The user guide lists command line arguments, special features of the compiler, etc.

  • +
  • Tools documentation
    Description of some tools that come with the standard distribution.

  • +
  • Memory management
    Additional documentation about Nim's memory management strategies
    and how to operate them in a realtime setting.

  • +
  • Source code filters
    The Nim compiler supports source code filters as a simple yet powerful builtin templating system.

  • +
  • Internal documentation
    The internal documentation describes how the compiler is implemented. Read this if you want to hack the compiler.

  • +
  • Index
    The generated index. Index + (Ctrl+F) == Joy

  • +
+ + + + +
+
+ + + + diff --git a/inotify.html b/inotify.html new file mode 100644 index 0000000000000..5175643d55875 --- /dev/null +++ b/inotify.html @@ -0,0 +1,546 @@ + + + + + + + +std/inotify + + + + + + + + + + + + + + + + +
+
+

std/inotify

+
+ +
+ Source   +Edit   + +
+ +

+

Example:

+
import std/inotify
+when defined(linux):
+  let inotifyFd = inotify_init()  # create and get new inotify FileHandle
+  doAssert inotifyFd >= 0         # check for errors
+
+  let wd = inotifyFd.inotify_add_watch("/tmp", IN_CREATE or IN_DELETE)  # Add new watch
+  doAssert wd >= 0                 # check for errors
+
+  discard inotifyFd.inotify_rm_watch(wd) # remove watch

+
+

Imports

+
+ syncio +
+
+
+

Types

+
+
+
InotifyEvent {.pure, final, importc: "struct inotify_event",
+               header: "<sys/inotify.h>", completeStruct.} = object
+  wd* {.importc: "wd".}: FileHandle ## Watch descriptor.
+  mask* {.importc: "mask".}: uint32 ## Watch mask.
+  cookie* {.importc: "cookie".}: uint32 ## Cookie to synchronize two events.
+  len* {.importc: "len".}: uint32 ## Length (including NULs) of name.
+  name* {.importc: "name".}: UncheckedArray[char] ## Name.
+
+ + An Inotify event. + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
IN_ACCESS = 0x00000001
+
+ + File was accessed. + Source   +Edit   + +
+
+
+
IN_ALL_EVENTS = 4095
+
+ + + Source   +Edit   + +
+
+
+
IN_ATTRIB = 0x00000004
+
+ + Metadata changed. + Source   +Edit   + +
+
+
+
IN_CLOSE = 24
+
+ + Close. + Source   +Edit   + +
+
+
+
IN_CLOSE_NOWRITE = 0x00000010
+
+ + Unwrittable file closed. + Source   +Edit   + +
+
+
+
IN_CLOSE_WRITE = 0x00000008
+
+ + Writtable file was closed. + Source   +Edit   + +
+
+
+
IN_CREATE = 0x00000100
+
+ + Subfile was created. + Source   +Edit   + +
+
+
+
IN_DELETE = 0x00000200
+
+ + Subfile was deleted. + Source   +Edit   + +
+
+
+
IN_DELETE_SELF = 0x00000400
+
+ + Self was deleted. + Source   +Edit   + +
+
+
+
IN_DONT_FOLLOW = 0x02000000
+
+ + Do not follow a sym link. + Source   +Edit   + +
+
+ +
+
IN_IGNORED = 0x00008000
+
+ + File was ignored. + Source   +Edit   + +
+
+
+
IN_ISDIR = 0x40000000
+
+ + Event occurred against dir. + Source   +Edit   + +
+
+
+
IN_MASK_ADD = 0x20000000
+
+ + Add to the mask of an already existing watch. + Source   +Edit   + +
+
+
+
IN_MODIFY = 0x00000002
+
+ + File was modified. + Source   +Edit   + +
+
+
+
IN_MOVE = 192
+
+ + Moves. + Source   +Edit   + +
+
+
+
IN_MOVE_SELF = 0x00000800
+
+ + Self was moved. + Source   +Edit   + +
+
+
+
IN_MOVED_FROM = 0x00000040
+
+ + File was moved from X. + Source   +Edit   + +
+
+
+
IN_MOVED_TO = 0x00000080
+
+ + File was moved to Y. + Source   +Edit   + +
+
+
+
IN_ONESHOT = 0x0000000080000000'i64
+
+ + Only send event once. + Source   +Edit   + +
+
+
+
IN_ONLYDIR = 0x01000000
+
+ + Only watch the path if it is a directory. + Source   +Edit   + +
+
+
+
IN_OPEN = 0x00000020
+
+ + File was opened. + Source   +Edit   + +
+
+
+
IN_Q_OVERFLOW = 0x00004000
+
+ + Event queued overflowed. + Source   +Edit   + +
+
+
+
IN_UNMOUNT = 0x00002000
+
+ + Backing fs was unmounted. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc inotify_add_watch(fd: cint; name: cstring; mask: uint32): cint {.cdecl,
+    importc: "inotify_add_watch", header: "<sys/inotify.h>", ...raises: [],
+    tags: [], forbids: [].}
+
+ + Add watch of object NAME to inotify instance FD. Notify about events specified by MASK. + Source   +Edit   + +
+
+ +
+
+
+
proc inotify_init(): FileHandle {.cdecl, importc: "inotify_init",
+                                  header: "<sys/inotify.h>", ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + Create and initialize inotify instance. + Source   +Edit   + +
+
+ +
+
+
+
proc inotify_init1(flags: cint): FileHandle {.cdecl, importc: "inotify_init1",
+    header: "<sys/inotify.h>", ...raises: [], tags: [], forbids: [].}
+
+ + Like inotify_init , but has a flags argument that provides access to some extra functionality. + Source   +Edit   + +
+
+ +
+
+
+
proc inotify_rm_watch(fd: cint; wd: cint): cint {.cdecl,
+    importc: "inotify_rm_watch", header: "<sys/inotify.h>", ...raises: [],
+    tags: [], forbids: [].}
+
+ + Remove the watch specified by WD from the inotify instance FD. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator inotify_events(evs: pointer; n: int): ptr InotifyEvent {....raises: [],
+    tags: [], forbids: [].}
+
+ + Abstract the packed buffer interface to yield event object pointers. +

Example: cmd: -r:off

+
when defined(linux):
+   import std/posix  # needed for FileHandle read procedure
+   const MaxWatches = 8192
+
+   let inotifyFd = inotify_init()  # create new inotify instance and get it's FileHandle
+   let wd = inotifyFd.inotify_add_watch("/tmp", IN_CREATE or IN_DELETE)  # Add new watch
+
+   var events: array[MaxWatches, byte]  # event buffer
+   while (let n = read(inotifyFd, addr events, MaxWatches); n) > 0:  # blocks until any events have been read
+     for e in inotify_events(addr events, n):
+       echo (e[].wd, e[].mask, cast[cstring](addr e[].name))    # echo watch id, mask, and name value of each event
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/inotify.idx b/inotify.idx new file mode 100644 index 0000000000000..19d0ff241b341 --- /dev/null +++ b/inotify.idx @@ -0,0 +1,31 @@ +nimTitle inotify inotify.html module std/inotify 0 +nim InotifyEvent inotify.html#InotifyEvent object InotifyEvent 18 +nim IN_ACCESS inotify.html#IN_ACCESS const IN_ACCESS 27 +nim IN_MODIFY inotify.html#IN_MODIFY const IN_MODIFY 28 +nim IN_ATTRIB inotify.html#IN_ATTRIB const IN_ATTRIB 29 +nim IN_CLOSE_WRITE inotify.html#IN_CLOSE_WRITE const IN_CLOSE_WRITE 30 +nim IN_CLOSE_NOWRITE inotify.html#IN_CLOSE_NOWRITE const IN_CLOSE_NOWRITE 31 +nim IN_CLOSE inotify.html#IN_CLOSE const IN_CLOSE 32 +nim IN_OPEN inotify.html#IN_OPEN const IN_OPEN 33 +nim IN_MOVED_FROM inotify.html#IN_MOVED_FROM const IN_MOVED_FROM 34 +nim IN_MOVED_TO inotify.html#IN_MOVED_TO const IN_MOVED_TO 35 +nim IN_MOVE inotify.html#IN_MOVE const IN_MOVE 36 +nim IN_CREATE inotify.html#IN_CREATE const IN_CREATE 37 +nim IN_DELETE inotify.html#IN_DELETE const IN_DELETE 38 +nim IN_DELETE_SELF inotify.html#IN_DELETE_SELF const IN_DELETE_SELF 39 +nim IN_MOVE_SELF inotify.html#IN_MOVE_SELF const IN_MOVE_SELF 40 +nim IN_UNMOUNT inotify.html#IN_UNMOUNT const IN_UNMOUNT 44 +nim IN_Q_OVERFLOW inotify.html#IN_Q_OVERFLOW const IN_Q_OVERFLOW 45 +nim IN_IGNORED inotify.html#IN_IGNORED const IN_IGNORED 46 +nim IN_ONLYDIR inotify.html#IN_ONLYDIR const IN_ONLYDIR 50 +nim IN_DONT_FOLLOW inotify.html#IN_DONT_FOLLOW const IN_DONT_FOLLOW 51 +nim IN_EXCL_UNLINK inotify.html#IN_EXCL_UNLINK const IN_EXCL_UNLINK 52 +nim IN_MASK_ADD inotify.html#IN_MASK_ADD const IN_MASK_ADD 53 +nim IN_ISDIR inotify.html#IN_ISDIR const IN_ISDIR 54 +nim IN_ONESHOT inotify.html#IN_ONESHOT const IN_ONESHOT 55 +nim IN_ALL_EVENTS inotify.html#IN_ALL_EVENTS const IN_ALL_EVENTS 59 +nim inotify_init inotify.html#inotify_init proc inotify_init(): FileHandle 64 +nim inotify_init1 inotify.html#inotify_init1,cint proc inotify_init1(flags: cint): FileHandle 68 +nim inotify_add_watch inotify.html#inotify_add_watch,cint,cstring,uint32 proc inotify_add_watch(fd: cint; name: cstring; mask: uint32): cint 73 +nim inotify_rm_watch inotify.html#inotify_rm_watch,cint,cint proc inotify_rm_watch(fd: cint; wd: cint): cint 77 +nim inotify_events inotify.html#inotify_events.i,pointer,int iterator inotify_events(evs: pointer; n: int): ptr InotifyEvent 81 diff --git a/intern.html b/intern.html new file mode 100644 index 0000000000000..ca380d2946b2e --- /dev/null +++ b/intern.html @@ -0,0 +1,474 @@ + + + + + + + +Internals of the Nim Compiler + + + + + + + + + + + + + + + + +
+
+

Internals of the Nim Compiler

+
+ +
+ Source   +Edit   + +
+ +

+ +
Author:Andreas Rumpf
Version:2.2.1

"Abstraction is layering ignorance on top of reality." -- Richard Gabriel

+ +

Directory structure

The Nim project's directory structure is:

+ + + + + + + + +
PathPurpose
bingenerated binary files
buildgenerated C code for the installation
compilerthe Nim compiler itself; note that this code has been translated from a bootstrapping version written in Pascal, so the code is not a poster child of good Nim code
configconfiguration files for Nim
distadditional packages for the distribution
docthe documentation; it is a bunch of reStructuredText files
libthe Nim library
+

Bootstrapping the compiler

Note: Add . to your PATH so that koch can be used without the ./.

+

Compiling the compiler is a simple matter of running:

+

nim c koch.nim
+koch boot -d:release

+

For a debug version use:

+

nim c koch.nim
+koch boot

+

And for a debug version compatible with GDB:

+

nim c koch.nim
+koch boot --debuginfo --linedir:on

+

The koch program is Nim's maintenance script. It is a replacement for make and shell scripting with the advantage that it is much more portable. More information about its options can be found in the koch documentation.

+ +

Reproducible builds

Set the compilation timestamp with the SOURCE_DATE_EPOCH environment variable.

+

export SOURCE_DATE_EPOCH=$(git log -n 1 --format=%at)
+koch boot # or `./build_all.sh`

+ +

Debugging the compiler

+

Bisecting for regressions

There are often times when there is a bug that is caused by a regression in the compiler or stdlib. Bisecting the Nim repo commits is a useful tool to identify what commit introduced the regression.

+

Even if it's not known whether a bug is caused by a regression, bisection can reduce debugging time by ruling it out. If the bug is found to be a regression, then you focus on the changes introduced by that one specific commit.

+

koch temp returns 125 as the exit code in case the compiler compilation fails. This exit code tells git bisect to skip the current commit:

+

git bisect start bad-commit good-commit
+git bisect run ./koch temp -r c test-source.nim

+

You can also bisect using custom options to build the compiler, for example if you don't need a debug version of the compiler (which runs slower), you can replace ./koch temp by explicit compilation command, see Bootstrapping the compiler.

+

See also:

+ + +

Building an instrumented compiler

Considering that a useful method of debugging the compiler is inserting debug logging, or changing code and then observing the outcome of a testcase, it is fastest to build a compiler that is instrumented for debugging from an existing release build. koch temp provides a convenient method of doing just that.

+

By default, running koch temp will build a lean version of the compiler with -d:debug enabled. The compiler is written to bin/nim_temp by default. A lean version of the compiler lacks JS and documentation generation.

+

bin/nim_temp can be directly used to run testcases, or used with testament with testament --nim:bin/nim_temp r tests/category/tsometest.

+

koch temp will build the temporary compiler with the -d:debug enabled. Here are compiler options that are of interest when debugging:

+
  • -d:debug: enables assert statements and stacktraces and all runtime checks
  • +
  • --opt:speed: build with optimizations enabled
  • +
  • --debugger:native: enables --debuginfo --lineDir:on for using a native debugger like GDB, LLDB or CDB
  • +
  • -d:nimDebug cause calls to quit to raise an assertion exception
  • +
  • -d:nimDebugUtils: enables various debugging utilities; see compiler/debugutils
  • +
  • -d:stacktraceMsgs -d:nimCompilerStacktraceHints: adds some additional stacktrace hints; see https://github.com/nim-lang/Nim/pull/13351
  • +
  • -u:leanCompiler: enable JS and doc generation
  • +
+

Another method to build and run the compiler is directly through koch:

+

koch temp [options] c test.nim
+
+# (will build with js support)
+koch temp [options] js test.nim
+
+# (will build with doc support)
+koch temp [options] doc test.nim

+ +

Debug logging

"Printf debugging" is still the most appropriate way to debug many problems arising in compiler development. The typical usage of breakpoints to debug the code is often less practical, because almost all code paths in the compiler will be executed hundreds of times before a particular section of the tested program is reached where the newly developed code must be activated.

+

To work around this problem, you'll typically introduce an if statement in the compiler code detecting more precisely the conditions where the tested feature is being used. One very common way to achieve this is to use the mdbg condition, which will be true only in contexts, processing expressions and statements from the currently compiled main module:

+

# inside some compiler module
+if mdbg:
+  debug someAstNode

+

Using the isCompilerDebug condition along with inserting some statements into the testcase provides more granular logging:

+

# compilermodule.nim
+if isCompilerDebug():
+  debug someAstNode
+
+# testcase.nim
+proc main =
+  {.define(nimCompilerDebug).}
+  let a = 2.5 * 3
+  {.undef(nimCompilerDebug).}

+

Logging can also be scoped to a specific filename as well. This will of course match against every module with that name.

+

if `??`(conf, n.info, "module.nim"):
+  debug(n)

+

The above examples also makes use of the debug proc, which is able to print a human-readable form of an arbitrary AST tree. Other common ways to print information about the internal compiler types include:

+

# pretty print PNode
+
+# pretty prints the Nim ast
+echo renderTree(someNode)
+
+# pretty prints the Nim ast, but annotates symbol IDs
+echo renderTree(someNode, {renderIds})
+
+# pretty print ast as JSON
+debug(someNode)
+
+# print as YAML
+echo treeToYaml(config, someNode)
+
+
+# pretty print PType
+
+# print type name
+echo typeToString(someType)
+
+# pretty print as JSON
+debug(someType)
+
+# print as YAML
+echo typeToYaml(config, someType)
+
+
+# pretty print PSym
+
+# print the symbol's name
+echo symbol.name.s
+
+# pretty print as JSON
+debug(symbol)
+
+# print as YAML
+echo symToYaml(config, symbol)
+
+
+# pretty print TLineInfo
+lineInfoToStr(lineInfo)
+
+
+# print the structure of any type
+repr(someVar)

+

Here are some other helpful utilities:

+

# how did execution reach this location?
+writeStackTrace()

+

These procs may not already be imported by the module you're editing. You can import them directly for debugging:

+

from astalgo import debug
+from types import typeToString
+from renderer import renderTree
+from msgs import `??`

+ +

Native debugging

Stepping through the compiler with a native debugger is a very powerful tool to both learn and debug it. However, there is still the need to constrain when breakpoints are triggered. The same methods as in Debug logging can be applied here when combined with calls to the debug helpers enteringDebugSection() and exitingDebugSection().

+
  1. Compile the temp compiler with --debugger:native -d:nimDebugUtils
  2. +
  3. Set your desired breakpoints or watchpoints.
  4. +
  5. Configure your debugger:
    • GDB: execute source tools/compiler.gdb at startup
    • +
    • LLDB execute command source tools/compiler.lldb at startup
    • +
    +
  6. +
  7. Use one of the scoping helpers like so:
  8. +
+

if isCompilerDebug():
+  enteringDebugSection()
+else:
+  exitingDebugSection()

+

A caveat of this method is that all breakpoints and watchpoints are enabled or disabled. Also, due to a bug, only breakpoints can be constrained for LLDB.

+ +

The compiler's architecture

Nim uses the classic compiler architecture: A lexer/scanner feeds tokens to a parser. The parser builds a syntax tree that is used by the code generators. This syntax tree is the interface between the parser and the code generator. It is essential to understand most of the compiler's code.

+

Semantic analysis is separated from parsing.

+ +

Short description of Nim's modules

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModuleDescription
nimmain module: parses the command line and calls main.MainCommand
mainimplements the top-level command dispatching
nimconfimplements the config file reader
syntaxesdispatcher for the different parsers and filters
filter_tmplstandard template filter (#? stdtempl)
lexbasebuffer handling of the lexical analyser
lexerlexical analyser
parserNim's parser
rendererNim code renderer (AST back to its textual form)
optionscontains global and local compiler options
asttype definitions of the abstract syntax tree (AST) and node constructors
astalgoalgorithms for containers of AST nodes; converting the AST to YAML; the symbol table
passesimplement the passes manager for passes over the AST
treessome algorithms for nodes; this module is less important
typesmodule for traversing type graphs; also contain several helpers for dealing with types
sigmatchcontains the matching algorithm that is used for proc calls
semexprscontains the semantic checking phase for expressions
semstmtscontains the semantic checking phase for statements
semtypescontains the semantic checking phase for types
seminstinstantiation of generic procs and types
semfoldcontains code to deal with constant folding
sempass2Second semantic checking pass over the AST
vmcontains an AST interpreter for compile time evaluation
pragmassemantic checking of pragmas
identsimplements a general mapping from identifiers to an internal representation (PIdent) that is used so that a simple id-comparison suffices to establish whether two Nim identifiers are equivalent
transftransformations on the AST that need to be done before code generation
cgenmain file of the C code generator
ccgutilscontains helpers for the C code generator
ccgtypesthe generator for C types
ccgstmtsthe generator for statements
ccgexprsthe generator for expressions
extccompthis module calls the C compiler and linker; interesting if you want to add support for a new C compiler
+

The syntax tree

The syntax tree consists of nodes which may have an arbitrary number of children. Types and symbols are represented by other nodes, because they may contain cycles. The AST changes its shape after semantic checking. This is needed to make life easier for the code generators. See the "ast" module for the type definitions. The macros module contains many examples how the AST represents each syntactic structure.

+ +

Runtimes

Nim has two different runtimes, the "old runtime" and the "new runtime". The old runtime supports the old GCs (markAndSweep, refc, Boehm), the new runtime supports ARC/ORC. The new runtime is active when defined(nimV2).

+ +

Coding Guidelines

  • We follow Nim's official style guide, see NEP1.
  • +
  • Max line length is 100 characters.
  • +
  • Provide spaces around binary operators if that enhances readability.
  • +
  • Use a space after a colon, but not before it.
  • +
  • (deprecated) Start types with a capital T, unless they are pointers/references which start with P.
  • +
  • Prefer import package over from package import symbol.
  • +
+

See also the API naming design document.

+ +

Porting to new platforms

Porting Nim to a new architecture is pretty easy, since C is the most portable programming language (within certain limits) and Nim generates C code, porting the code generator is not necessary.

+

POSIX-compliant systems on conventional hardware are usually pretty easy to port: Add the platform to platform (if it is not already listed there), check that the OS, System modules work and recompile Nim.

+

The only case where things aren't as easy is when old runtime's garbage collectors need some assembler tweaking to work. The default implementation uses C's setjmp function to store all registers on the hardware stack. It may be necessary that the new platform needs to replace this generic code by some assembler code.

+

Files that may need changed for your platform include:

+
  • compiler/platform.nim Add os/cpu properties.
  • +
  • lib/system.nim Add os/cpu to the documentation for system.hostOS and system.hostCPU.
  • +
  • compiler/options.nim Add special os/cpu property checks in isDefined.
  • +
  • compiler/installer.ini Add os/cpu to Project.Platforms field.
  • +
  • lib/system/platforms.nim Add os/cpu.
  • +
  • std/private/osseps.nim Add os specializations.
  • +
  • lib/pure/distros.nim Add os, package handler.
  • +
  • tools/niminst/makefile.nimf Add os/cpu compiler/linker flags.
  • +
  • tools/niminst/buildsh.nimf Add os/cpu compiler/linker flags.
  • +
+

If the --os or --cpu options aren't passed to the compiler, then Nim will determine the current host os, cpu and endianness from system.cpuEndian, system.hostOS and system.hostCPU. Those values are derived from compiler/platform.nim.

+

In order for the new platform to be bootstrapped from the csources, it must:

+
  • have compiler/platform.nim updated
  • +
  • have compiler/installer.ini updated
  • +
  • have tools/niminst/buildsh.nimf updated
  • +
  • have tools/niminst/makefile.nimf updated
  • +
  • be backported to the Nim version used by the csources
  • +
  • the new csources must be pushed
  • +
  • the new csources revision must be updated in config/build_config.txt
  • +
+ +

Runtime type information

Note: This section describes the "old runtime".

+

Runtime type information (RTTI) is needed for several aspects of the Nim programming language:

+
Garbage collection
+
The old GCs use the RTTI for traversing arbitrary Nim types, but usually only the marker field which contains a proc that does the traversal.
+
Complex assignments
+
Sequences and strings are implemented as pointers to resizable buffers, but Nim requires copying for assignments. Apart from RTTI the compiler also generates copy procedures as a specialization.
+
+

We already know the type information as a graph in the compiler. Thus, we need to serialize this graph as RTTI for C code generation. Look at the file lib/system/hti.nim for more information.

+ +

Magics and compilerProcs

The system module contains the part of the RTL which needs support by compiler magic. The C code generator generates the C code for it, just like any other module. However, calls to some procedures like addInt are inserted by the generator. Therefore, there is a table (compilerprocs) with all symbols that are marked as compilerproc. compilerprocs are needed by the code generator. A magic proc is not the same as a compilerproc: A magic is a proc that needs compiler magic for its semantic checking, a compilerproc is a proc that is used by the code generator.

+ +

Code generation for closures

Code generation for closures is implemented by lambda lifting.

+ +

Design

A closure proc var can call ordinary procs of the default Nim calling convention. But not the other way round! A closure is implemented as a tuple[prc, env]. env can be nil implying a call without a closure. This means that a call through a closure generates an if but the interoperability is worth the cost of the if. Thunk generation would be possible too, but it's slightly more effort to implement.

+

Tests with GCC on Amd64 showed that it's really beneficial if the 'environment' pointer is passed as the last argument, not as the first argument.

+

Proper thunk generation is harder because the proc that is to wrap could stem from a complex expression:

+

receivesClosure(returnsDefaultCC[i])

+

A thunk would need to call returnsDefaultCC[i] somehow and that would require an additional closure generation... Ok, not really, but it requires to pass the function to call. So we'd end up with 2 indirect calls instead of one. Another much more severe problem with this solution is that it's not GC-safe to pass a proc pointer around via a generic ref type.

+

Example code:

+

proc add(x: int): proc (y: int): int {.closure.} =
+  return proc (y: int): int =
+    return x + y
+
+var add2 = add(2)
+echo add2(5) #OUT 7

+

This should produce roughly this code:

+

type
+  Env = ref object
+    x: int # data
+
+proc anon(y: int, c: Env): int =
+  return y + c.x
+
+proc add(x: int): tuple[prc, data] =
+  var env: Env
+  new env
+  env.x = x
+  result = (anon, env)
+
+var add2 = add(2)
+let tmp = if add2.data == nil: add2.prc(5) else: add2.prc(5, add2.data)
+echo tmp

+

Beware of nesting:

+

proc add(x: int): proc (y: int): proc (z: int): int {.closure.} {.closure.} =
+  return lambda (y: int): proc (z: int): int {.closure.} =
+    return lambda (z: int): int =
+      return x + y + z
+
+var add24 = add(2)(4)
+echo add24(5) #OUT 11

+

This should produce roughly this code:

+

type
+  EnvX = ref object
+    x: int # data
+  
+  EnvY = ref object
+    y: int
+    ex: EnvX
+
+proc lambdaZ(z: int, ey: EnvY): int =
+  return ey.ex.x + ey.y + z
+
+proc lambdaY(y: int, ex: EnvX): tuple[prc, data: EnvY] =
+  var ey: EnvY
+  new ey
+  ey.y = y
+  ey.ex = ex
+  result = (lambdaZ, ey)
+
+proc add(x: int): tuple[prc, data: EnvX] =
+  var ex: EnvX
+  ex.x = x
+  result = (lambdaY, ex)
+
+var tmp = add(2)
+var tmp2 = tmp.fn(4, tmp.data)
+var add24 = tmp2.fn(4, tmp2.data)
+echo add24(5)

+

We could get rid of nesting environments by always inlining inner anon procs. More useful is escape analysis and stack allocation of the environment, however.

+ +

Accumulator

proc getAccumulator(start: int): proc (): int {.closure} =
+  var i = start
+  return lambda: int =
+    inc i
+    return i
+
+proc p =
+  var delta = 7
+  proc accumulator(start: int): proc(): int =
+    var x = start-1
+    result = proc (): int =
+      x = x + delta
+      inc delta
+      return x
+  
+  var a = accumulator(3)
+  var b = accumulator(4)
+  echo a() + b()

+ +

Internals

Lambda lifting is implemented as part of the transf pass. The transf pass generates code to set up the environment and to pass it around. However, this pass does not change the types! So we have some kind of mismatch here; on the one hand the proc expression becomes an explicit tuple, on the other hand the tyProc(ccClosure) type is not changed. For C code generation it's also important the hidden formal param is void* and not something more specialized. However, the more specialized env type needs to passed to the backend somehow. We deal with this by modifying s.ast[paramPos] to contain the formal hidden parameter, but not s.typ!

+ +

Notes on type and AST representation

To be expanded.

+ +

Integer literals

In Nim, there is a redundant way to specify the type of an integer literal. First, it should be unsurprising that every node has a node kind. The node of an integer literal can be any of the following values:

+
nkIntLit, nkInt8Lit, nkInt16Lit, nkInt32Lit, nkInt64Lit,
+nkUIntLit, nkUInt8Lit, nkUInt16Lit, nkUInt32Lit, nkUInt64Lit
+

On top of that, there is also the typ field for the type. The kind of the typ field can be one of the following ones, and it should be matching the literal kind:

+
tyInt, tyInt8, tyInt16, tyInt32, tyInt64, tyUInt, tyUInt8,
+tyUInt16, tyUInt32, tyUInt64
+

Then there is also the integer literal type. This is a specific type that is implicitly convertible into the requested type if the requested type can hold the value. For this to work, the type needs to know the concrete value of the literal. For example an expression 321 will be of type int literal(321). This type is implicitly convertible to all integer types and ranges that contain the value 321. That would be all builtin integer types except uint8 and int8 where 321 would be out of range. When this literal type is assigned to a new var or let variable, it's type will be resolved to just int, not int literal(321) unlike constants. A constant keeps the full int literal(321) type. Here is an example where that difference matters.

+

proc foo(arg: int8) =
+  echo "def"
+
+const tmp1 = 123
+foo(tmp1)  # OK
+
+let tmp2 = 123
+foo(tmp2) # Error

+

In a context with multiple overloads, the integer literal kind will always prefer the int type over all other types. If none of the overloads is of type int, then there will be an error because of ambiguity.

+

proc foo(arg: int) =
+  echo "abc"
+proc foo(arg: int8) =
+  echo "def"
+foo(123) # output: abc
+
+proc bar(arg: int16) =
+  echo "abc"
+proc bar(arg: int8) =
+  echo "def"
+
+bar(123) # Error ambiguous call

+

In the compiler these integer literal types are represented with the node kind nkIntLit, type kind tyInt and the member n of the type pointing back to the integer literal node in the ast containing the integer value. These are the properties that hold true for integer literal types.

+
n.kind == nkIntLit
+n.typ.kind == tyInt
+n.typ.n == n
+

Other literal types, such as uint literal(123) that would automatically convert to other integer types, but prefers to become a uint are not part of the Nim language.

+

In an unchecked AST, the typ field is nil. The type checker will set the typ field accordingly to the node kind. Nodes of kind nkIntLit will get the integer literal type (e.g. int literal(123)). Nodes of kind nkUIntLit will get type uint (kind tyUint), etc.

+

This also means that it is not possible to write a literal in an unchecked AST that will after sem checking just be of type int and not implicitly convertible to other integer types. This only works for all integer types that are not int.

+

+ +
+
+ + +
+
+ + + + diff --git a/intern.idx b/intern.idx new file mode 100644 index 0000000000000..24e9223827304 --- /dev/null +++ b/intern.idx @@ -0,0 +1,24 @@ +markupTitle Internals of the Nim Compiler intern.html Internals of the Nim Compiler 0 +heading Directory structure intern.html#directory-structure Directory structure 0 +heading Bootstrapping the compiler intern.html#bootstrapping-the-compiler Bootstrapping the compiler 0 +heading Reproducible builds intern.html#bootstrapping-the-compiler-reproducible-builds Reproducible builds 0 +heading Debugging the compiler intern.html#debugging-the-compiler Debugging the compiler 0 +heading Bisecting for regressions intern.html#debugging-the-compiler-bisecting-for-regressions Bisecting for regressions 0 +heading Building an instrumented compiler intern.html#debugging-the-compiler-building-an-instrumented-compiler Building an instrumented compiler 0 +heading Debug logging intern.html#debugging-the-compiler-debug-logging Debug logging 0 +heading Native debugging intern.html#debugging-the-compiler-native-debugging Native debugging 0 +heading The compiler's architecture intern.html#the-compiler-s-architecture The compiler's architecture 0 +heading Short description of Nim's modules intern.html#the-compiler-s-architecture-short-description-of-nim-s-modules Short description of Nim's modules 0 +heading The syntax tree intern.html#the-compiler-s-architecture-the-syntax-tree The syntax tree 0 +heading Runtimes intern.html#runtimes Runtimes 0 +heading Coding Guidelines intern.html#coding-guidelines Coding Guidelines 0 +heading Porting to new platforms intern.html#porting-to-new-platforms Porting to new platforms 0 +heading Runtime type information intern.html#runtime-type-information Runtime type information 0 +heading Magics and compilerProcs intern.html#magics-and-compilerprocs Magics and compilerProcs 0 +heading Code generation for closures intern.html#code-generation-for-closures Code generation for closures 0 +idx lambda lifting intern.html#lambda-lifting_1 Code generation for closures 0 +heading Design intern.html#code-generation-for-closures-design Design 0 +heading Accumulator intern.html#code-generation-for-closures-accumulator Accumulator 0 +heading Internals intern.html#code-generation-for-closures-internals Internals 0 +heading Notes on type and AST representation intern.html#notes-on-type-and-ast-representation Notes on type and AST representation 0 +heading Integer literals intern.html#notes-on-type-and-ast-representation-integer-literals Integer literals 0 diff --git a/intsets.html b/intsets.html new file mode 100644 index 0000000000000..ef800d6b1847a --- /dev/null +++ b/intsets.html @@ -0,0 +1,162 @@ + + + + + + + +std/intsets + + + + + + + + + + + + + + + + +
+
+

std/intsets

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Specialization of the generic packedsets module (see its documentation for more examples) for ordinal sparse sets.

+ +
+

Types

+
+
+
IntSet = PackedSet[int]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc initIntSet(): IntSet {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toIntSet(x: openArray[int]): IntSet {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/intsets.idx b/intsets.idx new file mode 100644 index 0000000000000..ed5ca55eb47ab --- /dev/null +++ b/intsets.idx @@ -0,0 +1,4 @@ +nimTitle intsets intsets.html module std/intsets 0 +nim IntSet intsets.html#IntSet type IntSet 18 +nim toIntSet intsets.html#toIntSet,openArray[int] proc toIntSet(x: openArray[int]): IntSet 20 +nim initIntSet intsets.html#initIntSet proc initIntSet(): IntSet 22 diff --git a/isolation.html b/isolation.html new file mode 100644 index 0000000000000..3dfff601c36cb --- /dev/null +++ b/isolation.html @@ -0,0 +1,227 @@ + + + + + + + +std/isolation + + + + + + + + + + + + + + + + +
+
+

std/isolation

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements the Isolated[T] type for safe construction of isolated subgraphs that can be passed efficiently to different channels and threads.

Warning: +This module is experimental and its interface may change.
+

+
+

Types

+
+
+
Isolated[T] {.sendable.} = object
+
+ + Isolated data can only be moved, not copied. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `=copy`[T](dest: var Isolated[T]; src: Isolated[T]) {.error.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `=destroy`[T](dest: var Isolated[T]) {.inline, ...raises: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `=sink`[T](dest: var Isolated[T]; src: Isolated[T]) {.inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func extract[T](src: var Isolated[T]): T
+
+ + Returns the internal value of src. The value is moved from src. + Source   +Edit   + +
+
+ +
+
+
+
func isolate[T](value: sink T): Isolated[T] {.magic: "Isolate", ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Creates an isolated subgraph from the expression value. Isolation is checked at compile time.

+

Please read https://github.com/nim-lang/RFCs/issues/244 for more details.

+ + Source   +Edit   + +
+
+ +
+
+
+
func unsafeIsolate[T](value: sink T): Isolated[T]
+
+ + Creates an isolated subgraph from the expression value.
Warning: +The proc doesn't check whether value is isolated.
+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/isolation.idx b/isolation.idx new file mode 100644 index 0000000000000..e815b40e8f8ea --- /dev/null +++ b/isolation.idx @@ -0,0 +1,8 @@ +nimTitle isolation isolation.html module std/isolation 0 +nim Isolated isolation.html#Isolated object Isolated 18 +nim `=copy` isolation.html#=copy,Isolated[T],Isolated[T] proc `=copy`[T](dest: var Isolated[T]; src: Isolated[T]) 21 +nim `=sink` isolation.html#=sink,Isolated[T],Isolated[T] proc `=sink`[T](dest: var Isolated[T]; src: Isolated[T]) 23 +nim `=destroy` isolation.html#=destroy,Isolated[T] proc `=destroy`[T](dest: var Isolated[T]) 27 +nim isolate isolation.html#isolate,sinkT proc isolate[T](value: sink T): Isolated[T] 31 +nim unsafeIsolate isolation.html#unsafeIsolate,sinkT proc unsafeIsolate[T](value: sink T): Isolated[T] 39 +nim extract isolation.html#extract,Isolated[T] proc extract[T](src: var Isolated[T]): T 46 diff --git a/iterators.html b/iterators.html new file mode 100644 index 0000000000000..2b7cb8ae2f129 --- /dev/null +++ b/iterators.html @@ -0,0 +1,522 @@ + + + + + + + +system/iterators + + + + + + + + + + + + + + + + +
+
+

system/iterators

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Default iterators for some Nim types.

+
+

Imports

+
+ assertions +
+
+
+

Iterators

+
+
+
+
iterator fieldPairs[S: tuple | object; T: tuple | object](x: S; y: T): tuple[
+    key: string, a, b: RootObj] {.magic: "FieldPairs", noSideEffect, ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + Iterates over every field of x and y.
Warning: +This really transforms the 'for' and unrolls the loop. The current implementation also has a bug that affects symbol binding in the loop body.
+ +

Example:

+
type Foo = object
+  x1: int
+  x2: string
+var a1 = Foo(x1: 12, x2: "abc")
+var a2: Foo
+for name, v1, v2 in fieldPairs(a1, a2):
+  when name == "x2": v2 = v1
+doAssert a2 == Foo(x1: 0, x2: "abc")
+ Source   +Edit   + +
+
+
+
iterator fieldPairs[T: tuple | object](x: T): tuple[key: string, val: RootObj] {.
+    magic: "FieldPairs", noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Iterates over every field of x returning their name and value.

+

When you iterate over objects with different field types you have to use the compile time when instead of a runtime if to select the code you want to run for each type. To perform the comparison use the is operator. Another way to do the same without when is to leave the task of picking the appropriate code to a secondary proc which you overload for each field type and pass the value to.

+
Warning: +This really transforms the 'for' and unrolls the loop. The current implementation also has a bug that affects symbol binding in the loop body.
+ +

Example:

+
type
+  Custom = object
+    foo: string
+    bar: bool
+proc `$`(x: Custom): string =
+  result = "Custom:"
+  for name, value in x.fieldPairs:
+    when value is bool:
+      result.add("\n\t" & name & " is " & $value)
+    else:
+      result.add("\n\t" & name & " '" & value & "'")
+ Source   +Edit   + +
+
+ +
+
+
+
iterator fields[S: tuple | object; T: tuple | object](x: S; y: T): tuple[
+    key: string, val: RootObj] {.magic: "Fields", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + Iterates over every field of x and y.
Warning: +This really transforms the 'for' and unrolls the loop. The current implementation also has a bug that affects symbol binding in the loop body.
+ +

Example:

+
var t1 = (1, "foo")
+var t2 = default(typeof(t1))
+for v1, v2 in fields(t1, t2): v2 = v1
+doAssert t1 == t2
+ Source   +Edit   + +
+
+
+
iterator fields[T: tuple | object](x: T): RootObj {.magic: "Fields",
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + Iterates over every field of x.
Warning: +This really transforms the 'for' and unrolls the loop. The current implementation also has a bug that affects symbol binding in the loop body.
+ +

Example:

+
var t = (1, "foo")
+for v in fields(t): v = default(typeof(v))
+doAssert t == (0, "")
+ Source   +Edit   + +
+
+ +
+
+
+
iterator items(a: cstring): char {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Iterates over each item of a. +

Example:

+
from std/sequtils import toSeq
+assert toSeq("abc\0def".cstring) == @['a', 'b', 'c']
+assert toSeq("abc".cstring) == @['a', 'b', 'c']
+ Source   +Edit   + +
+
+
+
iterator items(a: string): char {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Iterates over each item of a. + Source   +Edit   + +
+
+
+
iterator items[IX, T](a: array[IX, T]): T {.inline.}
+
+ + Iterates over each item of a. + Source   +Edit   + +
+
+
+
iterator items[T: char](a: openArray[T]): T {.inline.}
+
+ + Iterates over each item of a. + Source   +Edit   + +
+
+
+
iterator items[T: enum and Ordinal](E: typedesc[T]): T
+
+ + Iterates over the values of E. See also enumutils.items for enums with holes. +

Example:

+
type Goo = enum g0 = 2, g1, g2
+from std/sequtils import toSeq
+assert Goo.toSeq == [g0, g1, g2]
+ Source   +Edit   + +
+
+
+
iterator items[T: not char](a: openArray[T]): lent2 T {.inline.}
+
+ + Iterates over each item of a. + Source   +Edit   + +
+
+
+
iterator items[T: Ordinal](s: Slice[T]): T
+
+ + Iterates over the slice s, yielding each value between s.a and s.b (inclusively). + Source   +Edit   + +
+
+
+
iterator items[T](a: seq[T]): lent2 T {.inline.}
+
+ + Iterates over each item of a. + Source   +Edit   + +
+
+
+
iterator items[T](a: set[T]): T {.inline.}
+
+ + Iterates over each element of a. items iterates only over the elements that are really in the set (and not over the ones the set is able to hold). + Source   +Edit   + +
+
+ +
+
+
+
iterator mitems(a: var cstring): var char {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Iterates over each item of a so that you can modify the yielded value. +

Example:

+
from std/sugar import collect
+var a = "abc\0def"
+prepareMutation(a)
+var b = a.cstring
+let s = collect:
+  for bi in mitems(b):
+    if bi == 'b': bi = 'B'
+    bi
+assert s == @['a', 'B', 'c']
+assert b == "aBc"
+assert a == "aBc\0def"
+ Source   +Edit   + +
+
+
+
iterator mitems(a: var string): var char {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Iterates over each item of a so that you can modify the yielded value. + Source   +Edit   + +
+
+
+
iterator mitems[IX, T](a: var array[IX, T]): var T {.inline.}
+
+ + Iterates over each item of a so that you can modify the yielded value. + Source   +Edit   + +
+
+
+
iterator mitems[T](a: var openArray[T]): var T {.inline.}
+
+ + Iterates over each item of a so that you can modify the yielded value. + Source   +Edit   + +
+
+
+
iterator mitems[T](a: var seq[T]): var T {.inline.}
+
+ + Iterates over each item of a so that you can modify the yielded value. + Source   +Edit   + +
+
+ +
+
+
+
iterator mpairs(a: var cstring): tuple[key: int, val: var char] {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Iterates over each item of a. Yields (index, a[index]) pairs. a[index] can be modified. + Source   +Edit   + +
+
+
+
iterator mpairs(a: var string): tuple[key: int, val: var char] {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Iterates over each item of a. Yields (index, a[index]) pairs. a[index] can be modified. + Source   +Edit   + +
+
+
+
iterator mpairs[IX, T](a: var array[IX, T]): tuple[key: IX, val: var T] {.inline.}
+
+ + Iterates over each item of a. Yields (index, a[index]) pairs. a[index] can be modified. + Source   +Edit   + +
+
+
+
iterator mpairs[T](a: var openArray[T]): tuple[key: int, val: var T] {.inline.}
+
+ + Iterates over each item of a. Yields (index, a[index]) pairs. a[index] can be modified. + Source   +Edit   + +
+
+
+
iterator mpairs[T](a: var seq[T]): tuple[key: int, val: var T] {.inline.}
+
+ + Iterates over each item of a. Yields (index, a[index]) pairs. a[index] can be modified. + Source   +Edit   + +
+
+ +
+
+
+
iterator pairs(a: cstring): tuple[key: int, val: char] {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Iterates over each item of a. Yields (index, a[index]) pairs. + Source   +Edit   + +
+
+
+
iterator pairs(a: string): tuple[key: int, val: char] {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Iterates over each item of a. Yields (index, a[index]) pairs. + Source   +Edit   + +
+
+
+
iterator pairs[IX, T](a: array[IX, T]): tuple[key: IX, val: T] {.inline.}
+
+ + Iterates over each item of a. Yields (index, a[index]) pairs. + Source   +Edit   + +
+
+
+
iterator pairs[T](a: openArray[T]): tuple[key: int, val: T] {.inline.}
+
+ + Iterates over each item of a. Yields (index, a[index]) pairs. + Source   +Edit   + +
+
+
+
iterator pairs[T](a: seq[T]): tuple[key: int, val: T] {.inline.}
+
+ + Iterates over each item of a. Yields (index, a[index]) pairs. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/iterators.idx b/iterators.idx new file mode 100644 index 0000000000000..6cd9c84930e72 --- /dev/null +++ b/iterators.idx @@ -0,0 +1,35 @@ +nimTitle iterators iterators.html module system/iterators 0 +nim items iterators.html#items.i,openArray[T] iterator items[T: not char](a: openArray[T]): lent2 T 16 +nim items iterators.html#items.i,openArray[T]_2 iterator items[T: char](a: openArray[T]): T 23 +nim mitems iterators.html#mitems.i,openArray[T] iterator mitems[T](a: var openArray[T]): var T 33 +nim items iterators.html#items.i,array[IX,T] iterator items[IX, T](a: array[IX, T]): T 40 +nim mitems iterators.html#mitems.i,array[IX,T] iterator mitems[IX, T](a: var array[IX, T]): var T 49 +nim items iterators.html#items.i,set[T] iterator items[T](a: set[T]): T 58 +nim items iterators.html#items.i,cstring iterator items(a: cstring): char 70 +nim mitems iterators.html#mitems.i,cstring iterator mitems(a: var cstring): var char 99 +nim items iterators.html#items.i,typedesc[T] iterator items[T: enum and Ordinal](E: typedesc[T]): T 130 +nim items iterators.html#items.i,Slice[T: Ordinal] iterator items[T: Ordinal](s: Slice[T]): T 140 +nim pairs iterators.html#pairs.i,openArray[T] iterator pairs[T](a: openArray[T]): tuple[key: int, val: T] 146 +nim mpairs iterators.html#mpairs.i,openArray[T] iterator mpairs[T](a: var openArray[T]): tuple[key: int, val: var T] 153 +nim pairs iterators.html#pairs.i,array[IX,T] iterator pairs[IX, T](a: array[IX, T]): tuple[key: IX, val: T] 161 +nim mpairs iterators.html#mpairs.i,array[IX,T] iterator mpairs[IX, T](a: var array[IX, T]): tuple[key: IX, val: var T] 170 +nim pairs iterators.html#pairs.i,seq[T] iterator pairs[T](a: seq[T]): tuple[key: int, val: T] 180 +nim mpairs iterators.html#mpairs.i,seq[T] iterator mpairs[T](a: var seq[T]): tuple[key: int, val: var T] 189 +nim pairs iterators.html#pairs.i,string iterator pairs(a: string): tuple[key: int, val: char] 199 +nim mpairs iterators.html#mpairs.i,string iterator mpairs(a: var string): tuple[key: int, val: var char] 208 +nim pairs iterators.html#pairs.i,cstring iterator pairs(a: cstring): tuple[key: int, val: char] 218 +nim mpairs iterators.html#mpairs.i,cstring iterator mpairs(a: var cstring): tuple[key: int, val: var char] 232 +nim items iterators.html#items.i,seq[T] iterator items[T](a: seq[T]): lent2 T 247 +nim mitems iterators.html#mitems.i,seq[T] iterator mitems[T](a: var seq[T]): var T 256 +nim items iterators.html#items.i,string iterator items(a: string): char 265 +nim mitems iterators.html#mitems.i,string iterator mitems(a: var string): var char 274 +nim fields iterators.html#fields.i,T iterator fields[T: tuple | object](x: T): RootObj 284 +nim fields iterators.html#fields.i,S,T iterator fields[S: tuple | object; T: tuple | object](x: S; y: T): tuple[key: string,\n val: RootObj] 296 +nim fieldPairs iterators.html#fieldPairs.i,T iterator fieldPairs[T: tuple | object](x: T): tuple[key: string, val: RootObj] 309 +nim fieldPairs iterators.html#fieldPairs.i,S,T iterator fieldPairs[S: tuple | object; T: tuple | object](x: S; y: T): tuple[key: string,\n a, b: RootObj] 337 +nimgrp items iterators.html#items-iterators-all iterator 16 +nimgrp mpairs iterators.html#mpairs-iterators-all iterator 153 +nimgrp mitems iterators.html#mitems-iterators-all iterator 33 +nimgrp fieldpairs iterators.html#fieldPairs-iterators-all iterator 309 +nimgrp pairs iterators.html#pairs-iterators-all iterator 146 +nimgrp fields iterators.html#fields-iterators-all iterator 284 diff --git a/jsbigints.html b/jsbigints.html new file mode 100644 index 0000000000000..377c56c157073 --- /dev/null +++ b/jsbigints.html @@ -0,0 +1,846 @@ + + + + + + + +std/jsbigints + + + + + + + + + + + + + + + + +
+
+

std/jsbigints

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Arbitrary precision integers.

+ +

Example:

+
import std/jsbigints
+block:
+  let big1: JsBigInt = big"2147483647"
+  let big2: JsBigInt = big"666"
+  doAssert JsBigInt isnot int
+  doAssert big1 != big2
+  doAssert big1 > big2
+  doAssert big1 >= big2
+  doAssert big2 < big1
+  doAssert big2 <= big1
+  doAssert not(big1 == big2)
+  let z = JsBigInt.default
+  doAssert $z == "0n"
+block:
+  var a: seq[JsBigInt]
+  a.setLen 2
+  doAssert a == @[big"0", big"0"]
+  doAssert a[^1] == big"0"
+  var b: JsBigInt
+  doAssert b == big"0"
+  doAssert b == JsBigInt.default

+
+

Imports

+
+ assertions +
+
+
+

Types

+
+
+
JsBigInt = distinct JsBigIntImpl
+
+ + Arbitrary precision integer for JavaScript target. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `$`(this: JsBigInt): string {....raises: [], tags: [], forbids: [].}
+
+ + Returns a string representation of JsBigInt. +

Example:

+
doAssert $big"1024" == "1024n"
+ Source   +Edit   + +
+
+ +
+
+
+
func `'big`(num: cstring): JsBigInt {.importjs: "BigInt(#)", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + Constructor for JsBigInt. +

Example:

+
doAssert -1'big == 1'big - 2'big
+# supports decimal, binary, octal, hex:
+doAssert -12'big == big"-12"
+doAssert 12'big == 12.big
+doAssert 0b101'big == 0b101.big
+doAssert 0o701'big == 0o701.big
+doAssert 0xdeadbeaf'big == 0xdeadbeaf.big
+doAssert 0xffffffffffffffff'big == (1'big shl 64'big) - 1'big
+doAssert not compiles(static(12'big))
+ Source   +Edit   + +
+
+ +
+
+
+
func `*`(x, y: JsBigInt): JsBigInt {.importjs: "(# $1 #)", ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + +

Example:

+
doAssert (big"42" * big"9") == big"378"
+ Source   +Edit   + +
+
+ +
+
+
+
func `**`(x, y: JsBigInt): JsBigInt {.importjs: "((#) $1 #)", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + +

Example:

+
doAssert big"2" ** big"64" == big"18446744073709551616"
+doAssert big"-2" ** big"3" == big"-8"
+doAssert -big"2" ** big"2" == big"4" # parsed as: (-2n) ** 2n
+doAssert big"0" ** big"0" == big"1" # edge case
+var ok = false
+try: discard big"2" ** big"-1" # raises foreign `RangeError`
+except: ok = true
+doAssert ok
+ Source   +Edit   + +
+
+ +
+
+
+
func `*=`(x: var JsBigInt; y: JsBigInt) {.importjs: "([#][0][0] $1 #)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + +

Example:

+
var big1: JsBigInt = big"2"
+big1 *= big"4"
+doAssert big1 == big"8"
+ Source   +Edit   + +
+
+ +
+
+
+
proc `+`(_: JsBigInt): JsBigInt {.error: "See https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs".}
+
+ + Do NOT use. https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs + Source   +Edit   + +
+
+
+
func `+`(x, y: JsBigInt): JsBigInt {.importjs: "(# $1 #)", ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + +

Example:

+
doAssert (big"9" + big"1") == big"10"
+ Source   +Edit   + +
+
+ +
+
+
+
func `+=`(x: var JsBigInt; y: JsBigInt) {.importjs: "([#][0][0] $1 #)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + +

Example:

+
var big1: JsBigInt = big"1"
+big1 += big"2"
+doAssert big1 == big"3"
+ Source   +Edit   + +
+
+ +
+
+
+
func `-`(this: JsBigInt): JsBigInt {.importjs: "($1#)", ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + +

Example:

+
doAssert -(big"10101010101") == big"-10101010101"
+ Source   +Edit   + +
+
+
+
func `-`(x, y: JsBigInt): JsBigInt {.importjs: "(# $1 #)", ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + +

Example:

+
doAssert (big"9" - big"1") == big"8"
+ Source   +Edit   + +
+
+ +
+
+
+
func `-=`(x: var JsBigInt; y: JsBigInt) {.importjs: "([#][0][0] $1 #)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + +

Example:

+
var big1: JsBigInt = big"1"
+big1 -= big"2"
+doAssert big1 == big"-1"
+ Source   +Edit   + +
+
+ +
+
+
+
func `/=`(x: var JsBigInt; y: JsBigInt) {.importjs: "([#][0][0] $1 #)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Same as x = x div y. +

Example:

+
var big1: JsBigInt = big"11"
+big1 /= big"2"
+doAssert big1 == big"5"
+ Source   +Edit   + +
+
+ +
+
+
+
func `<`(x, y: JsBigInt): bool {.importjs: "(# $1 #)", ...raises: [], tags: [],
+                                 forbids: [].}
+
+ + +

Example:

+
doAssert big"2" < big"9"
+ Source   +Edit   + +
+
+ +
+
+
+
func `<=`(x, y: JsBigInt): bool {.importjs: "(# $1 #)", ...raises: [], tags: [],
+                                  forbids: [].}
+
+ + +

Example:

+
doAssert big"1" <= big"5"
+ Source   +Edit   + +
+
+ +
+
+
+
func `==`(x, y: JsBigInt): bool {.importjs: "(# == #)", ...raises: [], tags: [],
+                                  forbids: [].}
+
+ + +

Example:

+
doAssert big"42" == big"42"
+ Source   +Edit   + +
+
+ +
+
+
+
func `and`(x, y: JsBigInt): JsBigInt {.importjs: "(# & #)", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + +

Example:

+
doAssert (big"555" and big"2") == big"2"
+ Source   +Edit   + +
+
+ +
+
+
+
func big(integer: cstring): JsBigInt {.importjs: "BigInt(#)", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + Alias for 'big + Source   +Edit   + +
+
+
+
func big(integer: SomeInteger): JsBigInt {.importjs: "BigInt(#)", ...raises: [],
+    tags: [], forbids: [].}
+
+ + Constructor for JsBigInt. +

Example:

+
doAssert big(1234567890) == big"1234567890"
+doAssert 0b1111100111.big == 0o1747.big and 0o1747.big == 999.big
+ Source   +Edit   + +
+
+ +
+
+
+
func dec(this: var JsBigInt) {.importjs: "(--[#][0][0])", ...raises: [], tags: [],
+                               forbids: [].}
+
+ + +

Example:

+
var big1: JsBigInt = big"2"
+dec big1
+doAssert big1 == big"1"
+ Source   +Edit   + +
+
+
+
func dec(this: var JsBigInt; amount: JsBigInt) {.importjs: "([#][0][0] -= #)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + +

Example:

+
var big1: JsBigInt = big"1"
+dec big1, big"2"
+doAssert big1 == big"-1"
+ Source   +Edit   + +
+
+ +
+
+
+
func `div`(x, y: JsBigInt): JsBigInt {.importjs: "(# / #)", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + Same as div but for JsBigInt(uses JavaScript BigInt() / BigInt()). +

Example:

+
doAssert big"13" div big"3" == big"4"
+doAssert big"-13" div big"3" == big"-4"
+doAssert big"13" div big"-3" == big"-4"
+doAssert big"-13" div big"-3" == big"4"
+ Source   +Edit   + +
+
+ +
+
+
+
proc high(_: typedesc[JsBigInt]): JsBigInt {.
+    error: "Arbitrary precision integers do not have a known high.".}
+
+ + Do NOT use. + Source   +Edit   + +
+
+ +
+
+
+
func inc(this: var JsBigInt) {.importjs: "(++[#][0][0])", ...raises: [], tags: [],
+                               forbids: [].}
+
+ + +

Example:

+
var big1: JsBigInt = big"1"
+inc big1
+doAssert big1 == big"2"
+ Source   +Edit   + +
+
+
+
func inc(this: var JsBigInt; amount: JsBigInt) {.importjs: "([#][0][0] += #)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + +

Example:

+
var big1: JsBigInt = big"1"
+inc big1, big"2"
+doAssert big1 == big"3"
+ Source   +Edit   + +
+
+ +
+
+
+
proc low(_: typedesc[JsBigInt]): JsBigInt {.
+    error: "Arbitrary precision integers do not have a known low.".}
+
+ + Do NOT use. + Source   +Edit   + +
+
+ +
+
+
+
func `mod`(x, y: JsBigInt): JsBigInt {.importjs: "(# % #)", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + Same as mod but for JsBigInt (uses JavaScript BigInt() % BigInt()). +

Example:

+
doAssert big"13" mod big"3" == big"1"
+doAssert big"-13" mod big"3" == big"-1"
+doAssert big"13" mod big"-3" == big"1"
+doAssert big"-13" mod big"-3" == big"-1"
+ Source   +Edit   + +
+
+ +
+
+
+
func `or`(x, y: JsBigInt): JsBigInt {.importjs: "(# | #)", ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + +

Example:

+
doAssert (big"555" or big"2") == big"555"
+ Source   +Edit   + +
+
+ +
+
+
+
func `shl`(a, b: JsBigInt): JsBigInt {.importjs: "(# << #)", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + +

Example:

+
doAssert (big"999" shl big"2") == big"3996"
+ Source   +Edit   + +
+
+ +
+
+
+
func `shr`(a, b: JsBigInt): JsBigInt {.importjs: "(# >> #)", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + +

Example:

+
doAssert (big"999" shr big"2") == big"249"
+ Source   +Edit   + +
+
+ +
+
+
+
func toCstring(this: JsBigInt): cstring {.importjs: "#.toString()", ...raises: [],
+    tags: [], forbids: [].}
+
+ + Converts from JsBigInt to cstring representation. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/toString + Source   +Edit   + +
+
+
+
func toCstring(this: JsBigInt; radix: 2 .. 36): cstring {.
+    importjs: "#.toString(#)", ...raises: [], tags: [], forbids: [].}
+
+ + Converts from JsBigInt to cstring representation.
  • radix Base to use for representing numeric values.
  • +
+

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/toString

+ +

Example:

+
doAssert big"2147483647".toCstring(2) == "1111111111111111111111111111111".cstring
+ Source   +Edit   + +
+
+ +
+
+
+
func toNumber(this: JsBigInt): int {.importjs: "Number(#)", ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + Does not do any bounds check and may or may not return an inexact representation. +

Example:

+
doAssert toNumber(big"2147483647") == 2147483647.int
+ Source   +Edit   + +
+
+ +
+
+
+
func wrapToInt(this: JsBigInt; bits: Natural): JsBigInt {.
+    importjs: "(() => { const i = #, b = #; return BigInt.asIntN(b, i) })()",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Wraps this to a signed JsBigInt of bits bits in -2 ^ (bits - 1) .. 2 ^ (bits - 1) - 1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/asIntN +

Example:

+
doAssert (big("3") + big("2") ** big("66")).wrapToInt(13) == big("3")
+ Source   +Edit   + +
+
+ +
+
+
+
func wrapToUint(this: JsBigInt; bits: Natural): JsBigInt {.
+    importjs: "(() => { const i = #, b = #; return BigInt.asUintN(b, i) })()",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Wraps this to an unsigned JsBigInt of bits bits in 0 .. 2 ^ bits - 1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/asUintN +

Example:

+
doAssert (big("3") + big("2") ** big("66")).wrapToUint(66) == big("3")
+ Source   +Edit   + +
+
+ +
+
+
+
func `xor`(x, y: JsBigInt): JsBigInt {.importjs: "(# ^ #)", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + +

Example:

+
doAssert (big"555" xor big"2") == big"553"
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/jsbigints.idx b/jsbigints.idx new file mode 100644 index 0000000000000..dca3eb458f893 --- /dev/null +++ b/jsbigints.idx @@ -0,0 +1,43 @@ +nimTitle jsbigints jsbigints.html module std/jsbigints 0 +nim JsBigInt jsbigints.html#JsBigInt type JsBigInt 10 +nim big jsbigints.html#big,SomeInteger proc big(integer: SomeInteger): JsBigInt 12 +nim `'big` jsbigints.html#'big,cstring proc `'big`(num: cstring): JsBigInt 19 +nim big jsbigints.html#big,cstring proc big(integer: cstring): JsBigInt 33 +nim toCstring jsbigints.html#toCstring,JsBigInt, proc toCstring(this: JsBigInt; radix: 2 .. 36): cstring 37 +nim toCstring jsbigints.html#toCstring,JsBigInt proc toCstring(this: JsBigInt): cstring 44 +nim `$` jsbigints.html#$,JsBigInt proc `$`(this: JsBigInt): string 48 +nim wrapToInt jsbigints.html#wrapToInt,JsBigInt,Natural proc wrapToInt(this: JsBigInt; bits: Natural): JsBigInt 53 +nim wrapToUint jsbigints.html#wrapToUint,JsBigInt,Natural proc wrapToUint(this: JsBigInt; bits: Natural): JsBigInt 60 +nim toNumber jsbigints.html#toNumber,JsBigInt proc toNumber(this: JsBigInt): int 67 +nim `+` jsbigints.html#+,JsBigInt,JsBigInt proc `+`(x, y: JsBigInt): JsBigInt 72 +nim `-` jsbigints.html#-,JsBigInt,JsBigInt proc `-`(x, y: JsBigInt): JsBigInt 76 +nim `*` jsbigints.html#*,JsBigInt,JsBigInt proc `*`(x, y: JsBigInt): JsBigInt 80 +nim `div` jsbigints.html#div,JsBigInt,JsBigInt proc `div`(x, y: JsBigInt): JsBigInt 84 +nim `mod` jsbigints.html#mod,JsBigInt,JsBigInt proc `mod`(x, y: JsBigInt): JsBigInt 92 +nim `<` jsbigints.html#<,JsBigInt,JsBigInt proc `<`(x, y: JsBigInt): bool 100 +nim `<=` jsbigints.html#<=,JsBigInt,JsBigInt proc `<=`(x, y: JsBigInt): bool 104 +nim `==` jsbigints.html#==,JsBigInt,JsBigInt proc `==`(x, y: JsBigInt): bool 108 +nim `**` jsbigints.html#**,JsBigInt,JsBigInt proc `**`(x, y: JsBigInt): JsBigInt 112 +nim `and` jsbigints.html#and,JsBigInt,JsBigInt proc `and`(x, y: JsBigInt): JsBigInt 124 +nim `or` jsbigints.html#or,JsBigInt,JsBigInt proc `or`(x, y: JsBigInt): JsBigInt 128 +nim `xor` jsbigints.html#xor,JsBigInt,JsBigInt proc `xor`(x, y: JsBigInt): JsBigInt 132 +nim `shl` jsbigints.html#shl,JsBigInt,JsBigInt proc `shl`(a, b: JsBigInt): JsBigInt 136 +nim `shr` jsbigints.html#shr,JsBigInt,JsBigInt proc `shr`(a, b: JsBigInt): JsBigInt 140 +nim `-` jsbigints.html#-,JsBigInt proc `-`(this: JsBigInt): JsBigInt 144 +nim inc jsbigints.html#inc,JsBigInt proc inc(this: var JsBigInt) 148 +nim dec jsbigints.html#dec,JsBigInt proc dec(this: var JsBigInt) 154 +nim inc jsbigints.html#inc,JsBigInt,JsBigInt proc inc(this: var JsBigInt; amount: JsBigInt) 160 +nim dec jsbigints.html#dec,JsBigInt,JsBigInt proc dec(this: var JsBigInt; amount: JsBigInt) 166 +nim `+=` jsbigints.html#+=,JsBigInt,JsBigInt proc `+=`(x: var JsBigInt; y: JsBigInt) 172 +nim `-=` jsbigints.html#-=,JsBigInt,JsBigInt proc `-=`(x: var JsBigInt; y: JsBigInt) 178 +nim `*=` jsbigints.html#*=,JsBigInt,JsBigInt proc `*=`(x: var JsBigInt; y: JsBigInt) 184 +nim `/=` jsbigints.html#/=,JsBigInt,JsBigInt proc `/=`(x: var JsBigInt; y: JsBigInt) 190 +nim `+` jsbigints.html#+,JsBigInt proc `+`(_: JsBigInt): JsBigInt 197 +nim low jsbigints.html#low,typedesc[JsBigInt] proc low(_: typedesc[JsBigInt]): JsBigInt 201 +nim high jsbigints.html#high,typedesc[JsBigInt] proc high(_: typedesc[JsBigInt]): JsBigInt 204 +nimgrp + jsbigints.html#+-procs-all proc 72 +nimgrp - jsbigints.html#--procs-all proc 76 +nimgrp big jsbigints.html#big-procs-all proc 12 +nimgrp dec jsbigints.html#dec-procs-all proc 154 +nimgrp inc jsbigints.html#inc-procs-all proc 148 +nimgrp tocstring jsbigints.html#toCstring-procs-all proc 37 diff --git a/jsconsole.html b/jsconsole.html new file mode 100644 index 0000000000000..519d489b57c4f --- /dev/null +++ b/jsconsole.html @@ -0,0 +1,555 @@ + + + + + + + +std/jsconsole + + + + + + + + + + + + + + + + +
+
+

std/jsconsole

+
+ +
+ Source   +Edit   + +
+ +

Wrapper for the console object for the JavaScript backend. +

Styled Messages

CSS-styled messages in the browser are useful for debugging purposes. To use them, prefix the message with one or more %c, and provide the CSS style as the last argument. The amount of %c's must match the amount of CSS-styled strings.

+ +

Example: cmd: -r:off

+
import std/jsconsole
+console.log "%c My Debug Message", "color: red" # Notice the "%c"
+console.log "%c My Debug %c Message", "color: red", "font-size: 2em"

+ +
+

Types

+
+
+
Console = ref object of JsRoot
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
console {.importc, nodecl.}: Console
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc clear(console: Console) {.importcpp, varargs, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + https://developer.mozilla.org/docs/Web/API/Console/clear + Source   +Edit   + +
+
+ +
+
+
+
proc count(console: Console; label = "".cstring) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/docs/Web/API/Console/count + Source   +Edit   + +
+
+ +
+
+
+
proc countReset(console: Console; label = "".cstring) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/docs/Web/API/Console/countReset + Source   +Edit   + +
+
+ +
+
+
+
proc debug(console: Console) {.importcpp, varargs, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + https://developer.mozilla.org/docs/Web/API/Console/debug + Source   +Edit   + +
+
+ +
+
+
+
func dir(console: Console; obj: auto) {.importcpp, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Console/dir + Source   +Edit   + +
+
+ +
+
+
+
func dirxml(console: Console; obj: auto) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Console/dirxml + Source   +Edit   + +
+
+ +
+
+
+
proc error(console: Console) {.importcpp, varargs, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + https://developer.mozilla.org/docs/Web/API/Console/error + Source   +Edit   + +
+
+ +
+
+
+
proc group(console: Console; label = "".cstring) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/docs/Web/API/Console/group + Source   +Edit   + +
+
+ +
+
+
+
proc groupCollapsed(console: Console; label = "".cstring) {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Console/groupCollapsed + Source   +Edit   + +
+
+ +
+
+
+
proc groupEnd(console: Console) {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/docs/Web/API/Console/groupEnd + Source   +Edit   + +
+
+ +
+
+
+
proc info(console: Console) {.importcpp, varargs, ...raises: [], tags: [],
+                              forbids: [].}
+
+ + https://developer.mozilla.org/docs/Web/API/Console/info + Source   +Edit   + +
+
+ +
+
+
+
proc log(console: Console) {.importcpp, varargs, ...raises: [], tags: [],
+                             forbids: [].}
+
+ + https://developer.mozilla.org/docs/Web/API/Console/log + Source   +Edit   + +
+
+ +
+
+
+
proc table(console: Console) {.importcpp, varargs, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + https://developer.mozilla.org/docs/Web/API/Console/table + Source   +Edit   + +
+
+ +
+
+
+
proc time(console: Console; label = "".cstring) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/docs/Web/API/Console/time + Source   +Edit   + +
+
+ +
+
+
+
proc timeEnd(console: Console; label = "".cstring) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/docs/Web/API/Console/timeEnd + Source   +Edit   + +
+
+ +
+
+
+
proc timeLog(console: Console; label = "".cstring) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/docs/Web/API/Console/timeLog + Source   +Edit   + +
+
+ +
+
+
+
func timeStamp(console: Console; label: cstring) {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ +

https://developer.mozilla.org/en-US/docs/Web/API/Console/timeStamp

+

..warning:: non-standard

+ + Source   +Edit   + +
+
+ +
+
+
+
proc trace(console: Console) {.importcpp, varargs, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + https://developer.mozilla.org/docs/Web/API/Console/trace + Source   +Edit   + +
+
+ +
+
+
+
proc warn(console: Console) {.importcpp, varargs, ...raises: [], tags: [],
+                              forbids: [].}
+
+ + https://developer.mozilla.org/docs/Web/API/Console/warn + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template exception(console: Console; args: varargs[untyped])
+
+ + Alias for console.error(). + Source   +Edit   + +
+
+ +
+
+
+
template jsAssert(console: Console; assertion)
+
+ + JavaScript console.assert, for NodeJS this prints to stderr, assert failure just prints to console and do not quit the program, this is not meant to be better or even equal than normal assertions, is just for when you need faster performance and assertions, otherwise use the normal assertions for better user experience. https://developer.mozilla.org/en-US/docs/Web/API/Console/assert +

Example:

+
console.jsAssert(42 == 42) # OK
+console.jsAssert(42 != 42) # Fail, prints "Assertion failed" and continues
+console.jsAssert('`' == '\n' and '\t' == '\0') # Message correctly formatted
+assert 42 == 42  # Normal assertions keep working
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/jsconsole.idx b/jsconsole.idx new file mode 100644 index 0000000000000..40149cb87a454 --- /dev/null +++ b/jsconsole.idx @@ -0,0 +1,25 @@ +nimTitle jsconsole jsconsole.html module std/jsconsole 0 +nim Console jsconsole.html#Console type Console 30 +nim log jsconsole.html#log,Console proc log(console: Console) 32 +nim debug jsconsole.html#debug,Console proc debug(console: Console) 35 +nim info jsconsole.html#info,Console proc info(console: Console) 38 +nim error jsconsole.html#error,Console proc error(console: Console) 41 +nim exception jsconsole.html#exception.t,Console,varargs[untyped] template exception(console: Console; args: varargs[untyped]) 44 +nim trace jsconsole.html#trace,Console proc trace(console: Console) 48 +nim warn jsconsole.html#warn,Console proc warn(console: Console) 51 +nim clear jsconsole.html#clear,Console proc clear(console: Console) 54 +nim count jsconsole.html#count,Console proc count(console: Console; label = "".cstring) 57 +nim countReset jsconsole.html#countReset,Console proc countReset(console: Console; label = "".cstring) 60 +nim group jsconsole.html#group,Console proc group(console: Console; label = "".cstring) 63 +nim groupCollapsed jsconsole.html#groupCollapsed,Console proc groupCollapsed(console: Console; label = "".cstring) 66 +nim groupEnd jsconsole.html#groupEnd,Console proc groupEnd(console: Console) 69 +nim time jsconsole.html#time,Console proc time(console: Console; label = "".cstring) 72 +nim timeEnd jsconsole.html#timeEnd,Console proc timeEnd(console: Console; label = "".cstring) 75 +nim timeLog jsconsole.html#timeLog,Console proc timeLog(console: Console; label = "".cstring) 78 +nim table jsconsole.html#table,Console proc table(console: Console) 81 +nim jsAssert jsconsole.html#jsAssert.t,Console, template jsAssert(console: Console; assertion) 94 +nim dir jsconsole.html#dir,Console,auto proc dir(console: Console; obj: auto) 113 +nim dirxml jsconsole.html#dirxml,Console,auto proc dirxml(console: Console; obj: auto) 116 +nim timeStamp jsconsole.html#timeStamp,Console,cstring proc timeStamp(console: Console; label: cstring) 119 +nim console jsconsole.html#console_2 var console 125 +heading Styled Messages jsconsole.html#styled-messages Styled Messages 0 diff --git a/jscore.html b/jscore.html new file mode 100644 index 0000000000000..641a2cb423959 --- /dev/null +++ b/jscore.html @@ -0,0 +1,1525 @@ + + + + + + + +std/jscore + + + + + + + + + + + + + + + + +
+
+

std/jscore

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module wraps core JavaScript functions.

+

Unless your application has very specific requirements and solely targets JavaScript, you should be using the relevant functions in the math, json, and times stdlib modules instead.

+

+
+

Imports

+
+ since, jsutils +
+
+
+

Types

+
+
+
DateLib = ref object
+
+ + + Source   +Edit   + +
+
+
+
DateTime = ref object
+
+ + + Source   +Edit   + +
+
+
+
JsonLib = ref object
+
+ + + Source   +Edit   + +
+
+
+
MathLib = ref object
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
Date {.importc, nodecl.}: DateLib
+
+ + + Source   +Edit   + +
+
+
+
JSON {.importc, nodecl.}: JsonLib
+
+ + + Source   +Edit   + +
+
+
+
Math {.importc, nodecl.}: MathLib
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc abs(m: MathLib; a: SomeNumber): SomeNumber {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc acos(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc acosh(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc asin(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc asinh(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc atan(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc atan2(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc atanh(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cbrt(m: MathLib; f: SomeFloat): SomeFloat {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ceil(m: MathLib; f: SomeFloat): SomeFloat {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clz32(m: MathLib; f: SomeInteger): int {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func copyWithin[T](self: openArray[T]; target, start, ends: int): seq[T] {.
+    importjs: "#.copyWithin(#, #, #)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin copyWithin uses shallow copy. +

Example:

+
assert ['a', 'b', 'c', 'd', 'e'].copyWithin(0, 3, 4) == @['d', 'b', 'c', 'd', 'e']
+assert ['a', 'b', 'c', 'd', 'e'].copyWithin(1, 3) == @['a', 'd', 'e', 'd', 'e']
+assert [1, 2, 3, 4, 5].copyWithin(-2) == @[1, 2, 3, 1, 2]
+assert [1, 2, 3, 4, 5].copyWithin(0, 3) == @[4, 5, 3, 4, 5]
+assert [1, 2, 3, 4, 5].copyWithin(0, 3, 4) == @[4, 2, 3, 4, 5]
+assert [1, 2, 3, 4, 5].copyWithin(-2, -3, -1) == @[1, 2, 3, 3, 4]
+ Source   +Edit   + +
+
+
+
func copyWithin[T](self: openArray[T]; target, start: int): seq[T] {.
+    importjs: "#.copyWithin(#, #)", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func copyWithin[T](self: openArray[T]; target: int): seq[T] {.
+    importjs: "#.copyWithin(#)", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cos(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cosh(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func debugger() {.importjs: "debugger@", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger + Source   +Edit   + +
+
+ +
+
+
+
proc exp(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc expm1(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc floor(m: MathLib; f: SomeFloat): int {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fround(m: MathLib; f: SomeFloat): float32 {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getDay(d: DateTime): int {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getFullYear(d: DateTime): int {.importcpp, ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getHours(d: DateTime): int {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getMilliseconds(d: DateTime): int {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getMinutes(d: DateTime): int {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getMonth(d: DateTime): int {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getSeconds(d: DateTime): int {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getTime(d: DateTime): int {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getTimezoneOffset(d: DateTime): int {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getUTCDate(d: DateTime): int {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getUTCDay(d: DateTime): int {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getUTCFullYear(d: DateTime): int {.importcpp, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getUTCHours(d: DateTime): int {.importcpp, ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getUTCMilliseconds(d: DateTime): int {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getUTCMinutes(d: DateTime): int {.importcpp, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getUTCMonth(d: DateTime): int {.importcpp, ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getUTCSeconds(d: DateTime): int {.importcpp, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getYear(d: DateTime): int {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hypot(m: MathLib; args: varargs[distinct SomeNumber]): float {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc imul(m: MathLib; a, b: int32): int32 {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc log(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc log1p(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc log2(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc log10(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc max(m: MathLib; a, b: SomeNumber): SomeNumber {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc min[T: SomeNumber | JsRoot](m: MathLib; a, b: T): T {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newDate(): DateTime {.importcpp: "new Date()", ...raises: [], tags: [],
+                           forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newDate(date: int | string): DateTime {.importcpp: "new Date(#)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newDate(date: int64): DateTime {.importcpp: "new Date(Number(#))",
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newDate(year, month, day, hours, minutes, seconds, milliseconds: int): DateTime {.
+    importcpp: "new Date(#,#,#,#,#,#,#)", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc now(d: DateLib): int {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc parse(d: DateLib; s: cstring): int {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc parse(l: JsonLib; s: cstring): JsRoot {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pow(m: MathLib; a, b: distinct SomeNumber): float {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func queueMicrotask(function: proc) {.importjs: "$1(#)", ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + +

Example: cmd: -r:off

+
queueMicrotask(proc() = echo "Microtask")
+ Source   +Edit   + +
+
+ +
+
+
+
proc random(m: MathLib): float {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc round(m: MathLib; f: SomeFloat): int {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setFullYear(d: DateTime; year: int) {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func shift[T](self: seq[T]): T {.importjs: "#.$1()", ...raises: [], tags: [],
+                                 forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift +

Example:

+
var arrai = @[1, 2, 3]
+assert arrai.shift() == 1
+assert arrai == @[2, 3]
+ Source   +Edit   + +
+
+ +
+
+
+
proc sign(m: MathLib; f: SomeNumber): int {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sin(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sinh(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sqrt(m: MathLib; f: SomeFloat): SomeFloat {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc stringify(l: JsonLib; s: JsRoot): cstring {.importcpp, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc tan(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc tanh(m: MathLib; a: SomeNumber): float {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func toDateString(d: DateTime): cstring {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func toISOString(d: DateTime): cstring {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func toJSON(d: DateTime): cstring {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toString(d: DateTime): cstring {.importcpp, ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func toTimeString(d: DateTime): cstring {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func toUTCString(d: DateTime): cstring {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc trunc(m: MathLib; f: SomeFloat): int {.importcpp, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc UTC(d: DateLib): int {.importcpp, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/jscore.idx b/jscore.idx new file mode 100644 index 0000000000000..e7aeb24eb839f --- /dev/null +++ b/jscore.idx @@ -0,0 +1,86 @@ +nimTitle jscore jscore.html module std/jscore 0 +nim MathLib jscore.html#MathLib type MathLib 22 +nim JsonLib jscore.html#JsonLib type JsonLib 23 +nim DateLib jscore.html#DateLib type DateLib 24 +nim DateTime jscore.html#DateTime type DateTime 25 +nim Math jscore.html#Math var Math 28 +nim Date jscore.html#Date var Date 29 +nim JSON jscore.html#JSON var JSON 30 +nim abs jscore.html#abs,MathLib,SomeNumber proc abs(m: MathLib; a: SomeNumber): SomeNumber 33 +nim acos jscore.html#acos,MathLib,SomeNumber proc acos(m: MathLib; a: SomeNumber): float 34 +nim acosh jscore.html#acosh,MathLib,SomeNumber proc acosh(m: MathLib; a: SomeNumber): float 35 +nim asin jscore.html#asin,MathLib,SomeNumber proc asin(m: MathLib; a: SomeNumber): float 36 +nim asinh jscore.html#asinh,MathLib,SomeNumber proc asinh(m: MathLib; a: SomeNumber): float 37 +nim atan jscore.html#atan,MathLib,SomeNumber proc atan(m: MathLib; a: SomeNumber): float 38 +nim atan2 jscore.html#atan2,MathLib,SomeNumber proc atan2(m: MathLib; a: SomeNumber): float 39 +nim atanh jscore.html#atanh,MathLib,SomeNumber proc atanh(m: MathLib; a: SomeNumber): float 40 +nim cbrt jscore.html#cbrt,MathLib,SomeFloat proc cbrt(m: MathLib; f: SomeFloat): SomeFloat 41 +nim ceil jscore.html#ceil,MathLib,SomeFloat proc ceil(m: MathLib; f: SomeFloat): SomeFloat 42 +nim clz32 jscore.html#clz32,MathLib,SomeInteger proc clz32(m: MathLib; f: SomeInteger): int 43 +nim cos jscore.html#cos,MathLib,SomeNumber proc cos(m: MathLib; a: SomeNumber): float 44 +nim cosh jscore.html#cosh,MathLib,SomeNumber proc cosh(m: MathLib; a: SomeNumber): float 45 +nim exp jscore.html#exp,MathLib,SomeNumber proc exp(m: MathLib; a: SomeNumber): float 46 +nim expm1 jscore.html#expm1,MathLib,SomeNumber proc expm1(m: MathLib; a: SomeNumber): float 47 +nim floor jscore.html#floor,MathLib,SomeFloat proc floor(m: MathLib; f: SomeFloat): int 48 +nim fround jscore.html#fround,MathLib,SomeFloat proc fround(m: MathLib; f: SomeFloat): float32 49 +nim hypot jscore.html#hypot,MathLib,varargs[] proc hypot(m: MathLib; args: varargs[distinct SomeNumber]): float 50 +nim imul jscore.html#imul,MathLib,int32,int32 proc imul(m: MathLib; a, b: int32): int32 51 +nim log jscore.html#log,MathLib,SomeNumber proc log(m: MathLib; a: SomeNumber): float 52 +nim log10 jscore.html#log10,MathLib,SomeNumber proc log10(m: MathLib; a: SomeNumber): float 53 +nim log1p jscore.html#log1p,MathLib,SomeNumber proc log1p(m: MathLib; a: SomeNumber): float 54 +nim log2 jscore.html#log2,MathLib,SomeNumber proc log2(m: MathLib; a: SomeNumber): float 55 +nim max jscore.html#max,MathLib,SomeNumber,SomeNumber proc max(m: MathLib; a, b: SomeNumber): SomeNumber 56 +nim min jscore.html#min,MathLib,T,T proc min[T: SomeNumber | JsRoot](m: MathLib; a, b: T): T 57 +nim pow jscore.html#pow,MathLib,, proc pow(m: MathLib; a, b: distinct SomeNumber): float 58 +nim random jscore.html#random,MathLib proc random(m: MathLib): float 59 +nim round jscore.html#round,MathLib,SomeFloat proc round(m: MathLib; f: SomeFloat): int 60 +nim sign jscore.html#sign,MathLib,SomeNumber proc sign(m: MathLib; f: SomeNumber): int 61 +nim sin jscore.html#sin,MathLib,SomeNumber proc sin(m: MathLib; a: SomeNumber): float 62 +nim sinh jscore.html#sinh,MathLib,SomeNumber proc sinh(m: MathLib; a: SomeNumber): float 63 +nim sqrt jscore.html#sqrt,MathLib,SomeFloat proc sqrt(m: MathLib; f: SomeFloat): SomeFloat 64 +nim tan jscore.html#tan,MathLib,SomeNumber proc tan(m: MathLib; a: SomeNumber): float 65 +nim tanh jscore.html#tanh,MathLib,SomeNumber proc tanh(m: MathLib; a: SomeNumber): float 66 +nim trunc jscore.html#trunc,MathLib,SomeFloat proc trunc(m: MathLib; f: SomeFloat): int 67 +nim now jscore.html#now,DateLib proc now(d: DateLib): int 70 +nim UTC jscore.html#UTC,DateLib proc UTC(d: DateLib): int 71 +nim parse jscore.html#parse,DateLib,cstring proc parse(d: DateLib; s: cstring): int 72 +nim newDate jscore.html#newDate proc newDate(): DateTime 74 +nim newDate jscore.html#newDate_2 proc newDate(date: int | string): DateTime 77 +nim newDate jscore.html#newDate,int64 proc newDate(date: int64): DateTime 84 +nim newDate jscore.html#newDate,int,int,int,int,int,int,int proc newDate(year, month, day, hours, minutes, seconds, milliseconds: int): DateTime 87 +nim getDay jscore.html#getDay,DateTime proc getDay(d: DateTime): int 91 +nim getFullYear jscore.html#getFullYear,DateTime proc getFullYear(d: DateTime): int 92 +nim getHours jscore.html#getHours,DateTime proc getHours(d: DateTime): int 93 +nim getMilliseconds jscore.html#getMilliseconds,DateTime proc getMilliseconds(d: DateTime): int 94 +nim getMinutes jscore.html#getMinutes,DateTime proc getMinutes(d: DateTime): int 95 +nim getMonth jscore.html#getMonth,DateTime proc getMonth(d: DateTime): int 96 +nim getSeconds jscore.html#getSeconds,DateTime proc getSeconds(d: DateTime): int 97 +nim getTime jscore.html#getTime,DateTime proc getTime(d: DateTime): int 98 +nim getTimezoneOffset jscore.html#getTimezoneOffset,DateTime proc getTimezoneOffset(d: DateTime): int 99 +nim getUTCDate jscore.html#getUTCDate,DateTime proc getUTCDate(d: DateTime): int 100 +nim getUTCDay jscore.html#getUTCDay,DateTime proc getUTCDay(d: DateTime): int 101 +nim getUTCFullYear jscore.html#getUTCFullYear,DateTime proc getUTCFullYear(d: DateTime): int 102 +nim getUTCHours jscore.html#getUTCHours,DateTime proc getUTCHours(d: DateTime): int 103 +nim getUTCMilliseconds jscore.html#getUTCMilliseconds,DateTime proc getUTCMilliseconds(d: DateTime): int 104 +nim getUTCMinutes jscore.html#getUTCMinutes,DateTime proc getUTCMinutes(d: DateTime): int 105 +nim getUTCMonth jscore.html#getUTCMonth,DateTime proc getUTCMonth(d: DateTime): int 106 +nim getUTCSeconds jscore.html#getUTCSeconds,DateTime proc getUTCSeconds(d: DateTime): int 107 +nim getYear jscore.html#getYear,DateTime proc getYear(d: DateTime): int 108 +nim setFullYear jscore.html#setFullYear,DateTime,int proc setFullYear(d: DateTime; year: int) 110 +nim toDateString jscore.html#toDateString,DateTime proc toDateString(d: DateTime): cstring 112 +nim toISOString jscore.html#toISOString,DateTime proc toISOString(d: DateTime): cstring 113 +nim toJSON jscore.html#toJSON,DateTime proc toJSON(d: DateTime): cstring 114 +nim toString jscore.html#toString,DateTime proc toString(d: DateTime): cstring 115 +nim toTimeString jscore.html#toTimeString,DateTime proc toTimeString(d: DateTime): cstring 116 +nim toUTCString jscore.html#toUTCString,DateTime proc toUTCString(d: DateTime): cstring 117 +nim stringify jscore.html#stringify,JsonLib,JsRoot proc stringify(l: JsonLib; s: JsRoot): cstring 120 +nim parse jscore.html#parse,JsonLib,cstring proc parse(l: JsonLib; s: cstring): JsRoot 121 +nim debugger jscore.html#debugger proc debugger() 125 +nim copyWithin jscore.html#copyWithin,openArray[T],int proc copyWithin[T](self: openArray[T]; target: int): seq[T] 128 +nim copyWithin jscore.html#copyWithin,openArray[T],int,int proc copyWithin[T](self: openArray[T]; target, start: int): seq[T] 129 +nim copyWithin jscore.html#copyWithin,openArray[T],int,int,int proc copyWithin[T](self: openArray[T]; target, start, ends: int): seq[T] 130 +nim shift jscore.html#shift,seq[T] proc shift[T](self: seq[T]): T 143 +nim queueMicrotask jscore.html#queueMicrotask,proc proc queueMicrotask(function: proc) 150 +nimgrp newdate jscore.html#newDate-procs-all proc 74 +nimgrp parse jscore.html#parse-procs-all proc 72 +nimgrp copywithin jscore.html#copyWithin-procs-all proc 128 diff --git a/jsfetch.html b/jsfetch.html new file mode 100644 index 0000000000000..20637d3142d98 --- /dev/null +++ b/jsfetch.html @@ -0,0 +1,588 @@ + + + + + + + +std/jsfetch + + + + + + + + + + + + + + + + +
+
+

std/jsfetch

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+ +

Example: cmd: -r:off

+
import std/jsfetch
+import std/[asyncjs, jsconsole, jsformdata, jsheaders]
+from std/httpcore import HttpMethod
+from std/jsffi import JsObject
+from std/sugar import `=>`
+
+block:
+  let options0: FetchOptions = unsafeNewFetchOptions(
+    metod = "POST".cstring,
+    body = """{"key": "value"}""".cstring,
+    mode = "no-cors".cstring,
+    credentials = "omit".cstring,
+    cache = "no-cache".cstring,
+    referrerPolicy = "no-referrer".cstring,
+    keepalive = false,
+    redirect = "follow".cstring,
+    referrer = "client".cstring,
+    integrity = "".cstring,
+    headers = newHeaders()
+  )
+  assert options0.keepalive == false
+  assert options0.metod == "POST".cstring
+  assert options0.body == """{"key": "value"}""".cstring
+  assert options0.mode == "no-cors".cstring
+  assert options0.credentials == "omit".cstring
+  assert options0.cache == "no-cache".cstring
+  assert options0.referrerPolicy == "no-referrer".cstring
+  assert options0.redirect == "follow".cstring
+  assert options0.referrer == "client".cstring
+  assert options0.integrity == "".cstring
+  assert options0.headers.len == 0
+
+block:
+  let options1: FetchOptions = newFetchOptions(
+    metod =  HttpPost,
+    body = """{"key": "value"}""".cstring,
+    mode = fmNoCors,
+    credentials = fcOmit,
+    cache = fchNoCache,
+    referrerPolicy = frpNoReferrer,
+    keepalive = false,
+    redirect = frFollow,
+    referrer = "client".cstring,
+    integrity = "".cstring,
+    headers = newHeaders()
+  )
+  assert options1.keepalive == false
+  assert options1.metod == $HttpPost
+  assert options1.body == """{"key": "value"}""".cstring
+  assert options1.mode == $fmNoCors
+  assert options1.credentials == $fcOmit
+  assert options1.cache == $fchNoCache
+  assert options1.referrerPolicy == $frpNoReferrer
+  assert options1.redirect == $frFollow
+  assert options1.referrer == "client".cstring
+  assert options1.integrity == "".cstring
+  assert options1.headers.len == 0
+
+block:
+  let response: Response = newResponse(body = "-. .. --".cstring)
+  let request: Request = newRequest(url = "http://nim-lang.org".cstring)
+
+if not defined(nodejs):
+  block:
+    proc doFetch(): Future[Response] {.async.} =
+      fetch "https://httpbin.org/get".cstring
+
+    proc example() {.async.} =
+      let response: Response = await doFetch()
+      assert response.ok
+      assert response.status == 200.cint
+      assert response.headers is Headers
+      assert response.body is cstring
+
+    discard example()
+
+  block:
+    proc example2 {.async.} =
+      await fetch("https://api.github.com/users/torvalds".cstring)
+        .then((response: Response) => response.json())
+        .then((json: JsObject) => console.log(json))
+        .catch((err: Error) => console.log("Request Failed", err))
+
+    discard example2()

+ +
+

Types

+
+
+
FetchCaches = enum
+  fchDefault = "default", fchNoStore = "no-store", fchReload = "reload",
+  fchNoCache = "no-cache", fchForceCache = "force-cache"
+
+ + https://developer.mozilla.org/docs/Web/API/Request/cache + Source   +Edit   + +
+
+
+
FetchCredentials = enum
+  fcInclude = "include", fcSameOrigin = "same-origin", fcOmit = "omit"
+
+ + Credential options. See https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials + Source   +Edit   + +
+
+
+
FetchModes = enum
+  fmCors = "cors", fmNoCors = "no-cors", fmSameOrigin = "same-origin"
+
+ + Mode options. + Source   +Edit   + +
+
+
+
FetchOptions = ref object of JsRoot
+  keepalive*: bool
+  metod* {.importjs: "method".}: cstring
+  body*, integrity*, referrer*, mode*, credentials*, cache*, redirect*,
+  referrerPolicy*: cstring
+  headers*: Headers
+
+ + Options for Fetch API. + Source   +Edit   + +
+
+
+
FetchRedirects = enum
+  frFollow = "follow", frError = "error", frManual = "manual"
+
+ + Redirects options. + Source   +Edit   + +
+
+
+
FetchReferrerPolicies = enum
+  frpNoReferrer = "no-referrer",
+  frpNoReferrerWhenDowngrade = "no-referrer-when-downgrade",
+  frpOrigin = "origin", frpOriginWhenCrossOrigin = "origin-when-cross-origin",
+  frpUnsafeUrl = "unsafe-url"
+
+ + Referrer Policy options. + Source   +Edit   + +
+
+
+
Request = ref object of JsRoot
+  bodyUsed*, ok*, redirected*: bool
+  typ* {.importjs: "type".}: cstring
+  url*, statusText*: cstring
+  status*: cint
+  headers*: Headers
+  body*: cstring
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Request + Source   +Edit   + +
+
+
+
Response = ref object of JsRoot
+  bodyUsed*, ok*, redirected*: bool
+  typ* {.importjs: "type".}: cstring
+  url*, statusText*: cstring
+  status*: cint
+  headers*: Headers
+  body*: cstring
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Response + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `$`(self: Request | Response | FetchOptions): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func clone(self: Response | Request): Response {.importjs: "#.$1()", ...raises: [],
+    tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Response/clone + Source   +Edit   + +
+
+ +
+
+
+
proc fetch(url: cstring | Request): Future[Response] {.importjs: "$1(#)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + fetch() API, simple GET only, returns a Future[Response]. + Source   +Edit   + +
+
+
+
proc fetch(url: cstring | Request; options: FetchOptions): Future[Response] {.
+    importjs: "$1(#, #)", ...raises: [], tags: [], forbids: [].}
+
+ + fetch() API that takes a FetchOptions, returns a Future[Response]. + Source   +Edit   + +
+
+ +
+
+
+
proc formData(self: Response): Future[FormData] {.importjs: "#.$1()",
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Response/formData + Source   +Edit   + +
+
+ +
+
+
+
proc json(self: Response): Future[JsObject] {.importjs: "#.$1()", ...raises: [],
+    tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Response/json + Source   +Edit   + +
+
+ +
+
+
+
func newfetchOptions(metod = HttpGet; body: cstring = nil; mode = fmCors;
+                     credentials = fcSameOrigin; cache = fchDefault;
+                     referrerPolicy = frpNoReferrerWhenDowngrade;
+                     keepalive = false; redirect = frFollow;
+                     referrer = "client".cstring; integrity = "".cstring;
+                     headers: Headers = newHeaders()): FetchOptions {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Constructor for FetchOptions. + Source   +Edit   + +
+
+ +
+
+
+
func newRequest(url: cstring): Request {.importjs: "(new Request(#))",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Constructor for Request. This does not call fetch(). Same as new Request(). + Source   +Edit   + +
+
+
+
func newRequest(url: cstring; fetchOptions: FetchOptions): Request {.
+    importjs: "(new Request(#, #))", ...raises: [], tags: [], forbids: [].}
+
+ + Constructor for Request with fetchOptions. Same as fetch(url, fetchOptions). + Source   +Edit   + +
+
+ +
+
+
+
func newResponse(body: cstring | FormData): Response {.
+    importjs: "(new Response(#))", ...raises: [], tags: [], forbids: [].}
+
+ + Constructor for Response. This does not call fetch(). Same as new Response(). + Source   +Edit   + +
+
+ +
+
+
+
proc text(self: Response): Future[cstring] {.importjs: "#.$1()", ...raises: [],
+    tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Response/text + Source   +Edit   + +
+
+ +
+
+
+
func toCstring(self: Request | Response | FetchOptions): cstring {.
+    importjs: "JSON.stringify(#)", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc unsafeNewFetchOptions(metod, body, mode, credentials, cache, referrerPolicy: cstring;
+                           keepalive: bool; redirect = "follow".cstring;
+                           referrer = "client".cstring; integrity = "".cstring;
+                           headers: Headers = newHeaders()): FetchOptions {.importjs: "{method: #, body: #, mode: #, credentials: #, cache: #, referrerPolicy: #, keepalive: #, redirect: #, referrer: #, integrity: #, headers: #}",
+    ...raises: [], tags: [], forbids: [].}
+
+ +
Warning: +Unsafe newfetchOptions.
+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/jsfetch.idx b/jsfetch.idx new file mode 100644 index 0000000000000..f3cf3b507781c --- /dev/null +++ b/jsfetch.idx @@ -0,0 +1,43 @@ +nimTitle jsfetch jsfetch.html module std/jsfetch 0 +nim FetchOptions jsfetch.html#FetchOptions type FetchOptions 11 +nim fmCors jsfetch.html#fmCors FetchModes.fmCors 17 +nim fmNoCors jsfetch.html#fmNoCors FetchModes.fmNoCors 17 +nim fmSameOrigin jsfetch.html#fmSameOrigin FetchModes.fmSameOrigin 17 +nim FetchModes jsfetch.html#FetchModes enum FetchModes 17 +nim fcInclude jsfetch.html#fcInclude FetchCredentials.fcInclude 22 +nim fcSameOrigin jsfetch.html#fcSameOrigin FetchCredentials.fcSameOrigin 22 +nim fcOmit jsfetch.html#fcOmit FetchCredentials.fcOmit 22 +nim FetchCredentials jsfetch.html#FetchCredentials enum FetchCredentials 22 +nim fchDefault jsfetch.html#fchDefault FetchCaches.fchDefault 27 +nim fchNoStore jsfetch.html#fchNoStore FetchCaches.fchNoStore 27 +nim fchReload jsfetch.html#fchReload FetchCaches.fchReload 27 +nim fchNoCache jsfetch.html#fchNoCache FetchCaches.fchNoCache 27 +nim fchForceCache jsfetch.html#fchForceCache FetchCaches.fchForceCache 27 +nim FetchCaches jsfetch.html#FetchCaches enum FetchCaches 27 +nim frFollow jsfetch.html#frFollow FetchRedirects.frFollow 34 +nim frError jsfetch.html#frError FetchRedirects.frError 34 +nim frManual jsfetch.html#frManual FetchRedirects.frManual 34 +nim FetchRedirects jsfetch.html#FetchRedirects enum FetchRedirects 34 +nim frpNoReferrer jsfetch.html#frpNoReferrer FetchReferrerPolicies.frpNoReferrer 39 +nim frpNoReferrerWhenDowngrade jsfetch.html#frpNoReferrerWhenDowngrade FetchReferrerPolicies.frpNoReferrerWhenDowngrade 39 +nim frpOrigin jsfetch.html#frpOrigin FetchReferrerPolicies.frpOrigin 39 +nim frpOriginWhenCrossOrigin jsfetch.html#frpOriginWhenCrossOrigin FetchReferrerPolicies.frpOriginWhenCrossOrigin 39 +nim frpUnsafeUrl jsfetch.html#frpUnsafeUrl FetchReferrerPolicies.frpUnsafeUrl 39 +nim FetchReferrerPolicies jsfetch.html#FetchReferrerPolicies enum FetchReferrerPolicies 39 +nim Response jsfetch.html#Response type Response 46 +nim Request jsfetch.html#Request type Request 54 +nim newResponse jsfetch.html#newResponse proc newResponse(body: cstring | FormData): Response 62 +nim newRequest jsfetch.html#newRequest,cstring proc newRequest(url: cstring): Request 65 +nim newRequest jsfetch.html#newRequest,cstring,FetchOptions proc newRequest(url: cstring; fetchOptions: FetchOptions): Request 68 +nim clone jsfetch.html#clone proc clone(self: Response | Request): Response 71 +nim text jsfetch.html#text,Response proc text(self: Response): Future[cstring] 74 +nim json jsfetch.html#json,Response proc json(self: Response): Future[JsObject] 77 +nim formData jsfetch.html#formData,Response proc formData(self: Response): Future[FormData] 80 +nim unsafeNewFetchOptions jsfetch.html#unsafeNewFetchOptions,cstring,cstring,cstring,cstring,cstring,cstring,bool,Headers proc unsafeNewFetchOptions(metod, body, mode, credentials, cache, referrerPolicy: cstring;\n keepalive: bool; redirect = "follow".cstring;\n referrer = "client".cstring; integrity = "".cstring;\n headers: Headers = newHeaders()): FetchOptions 83 +nim newfetchOptions jsfetch.html#newfetchOptions,cstring,Headers proc newfetchOptions(metod = HttpGet; body: cstring = nil; mode = fmCors;\n credentials = fcSameOrigin; cache = fchDefault;\n referrerPolicy = frpNoReferrerWhenDowngrade; keepalive = false;\n redirect = frFollow; referrer = "client".cstring;\n integrity = "".cstring; headers: Headers = newHeaders()): FetchOptions 88 +nim fetch jsfetch.html#fetch proc fetch(url: cstring | Request): Future[Response] 108 +nim fetch jsfetch.html#fetch,,FetchOptions proc fetch(url: cstring | Request; options: FetchOptions): Future[Response] 111 +nim toCstring jsfetch.html#toCstring proc toCstring(self: Request | Response | FetchOptions): cstring 114 +nim `$` jsfetch.html#$ proc `$`(self: Request | Response | FetchOptions): string 116 +nimgrp fetch jsfetch.html#fetch-procs-all proc 108 +nimgrp newrequest jsfetch.html#newRequest-procs-all proc 65 diff --git a/jsffi.html b/jsffi.html new file mode 100644 index 0000000000000..251a6b42c3bbf --- /dev/null +++ b/jsffi.html @@ -0,0 +1,1426 @@ + + + + + + + +std/jsffi + + + + + + + + + + + + + + + + +
+
+

std/jsffi

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This Module implements types and macros to facilitate the wrapping of, and interaction with JavaScript libraries. Using the provided types JsObject and JsAssoc together with the provided macros allows for smoother interfacing with JavaScript, allowing for example quick and easy imports of JavaScript variables: +

Example:

+
import std/jsffi
+# Here, we are using jQuery for just a few calls and do not want to wrap the
+# whole library:
+
+# import the document object and the console
+var document {.importc, nodecl.}: JsObject
+var console {.importc, nodecl.}: JsObject
+# import the "$" function
+proc jq(selector: JsObject): JsObject {.importjs: "$$(#)".}
+
+# Use jQuery to make the following code run, after the document is ready.
+# This uses an experimental `.()` operator for `JsObject`, to emit
+# JavaScript calls, when no corresponding proc exists for `JsObject`.
+proc main =
+  jq(document).ready(proc() =
+    console.log("Hello JavaScript!")
+  )

+
+

Imports

+
+ macros, tables +
+
+
+

Types

+
+
+
js = JsObject
+
+ + + Source   +Edit   + +
+
+
+
JsAssoc[K; V] = ref object of JsRoot
+
+ + Statically typed wrapper around a JavaScript object. + Source   +Edit   + +
+
+
+
JsError {.importc: "Error".} = object of JsRoot
+  message*: cstring
+
+ + + Source   +Edit   + +
+
+
+
JsEvalError {.importc: "EvalError".} = object of JsError
+
+ + + Source   +Edit   + +
+
+
+
JsKey = concept atypeof(T)
+    cstring.toJsKey(T) is T
+
+ + + Source   +Edit   + +
+
+
+
JsObject = ref object of JsRoot
+
+ + Dynamically typed wrapper around a JavaScript object. + Source   +Edit   + +
+
+
+
JsRangeError {.importc: "RangeError".} = object of JsError
+
+ + + Source   +Edit   + +
+
+
+
JsReferenceError {.importc: "ReferenceError".} = object of JsError
+
+ + + Source   +Edit   + +
+
+
+
JsSyntaxError {.importc: "SyntaxError".} = object of JsError
+
+ + + Source   +Edit   + +
+
+
+
JsTypeError {.importc: "TypeError".} = object of JsError
+
+ + + Source   +Edit   + +
+
+
+
JsURIError {.importc: "URIError".} = object of JsError
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
jsArguments {.importc: "arguments", nodecl.}: JsObject
+
+ + JavaScript's arguments pseudo-variable. + Source   +Edit   + +
+
+
+
jsDirname {.importc: "__dirname", nodecl.}: cstring
+
+ + JavaScript's __dirname pseudo-variable. + Source   +Edit   + +
+
+
+
jsFilename {.importc: "__filename", nodecl.}: cstring
+
+ + JavaScript's __filename pseudo-variable. + Source   +Edit   + +
+
+
+
jsNull {.importc: "null", nodecl.}: JsObject
+
+ + JavaScript's null literal. + Source   +Edit   + +
+
+
+
jsUndefined {.importc: "undefined", nodecl.}: JsObject
+
+ + JavaScript's undefined literal. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `%`(x, y: JsObject): JsObject {.importjs: "(# % #)", ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `%=`(x, y: JsObject): JsObject {.importjs: "(# %= #)", discardable,
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `&`(a, b: cstring): cstring {.importjs: "(# + #)", ...raises: [], tags: [],
+                                   forbids: [].}
+
+ + Concatenation operator for JavaScript strings. + Source   +Edit   + +
+
+ +
+
+
+
proc `*`(x, y: JsObject): JsObject {.importjs: "(# * #)", ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `**`(x, y: JsObject): JsObject {.importjs: "((#) ** #)", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `*=`(x, y: JsObject): JsObject {.importjs: "(# *= #)", discardable,
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `+`(x, y: JsObject): JsObject {.importjs: "(# + #)", ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `++`(x: JsObject): JsObject {.importjs: "(++#)", ...raises: [], tags: [],
+                                   forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `+=`(x, y: JsObject): JsObject {.importjs: "(# += #)", discardable,
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `-`(x, y: JsObject): JsObject {.importjs: "(# - #)", ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `--`(x: JsObject): JsObject {.importjs: "(--#)", ...raises: [], tags: [],
+                                   forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `-=`(x, y: JsObject): JsObject {.importjs: "(# -= #)", discardable,
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `/`(x, y: JsObject): JsObject {.importjs: "(# / #)", ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `/=`(x, y: JsObject): JsObject {.importjs: "(# /= #)", discardable,
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `<`(x, y: JsObject): JsObject {.importjs: "(# < #)", ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `<=`(x, y: JsObject): JsObject {.importjs: "(# <= #)", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(x, y: JsRoot): bool {.importjs: "(# === #)", ...raises: [], tags: [],
+                                forbids: [].}
+
+ + Compares two JsObjects or JsAssocs. Be careful though, as this is comparison like in JavaScript, so if your JsObjects are in fact JavaScript Objects, and not strings or numbers, this is a comparison of references. + Source   +Edit   + +
+
+ +
+
+
+
proc `>`(x, y: JsObject): JsObject {.importjs: "(# > #)", ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `>=`(x, y: JsObject): JsObject {.importjs: "(# >= #)", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `[]`(obj: JsObject; field: cstring): JsObject {.importjs: "#[#]",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Returns the value of a property of name field from a JsObject obj. + Source   +Edit   + +
+
+
+
proc `[]`(obj: JsObject; field: int): JsObject {.importjs: "#[#]", ...raises: [],
+    tags: [], forbids: [].}
+
+ + Returns the value of a property of name field from a JsObject obj. + Source   +Edit   + +
+
+
+
proc `[]`[K: JsKey; V](obj: JsAssoc[K, V]; field: K): V {.importjs: "#[#]",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Returns the value of a property of name field from a JsAssoc obj. + Source   +Edit   + +
+
+
+
proc `[]`[V](obj: JsAssoc[cstring, V]; field: string): V
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `[]=`[K: JsKey; V](obj: JsAssoc[K, V]; field: K; val: V) {.
+    importjs: "#[#] = #", ...raises: [], tags: [], forbids: [].}
+
+ + Sets the value of a property of name field in a JsAssoc obj to v. + Source   +Edit   + +
+
+
+
proc `[]=`[T](obj: JsObject; field: cstring; val: T) {.importjs: "#[#] = #",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Sets the value of a property of name field in a JsObject obj to v. + Source   +Edit   + +
+
+
+
proc `[]=`[T](obj: JsObject; field: int; val: T) {.importjs: "#[#] = #",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Sets the value of a property of name field in a JsObject obj to v. + Source   +Edit   + +
+
+
+
proc `[]=`[V](obj: JsAssoc[cstring, V]; field: string; val: V)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `and`(x, y: JsObject): JsObject {.importjs: "(# && #)", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasOwnProperty(x: JsObject; prop: cstring): bool {.
+    importjs: "#.hasOwnProperty(#)", ...raises: [], tags: [], forbids: [].}
+
+ + Checks, whether x has a property of name prop. + Source   +Edit   + +
+
+ +
+
+
+
proc `in`(x, y: JsObject): JsObject {.importjs: "(# in #)", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isNull[T](x: T): bool {.noSideEffect, importjs: "(# === null)", ...raises: [],
+                             tags: [], forbids: [].}
+
+ + Checks if a value is exactly null. + Source   +Edit   + +
+
+ +
+
+
+
proc isUndefined[T](x: T): bool {.noSideEffect, importjs: "(# === undefined)",
+                                  ...raises: [], tags: [], forbids: [].}
+
+ + Checks if a value is exactly undefined. + Source   +Edit   + +
+
+ +
+
+
+
proc jsDelete(x: auto): JsObject {.importjs: "(delete #)", ...raises: [], tags: [],
+                                   forbids: [].}
+
+ + JavaScript's delete operator. + Source   +Edit   + +
+
+ +
+
+
+
proc jsNew(x: auto): JsObject {.importjs: "(new #)", ...raises: [], tags: [],
+                                forbids: [].}
+
+ + Turns a regular function call into an invocation of the JavaScript's new operator. + Source   +Edit   + +
+
+ +
+
+
+
proc jsTypeOf(x: JsObject): cstring {.importjs: "typeof(#)", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + Returns the name of the JsObject's JavaScript type as a cstring. + Source   +Edit   + +
+
+ +
+
+
+
proc newJsAssoc[K: JsKey; V](): JsAssoc[K, V] {.importjs: "{@}", ...raises: [],
+    tags: [], forbids: [].}
+
+ + Creates a new empty JsAssoc with key type K and value type V. + Source   +Edit   + +
+
+ +
+
+
+
proc newJsObject(): JsObject {.importjs: "{@}", ...raises: [], tags: [],
+                               forbids: [].}
+
+ + Creates a new empty JsObject. + Source   +Edit   + +
+
+ +
+
+
+
proc `not`(x: JsObject): JsObject {.importjs: "(!#)", ...raises: [], tags: [],
+                                    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `or`(x, y: JsObject): JsObject {.importjs: "(# || #)", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc require(module: cstring): JsObject {.importc, ...raises: [], tags: [],
+    forbids: [].}
+
+ + JavaScript's require function. + Source   +Edit   + +
+
+ +
+
+
+
proc to(x: JsObject; T: typedesc): T:type {.importjs: "(#)", ...raises: [],
+    tags: [], forbids: [].}
+
+ + Converts a JsObject x to type T. + Source   +Edit   + +
+
+ +
+
+
+
proc toJs[T](val: T): JsObject {.importjs: "(#)", ...raises: [], tags: [],
+                                 forbids: [].}
+
+ + Converts a value of any type to type JsObject. + Source   +Edit   + +
+
+ +
+
+
+
proc toJsKey(text: cstring; t: type cstring): cstring
+
+ + + Source   +Edit   + +
+
+
+
proc toJsKey[T: enum](text: cstring; t: type T): T
+
+ + + Source   +Edit   + +
+
+
+
proc toJsKey[T: SomeFloat](text: cstring; t: type T): T {.
+    importjs: "parseFloat(#)", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc toJsKey[T: SomeInteger](text: cstring; t: type T): T {.
+    importjs: "parseInt(#)", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator items(obj: JsObject): JsObject {....raises: [], tags: [], forbids: [].}
+
+ + Yields the values of each field in a JsObject, wrapped into a JsObject. + Source   +Edit   + +
+
+
+
iterator items[K, V](assoc: JsAssoc[K, V]): V
+
+ + Yields the values in a JsAssoc. + Source   +Edit   + +
+
+ +
+
+
+
iterator keys(obj: JsObject): cstring {....raises: [], tags: [], forbids: [].}
+
+ + Yields the names of each field in a JsObject. + Source   +Edit   + +
+
+
+
iterator keys[K: JsKey; V](assoc: JsAssoc[K, V]): K
+
+ + Yields the keys in a JsAssoc. + Source   +Edit   + +
+
+ +
+
+
+
iterator pairs(obj: JsObject): (cstring, JsObject) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Yields tuples of type (cstring, JsObject), with the first entry being the name of a fields in the JsObject and the second being its value wrapped into a JsObject. + Source   +Edit   + +
+
+
+
iterator pairs[K: JsKey; V](assoc: JsAssoc[K, V]): (K, V)
+
+ + Yields tuples of type (K, V), with the first entry being a key in the JsAssoc and the second being its corresponding value. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro `.`(obj: JsObject; field: untyped): JsObject
+
+ + Experimental dot accessor (get) for type JsObject. Returns the value of a property of name field from a JsObject x. +

Example:

+
let obj = newJsObject()
+obj.a = 20
+assert obj.a.to(int) == 20
+ Source   +Edit   + +
+
+
+
macro `.`[K: cstring; V](obj: JsAssoc[K, V]; field: untyped): V
+
+ + Experimental dot accessor (get) for type JsAssoc. Returns the value of a property of name field from a JsObject x. + Source   +Edit   + +
+
+ +
+
+
+
macro `.()`(obj: JsObject; field: untyped; args: varargs[JsObject, jsFromAst]): JsObject
+
+ +

Experimental "method call" operator for type JsObject. Takes the name of a method of the JavaScript object (field) and calls it with args as arguments, returning a JsObject (which may be discarded, and may be undefined, if the method does not return anything, so be careful when using this.)

+

Example:

+

# Let's get back to the console example:
+var console {.importc, nodecl.}: JsObject
+let res = console.log("I return undefined!")
+console.log(res) # This prints undefined, as console.log always returns
+                 # undefined. Thus one has to be careful, when using
+                 # JsObject calls.

+ + Source   +Edit   + +
+
+
+
macro `.()`[K: cstring; V: proc](obj: JsAssoc[K, V]; field: untyped;
+                                 args: varargs[untyped]): auto
+
+ + Experimental "method call" operator for type JsAssoc. Takes the name of a method of the JavaScript object (field) and calls it with args as arguments. Here, everything is typechecked, so you do not have to worry about undefined return values. + Source   +Edit   + +
+
+ +
+
+
+
macro `.=`(obj: JsObject; field, value: untyped): untyped
+
+ + Experimental dot accessor (set) for type JsObject. Sets the value of a property of name field in a JsObject x to value. + Source   +Edit   + +
+
+
+
macro `.=`[K: cstring; V](obj: JsAssoc[K, V]; field: untyped; value: V): untyped
+
+ + Experimental dot accessor (set) for type JsAssoc. Sets the value of a property of name field in a JsObject x to value. + Source   +Edit   + +
+
+ +
+
+
+
macro bindMethod(procedure: typed): auto {.
+    ...deprecated: "Don\'t use it with closures".}
+
+
+ Deprecated: Don't use it with closures +
+ +

Takes the name of a procedure and wraps it into a lambda missing the first argument, which passes the JavaScript builtin this as the first argument to the procedure. Returns the resulting lambda.

+

Example:

+

We want to generate roughly this JavaScript:

+

var obj = {a: 10};
+obj.someMethod = function() {
+  return this.a + 42;
+};

+

We can achieve this using the bindMethod macro:

+

let obj = JsObject{ a: 10 }
+proc someMethodImpl(that: JsObject): int =
+  that.a.to(int) + 42
+obj.someMethod = bindMethod someMethodImpl
+
+# Alternatively:
+obj.someMethod = bindMethod
+  proc(that: JsObject): int = that.a.to(int) + 42

+ + Source   +Edit   + +
+
+ +
+
+
+
macro jsFromAst(n: untyped): untyped
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
macro `{}`(typ: typedesc; xs: varargs[untyped]): auto
+
+ +

Takes a typedesc as its first argument, and a series of expressions of type key: value, and returns a value of the specified type with each field key set to value, as specified in the arguments of {}.

+

Example:

+

# Let's say we have a type with a ton of fields, where some fields do not
+# need to be set, and we do not want those fields to be set to `nil`:
+type
+  ExtremelyHugeType = ref object
+    a, b, c, d, e, f, g: int
+    h, i, j, k, l: cstring
+    # And even more fields ...
+
+let obj = ExtremelyHugeType{ a: 1, k: "foo".cstring, d: 42 }
+
+# This generates roughly the same JavaScript as:
+{.emit: "var obj = {a: 1, k: "foo", d: 42};".}

+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template toJs(s: string): JsObject
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/jsffi.idx b/jsffi.idx new file mode 100644 index 0000000000000..e202e5b894c5a --- /dev/null +++ b/jsffi.idx @@ -0,0 +1,88 @@ +nimTitle jsffi jsffi.html module std/jsffi 0 +nim toJsKey jsffi.html#toJsKey,cstring,typeT proc toJsKey[T: SomeInteger](text: cstring; t: type T): T 73 +nim toJsKey jsffi.html#toJsKey,cstring,typeT_2 proc toJsKey[T: enum](text: cstring; t: type T): T 75 +nim toJsKey jsffi.html#toJsKey,cstring,typecstring proc toJsKey(text: cstring; t: type cstring): cstring 78 +nim toJsKey jsffi.html#toJsKey,cstring,typeT_3 proc toJsKey[T: SomeFloat](text: cstring; t: type T): T 81 +nim JsKey jsffi.html#JsKey type JsKey 84 +nim JsObject jsffi.html#JsObject type JsObject 87 +nim JsAssoc jsffi.html#JsAssoc type JsAssoc 89 +nim js jsffi.html#js type js 92 +nim jsArguments jsffi.html#jsArguments var jsArguments 95 +nim jsNull jsffi.html#jsNull var jsNull 97 +nim jsUndefined jsffi.html#jsUndefined var jsUndefined 99 +nim jsDirname jsffi.html#jsDirname var jsDirname 101 +nim jsFilename jsffi.html#jsFilename var jsFilename 103 +nim isNull jsffi.html#isNull,T proc isNull[T](x: T): bool 106 +nim isUndefined jsffi.html#isUndefined,T proc isUndefined[T](x: T): bool 109 +nim JsError jsffi.html#JsError object JsError 114 +nim JsEvalError jsffi.html#JsEvalError object JsEvalError 116 +nim JsRangeError jsffi.html#JsRangeError object JsRangeError 117 +nim JsReferenceError jsffi.html#JsReferenceError object JsReferenceError 118 +nim JsSyntaxError jsffi.html#JsSyntaxError object JsSyntaxError 119 +nim JsTypeError jsffi.html#JsTypeError object JsTypeError 120 +nim JsURIError jsffi.html#JsURIError object JsURIError 121 +nim newJsObject jsffi.html#newJsObject proc newJsObject(): JsObject 124 +nim newJsAssoc jsffi.html#newJsAssoc proc newJsAssoc[K: JsKey; V](): JsAssoc[K, V] 127 +nim hasOwnProperty jsffi.html#hasOwnProperty,JsObject,cstring proc hasOwnProperty(x: JsObject; prop: cstring): bool 131 +nim jsTypeOf jsffi.html#jsTypeOf,JsObject proc jsTypeOf(x: JsObject): cstring 135 +nim jsNew jsffi.html#jsNew,auto proc jsNew(x: auto): JsObject 138 +nim jsDelete jsffi.html#jsDelete,auto proc jsDelete(x: auto): JsObject 142 +nim require jsffi.html#require,cstring proc require(module: cstring): JsObject 145 +nim to jsffi.html#to,JsObject,typedesc proc to(x: JsObject; T: typedesc): T:type 149 +nim toJs jsffi.html#toJs,T proc toJs[T](val: T): JsObject 152 +nim toJs jsffi.html#toJs.t,string template toJs(s: string): JsObject 155 +nim jsFromAst jsffi.html#jsFromAst.m,untyped macro jsFromAst(n: untyped): untyped 157 +nim `&` jsffi.html#&,cstring,cstring proc `&`(a, b: cstring): cstring 163 +nim `+` jsffi.html#+,JsObject,JsObject proc `+`(x, y: JsObject): JsObject 166 +nim `-` jsffi.html#-,JsObject,JsObject proc `-`(x, y: JsObject): JsObject 167 +nim `*` jsffi.html#*,JsObject,JsObject proc `*`(x, y: JsObject): JsObject 168 +nim `/` jsffi.html#/,JsObject,JsObject proc `/`(x, y: JsObject): JsObject 169 +nim `%` jsffi.html#%,JsObject,JsObject proc `%`(x, y: JsObject): JsObject 170 +nim `+=` jsffi.html#+=,JsObject,JsObject proc `+=`(x, y: JsObject): JsObject 171 +nim `-=` jsffi.html#-=,JsObject,JsObject proc `-=`(x, y: JsObject): JsObject 172 +nim `*=` jsffi.html#*=,JsObject,JsObject proc `*=`(x, y: JsObject): JsObject 173 +nim `/=` jsffi.html#/=,JsObject,JsObject proc `/=`(x, y: JsObject): JsObject 174 +nim `%=` jsffi.html#%=,JsObject,JsObject proc `%=`(x, y: JsObject): JsObject 175 +nim `++` jsffi.html#++,JsObject proc `++`(x: JsObject): JsObject 176 +nim `--` jsffi.html#--,JsObject proc `--`(x: JsObject): JsObject 177 +nim `>` jsffi.html#>,JsObject,JsObject proc `>`(x, y: JsObject): JsObject 178 +nim `<` jsffi.html#<,JsObject,JsObject proc `<`(x, y: JsObject): JsObject 179 +nim `>=` jsffi.html#>=,JsObject,JsObject proc `>=`(x, y: JsObject): JsObject 180 +nim `<=` jsffi.html#<=,JsObject,JsObject proc `<=`(x, y: JsObject): JsObject 181 +nim `**` jsffi.html#**,JsObject,JsObject proc `**`(x, y: JsObject): JsObject 182 +nim `and` jsffi.html#and,JsObject,JsObject proc `and`(x, y: JsObject): JsObject 184 +nim `or` jsffi.html#or,JsObject,JsObject proc `or`(x, y: JsObject): JsObject 185 +nim `not` jsffi.html#not,JsObject proc `not`(x: JsObject): JsObject 186 +nim `in` jsffi.html#in,JsObject,JsObject proc `in`(x, y: JsObject): JsObject 187 +nim `[]` jsffi.html#[],JsObject,cstring proc `[]`(obj: JsObject; field: cstring): JsObject 189 +nim `[]` jsffi.html#[],JsObject,int proc `[]`(obj: JsObject; field: int): JsObject 192 +nim `[]=` jsffi.html#[]=,JsObject,cstring,T proc `[]=`[T](obj: JsObject; field: cstring; val: T) 195 +nim `[]=` jsffi.html#[]=,JsObject,int,T proc `[]=`[T](obj: JsObject; field: int; val: T) 198 +nim `[]` jsffi.html#[],JsAssoc[K: JsKey,V],K proc `[]`[K: JsKey; V](obj: JsAssoc[K, V]; field: K): V 201 +nim `[]=` jsffi.html#[]=,JsAssoc[K: JsKey,V],K,V proc `[]=`[K: JsKey; V](obj: JsAssoc[K, V]; field: K; val: V) 205 +nim `[]` jsffi.html#[],JsAssoc[cstring,V],string proc `[]`[V](obj: JsAssoc[cstring, V]; field: string): V 209 +nim `[]=` jsffi.html#[]=,JsAssoc[cstring,V],string,V proc `[]=`[V](obj: JsAssoc[cstring, V]; field: string; val: V) 212 +nim `==` jsffi.html#==,JsRoot,JsRoot proc `==`(x, y: JsRoot): bool 215 +nim `.` jsffi.html#..m,JsObject,untyped macro `.`(obj: JsObject; field: untyped): JsObject 221 +nim `.=` jsffi.html#.=.m,JsObject,untyped,untyped macro `.=`(obj: JsObject; field, value: untyped): untyped 245 +nim `.()` jsffi.html#.().m,JsObject,untyped,varargs[JsObject,jsFromAst] macro `.()`(obj: JsObject; field: untyped; args: varargs[JsObject, jsFromAst]): JsObject 265 +nim `.` jsffi.html#..m,JsAssoc[K: cstring,V],untyped macro `.`[K: cstring; V](obj: JsAssoc[K, V]; field: untyped): V 300 +nim `.=` jsffi.html#.=.m,JsAssoc[K: cstring,V],untyped,V macro `.=`[K: cstring; V](obj: JsAssoc[K, V]; field: untyped; value: V): untyped 317 +nim `.()` jsffi.html#.().m,JsAssoc[K: cstring,V: proc],untyped,varargs[untyped] macro `.()`[K: cstring; V: proc](obj: JsAssoc[K, V]; field: untyped;\n args: varargs[untyped]): auto 335 +nim pairs jsffi.html#pairs.i,JsObject iterator pairs(obj: JsObject): (cstring, JsObject) 350 +nim items jsffi.html#items.i,JsObject iterator items(obj: JsObject): JsObject 362 +nim keys jsffi.html#keys.i,JsObject iterator keys(obj: JsObject): cstring 371 +nim pairs jsffi.html#pairs.i,JsAssoc[K: JsKey,V] iterator pairs[K: JsKey; V](assoc: JsAssoc[K, V]): (K, V) 379 +nim items jsffi.html#items.i,JsAssoc[K,V] iterator items[K, V](assoc: JsAssoc[K, V]): V 390 +nim keys jsffi.html#keys.i,JsAssoc[K: JsKey,V] iterator keys[K: JsKey; V](assoc: JsAssoc[K, V]): K 399 +nim `{}` jsffi.html#{}.m,typedesc,varargs[untyped] macro `{}`(typ: typedesc; xs: varargs[untyped]): auto 409 +nim bindMethod jsffi.html#bindMethod.m,typed macro bindMethod(procedure: typed): auto 471 +nimgrp tojskey jsffi.html#toJsKey-procs-all proc 73 +nimgrp []= jsffi.html#[]=-procs-all proc 195 +nimgrp [] jsffi.html#[]-procs-all proc 189 +nimgrp items jsffi.html#items-iterators-all iterator 362 +nimgrp pairs jsffi.html#pairs-iterators-all iterator 350 +nimgrp keys jsffi.html#keys-iterators-all iterator 371 +nimgrp .() jsffi.html#.()-macros-all macro 265 +nimgrp . jsffi.html#.-macros-all macro 221 +nimgrp .= jsffi.html#.=-macros-all macro 245 diff --git a/jsformdata.html b/jsformdata.html new file mode 100644 index 0000000000000..0588134619c9a --- /dev/null +++ b/jsformdata.html @@ -0,0 +1,434 @@ + + + + + + + +std/jsformdata + + + + + + + + + + + + + + + + +
+
+

std/jsformdata

+
+ +
+ Source   +Edit   + +
+ +

+ +

Example: cmd: -r:off

+
import std/jsformdata
+let data: FormData = newFormData()
+data["key0"] = "value0".cstring
+data.add("key1".cstring, "value1".cstring)
+data.delete("key1")
+assert data.hasKey("key0")
+assert data["key0"] == "value0".cstring
+data.clear()
+assert data.len == 0

+
+

Imports

+
+ dom +
+
+
+

Types

+
+
+
FormData = ref object of JsRoot
+
+ + FormData API. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `$`(self: FormData): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `[]`(self: FormData; name: cstring): cstring {.importjs: "#.get(#)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FormData/get + Source   +Edit   + +
+
+ +
+
+
+
func `[]=`(self: FormData; name: cstring;
+           value: SomeNumber | bool | cstring | Blob) {.importjs: "#.set(#, #)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FormData/set + Source   +Edit   + +
+
+ +
+
+
+
func add(self: FormData; name: cstring;
+         value: SomeNumber | bool | cstring | Blob) {.
+    importjs: "#.append(#, #)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
Hint: +Duplicate keys are allowed and order is preserved.
+ + Source   +Edit   + +
+
+
+
func add(self: FormData; name: cstring;
+         value: SomeNumber | bool | cstring | Blob; filename: cstring) {.
+    importjs: "#.append(#, #, #)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
Hint: +Duplicate keys are allowed and order is preserved.
+ + Source   +Edit   + +
+
+ +
+
+
+
func clear(self: FormData) {.importjs: "(() => { const frmdt = #; Array.from(frmdt.keys()).forEach((key) => frmdt.delete(key)) })()",
+                             ...raises: [], tags: [], forbids: [].}
+
+ + Convenience func to delete all items from FormData. + Source   +Edit   + +
+
+ +
+
+
+
func delete(self: FormData; name: cstring) {.importjs: "#.$1(#)", ...raises: [],
+    tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FormData/delete
Warning: +Deletes all items with the same key name.
+ + Source   +Edit   + +
+
+ +
+
+
+
func getAll(self: FormData; name: cstring): seq[cstring] {.importjs: "#.$1(#)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FormData/getAll + Source   +Edit   + +
+
+ +
+
+
+
func hasKey(self: FormData; name: cstring): bool {.importjs: "#.has(#)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FormData/has + Source   +Edit   + +
+
+ +
+
+
+
func keys(self: FormData): seq[cstring] {.importjs: "Array.from(#.$1())",
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FormData/keys + Source   +Edit   + +
+
+ +
+
+
+
func len(self: FormData): int {.importjs: "Array.from(#.entries()).length",
+                                ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func newFormData(): FormData {.importjs: "new FormData()", ...raises: [], tags: [],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func pairs(self: FormData): seq[tuple[key, val: cstring]] {.
+    importjs: "Array.from(#.entries())", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries + Source   +Edit   + +
+
+ +
+
+
+
func put(self: FormData; name: cstring;
+         value: SomeNumber | bool | cstring | Blob; filename: cstring) {.
+    importjs: "#.set(#, #, #)", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FormData/set + Source   +Edit   + +
+
+ +
+
+
+
func toCstring(self: FormData): cstring {.importjs: "JSON.stringify(#)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func values(self: FormData): seq[cstring] {.importjs: "Array.from(#.$1())",
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/FormData/values + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/jsformdata.idx b/jsformdata.idx new file mode 100644 index 0000000000000..cce550dd148e5 --- /dev/null +++ b/jsformdata.idx @@ -0,0 +1,19 @@ +nimTitle jsformdata jsformdata.html module std/jsformdata 0 +nim FormData jsformdata.html#FormData type FormData 7 +nim newFormData jsformdata.html#newFormData proc newFormData(): FormData 9 +nim add jsformdata.html#add,FormData,cstring, proc add(self: FormData; name: cstring; value: SomeNumber | bool | cstring | Blob) 11 +nim add jsformdata.html#add,FormData,cstring,,cstring proc add(self: FormData; name: cstring; value: SomeNumber | bool | cstring | Blob;\n filename: cstring) 16 +nim delete jsformdata.html#delete,FormData,cstring proc delete(self: FormData; name: cstring) 21 +nim getAll jsformdata.html#getAll,FormData,cstring proc getAll(self: FormData; name: cstring): seq[cstring] 26 +nim hasKey jsformdata.html#hasKey,FormData,cstring proc hasKey(self: FormData; name: cstring): bool 29 +nim keys jsformdata.html#keys,FormData proc keys(self: FormData): seq[cstring] 32 +nim values jsformdata.html#values,FormData proc values(self: FormData): seq[cstring] 35 +nim pairs jsformdata.html#pairs,FormData proc pairs(self: FormData): seq[tuple[key, val: cstring]] 38 +nim put jsformdata.html#put,FormData,cstring,,cstring proc put(self: FormData; name: cstring; value: SomeNumber | bool | cstring | Blob;\n filename: cstring) 41 +nim `[]=` jsformdata.html#[]=,FormData,cstring, proc `[]=`(self: FormData; name: cstring; value: SomeNumber | bool | cstring | Blob) 44 +nim `[]` jsformdata.html#[],FormData,cstring proc `[]`(self: FormData; name: cstring): cstring 47 +nim clear jsformdata.html#clear,FormData proc clear(self: FormData) 50 +nim toCstring jsformdata.html#toCstring,FormData proc toCstring(self: FormData): cstring 54 +nim `$` jsformdata.html#$,FormData proc `$`(self: FormData): string 56 +nim len jsformdata.html#len,FormData proc len(self: FormData): int 58 +nimgrp add jsformdata.html#add-procs-all proc 11 diff --git a/jsheaders.html b/jsheaders.html new file mode 100644 index 0000000000000..37b540405715b --- /dev/null +++ b/jsheaders.html @@ -0,0 +1,390 @@ + + + + + + + +std/jsheaders + + + + + + + + + + + + + + + + +
+
+

std/jsheaders

+
+ +
+ Source   +Edit   + +
+ +

+ +

Example: cmd: -r:off

+
import std/jsheaders
+
+block:
+  let header: Headers = newHeaders()
+  header.add("key", "value")
+  assert header.hasKey("key")
+  assert header.keys() == @["key".cstring]
+  assert header.values() == @["value".cstring]
+  assert header["key"] == "value".cstring
+  header["other"] = "another".cstring
+  assert header["other"] == "another".cstring
+  assert header.entries() == @[("key".cstring, "value".cstring), ("other".cstring, "another".cstring)]
+  assert header.toCstring() == """[["key","value"],["other","another"]]""".cstring
+  header.delete("other")
+  assert header.entries() == @[("key".cstring, "value".cstring)]
+  header.clear()
+  assert header.entries() == @[]
+  assert header.len == 0
+
+block:
+  let header: Headers = newHeaders()
+  header.add("key", "a")
+  header.add("key", "b")  ## Duplicated.
+  header.add("key", "c")  ## Duplicated.
+  assert header["key"] == "a, b, c".cstring
+  header["key"] = "value".cstring
+  assert header["key"] == "value".cstring
+
+block:
+  let header: Headers = newHeaders()
+  header["key"] = "a"
+  header["key"] = "b"  ## Overwrites.
+  assert header["key"] == "b".cstring

+
+

Types

+
+
+
Headers = ref object of JsRoot
+
+ + HTTP Headers API. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `$`(self: Headers): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `[]`(self: Headers; key: cstring): cstring {.importjs: "#.get(#)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Get all items with key from the headers, including duplicated values. https://developer.mozilla.org/en-US/docs/Web/API/Headers/get + Source   +Edit   + +
+
+ +
+
+
+
func `[]=`(self: Headers; key: cstring; value: cstring) {.
+    importjs: "#.set(#, #)", ...raises: [], tags: [], forbids: [].}
+
+ + Do not allow duplicated keys, overwrites duplicated keys. https://developer.mozilla.org/en-US/docs/Web/API/Headers/set + Source   +Edit   + +
+
+ +
+
+
+
func add(self: Headers; key: cstring; value: cstring) {.
+    importjs: "#.append(#, #)", ...raises: [], tags: [], forbids: [].}
+
+ + Allows duplicated keys. https://developer.mozilla.org/en-US/docs/Web/API/Headers/append + Source   +Edit   + +
+
+ +
+
+
+
func clear(self: Headers) {.importjs: "(() => { const header = #; Array.from(header.keys()).forEach((key) => header.delete(key)) })()",
+                            ...raises: [], tags: [], forbids: [].}
+
+ + Convenience func to delete all items from Headers. + Source   +Edit   + +
+
+ +
+
+
+
func delete(self: Headers; key: cstring) {.importjs: "#.$1(#)", ...raises: [],
+    tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Headers/delete
Warning: +Delete all items with key from the headers, including duplicated keys.
+ + Source   +Edit   + +
+
+ +
+
+
+
func entries(self: Headers): seq[tuple[key, value: cstring]] {.
+    importjs: "Array.from(#.$1())", ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries + Source   +Edit   + +
+
+ +
+
+
+
func hasKey(self: Headers; key: cstring): bool {.importjs: "#.has(#)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Headers/has + Source   +Edit   + +
+
+ +
+
+
+
func keys(self: Headers): seq[cstring] {.importjs: "Array.from(#.$1())",
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Headers/keys + Source   +Edit   + +
+
+ +
+
+
+
func len(self: Headers): int {.importjs: "Array.from(#.entries()).length",
+                               ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func newHeaders(): Headers {.importjs: "new Headers()", ...raises: [], tags: [],
+                             forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Headers + Source   +Edit   + +
+
+ +
+
+
+
func toCstring(self: Headers): cstring {.
+    importjs: "JSON.stringify(Array.from(#.entries()))", ...raises: [], tags: [],
+    forbids: [].}
+
+ + Returns a cstring representation of Headers. + Source   +Edit   + +
+
+ +
+
+
+
func values(self: Headers): seq[cstring] {.importjs: "Array.from(#.$1())",
+    ...raises: [], tags: [], forbids: [].}
+
+ + https://developer.mozilla.org/en-US/docs/Web/API/Headers/values + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/jsheaders.idx b/jsheaders.idx new file mode 100644 index 0000000000000..658aa94496caf --- /dev/null +++ b/jsheaders.idx @@ -0,0 +1,15 @@ +nimTitle jsheaders jsheaders.html module std/jsheaders 0 +nim Headers jsheaders.html#Headers type Headers 5 +nim newHeaders jsheaders.html#newHeaders proc newHeaders(): Headers 7 +nim add jsheaders.html#add,Headers,cstring,cstring proc add(self: Headers; key: cstring; value: cstring) 10 +nim delete jsheaders.html#delete,Headers,cstring proc delete(self: Headers; key: cstring) 14 +nim hasKey jsheaders.html#hasKey,Headers,cstring proc hasKey(self: Headers; key: cstring): bool 19 +nim keys jsheaders.html#keys,Headers proc keys(self: Headers): seq[cstring] 22 +nim values jsheaders.html#values,Headers proc values(self: Headers): seq[cstring] 25 +nim entries jsheaders.html#entries,Headers proc entries(self: Headers): seq[tuple[key, value: cstring]] 28 +nim `[]` jsheaders.html#[],Headers,cstring proc `[]`(self: Headers; key: cstring): cstring 31 +nim `[]=` jsheaders.html#[]=,Headers,cstring,cstring proc `[]=`(self: Headers; key: cstring; value: cstring) 35 +nim clear jsheaders.html#clear,Headers proc clear(self: Headers) 39 +nim toCstring jsheaders.html#toCstring,Headers proc toCstring(self: Headers): cstring 43 +nim `$` jsheaders.html#$,Headers proc `$`(self: Headers): string 46 +nim len jsheaders.html#len,Headers proc len(self: Headers): int 48 diff --git a/json.html b/json.html new file mode 100644 index 0000000000000..2be64357d0715 --- /dev/null +++ b/json.html @@ -0,0 +1,1485 @@ + + + + + + + +std/json + + + + + + + + + + + + + + + + +
+
+

std/json

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a simple high performance JSON parser. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write (unlike XML). It is easy for machines to parse and generate. JSON is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. +

See also

+ +

Overview

+

Parsing JSON

JSON often arrives into your program (via an API or a file) as a string. The first step is to change it from its serialized form into a nested object structure called a JsonNode.

+

The parseJson procedure takes a string containing JSON and returns a JsonNode object. This is an object variant and it is either a JObject, JArray, JString, JInt, JFloat, JBool or JNull. You check the kind of this object variant by using the kind accessor.

+

For a JsonNode who's kind is JObject, you can access its fields using the [] operator. The following example shows how to do this:

+

import std/json
+
+let jsonNode = parseJson("""{"key": 3.14}""")
+
+doAssert jsonNode.kind == JObject
+doAssert jsonNode["key"].kind == JFloat

+ +

Reading values

Once you have a JsonNode, retrieving the values can then be achieved by using one of the helper procedures, which include:

+
  • getInt
  • +
  • getFloat
  • +
  • getStr
  • +
  • getBool
  • +
+

To retrieve the value of "key" you can do the following:

+

import std/json
+
+let jsonNode = parseJson("""{"key": 3.14}""")
+
+doAssert jsonNode["key"].getFloat() == 3.14

+

Important: The [] operator will raise an exception when the specified field does not exist.

+ +

Handling optional keys

By using the {} operator instead of [], it will return nil when the field is not found. The get-family of procedures will return a type's default value when called on nil.

+

import std/json
+
+let jsonNode = parseJson("{}")
+
+doAssert jsonNode{"nope"}.getInt() == 0
+doAssert jsonNode{"nope"}.getFloat() == 0
+doAssert jsonNode{"nope"}.getStr() == ""
+doAssert jsonNode{"nope"}.getBool() == false

+ +

Using default values

The get-family helpers also accept an additional parameter which allow you to fallback to a default value should the key's values be null:

+

import std/json
+
+let jsonNode = parseJson("""{"key": 3.14, "key2": null}""")
+
+doAssert jsonNode["key"].getFloat(6.28) == 3.14
+doAssert jsonNode["key2"].getFloat(3.14) == 3.14
+doAssert jsonNode{"nope"}.getFloat(3.14) == 3.14 # note the {}

+ +

Unmarshalling

In addition to reading dynamic data, Nim can also unmarshal JSON directly into a type with the to macro.

+

Note: Use Option for keys sometimes missing in json responses, and backticks around keys with a reserved keyword as name.

+

import std/json
+import std/options
+
+type
+  User = object
+    name: string
+    age: int
+    `type`: Option[string]
+
+let userJson = parseJson("""{ "name": "Nim", "age": 12 }""")
+let user = to(userJson, User)
+if user.`type`.isSome():
+  assert user.`type`.get() != "robot"

+ +

Creating JSON

This module can also be used to comfortably create JSON using the %* operator:

+

import std/json
+
+var hisName = "John"
+let herAge = 31
+var j = %*
+  [
+    { "name": hisName, "age": 30 },
+    { "name": "Susan", "age": herAge }
+  ]
+
+var j2 = %* {"name": "Isaac", "books": ["Robot Dreams"]}
+j2["details"] = %* {"age":35, "pi":3.1415}
+echo j2

+

See also: std/jsonutils for hookable json serialization/deserialization of arbitrary types.

+ +

Example:

+
import std/json
+## Note: for JObject, key ordering is preserved, unlike in some languages,
+## this is convenient for some use cases. Example:
+type Foo = object
+  a1, a2, a0, a3, a4: int
+doAssert $(%* Foo()) == """{"a1":0,"a2":0,"a0":0,"a3":0,"a4":0}"""

+ +
+

Types

+
+
+
JsonNode = ref JsonNodeObj
+
+ + JSON node + Source   +Edit   + +
+
+
+
JsonNodeKind = enum
+  JNull, JBool, JInt, JFloat, JString, JObject, JArray
+
+ + possible JSON node types + Source   +Edit   + +
+
+
+
JsonNodeObj {.acyclic.} = object
+  case kind*: JsonNodeKind
+  of JString:
+    str*: string
+  of JInt:
+    num*: BiggestInt
+  of JFloat:
+    fnum*: float
+  of JBool:
+    bval*: bool
+  of JNull:
+    nil
+  of JObject:
+    fields*: OrderedTable[string, JsonNode]
+  of JArray:
+    elems*: seq[JsonNode]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(node: JsonNode): string {....raises: [], tags: [], forbids: [].}
+
+ + Converts node to its JSON Representation on one line. + Source   +Edit   + +
+
+ +
+
+
+
proc `%`(b: bool): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Generic constructor for JSON data. Creates a new JBool JsonNode. + Source   +Edit   + +
+
+
+
proc `%`(keyVals: openArray[tuple[key: string, val: JsonNode]]): JsonNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Generic constructor for JSON data. Creates a new JObject JsonNode + Source   +Edit   + +
+
+
+
proc `%`(n: BiggestInt): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Generic constructor for JSON data. Creates a new JInt JsonNode. + Source   +Edit   + +
+
+
+
proc `%`(n: BiggestUInt): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Generic constructor for JSON data. Creates a new JInt JsonNode. + Source   +Edit   + +
+
+
+
proc `%`(n: float): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Generic constructor for JSON data. Creates a new JFloat JsonNode. +

Example:

+
assert $(%[NaN, Inf, -Inf, 0.0, -0.0, 1.0, 1e-2]) == """["nan","inf","-inf",0.0,-0.0,1.0,0.01]"""
+assert (%NaN).kind == JString
+assert (%0.0).kind == JFloat
+ Source   +Edit   + +
+
+
+
proc `%`(n: int): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Generic constructor for JSON data. Creates a new JInt JsonNode. + Source   +Edit   + +
+
+
+
proc `%`(n: uint): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Generic constructor for JSON data. Creates a new JInt JsonNode. + Source   +Edit   + +
+
+
+
proc `%`(o: enum): JsonNode
+
+ + Construct a JsonNode that represents the specified enum value as a string. Creates a new JString JsonNode. + Source   +Edit   + +
+
+
+
proc `%`(o: ref object): JsonNode
+
+ + Generic constructor for JSON data. Creates a new JObject JsonNode + Source   +Edit   + +
+
+
+
proc `%`(s: string): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Generic constructor for JSON data. Creates a new JString JsonNode. + Source   +Edit   + +
+
+
+
proc `%`[T: object](o: T): JsonNode
+
+ + Construct JsonNode from tuples and objects. + Source   +Edit   + +
+
+
+
proc `%`[T](elements: openArray[T]): JsonNode
+
+ + Generic constructor for JSON data. Creates a new JArray JsonNode + Source   +Edit   + +
+
+
+
proc `%`[T](opt: Option[T]): JsonNode
+
+ + Generic constructor for JSON data. Creates a new JNull JsonNode if opt is empty, otherwise it delegates to the underlying value. + Source   +Edit   + +
+
+
+
proc `%`[T](table: Table[string, T] | OrderedTable[string, T]): JsonNode
+
+ + Generic constructor for JSON data. Creates a new JObject JsonNode. + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(a, b: JsonNode): bool {.noSideEffect, ...raises: [], tags: [RootEffect],
+                                  forbids: [].}
+
+ + Check two nodes for equality + Source   +Edit   + +
+
+ +
+
+
+
proc `[]`(node: JsonNode; index: BackwardsIndex): JsonNode {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Gets the node at array.len-i in an array through the ^ operator.

+

i.e. j[^i] is a shortcut for j[j.len-i].

+ +

Example:

+
let
+  j = parseJson("[1,2,3,4,5]")
+
+doAssert j[^1].getInt == 5
+doAssert j[^2].getInt == 4
+ Source   +Edit   + +
+
+
+
proc `[]`(node: JsonNode; index: int): JsonNode {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Gets the node at index in an Array. Result is undefined if index is out of bounds, but as long as array bound checks are enabled it will result in an exception. + Source   +Edit   + +
+
+
+
proc `[]`(node: JsonNode; name: string): JsonNode {.inline, ...raises: [KeyError],
+    tags: [], forbids: [].}
+
+ + Gets a field from a JObject, which must not be nil. If the value at name does not exist, raises KeyError. + Source   +Edit   + +
+
+
+
proc `[]`[U, V](a: JsonNode; x: HSlice[U, V]): JsonNode
+
+ +

Slice operation for JArray.

+

Returns the inclusive range [a[x.a], a[x.b]]:

+ +

Example:

+
import std/json
+let arr = %[0,1,2,3,4,5]
+doAssert arr[2..4] == %[2,3,4]
+doAssert arr[2..^2] == %[2,3,4]
+doAssert arr[^4..^2] == %[2,3,4]
+ Source   +Edit   + +
+
+ +
+
+
+
proc `[]=`(obj: JsonNode; key: string; val: JsonNode) {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Sets a field from a JObject. + Source   +Edit   + +
+
+ +
+
+
+
proc add(father, child: JsonNode) {....raises: [], tags: [], forbids: [].}
+
+ + Adds child to a JArray node father. + Source   +Edit   + +
+
+
+
proc add(obj: JsonNode; key: string; val: JsonNode) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Sets a field from a JObject. + Source   +Edit   + +
+
+ +
+
+
+
proc contains(node: JsonNode; key: string): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + Checks if key exists in node. + Source   +Edit   + +
+
+
+
proc contains(node: JsonNode; val: JsonNode): bool {....raises: [],
+    tags: [RootEffect], forbids: [].}
+
+ + Checks if val exists in array node. + Source   +Edit   + +
+
+ +
+
+
+
proc copy(p: JsonNode): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Performs a deep copy of p. + Source   +Edit   + +
+
+ +
+
+
+
proc delete(obj: JsonNode; key: string) {....raises: [KeyError], tags: [],
+    forbids: [].}
+
+ + Deletes obj[key]. + Source   +Edit   + +
+
+ +
+
+
+
proc escapeJson(s: string): string {....raises: [], tags: [], forbids: [].}
+
+ + Converts a string s to its JSON representation with quotes. + Source   +Edit   + +
+
+
+
proc escapeJson(s: string; result: var string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Converts a string s to its JSON representation with quotes. Appends to result. + Source   +Edit   + +
+
+ +
+
+
+
proc escapeJsonUnquoted(s: string): string {....raises: [], tags: [], forbids: [].}
+
+ + Converts a string s to its JSON representation without quotes. + Source   +Edit   + +
+
+
+
proc escapeJsonUnquoted(s: string; result: var string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Converts a string s to its JSON representation without quotes. Appends to result. + Source   +Edit   + +
+
+ +
+
+
+
proc getBiggestInt(n: JsonNode; default: BiggestInt = 0): BiggestInt {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Retrieves the BiggestInt value of a JInt JsonNode.

+

Returns default if n is not a JInt, or if n is nil.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getBool(n: JsonNode; default: bool = false): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Retrieves the bool value of a JBool JsonNode.

+

Returns default if n is not a JBool, or if n is nil.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getElems(n: JsonNode; default: seq[JsonNode] = @[]): seq[JsonNode] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Retrieves the array of a JArray JsonNode.

+

Returns default if n is not a JArray, or if n is nil.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getFields(n: JsonNode; default = initOrderedTable[string, JsonNode](2)): OrderedTable[
+    string, JsonNode] {....raises: [], tags: [], forbids: [].}
+
+ +

Retrieves the key, value pairs of a JObject JsonNode.

+

Returns default if n is not a JObject, or if n is nil.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getFloat(n: JsonNode; default: float = 0.0): float {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Retrieves the float value of a JFloat JsonNode.

+

Returns default if n is not a JFloat or JInt, or if n is nil.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getInt(n: JsonNode; default: int = 0): int {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Retrieves the int value of a JInt JsonNode.

+

Returns default if n is not a JInt, or if n is nil.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getOrDefault(node: JsonNode; key: string): JsonNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Gets a field from a node. If node is nil or not an object or value at key does not exist, returns nil + Source   +Edit   + +
+
+ +
+
+
+
proc getStr(n: JsonNode; default: string = ""): string {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Retrieves the string value of a JString JsonNode.

+

Returns default if n is not a JString, or if n is nil.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc hash(n: JsonNode): Hash {.noSideEffect, ...raises: [Exception],
+                               tags: [RootEffect], forbids: [].}
+
+ + Compute the hash for a JSON node + Source   +Edit   + +
+
+
+
proc hash(n: OrderedTable[string, JsonNode]): Hash {.noSideEffect,
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasKey(node: JsonNode; key: string): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + Checks if key exists in node. + Source   +Edit   + +
+
+ +
+
+
+
proc len(n: JsonNode): int {....raises: [], tags: [], forbids: [].}
+
+ + If n is a JArray, it returns the number of elements. If n is a JObject, it returns the number of pairs. Else it returns 0. + Source   +Edit   + +
+
+ +
+
+
+
proc newJArray(): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new JArray JsonNode + Source   +Edit   + +
+
+ +
+
+
+
proc newJBool(b: bool): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new JBool JsonNode. + Source   +Edit   + +
+
+ +
+
+
+
proc newJFloat(n: float): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new JFloat JsonNode. + Source   +Edit   + +
+
+ +
+
+
+
proc newJInt(n: BiggestInt): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new JInt JsonNode. + Source   +Edit   + +
+
+ +
+
+
+
proc newJNull(): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new JNull JsonNode. + Source   +Edit   + +
+
+ +
+
+
+
proc newJObject(): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new JObject JsonNode + Source   +Edit   + +
+
+ +
+
+
+
proc newJString(s: string): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new JString JsonNode. + Source   +Edit   + +
+
+ +
+
+
+
proc parseFile(filename: string): JsonNode {.
+    ...raises: [IOError, OSError, JsonParsingError, ValueError],
+    tags: [ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + Parses file into a JsonNode. If file contains extra data, it will raise JsonParsingError. + Source   +Edit   + +
+
+ +
+
+
+
proc parseJson(buffer: string; rawIntegers = false; rawFloats = false): JsonNode {.
+    ...raises: [IOError, OSError, JsonParsingError, ValueError],
+    tags: [ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + Parses JSON from buffer. If buffer contains extra data, it will raise JsonParsingError. If rawIntegers is true, integer literals will not be converted to a JInt field but kept as raw numbers via JString. If rawFloats is true, floating point literals will not be converted to a JFloat field but kept as raw numbers via JString. + Source   +Edit   + +
+
+
+
proc parseJson(s: Stream; filename: string = ""; rawIntegers = false;
+               rawFloats = false): JsonNode {.
+    ...raises: [IOError, OSError, IOError, OSError, JsonParsingError, ValueError],
+    tags: [ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + Parses from a stream s into a JsonNode. filename is only needed for nice error messages. If s contains extra data, it will raise JsonParsingError. This closes the stream s after it's done. If rawIntegers is true, integer literals will not be converted to a JInt field but kept as raw numbers via JString. If rawFloats is true, floating point literals will not be converted to a JFloat field but kept as raw numbers via JString. + Source   +Edit   + +
+
+ +
+
+
+
proc pretty(node: JsonNode; indent = 2): string {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Returns a JSON Representation of node, with indentation and on multiple lines.

+

Similar to prettyprint in Python.

+ +

Example:

+
let j = %* {"name": "Isaac", "books": ["Robot Dreams"],
+            "details": {"age": 35, "pi": 3.1415}}
+doAssert pretty(j) == """
+{
+  "name": "Isaac",
+  "books": [
+    "Robot Dreams"
+  ],
+  "details": {
+    "age": 35,
+    "pi": 3.1415
+  }
+}"""
+ Source   +Edit   + +
+
+ +
+
+
+
proc to[T](node: JsonNode; t: typedesc[T]): T
+
+ +

Unmarshals the specified node into the object type specified.

+

Known limitations:

+
  • Heterogeneous arrays are not supported.
  • +
  • Sets in object variants are not supported.
  • +
  • Not nil annotations are not supported.
  • +
+ +

Example:

+
let jsonNode = parseJson("""
+      {
+        "person": {
+          "name": "Nimmer",
+          "age": 21
+        },
+        "list": [1, 2, 3, 4]
+      }
+    """)
+
+type
+  Person = object
+    name: string
+    age: int
+
+  Data = object
+    person: Person
+    list: seq[int]
+
+var data = to(jsonNode, Data)
+doAssert data.person.name == "Nimmer"
+doAssert data.person.age == 21
+doAssert data.list == @[1, 2, 3, 4]
+ Source   +Edit   + +
+
+ +
+
+
+
proc toUgly(result: var string; node: JsonNode) {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Converts node to its JSON Representation, without regard for human readability. Meant to improve $ string conversion performance.

+

JSON representation is stored in the passed result

+

This provides higher efficiency than the pretty procedure as it does not attempt to format the resulting JSON to make it human readable.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `{}`(node: JsonNode; index: varargs[int]): JsonNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Traverses the node and gets the given value. If any of the indexes do not exist, returns nil. Also returns nil if one of the intermediate data structures is not an array. + Source   +Edit   + +
+
+
+
proc `{}`(node: JsonNode; key: string): JsonNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Gets a field from a node. If node is nil or not an object or value at key does not exist, returns nil + Source   +Edit   + +
+
+
+
proc `{}`(node: JsonNode; keys: varargs[string]): JsonNode {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Traverses the node and gets the given value. If any of the keys do not exist, returns nil. Also returns nil if one of the intermediate data structures is not an object.

+

This proc can be used to create tree structures on the fly (sometimes called autovivification):

+ +

Example:

+
var myjson = %* {"parent": {"child": {"grandchild": 1}}}
+doAssert myjson{"parent", "child", "grandchild"} == newJInt(1)
+ Source   +Edit   + +
+
+ +
+
+
+
proc `{}=`(node: JsonNode; keys: varargs[string]; value: JsonNode) {.
+    ...raises: [KeyError], tags: [], forbids: [].}
+
+ + Traverses the node and tries to set the value at the given location to value. If any of the keys are missing, they are added. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator items(node: JsonNode): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ + Iterator for the items of node. node has to be a JArray. + Source   +Edit   + +
+
+ +
+
+
+
iterator keys(node: JsonNode): string {....raises: [], tags: [], forbids: [].}
+
+ + Iterator for the keys in node. node has to be a JObject. + Source   +Edit   + +
+
+ +
+
+
+
iterator mitems(node: var JsonNode): var JsonNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Iterator for the items of node. node has to be a JArray. Items can be modified. + Source   +Edit   + +
+
+ +
+
+
+
iterator mpairs(node: var JsonNode): tuple[key: string, val: var JsonNode] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Iterator for the child elements of node. node has to be a JObject. Values can be modified + Source   +Edit   + +
+
+ +
+
+
+
iterator pairs(node: JsonNode): tuple[key: string, val: JsonNode] {....raises: [],
+    tags: [], forbids: [].}
+
+ + Iterator for the child elements of node. node has to be a JObject. + Source   +Edit   + +
+
+ +
+
+
+
iterator parseJsonFragments(s: Stream; filename: string = "";
+                            rawIntegers = false; rawFloats = false): JsonNode {.
+    ...raises: [IOError, OSError, IOError, OSError, JsonParsingError, ValueError],
+    tags: [ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + Parses from a stream s into JsonNodes. filename is only needed for nice error messages. The JSON fragments are separated by whitespace. This can be substantially faster than the comparable loop for x in splitWhitespace(s): yield parseJson(x). This closes the stream s after it's done. If rawIntegers is true, integer literals will not be converted to a JInt field but kept as raw numbers via JString. If rawFloats is true, floating point literals will not be converted to a JFloat field but kept as raw numbers via JString. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro `%*`(x: untyped): untyped
+
+ + Convert an expression to a JsonNode directly, without having to specify % for every element. + Source   +Edit   + +
+
+ +
+
+
+
macro isRefSkipDistinct(arg: typed): untyped
+
+ + internal only, do not use + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template `%`(j: JsonNode): JsonNode
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/json.idx b/json.idx new file mode 100644 index 0000000000000..feb0e0f18c95e --- /dev/null +++ b/json.idx @@ -0,0 +1,100 @@ +nimTitle json json.html module std/json 0 +nim JNull json.html#JNull JsonNodeKind.JNull 185 +nim JBool json.html#JBool JsonNodeKind.JBool 185 +nim JInt json.html#JInt JsonNodeKind.JInt 185 +nim JFloat json.html#JFloat JsonNodeKind.JFloat 185 +nim JString json.html#JString JsonNodeKind.JString 185 +nim JObject json.html#JObject JsonNodeKind.JObject 185 +nim JArray json.html#JArray JsonNodeKind.JArray 185 +nim JsonNodeKind json.html#JsonNodeKind enum JsonNodeKind 185 +nim JsonNode json.html#JsonNode type JsonNode 194 +nim JsonNodeObj json.html#JsonNodeObj object JsonNodeObj 195 +nim newJString json.html#newJString,string proc newJString(s: string): JsonNode 216 +nim newJInt json.html#newJInt,BiggestInt proc newJInt(n: BiggestInt): JsonNode 227 +nim newJFloat json.html#newJFloat,float proc newJFloat(n: float): JsonNode 231 +nim newJBool json.html#newJBool,bool proc newJBool(b: bool): JsonNode 235 +nim newJNull json.html#newJNull proc newJNull(): JsonNode 239 +nim newJObject json.html#newJObject proc newJObject(): JsonNode 243 +nim newJArray json.html#newJArray proc newJArray(): JsonNode 247 +nim getStr json.html#getStr,JsonNode,string proc getStr(n: JsonNode; default: string = ""): string 251 +nim getInt json.html#getInt,JsonNode,int proc getInt(n: JsonNode; default: int = 0): int 258 +nim getBiggestInt json.html#getBiggestInt,JsonNode,BiggestInt proc getBiggestInt(n: JsonNode; default: BiggestInt = 0): BiggestInt 265 +nim getFloat json.html#getFloat,JsonNode,float proc getFloat(n: JsonNode; default: float = 0.0): float 272 +nim getBool json.html#getBool,JsonNode,bool proc getBool(n: JsonNode; default: bool = false): bool 282 +nim getFields json.html#getFields,JsonNode proc getFields(n: JsonNode; default = initOrderedTable[string, JsonNode](2)): OrderedTable[\n string, JsonNode] 289 +nim getElems json.html#getElems,JsonNode,seq[JsonNode] proc getElems(n: JsonNode; default: seq[JsonNode] = @[]): seq[JsonNode] 298 +nim add json.html#add,JsonNode,JsonNode proc add(father, child: JsonNode) 305 +nim add json.html#add,JsonNode,string,JsonNode proc add(obj: JsonNode; key: string; val: JsonNode) 310 +nim `%` json.html#%,string proc `%`(s: string): JsonNode 315 +nim `%` json.html#%,uint proc `%`(n: uint): JsonNode 319 +nim `%` json.html#%,int proc `%`(n: int): JsonNode 326 +nim `%` json.html#%,BiggestUInt proc `%`(n: BiggestUInt): JsonNode 330 +nim `%` json.html#%,BiggestInt proc `%`(n: BiggestInt): JsonNode 337 +nim `%` json.html#%,float proc `%`(n: float): JsonNode 341 +nim `%` json.html#%,bool proc `%`(b: bool): JsonNode 354 +nim `%` json.html#%,openArray[tuple[string,JsonNode]] proc `%`(keyVals: openArray[tuple[key: string, val: JsonNode]]): JsonNode 358 +nim `%` json.html#%.t,JsonNode template `%`(j: JsonNode): JsonNode 364 +nim `%` json.html#%,openArray[T] proc `%`[T](elements: openArray[T]): JsonNode 366 +nim `%` json.html#% proc `%`[T](table: Table[string, T] | OrderedTable[string, T]): JsonNode 371 +nim `%` json.html#%,Option[T] proc `%`[T](opt: Option[T]): JsonNode 376 +nim `[]=` json.html#[]=,JsonNode,string,JsonNode proc `[]=`(obj: JsonNode; key: string; val: JsonNode) 394 +nim `%` json.html#%,T proc `%`[T: object](o: T): JsonNode 399 +nim `%` json.html#%,ref. proc `%`(o: ref object): JsonNode 404 +nim `%` json.html#%_2 proc `%`(o: enum): JsonNode 411 +nim `%*` json.html#%*.m,untyped macro `%*`(x: untyped): untyped 442 +nim `==` json.html#==,JsonNode,JsonNode proc `==`(a, b: JsonNode): bool 447 +nim hash json.html#hash,OrderedTable[string,JsonNode] proc hash(n: OrderedTable[string, JsonNode]): Hash 483 +nim hash json.html#hash,JsonNode proc hash(n: JsonNode): Hash 485 +nim len json.html#len,JsonNode proc len(n: JsonNode): int 508 +nim `[]` json.html#[],JsonNode,string proc `[]`(node: JsonNode; name: string): JsonNode 517 +nim `[]` json.html#[],JsonNode,int proc `[]`(node: JsonNode; index: int): JsonNode 526 +nim `[]` json.html#[],JsonNode,BackwardsIndex proc `[]`(node: JsonNode; index: BackwardsIndex): JsonNode 534 +nim `[]` json.html#[],JsonNode,HSlice[U,V] proc `[]`[U, V](a: JsonNode; x: HSlice[U, V]): JsonNode 547 +nim hasKey json.html#hasKey,JsonNode,string proc hasKey(node: JsonNode; key: string): bool 565 +nim contains json.html#contains,JsonNode,string proc contains(node: JsonNode; key: string): bool 570 +nim contains json.html#contains,JsonNode,JsonNode proc contains(node: JsonNode; val: JsonNode): bool 575 +nim `{}` json.html#{},JsonNode,varargs[string] proc `{}`(node: JsonNode; keys: varargs[string]): JsonNode 580 +nim `{}` json.html#{},JsonNode,varargs[int] proc `{}`(node: JsonNode; index: varargs[int]): JsonNode 598 +nim getOrDefault json.html#getOrDefault,JsonNode,string proc getOrDefault(node: JsonNode; key: string): JsonNode 608 +nim `{}` json.html#{},JsonNode,string proc `{}`(node: JsonNode; key: string): JsonNode 614 +nim `{}=` json.html#{}=,JsonNode,varargs[string],JsonNode proc `{}=`(node: JsonNode; keys: varargs[string]; value: JsonNode) 619 +nim delete json.html#delete,JsonNode,string proc delete(obj: JsonNode; key: string) 629 +nim copy json.html#copy,JsonNode proc copy(p: JsonNode): JsonNode 636 +nim escapeJsonUnquoted json.html#escapeJsonUnquoted,string,string proc escapeJsonUnquoted(s: string; result: var string) 671 +nim escapeJsonUnquoted json.html#escapeJsonUnquoted,string proc escapeJsonUnquoted(s: string): string 688 +nim escapeJson json.html#escapeJson,string,string proc escapeJson(s: string; result: var string) 693 +nim escapeJson json.html#escapeJson,string proc escapeJson(s: string): string 700 +nim toUgly json.html#toUgly,string,JsonNode proc toUgly(result: var string; node: JsonNode) 705 +nim pretty json.html#pretty,JsonNode,int proc pretty(node: JsonNode; indent = 2): string 802 +nim `$` json.html#$,JsonNode proc `$`(node: JsonNode): string 824 +nim items json.html#items.i,JsonNode iterator items(node: JsonNode): JsonNode 829 +nim mitems json.html#mitems.i,JsonNode iterator mitems(node: var JsonNode): var JsonNode 835 +nim pairs json.html#pairs.i,JsonNode iterator pairs(node: JsonNode): tuple[key: string, val: JsonNode] 842 +nim keys json.html#keys.i,JsonNode iterator keys(node: JsonNode): string 848 +nim mpairs json.html#mpairs.i,JsonNode iterator mpairs(node: var JsonNode): tuple[key: string, val: var JsonNode] 854 +nim parseJsonFragments json.html#parseJsonFragments.i,Stream,string iterator parseJsonFragments(s: Stream; filename: string = ""; rawIntegers = false;\n rawFloats = false): JsonNode 929 +nim parseJson json.html#parseJson,Stream,string proc parseJson(s: Stream; filename: string = ""; rawIntegers = false;\n rawFloats = false): JsonNode 949 +nim parseJson json.html#parseJson,string proc parseJson(buffer: string; rawIntegers = false; rawFloats = false): JsonNode 1040 +nim parseFile json.html#parseFile,string proc parseFile(filename: string): JsonNode 1049 +nim isRefSkipDistinct json.html#isRefSkipDistinct.m,typed macro isRefSkipDistinct(arg: typed): untyped 1071 +nim to json.html#to,JsonNode,typedesc[T] proc to[T](node: JsonNode; t: typedesc[T]): T 1331 +idx JSON json.html#json_1 Module json 0 +heading See also json.html#see-also See also 0 +heading Overview json.html#overview Overview 0 +heading Parsing JSON json.html#overview-parsing-json Parsing JSON 0 +heading Reading values json.html#overview-reading-values Reading values 0 +heading Handling optional keys json.html#overview-handling-optional-keys Handling optional keys 0 +heading Using default values json.html#overview-using-default-values Using default values 0 +heading Unmarshalling json.html#overview-unmarshalling Unmarshalling 0 +heading Creating JSON json.html#creating-json Creating JSON 0 +idx Unmarshals json.html#unmarshals_1 Creating JSON 0 +idx autovivification json.html#autovivification_1 Creating JSON 0 +nimgrp parsejson json.html#parseJson-procs-all proc 949 +nimgrp escapejsonunquoted json.html#escapeJsonUnquoted-procs-all proc 671 +nimgrp contains json.html#contains-procs-all proc 570 +nimgrp % json.html#%-procs-all proc 315 +nimgrp escapejson json.html#escapeJson-procs-all proc 693 +nimgrp [] json.html#[]-procs-all proc 517 +nimgrp add json.html#add-procs-all proc 305 +nimgrp {} json.html#{}-procs-all proc 580 +nimgrp hash json.html#hash-procs-all proc 483 diff --git a/jsonutils.html b/jsonutils.html new file mode 100644 index 0000000000000..0800052d887cd --- /dev/null +++ b/jsonutils.html @@ -0,0 +1,457 @@ + + + + + + + +std/jsonutils + + + + + + + + + + + + + + + + +
+
+

std/jsonutils

+
+ +
+ Source   +Edit   + +
+ +

This module implements a hookable (de)serialization for arbitrary types using JSON. Design goal: avoid importing modules where a custom serialization is needed; see strtabs.fromJsonHook,toJsonHook for an example. +

Example:

+
import std/jsonutils
+import std/[strtabs,json]
+type Foo = ref object
+  t: bool
+  z1: int8
+let a = (1.5'f32, (b: "b2", a: "a2"), 'x', @[Foo(t: true, z1: -3), nil], [{"name": "John"}.newStringTable])
+let j = a.toJson
+assert j.jsonTo(typeof(a)).toJson == j
+assert $[NaN, Inf, -Inf, 0.0, -0.0, 1.0, 1e-2].toJson == """["nan","inf","-inf",0.0,-0.0,1.0,0.01]"""
+assert 0.0.toJson.kind == JFloat
+assert Inf.toJson.kind == JString

+ +
+

Types

+
+
+
EnumMode = enum
+  joptEnumOrd, joptEnumSymbol, joptEnumString
+
+ + + Source   +Edit   + +
+
+
+
Joptions = object
+  allowExtraKeys*: bool ## If `true` Nim's object to which the JSON is parsed is not required to
+                        ## have a field for every JSON key.
+  allowMissingKeys*: bool ## If `true` Nim's object to which JSON is parsed is allowed to have
+                          ## fields without corresponding JSON keys.
+
+ + Options controlling the behavior of fromJson. + Source   +Edit   + +
+
+
+
JsonNodeMode = enum
+  joptJsonNodeAsRef,        ## returns the ref as is
+  joptJsonNodeAsCopy,       ## returns a deep copy of the JsonNode
+  joptJsonNodeAsObject       ## treats JsonNode as a regular ref object
+
+ + controls toJson for JsonNode types + Source   +Edit   + +
+
+
+
ToJsonOptions = object
+  enumMode*: EnumMode
+  jsonNodeMode*: JsonNodeMode
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc fromJson[T](a: var T; b: JsonNode; opt = Joptions())
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fromJsonHook(a: var StringTableRef; b: JsonNode) {.
+    ...raises: [ValueError, KeyError, JsonKindError], tags: [RootEffect],
+    forbids: [].}
+
+ +

Enables fromJson for StringTableRef type.

+

See also:

+ + +

Example:

+
import std/[strtabs, json]
+var t = newStringTable(modeCaseSensitive)
+let jsonStr = """{"mode": 0, "table": {"name": "John", "surname": "Doe"}}"""
+fromJsonHook(t, parseJson(jsonStr))
+assert t[] == newStringTable("name", "John", "surname", "Doe",
+                             modeCaseSensitive)[]
+ Source   +Edit   + +
+
+
+
proc fromJsonHook[A](s: var SomeSet[A]; jsonNode: JsonNode; opt = Joptions())
+
+ +

Enables fromJson for HashSet and OrderedSet types.

+

See also:

+ + +

Example:

+
import std/[sets, json]
+var foo: tuple[hs: HashSet[string], os: OrderedSet[string]]
+fromJson(foo, parseJson("""
+      {"hs": ["hash", "set"], "os": ["ordered", "set"]}"""))
+assert foo.hs == ["hash", "set"].toHashSet
+assert foo.os == ["ordered", "set"].toOrderedSet
+ Source   +Edit   + +
+
+
+
proc fromJsonHook[K: string | cstring; V](
+    t: var (Table[K, V] | OrderedTable[K, V]); jsonNode: JsonNode;
+    opt = Joptions())
+
+ +

Enables fromJson for Table and OrderedTable types.

+

See also:

+ + +

Example:

+
import std/[tables, json]
+var foo: tuple[t: Table[string, int], ot: OrderedTable[string, int]]
+fromJson(foo, parseJson("""
+      {"t":{"two":2,"one":1},"ot":{"one":1,"three":3}}"""))
+assert foo.t == [("one", 1), ("two", 2)].toTable
+assert foo.ot == [("one", 1), ("three", 3)].toOrderedTable
+ Source   +Edit   + +
+
+
+
proc fromJsonHook[T](self: var Option[T]; jsonNode: JsonNode; opt = Joptions())
+
+ +

Enables fromJson for Option types.

+

See also:

+ + +

Example:

+
import std/[options, json]
+var opt: Option[string]
+fromJsonHook(opt, parseJson("\"test\""))
+assert get(opt) == "test"
+fromJson(opt, parseJson("null"))
+assert isNone(opt)
+ Source   +Edit   + +
+
+ +
+
+
+
proc initToJsonOptions(): ToJsonOptions {....raises: [], tags: [], forbids: [].}
+
+ + initializes ToJsonOptions with sane options. + Source   +Edit   + +
+
+ +
+
+
+
proc jsonTo(b: JsonNode; T: typedesc; opt = Joptions()): T:type
+
+ + reverse of toJson + Source   +Edit   + +
+
+ +
+
+
+
proc toJson[T](a: T; opt = initToJsonOptions()): JsonNode
+
+ + serializes a to json; uses toJsonHook(a: T) if it's in scope to customize serialization, see strtabs.toJsonHook for an example.
Note: +With -d:nimPreviewJsonutilsHoleyEnum, toJson now can serialize/deserialize holey enums as regular enums (via ord) instead of as strings. It is expected that this behavior becomes the new default in upcoming versions.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc toJsonHook(a: StringTableRef): JsonNode {....raises: [], tags: [], forbids: [].}
+
+ +

Enables toJson for StringTableRef type.

+

See also:

+ + +

Example:

+
import std/[strtabs, json]
+let t = newStringTable("name", "John", "surname", "Doe", modeCaseSensitive)
+let jsonStr = """{"mode": "modeCaseSensitive",
+                      "table": {"name": "John", "surname": "Doe"}}"""
+assert toJson(t) == parseJson(jsonStr)
+ Source   +Edit   + +
+
+
+
proc toJsonHook[A](s: SomeSet[A]; opt = initToJsonOptions()): JsonNode
+
+ +

Enables toJson for HashSet and OrderedSet types.

+

See also:

+ + +

Example:

+
import std/[sets, json]
+let foo = (hs: ["hash"].toHashSet, os: ["ordered", "set"].toOrderedSet)
+assert $toJson(foo) == """{"hs":["hash"],"os":["ordered","set"]}"""
+ Source   +Edit   + +
+
+
+
proc toJsonHook[K: string | cstring; V](t: (Table[K, V] | OrderedTable[K, V]);
+                                        opt = initToJsonOptions()): JsonNode
+
+ +

Enables toJson for Table and OrderedTable types.

+

See also:

+ + +

Example:

+
import std/[tables, json, sugar]
+let foo = (
+  t: [("two", 2)].toTable,
+  ot: [("one", 1), ("three", 3)].toOrderedTable)
+assert $toJson(foo) == """{"t":{"two":2},"ot":{"one":1,"three":3}}"""
+# if keys are not string|cstring, you can use this:
+let a = {10: "foo", 11: "bar"}.newOrderedTable
+let a2 = collect: (for k,v in a: (k,v))
+assert $toJson(a2) == """[[10,"foo"],[11,"bar"]]"""
+ Source   +Edit   + +
+
+
+
proc toJsonHook[T](self: Option[T]; opt = initToJsonOptions()): JsonNode
+
+ +

Enables toJson for Option types.

+

See also:

+ + +

Example:

+
import std/[options, json]
+let optSome = some("test")
+assert $toJson(optSome) == "\"test\""
+let optNone = none[string]()
+assert $toJson(optNone) == "null"
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/jsonutils.idx b/jsonutils.idx new file mode 100644 index 0000000000000..94f662db84024 --- /dev/null +++ b/jsonutils.idx @@ -0,0 +1,25 @@ +nimTitle jsonutils jsonutils.html module std/jsonutils 0 +nim Joptions jsonutils.html#Joptions object Joptions 44 +nim joptEnumOrd jsonutils.html#joptEnumOrd EnumMode.joptEnumOrd 53 +nim joptEnumSymbol jsonutils.html#joptEnumSymbol EnumMode.joptEnumSymbol 53 +nim joptEnumString jsonutils.html#joptEnumString EnumMode.joptEnumString 53 +nim EnumMode jsonutils.html#EnumMode enum EnumMode 53 +nim joptJsonNodeAsRef jsonutils.html#joptJsonNodeAsRef JsonNodeMode.joptJsonNodeAsRef 57 +nim joptJsonNodeAsCopy jsonutils.html#joptJsonNodeAsCopy JsonNodeMode.joptJsonNodeAsCopy 57 +nim joptJsonNodeAsObject jsonutils.html#joptJsonNodeAsObject JsonNodeMode.joptJsonNodeAsObject 57 +nim JsonNodeMode jsonutils.html#JsonNodeMode enum JsonNodeMode 57 +nim ToJsonOptions jsonutils.html#ToJsonOptions object ToJsonOptions 61 +nim initToJsonOptions jsonutils.html#initToJsonOptions proc initToJsonOptions(): ToJsonOptions 66 +nim fromJson jsonutils.html#fromJson,T,JsonNode proc fromJson[T](a: var T; b: JsonNode; opt = Joptions()) 183 +nim jsonTo jsonutils.html#jsonTo,JsonNode,typedesc proc jsonTo(b: JsonNode; T: typedesc; opt = Joptions()): T:type 294 +nim toJson jsonutils.html#toJson,T proc toJson[T](a: T; opt = initToJsonOptions()): JsonNode 299 +nim fromJsonHook jsonutils.html#fromJsonHook,,JsonNode proc fromJsonHook[K: string | cstring; V](t: var (Table[K, V] | OrderedTable[K, V]);\n jsonNode: JsonNode; opt = Joptions()) 349 +nim toJsonHook jsonutils.html#toJsonHook proc toJsonHook[K: string | cstring; V](t: (Table[K, V] | OrderedTable[K, V]);\n opt = initToJsonOptions()): JsonNode 370 +nim fromJsonHook jsonutils.html#fromJsonHook,SomeSet[A],JsonNode proc fromJsonHook[A](s: var SomeSet[A]; jsonNode: JsonNode; opt = Joptions()) 391 +nim toJsonHook jsonutils.html#toJsonHook,SomeSet[A] proc toJsonHook[A](s: SomeSet[A]; opt = initToJsonOptions()): JsonNode 411 +nim fromJsonHook jsonutils.html#fromJsonHook,Option[T],JsonNode proc fromJsonHook[T](self: var Option[T]; jsonNode: JsonNode; opt = Joptions()) 425 +nim toJsonHook jsonutils.html#toJsonHook,Option[T] proc toJsonHook[T](self: Option[T]; opt = initToJsonOptions()): JsonNode 443 +nim fromJsonHook jsonutils.html#fromJsonHook,StringTableRef,JsonNode proc fromJsonHook(a: var StringTableRef; b: JsonNode) 460 +nim toJsonHook jsonutils.html#toJsonHook,StringTableRef proc toJsonHook(a: StringTableRef): JsonNode 478 +nimgrp tojsonhook jsonutils.html#toJsonHook-procs-all proc 370 +nimgrp fromjsonhook jsonutils.html#fromJsonHook-procs-all proc 349 diff --git a/jsre.html b/jsre.html new file mode 100644 index 0000000000000..7579358a926ec --- /dev/null +++ b/jsre.html @@ -0,0 +1,406 @@ + + + + + + + +std/jsre + + + + + + + + + + + + + + + + +
+
+

std/jsre

+
+ +
+ Source   +Edit   + +
+ +

Regular Expressions for the JavaScript target.

+ +

Example:

+
import std/jsre
+let jsregex: RegExp = newRegExp(r"\s+", r"i")
+jsregex.compile(r"\w+", r"i")
+assert "nim javascript".contains jsregex
+assert jsregex.exec(r"nim javascript") == @["nim".cstring]
+assert jsregex.toCstring() == r"/\w+/i"
+jsregex.compile(r"[0-9]", r"i")
+assert "0123456789abcd".contains jsregex
+assert $jsregex == "/[0-9]/i"
+jsregex.compile(r"abc", r"i")
+assert "abcd".startsWith jsregex
+assert "dabc".endsWith jsregex
+jsregex.compile(r"\d", r"i")
+assert "do1ne".split(jsregex) == @["do".cstring, "ne".cstring]
+jsregex.compile(r"[lw]", r"i")
+assert "hello world".replace(jsregex,"X") == "heXlo world"
+jsregex.compile(r"([a-z])\1*", r"g")
+assert "abbcccdddd".replace(jsregex, proc (m: varargs[cstring]): cstring = ($m[0] & $(m.len)).cstring) == "a1b2c3d4"
+let digitsRegex: RegExp = newRegExp(r"\d")
+assert "foo".match(digitsRegex) == @[]

+
+

Types

+
+
+
RegExp = ref object of JsRoot
+  flags*: cstring            ## cstring that contains the flags of the RegExp object.
+  dotAll*: bool              ## Whether `.` matches newlines or not.
+  global*: bool              ## Whether to test against all possible matches in a string, or only against the first.
+  ignoreCase*: bool          ## Whether to ignore case while attempting a match in a string.
+  multiline*: bool           ## Whether to search in strings across multiple lines.
+  source*: cstring           ## The text of the pattern.
+  sticky*: bool              ## Whether the search is sticky.
+  unicode*: bool             ## Whether Unicode features are enabled.
+  lastIndex*: cint           ## Index at which to start the next match (read/write property).
+  input*: cstring            ## Read-only and modified on successful match.
+  lastMatch*: cstring        ## Ditto.
+  lastParen*: cstring        ## Ditto.
+  leftContext*: cstring      ## Ditto.
+  rightContext*: cstring     ## Ditto.
+  hasIndices*: bool          ## https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/hasIndices
+
+ + Regular Expressions for JavaScript target. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `$`(self: RegExp): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func compile(self: RegExp; pattern: cstring; flags: cstring) {.
+    importjs: "#.compile(@)", ...raises: [], tags: [], forbids: [].}
+
+ + Recompiles a regular expression during execution of a script. + Source   +Edit   + +
+
+ +
+
+
+
func contains(pattern: cstring; self: RegExp): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + Tests for a substring match in its string parameter. +

Example:

+
let jsregex: RegExp = newRegExp(r"bc$", r"i")
+assert jsregex in r"abc"
+assert jsregex notin r"abcd"
+assert "xabc".contains jsregex
+ Source   +Edit   + +
+
+ +
+
+
+
func endsWith(pattern: cstring; self: RegExp): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + Tests if string ends with given RegExp +

Example:

+
let jsregex: RegExp = newRegExp(r"bcd", r"i")
+assert "abcd".endsWith jsregex
+ Source   +Edit   + +
+
+ +
+
+
+
func exec(self: RegExp; pattern: cstring): seq[cstring] {.
+    importjs: "(#.exec(#) || [])", ...raises: [], tags: [], forbids: [].}
+
+ + Executes a search for a match in its string parameter. + Source   +Edit   + +
+
+ +
+
+
+
func match(pattern: cstring; self: RegExp): seq[cstring] {.
+    importjs: "(#.match(#) || [])", ...raises: [], tags: [], forbids: [].}
+
+ + Returns an array of matches of a RegExp against given string + Source   +Edit   + +
+
+ +
+
+
+
func newRegExp(pattern: cstring): RegExp {.importjs: "new RegExp(@)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func newRegExp(pattern: cstring; flags: cstring): RegExp {.
+    importjs: "new RegExp(@)", ...raises: [], tags: [], forbids: [].}
+
+ + Creates a new RegExp object. + Source   +Edit   + +
+
+ +
+
+
+
func replace(pattern: cstring; self: RegExp;
+             cb: proc (args: varargs[cstring]): cstring): cstring {.importcpp,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Returns a new string with some or all matches of a pattern replaced by given callback function + Source   +Edit   + +
+
+
+
func replace(pattern: cstring; self: RegExp; replacement: cstring): cstring {.
+    importjs: "#.replace(#, #)", ...raises: [], tags: [], forbids: [].}
+
+ + Returns a new string with some or all matches of a pattern replaced by given replacement + Source   +Edit   + +
+
+ +
+
+
+
func split(pattern: cstring; self: RegExp): seq[cstring] {.
+    importjs: "(#.split(#) || [])", ...raises: [], tags: [], forbids: [].}
+
+ + Divides a string into an ordered list of substrings and returns the array + Source   +Edit   + +
+
+ +
+
+
+
func startsWith(pattern: cstring; self: RegExp): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + Tests if string starts with given RegExp +

Example:

+
let jsregex: RegExp = newRegExp(r"abc", r"i")
+assert "abcd".startsWith jsregex
+ Source   +Edit   + +
+
+ +
+
+
+
func toCstring(self: RegExp): cstring {.importjs: "#.toString()", ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + Returns a string representing the RegExp object. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/jsre.idx b/jsre.idx new file mode 100644 index 0000000000000..79be62abad23c --- /dev/null +++ b/jsre.idx @@ -0,0 +1,17 @@ +nimTitle jsre jsre.html module std/jsre 0 +nim RegExp jsre.html#RegExp type RegExp 6 +nim newRegExp jsre.html#newRegExp,cstring,cstring proc newRegExp(pattern: cstring; flags: cstring): RegExp 26 +nim newRegExp jsre.html#newRegExp,cstring proc newRegExp(pattern: cstring): RegExp 29 +nim compile jsre.html#compile,RegExp,cstring,cstring proc compile(self: RegExp; pattern: cstring; flags: cstring) 31 +nim replace jsre.html#replace,cstring,RegExp,cstring proc replace(pattern: cstring; self: RegExp; replacement: cstring): cstring 34 +nim replace jsre.html#replace,cstring,RegExp,proc(varargs[cstring]) proc replace(pattern: cstring; self: RegExp;\n cb: proc (args: varargs[cstring]): cstring): cstring 37 +nim split jsre.html#split,cstring,RegExp proc split(pattern: cstring; self: RegExp): seq[cstring] 40 +nim match jsre.html#match,cstring,RegExp proc match(pattern: cstring; self: RegExp): seq[cstring] 43 +nim exec jsre.html#exec,RegExp,cstring proc exec(self: RegExp; pattern: cstring): seq[cstring] 46 +nim toCstring jsre.html#toCstring,RegExp proc toCstring(self: RegExp): cstring 49 +nim `$` jsre.html#$,RegExp proc `$`(self: RegExp): string 52 +nim contains jsre.html#contains,cstring,RegExp proc contains(pattern: cstring; self: RegExp): bool 54 +nim startsWith jsre.html#startsWith,cstring,RegExp proc startsWith(pattern: cstring; self: RegExp): bool 63 +nim endsWith jsre.html#endsWith,cstring,RegExp proc endsWith(pattern: cstring; self: RegExp): bool 70 +nimgrp replace jsre.html#replace-procs-all proc 34 +nimgrp newregexp jsre.html#newRegExp-procs-all proc 26 diff --git a/jsutils.html b/jsutils.html new file mode 100644 index 0000000000000..10a1038f3516d --- /dev/null +++ b/jsutils.html @@ -0,0 +1,531 @@ + + + + + + + +std/private/jsutils + + + + + + + + + + + + + + + + +
+
+

std/private/jsutils

+
+ +
+ Source   +Edit   + +
+ +

+

Example:

+
import std/private/jsutils
+let a {.importjs: "Number.MAX_SAFE_INTEGER".}: int64
+assert a == maxSafeInteger

+
+

Imports

+
+ jsbigints +
+
+
+

Types

+
+
+
ArrayBuffer = ref object of JsRoot
+
+ + + Source   +Edit   + +
+
+
+
BigUint64Array = ref object of JsRoot
+
+ + + Source   +Edit   + +
+
+
+
Float64Array = ref object of JsRoot
+
+ + + Source   +Edit   + +
+
+
+
Uint8Array = ref object of JsRoot
+
+ + + Source   +Edit   + +
+
+
+
Uint32Array = ref object of JsRoot
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
hasWorkingInt64 = true
+
+ + + Source   +Edit   + +
+
+
+
jsNoBigInt64 = false
+
+ + + Source   +Edit   + +
+
+
+
maxSafeInteger = 9007199254740991'i64
+
+ + The same as Number.MAX_SAFE_INTEGER or 2^53 - 1. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `[]`(arr: BigUint64Array; i: int): JsBigInt {.importjs: "#[#]", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `[]`(arr: Uint8Array; i: int): uint8 {.importjs: "#[#]", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `[]`(arr: Uint32Array; i: int): uint32 {.importjs: "#[#]", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `[]=`(arr: Float64Array; i: int; v: float) {.importjs: "#[#] = #",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getProtoName[T](a: T): cstring {.importjs: "Object.prototype.toString.call(#)",
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + +

Example:

+
import std/[jsffi, jsbigints]
+type A = ref object
+assert 1.toJs.getProtoName == "[object Number]"
+assert "a".toJs.getProtoName == "[object String]"
+assert big"1".toJs.getProtoName == "[object BigInt]"
+assert false.toJs.getProtoName == "[object Boolean]"
+assert (a: 1).toJs.getProtoName == "[object Object]"
+assert A.default.toJs.getProtoName == "[object Null]"
+assert [1].toJs.getProtoName == "[object Int32Array]" # implementation defined
+assert @[1].toJs.getProtoName == "[object Array]" # ditto
+ Source   +Edit   + +
+
+ +
+
+
+
proc hasBigUint64Array(): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasJsBigInt(): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isInteger[T](x: T): bool {.importjs: "Number.isInteger(#)", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + +

Example:

+
import std/jsffi
+assert 1.isInteger
+assert not 1.5.isInteger
+assert 1.toJs.isInteger
+assert not 1.5.toJs.isInteger
+ Source   +Edit   + +
+
+ +
+
+
+
proc isSafeInteger[T](x: T): bool {.importjs: "Number.isSafeInteger(#)",
+                                    ...raises: [], tags: [], forbids: [].}
+
+ + +

Example:

+
import std/jsffi
+assert not "123".toJs.isSafeInteger
+assert 123.isSafeInteger
+assert 123.toJs.isSafeInteger
+when false:
+  assert 9007199254740991.toJs.isSafeInteger
+  assert not 9007199254740992.toJs.isSafeInteger
+ Source   +Edit   + +
+
+ +
+
+
+
proc jsConstructorName[T](a: T): cstring
+
+ + +

Example:

+
import std/jsffi
+let a = array[2, float64].default
+assert jsConstructorName(a) == "Float64Array"
+assert jsConstructorName(a.toJs) == "Float64Array"
+ Source   +Edit   + +
+
+ +
+
+
+
proc jsTypeOf[T](x: T): cstring {.importjs: "typeof(#)", ...raises: [], tags: [],
+                                  forbids: [].}
+
+ + Returns the name of the JsObject's JavaScript type as a cstring. +

Example:

+
import std/[jsffi, jsbigints]
+assert jsTypeOf(1.toJs) == "number"
+assert jsTypeOf(false.toJs) == "boolean"
+assert [1].toJs.jsTypeOf == "object" # note the difference with `getProtoName`
+assert big"1".toJs.jsTypeOf == "bigint"
+ Source   +Edit   + +
+
+ +
+
+
+
func newArrayBuffer(n: int): ArrayBuffer {.importjs: "new ArrayBuffer(#)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func newBigUint64Array(buffer: ArrayBuffer): BigUint64Array {.
+    importjs: "new BigUint64Array(#)", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func newFloat64Array(buffer: ArrayBuffer): Float64Array {.
+    importjs: "new Float64Array(#)", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func newUint8Array(n: int): Uint8Array {.importjs: "new Uint8Array(#)",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func newUint32Array(buffer: ArrayBuffer): Uint32Array {.
+    importjs: "new Uint32Array(#)", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/jsutils.idx b/jsutils.idx new file mode 100644 index 0000000000000..936bbc13e2ed1 --- /dev/null +++ b/jsutils.idx @@ -0,0 +1,26 @@ +nimTitle jsutils jsutils.html module std/private/jsutils 0 +nim ArrayBuffer jsutils.html#ArrayBuffer type ArrayBuffer 5 +nim Float64Array jsutils.html#Float64Array type Float64Array 6 +nim Uint32Array jsutils.html#Uint32Array type Uint32Array 7 +nim Uint8Array jsutils.html#Uint8Array type Uint8Array 8 +nim BigUint64Array jsutils.html#BigUint64Array type BigUint64Array 9 +nim newArrayBuffer jsutils.html#newArrayBuffer,int proc newArrayBuffer(n: int): ArrayBuffer 12 +nim newFloat64Array jsutils.html#newFloat64Array,ArrayBuffer proc newFloat64Array(buffer: ArrayBuffer): Float64Array 13 +nim newUint32Array jsutils.html#newUint32Array,ArrayBuffer proc newUint32Array(buffer: ArrayBuffer): Uint32Array 14 +nim newBigUint64Array jsutils.html#newBigUint64Array,ArrayBuffer proc newBigUint64Array(buffer: ArrayBuffer): BigUint64Array 15 +nim newUint8Array jsutils.html#newUint8Array,int proc newUint8Array(n: int): Uint8Array 17 +nim `[]` jsutils.html#[],Uint32Array,int proc `[]`(arr: Uint32Array; i: int): uint32 19 +nim `[]` jsutils.html#[],Uint8Array,int proc `[]`(arr: Uint8Array; i: int): uint8 20 +nim `[]` jsutils.html#[],BigUint64Array,int proc `[]`(arr: BigUint64Array; i: int): JsBigInt 21 +nim `[]=` jsutils.html#[]=,Float64Array,int,float proc `[]=`(arr: Float64Array; i: int; v: float) 22 +nim jsTypeOf jsutils.html#jsTypeOf,T proc jsTypeOf[T](x: T): cstring 24 +nim jsConstructorName jsutils.html#jsConstructorName,T proc jsConstructorName[T](a: T): cstring 34 +nim hasJsBigInt jsutils.html#hasJsBigInt proc hasJsBigInt(): bool 42 +nim hasBigUint64Array jsutils.html#hasBigUint64Array proc hasBigUint64Array(): bool 45 +nim getProtoName jsutils.html#getProtoName,T proc getProtoName[T](a: T): cstring 48 +nim maxSafeInteger jsutils.html#maxSafeInteger const maxSafeInteger 61 +nim isInteger jsutils.html#isInteger,T proc isInteger[T](x: T): bool 68 +nim isSafeInteger jsutils.html#isSafeInteger,T proc isSafeInteger[T](x: T): bool 76 +nim jsNoBigInt64 jsutils.html#jsNoBigInt64 const jsNoBigInt64 86 +nim hasWorkingInt64 jsutils.html#hasWorkingInt64 const hasWorkingInt64 95 +nimgrp [] jsutils.html#[]-procs-all proc 19 diff --git a/koch.html b/koch.html new file mode 100644 index 0000000000000..a59744514a475 --- /dev/null +++ b/koch.html @@ -0,0 +1,116 @@ + + + + + + + +Nim maintenance script + + + + + + + + + + + + + + + + +
+
+

Nim maintenance script

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + + +
+
+ Source   +Edit   + +
+ +

+
Version:2.2.1

"A great chef is an artist that I truly respect" -- Robert Stack.

+ +

Introduction

The koch program is Nim's maintenance script. It is a replacement for make and shell scripting with the advantage that it is much more portable. The word koch means cook in German. koch is used mainly to build the Nim compiler, but it can also be used for other tasks. This document describes the supported commands and their options.

+ +

Commands

+

boot command

The boot command bootstraps the compiler, and it accepts different options:

+
-d:release
By default a debug version is created, passing this option will force a release build, which is much faster and should be preferred unless you are debugging the compiler.
+
-d:nimUseLinenoise
Use the linenoise library for interactive mode (not needed on Windows).
+
-d:leanCompiler
Produce a compiler without JS codegen or documentation generator in order to use less RAM for bootstrapping.
+

After compilation is finished you will hopefully end up with the nim compiler in the bin directory. You can add Nim's bin directory to your $PATH or use the install command to place it where it will be found.

+ +

csource command

The csource command builds the C sources for installation. It accepts the same options as you would pass to the boot command.

+ +

temp command

The temp command builds the Nim compiler but with a different final name (nim_temp), so it doesn't overwrite your normal compiler. You can use this command to test different options, the same you would issue for the boot command.

+ +

test command

The test command can also be invoked with the alias tests. This command will compile and run testament/tester.nim, which is the main driver of Nim's test suite. You can pass options to the test command, they will be forwarded to the tester. See its source code for available options.

+ +

web command

The web command converts the documentation in the doc directory from rst to HTML. It also repeats the same operation but places the result in the web/upload which can be used to update the website at https://nim-lang.org.

+

By default, the documentation will be built in parallel using the number of available CPU cores. If any documentation build sub-commands fail, they will be rerun in serial fashion so that meaningful error output can be gathered for inspection. The --parallelBuild:n switch or configuration option can be used to force a specific number of parallel jobs or run everything serially from the start (n == 1).

+ +

pdf command

The pdf command builds PDF versions of Nim documentation: Manual, Tutorial and a few other documents. To run it one needs to install Latex/xelatex first.

+

+ +
+
+ + +
+
+ + + + diff --git a/koch.idx b/koch.idx new file mode 100644 index 0000000000000..cefe3bf3cb642 --- /dev/null +++ b/koch.idx @@ -0,0 +1,15 @@ +markupTitle Nim maintenance script koch.html Nim maintenance script 0 +heading Introduction koch.html#introduction Introduction 0 +idx koch koch.html#koch_1 Introduction 0 +heading Commands koch.html#commands Commands 0 +heading boot command koch.html#commands-boot-command boot command 0 +idx boot koch.html#boot_1 boot command 0 +heading csource command koch.html#commands-csource-command csource command 0 +idx csource koch.html#csource_1 csource command 0 +heading temp command koch.html#commands-temp-command temp command 0 +heading test command koch.html#commands-test-command test command 0 +idx test koch.html#test_1 test command 0 +heading web command koch.html#commands-web-command web command 0 +idx web koch.html#web_1 web command 0 +heading pdf command koch.html#commands-pdf-command pdf command 0 +idx pdf koch.html#pdf_1 pdf command 0 diff --git a/kqueue.html b/kqueue.html new file mode 100644 index 0000000000000..c002ffdd8e996 --- /dev/null +++ b/kqueue.html @@ -0,0 +1,561 @@ + + + + + + + +std/kqueue + + + + + + + + + + + + + + + + +
+
+

std/kqueue

+
+ +
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ posix +
+
+
+

Types

+
+
+
KEvent {.importc: "struct kevent", header: """#include <sys/types.h>
+                       #include <sys/event.h>
+                       #include <sys/time.h>""",
+         pure, final.} = object
+  ident*: uint               ## identifier for this event  (uintptr_t)
+  filter*: cshort            ## filter for event
+  flags*: cushort            ## general flags
+  fflags*: cuint             ## filter-specific flags
+  data*: int                 ## filter-specific data  (intptr_t)
+  udata*: pointer            ## opaque user data identifier
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
EV_ADD = 0x00000001
+
+ + Add event to queue (implies enable). Re-adding an existing element modifies it. + Source   +Edit   + +
+
+
+
EV_CLEAR = 0x00000020
+
+ + Clear event state after reporting. + Source   +Edit   + +
+
+
+
EV_DELETE = 0x00000002
+
+ + Delete event from queue. + Source   +Edit   + +
+
+
+
EV_DISABLE = 0x00000008
+
+ + Disable event (not reported). + Source   +Edit   + +
+
+
+
EV_DISPATCH = 0x00000080
+
+ + Disable event after reporting. + Source   +Edit   + +
+
+
+
EV_DROP = 0x00001000
+
+ + Not should be dropped + Source   +Edit   + +
+
+
+
EV_ENABLE = 0x00000004
+
+ + Enable event. + Source   +Edit   + +
+
+
+
EV_EOF = 0x00008000
+
+ + EOF detected + Source   +Edit   + +
+
+
+
EV_ERROR = 0x00004000
+
+ + Error, data contains errno + Source   +Edit   + +
+
+
+
EV_FLAG1 = 0x00002000
+
+ + Filter-specific flag + Source   +Edit   + +
+
+
+
EV_NODATA = 0x00001000
+
+ + EOF and no more data + Source   +Edit   + +
+
+
+
EV_ONESHOT = 0x00000010
+
+ + Only report one occurrence. + Source   +Edit   + +
+
+
+
EV_RECEIPT = 0x00000040
+
+ + Force EV_ERROR on success, data == 0 + Source   +Edit   + +
+
+
+
EV_SYSFLAGS = 0x0000F000
+
+ + Reserved by system + Source   +Edit   + +
+
+
+
NOTE_ATTRIB = 0x00000008
+
+ + attributes changed + Source   +Edit   + +
+
+
+
NOTE_CHILD = 0x00000004'u32
+
+ + am a child process + Source   +Edit   + +
+
+
+
NOTE_DELETE = 0x00000001
+
+ + vnode was removed + Source   +Edit   + +
+
+
+
NOTE_EXEC = 0x20000000'u32
+
+ + process exec'd + Source   +Edit   + +
+
+
+
NOTE_EXIT = 0x80000000'u32
+
+ + process exited + Source   +Edit   + +
+
+
+
NOTE_EXTEND = 0x00000004
+
+ + size increased + Source   +Edit   + +
+
+
+
NOTE_FORK = 0x40000000'u32
+
+ + process forked + Source   +Edit   + +
+
+ +
+
NOTE_LOWAT = 0x00000001
+
+ + low water mark + Source   +Edit   + +
+
+
+
NOTE_MSECONDS = 0x00000000'u32
+
+ + + Source   +Edit   + +
+
+
+
NOTE_PCTRLMASK = 0xF0000000'u32
+
+ + mask for hint bits + Source   +Edit   + +
+
+
+
NOTE_PDATAMASK = 0x000FFFFF'u32
+
+ + mask for pid + Source   +Edit   + +
+
+
+
NOTE_RENAME = 0x00000020
+
+ + vnode was renamed + Source   +Edit   + +
+
+
+
NOTE_REVOKE = 0x00000040
+
+ + vnode access was revoked + Source   +Edit   + +
+
+
+
NOTE_TRACK = 0x00000001'u32
+
+ + follow across forks + Source   +Edit   + +
+
+
+
NOTE_TRACKERR = 0x00000002'u32
+
+ + could not track child + Source   +Edit   + +
+
+
+
NOTE_WRITE = 0x00000002
+
+ + data contents changed + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc EV_SET(event: ptr KEvent; ident: uint; filter: cshort; flags: cushort;
+            fflags: cuint; data: int; udata: pointer) {.importc: "EV_SET",
+    header: "<sys/event.h>", ...raises: [], tags: [], forbids: [].}
+
+ + Fills event with given data. + Source   +Edit   + +
+
+ +
+
+
+
proc kevent(kqFD: cint; changelist: ptr KEvent; nchanges: cint;
+            eventlist: ptr KEvent; nevents: cint; timeout: ptr Timespec): cint {.
+    importc: "kevent", header: "<sys/event.h>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + Manipulates queue for given kqFD descriptor. + Source   +Edit   + +
+
+ +
+
+
+
proc kqueue(): cint {.importc: "kqueue", header: "<sys/event.h>", ...raises: [],
+                      tags: [], forbids: [].}
+
+ + Creates new queue and returns its descriptor. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/kqueue.idx b/kqueue.idx new file mode 100644 index 0000000000000..48416ad1e084e --- /dev/null +++ b/kqueue.idx @@ -0,0 +1,36 @@ +nimTitle kqueue kqueue.html module std/kqueue 0 +nim EV_ADD kqueue.html#EV_ADD const EV_ADD 50 +nim EV_DELETE kqueue.html#EV_DELETE const EV_DELETE 52 +nim EV_ENABLE kqueue.html#EV_ENABLE const EV_ENABLE 53 +nim EV_DISABLE kqueue.html#EV_DISABLE const EV_DISABLE 54 +nim EV_ONESHOT kqueue.html#EV_ONESHOT const EV_ONESHOT 58 +nim EV_CLEAR kqueue.html#EV_CLEAR const EV_CLEAR 59 +nim EV_RECEIPT kqueue.html#EV_RECEIPT const EV_RECEIPT 60 +nim EV_DISPATCH kqueue.html#EV_DISPATCH const EV_DISPATCH 61 +nim EV_SYSFLAGS kqueue.html#EV_SYSFLAGS const EV_SYSFLAGS 63 +nim EV_DROP kqueue.html#EV_DROP const EV_DROP 64 +nim EV_FLAG1 kqueue.html#EV_FLAG1 const EV_FLAG1 65 +nim EV_EOF kqueue.html#EV_EOF const EV_EOF 69 +nim EV_ERROR kqueue.html#EV_ERROR const EV_ERROR 70 +nim EV_NODATA kqueue.html#EV_NODATA const EV_NODATA 71 +nim NOTE_LOWAT kqueue.html#NOTE_LOWAT const NOTE_LOWAT 96 +nim NOTE_DELETE kqueue.html#NOTE_DELETE const NOTE_DELETE 100 +nim NOTE_WRITE kqueue.html#NOTE_WRITE const NOTE_WRITE 101 +nim NOTE_EXTEND kqueue.html#NOTE_EXTEND const NOTE_EXTEND 102 +nim NOTE_ATTRIB kqueue.html#NOTE_ATTRIB const NOTE_ATTRIB 103 +nim NOTE_LINK kqueue.html#NOTE_LINK const NOTE_LINK 104 +nim NOTE_RENAME kqueue.html#NOTE_RENAME const NOTE_RENAME 105 +nim NOTE_REVOKE kqueue.html#NOTE_REVOKE const NOTE_REVOKE 106 +nim NOTE_EXIT kqueue.html#NOTE_EXIT const NOTE_EXIT 110 +nim NOTE_FORK kqueue.html#NOTE_FORK const NOTE_FORK 111 +nim NOTE_EXEC kqueue.html#NOTE_EXEC const NOTE_EXEC 112 +nim NOTE_PCTRLMASK kqueue.html#NOTE_PCTRLMASK const NOTE_PCTRLMASK 113 +nim NOTE_PDATAMASK kqueue.html#NOTE_PDATAMASK const NOTE_PDATAMASK 114 +nim NOTE_TRACK kqueue.html#NOTE_TRACK const NOTE_TRACK 118 +nim NOTE_TRACKERR kqueue.html#NOTE_TRACKERR const NOTE_TRACKERR 119 +nim NOTE_CHILD kqueue.html#NOTE_CHILD const NOTE_CHILD 120 +nim NOTE_MSECONDS kqueue.html#NOTE_MSECONDS const NOTE_MSECONDS 133 +nim KEvent kqueue.html#KEvent object KEvent 141 +nim kqueue kqueue.html#kqueue proc kqueue(): cint 149 +nim kevent kqueue.html#kevent,cint,ptr.KEvent,cint,ptr.KEvent,cint,ptr.Timespec proc kevent(kqFD: cint; changelist: ptr KEvent; nchanges: cint;\n eventlist: ptr KEvent; nevents: cint; timeout: ptr Timespec): cint 152 +nim EV_SET kqueue.html#EV_SET,ptr.KEvent,uint,cshort,cushort,cuint,int,pointer proc EV_SET(event: ptr KEvent; ident: uint; filter: cshort; flags: cushort;\n fflags: cuint; data: int; udata: pointer) 158 diff --git a/lenientops.html b/lenientops.html new file mode 100644 index 0000000000000..58b3d52ba33ac --- /dev/null +++ b/lenientops.html @@ -0,0 +1,264 @@ + + + + + + + +std/lenientops + + + + + + + + + + + + + + + + +
+
+

std/lenientops

+
+ +
+ Source   +Edit   + +
+ +

This module offers implementations of common binary operations like +, -, *, / and comparison operations, which work for mixed float/int operands. All operations convert the integer operand into the type of the float operand. For numerical expressions, the return type is always the type of the float involved in the expression, i.e., there is no auto conversion from float32 to float64.

+

Note: In general, auto-converting from int to float loses information, which is why these operators live in a separate module. Use with care.

+

Regarding binary comparison, this module only provides unequal operators. The equality operator == is omitted, because depending on the use case either casting to float or rounding to int might be preferred, and users should make an explicit choice.

+

+
+

Procs

+
+
+
+
func `*`[I: SomeInteger; F: SomeFloat](f: F; i: I): F {.inline.}
+
+ + + Source   +Edit   + +
+
+
+
func `*`[I: SomeInteger; F: SomeFloat](i: I; f: F): F {.inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `+`[I: SomeInteger; F: SomeFloat](f: F; i: I): F {.inline.}
+
+ + + Source   +Edit   + +
+
+
+
func `+`[I: SomeInteger; F: SomeFloat](i: I; f: F): F {.inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `-`[I: SomeInteger; F: SomeFloat](f: F; i: I): F {.inline.}
+
+ + + Source   +Edit   + +
+
+
+
func `-`[I: SomeInteger; F: SomeFloat](i: I; f: F): F {.inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `/`[I: SomeInteger; F: SomeFloat](f: F; i: I): F {.inline.}
+
+ + + Source   +Edit   + +
+
+
+
func `/`[I: SomeInteger; F: SomeFloat](i: I; f: F): F {.inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `<`[I: SomeInteger; F: SomeFloat](f: F; i: I): bool {.inline.}
+
+ + + Source   +Edit   + +
+
+
+
func `<`[I: SomeInteger; F: SomeFloat](i: I; f: F): bool {.inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `<=`[I: SomeInteger; F: SomeFloat](f: F; i: I): bool {.inline.}
+
+ + + Source   +Edit   + +
+
+
+
func `<=`[I: SomeInteger; F: SomeFloat](i: I; f: F): bool {.inline.}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/lenientops.idx b/lenientops.idx new file mode 100644 index 0000000000000..270f0fe82ecff --- /dev/null +++ b/lenientops.idx @@ -0,0 +1,19 @@ +nimTitle lenientops lenientops.html module std/lenientops 0 +nim `+` lenientops.html#+,I,F proc `+`[I: SomeInteger; F: SomeFloat](i: I; f: F): F 27 +nim `+` lenientops.html#+,F,I proc `+`[I: SomeInteger; F: SomeFloat](f: F; i: I): F 29 +nim `-` lenientops.html#-,I,F proc `-`[I: SomeInteger; F: SomeFloat](i: I; f: F): F 32 +nim `-` lenientops.html#-,F,I proc `-`[I: SomeInteger; F: SomeFloat](f: F; i: I): F 34 +nim `*` lenientops.html#*,I,F proc `*`[I: SomeInteger; F: SomeFloat](i: I; f: F): F 37 +nim `*` lenientops.html#*,F,I proc `*`[I: SomeInteger; F: SomeFloat](f: F; i: I): F 39 +nim `/` lenientops.html#/,I,F proc `/`[I: SomeInteger; F: SomeFloat](i: I; f: F): F 42 +nim `/` lenientops.html#/,F,I proc `/`[I: SomeInteger; F: SomeFloat](f: F; i: I): F 44 +nim `<` lenientops.html#<,I,F proc `<`[I: SomeInteger; F: SomeFloat](i: I; f: F): bool 47 +nim `<` lenientops.html#<,F,I proc `<`[I: SomeInteger; F: SomeFloat](f: F; i: I): bool 49 +nim `<=` lenientops.html#<=,I,F proc `<=`[I: SomeInteger; F: SomeFloat](i: I; f: F): bool 51 +nim `<=` lenientops.html#<=,F,I proc `<=`[I: SomeInteger; F: SomeFloat](f: F; i: I): bool 53 +nimgrp + lenientops.html#+-procs-all proc 27 +nimgrp - lenientops.html#--procs-all proc 32 +nimgrp / lenientops.html#/-procs-all proc 42 +nimgrp * lenientops.html#*-procs-all proc 37 +nimgrp <= lenientops.html#<=-procs-all proc 51 +nimgrp < lenientops.html#<-procs-all proc 47 diff --git a/lexbase.html b/lexbase.html new file mode 100644 index 0000000000000..c5796a62a3bb4 --- /dev/null +++ b/lexbase.html @@ -0,0 +1,302 @@ + + + + + + + +std/lexbase + + + + + + + + + + + + + + + + +
+
+

std/lexbase

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a base object of a lexer with efficient buffer handling. Only at line endings checks are necessary if the buffer needs refilling.

+ +
+

Types

+
+
+
BaseLexer = object of RootObj
+  bufpos*: int               ## the current position within the buffer
+  buf*: string               ## the buffer itself
+  ## the input stream
+  lineNumber*: int           ## the current line number
+  offsetBase*: int
+
+ + the base lexer. Inherit your lexer from this object. + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
EndOfFile = '\x00'
+
+ + end of file marker + Source   +Edit   + +
+
+
+
NewLines = {'\r', '\n'}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc close(L: var BaseLexer) {....raises: [IOError, OSError],
+                               tags: [WriteIOEffect], forbids: [].}
+
+ + closes the base lexer. This closes L's associated stream too. + Source   +Edit   + +
+
+ +
+
+
+
proc getColNumber(L: BaseLexer; pos: int): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + retrieves the current column. + Source   +Edit   + +
+
+ +
+
+
+
proc getCurrentLine(L: BaseLexer; marker: bool = true): string {....raises: [],
+    tags: [], forbids: [].}
+
+ + retrieves the current line. + Source   +Edit   + +
+
+ +
+
+
+
proc handleCR(L: var BaseLexer; pos: int): int {....raises: [IOError, OSError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + Call this if you scanned over '\c' in the buffer; it returns the position to continue the scanning from. pos must be the position of the '\c'. + Source   +Edit   + +
+
+ +
+
+
+
proc handleLF(L: var BaseLexer; pos: int): int {....raises: [IOError, OSError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + Call this if you scanned over '\L' in the buffer; it returns the position to continue the scanning from. pos must be the position of the '\L'. + Source   +Edit   + +
+
+ +
+
+
+
proc handleRefillChar(L: var BaseLexer; pos: int): int {.
+    ...raises: [IOError, OSError], tags: [ReadIOEffect], forbids: [].}
+
+ + Call this if a terminator character other than a new line is scanned at pos; it returns the position to continue the scanning from. + Source   +Edit   + +
+
+ +
+
+
+
proc open(L: var BaseLexer; input: Stream; bufLen: int = 8192;
+          refillChars: set[char] = NewLines) {....raises: [IOError, OSError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + inits the BaseLexer with a stream to read from. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/lexbase.idx b/lexbase.idx new file mode 100644 index 0000000000000..64ba5edb46e13 --- /dev/null +++ b/lexbase.idx @@ -0,0 +1,11 @@ +nimTitle lexbase lexbase.html module std/lexbase 0 +nim EndOfFile lexbase.html#EndOfFile const EndOfFile 21 +nim NewLines lexbase.html#NewLines const NewLines 22 +nim BaseLexer lexbase.html#BaseLexer object BaseLexer 31 +nim close lexbase.html#close,BaseLexer proc close(L: var BaseLexer) 42 +nim handleCR lexbase.html#handleCR,BaseLexer,int proc handleCR(L: var BaseLexer; pos: int): int 106 +nim handleLF lexbase.html#handleLF,BaseLexer,int proc handleLF(L: var BaseLexer; pos: int): int 117 +nim handleRefillChar lexbase.html#handleRefillChar,BaseLexer,int proc handleRefillChar(L: var BaseLexer; pos: int): int 126 +nim open lexbase.html#open,BaseLexer,Stream,int,set[char] proc open(L: var BaseLexer; input: Stream; bufLen: int = 8192;\n refillChars: set[char] = NewLines) 137 +nim getColNumber lexbase.html#getColNumber,BaseLexer,int proc getColNumber(L: BaseLexer; pos: int): int 153 +nim getCurrentLine lexbase.html#getCurrentLine,BaseLexer,bool proc getCurrentLine(L: BaseLexer; marker: bool = true): string 157 diff --git a/lib.html b/lib.html new file mode 100644 index 0000000000000..638a90ceffca7 --- /dev/null +++ b/lib.html @@ -0,0 +1,342 @@ + + + + + + + +Nim Standard Library + + + + + + + + + + + + + + + + +
+
+

Nim Standard Library

+
+ +
+ Source   +Edit   + +
+ +

+ +
Author:Andreas Rumpf
Version:2.2.1

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 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 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.
  • +
+ +

Core

  • atomics Types and operations for atomic operations and lockless algorithms.
  • +
  • bitops Provides a series of low-level methods for bit manipulation.
  • +
  • compilesettings Querying the compiler about diverse configuration settings from code.
  • +
  • cpuinfo Procs to determine the number of CPUs / cores.
  • +
  • effecttraits Access to the inferred .raises effects for Nim's macro system.
  • +
  • endians Helpers that deal with different byte orders.
  • +
  • locks Locks and condition variables for Nim.
  • +
  • macrocache Provides an API for macros to collect compile-time information across modules.
  • +
  • macros Contains the AST API and documentation of Nim for writing macros.
  • +
  • rlocks Reentrant locks for Nim.
  • +
  • typeinfo Provides (unsafe) access to Nim's run-time type information.
  • +
  • typetraits Compile-time reflection procs for working with types.
  • +
  • volatile Code for generating volatile loads and stores, which are useful in embedded and systems programming.
  • +
+ +

Algorithms

  • algorithm Some common generic algorithms like sort or binary search.
  • +
  • enumutils Additional functionality for the built-in enum type.
  • +
  • sequtils Operations for the built-in seq type which were inspired by functional programming languages.
  • +
  • setutils Additional functionality for the built-in set type.
  • +
+ +

Collections

  • critbits A crit bit tree which is an efficient container for a sorted set of strings, or a sorted mapping of strings.
  • +
  • deques Implementation of a double-ended queue. The underlying implementation uses a seq.
  • +
  • heapqueue Implementation of a binary heap data structure that can be used as a priority queue.
  • +
  • intsets Efficient implementation of a set of ints as a sparse bit set.
  • +
  • lists Nim linked list support. Contains singly and doubly linked lists and circular lists ("rings").
  • +
  • options The option type encapsulates an optional value.
  • +
  • packedsets Efficient implementation of a set of ordinals as a sparse bit set.
  • +
  • ropes A rope data type. Ropes can represent very long strings efficiently; in particular, concatenation is done in O(1) instead of O(n).
  • +
  • sets Nim hash set support.
  • +
  • strtabs 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.
  • +
  • tables Nim hash table support. Contains tables, ordered tables, and count tables.
  • +
+ +

String handling

  • cstrutils Utilities for cstring handling.
  • +
  • editdistance An algorithm to compute the edit distance between two Unicode strings.
  • +
  • encodings Converts between different character encodings. On UNIX, this uses the iconv library, on Windows the Windows API.
  • +
  • formatfloat Formatting floats as strings.
  • +
  • objectdollar A generic $ operator to convert objects to strings.
  • +
  • punycode Implements a representation of Unicode with the limited ASCII character subset.
  • +
  • strbasics Some high performance string operations.
  • +
  • strformat Macro based standard string interpolation/formatting. Inspired by Python's f-strings. + Note: if you need templating, consider using Nim Source Code Filters (SCF).
  • +
  • strmisc Uncommon string handling operations that do not fit with the commonly used operations in strutils.
  • +
  • strscans A scanf macro for convenient parsing of mini languages.
  • +
  • strutils Common string handling operations like changing case of a string, splitting a string into substrings, searching for substrings, replacing substrings.
  • +
  • unicode Support for handling the Unicode UTF-8 encoding.
  • +
  • unidecode It provides a single proc that does Unicode to ASCII transliterations. Based on Python's Unidecode module.
  • +
  • widestrs Nim support for C/C++'s wide strings.
  • +
  • wordwrap An algorithm for word-wrapping Unicode strings.
  • +
+ +

Time handling

  • monotimes The monotimes module implements monotonic timestamps.
  • +
  • times The times module contains support for working with time.
  • +
+ +

Generic Operating System Services

  • appdirs Helpers for determining special directories used by apps.
  • +
  • cmdline System facilities for reading command line parameters.
  • +
  • dirs Directory handling.
  • +
  • distros 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 for hints on distributing Nim using OS packages.
  • +
  • dynlib Accessing symbols from shared libraries.
  • +
  • envvars Environment variable handling.
  • +
  • exitprocs Adding hooks to program exit.
  • +
  • files File handling.
  • +
  • memfiles Support for memory-mapped files (Posix's mmap) on the different operating systems.
  • +
  • os Basic operating system facilities like retrieving environment variables, reading command line arguments, working with directories, running shell commands, etc.
  • +
  • oserrors OS error reporting.
  • +
  • osproc Module for process communication beyond os.execShellCmd.
  • +
  • paths Path handling.
  • +
  • reservedmem Utilities for reserving portions of the address space of a program without consuming physical memory.
  • +
  • streams 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.
  • +
  • symlinks Symlink handling.
  • +
  • syncio Various synchronized I/O operations.
  • +
  • terminal A module to control the terminal output (also called console).
  • +
  • tempfiles Some utilities for generating temporary path names and creating temporary files and directories.
  • +
+ +

Math libraries

  • complex Complex numbers and relevant mathematical operations.
  • +
  • fenv Floating-point environment. Handling of floating-point rounding and exceptions (overflow, zero-divide, etc.).
  • +
  • lenientops Binary operators for mixed integer/float expressions for convenience.
  • +
  • math Mathematical operations like cosine, square root.
  • +
  • random Fast and tiny random number generator.
  • +
  • rationals Rational numbers and relevant mathematical operations.
  • +
  • stats Statistical analysis.
  • +
  • sysrand Cryptographically secure pseudorandom number generator.
  • +
+ +

Internet Protocols and Support

  • async Exports asyncmacro and asyncfutures for native backends, and asyncjs on the JS backend.
  • +
  • asyncdispatch An asynchronous dispatcher for IO operations.
  • +
  • asyncfile An asynchronous file reading and writing using asyncdispatch.
  • +
  • asyncftpclient An asynchronous FTP client using the asyncnet module.
  • +
  • asynchttpserver An asynchronous HTTP server using the asyncnet module.
  • +
  • asyncmacro async and multisync macros for asyncdispatch.
  • +
  • asyncnet Asynchronous sockets based on the asyncdispatch module.
  • +
  • asyncstreams FutureStream - a future that acts as a queue.
  • +
  • cgi Helpers for CGI applications.
  • +
  • cookies Helper procs for parsing and generating cookies.
  • +
  • httpclient A simple HTTP client with support for both synchronous and asynchronous retrieval of web pages.
  • +
  • mimetypes A mimetypes database.
  • +
  • nativesockets A low-level sockets API.
  • +
  • net A high-level sockets API.
  • +
  • selectors A selector API with backends specific to each OS. Supported OS primitives: epoll, kqueue, poll, and select on Windows.
  • +
  • smtp A simple SMTP client with support for both synchronous and asynchronous operation.
  • +
  • socketstreams An implementation of the streams interface for sockets.
  • +
  • uri Functions for working with URIs and URLs.
  • +
+ +

Threading

  • isolation The Isolated[T] type for safe construction of isolated subgraphs that can be passed efficiently to different channels and threads.
  • +
  • tasks Basic primitives for creating parallel programs.
  • +
  • threadpool Implements Nim's spawn.
  • +
  • typedthreads Basic Nim thread support.
  • +
+ +

Parsers

  • htmlparser HTML document parser that creates a XML tree representation.
  • +
  • json High-performance JSON parser.
  • +
  • lexbase A low-level module that implements an extremely efficient buffering scheme for lexers and parsers. This is used by the diverse parsing modules.
  • +
  • parsecfg 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 The parsecsv module implements a simple high-performance CSV parser.
  • +
  • parsejson A JSON parser. It is used and exported by the json module, but can also be used in its own right.
  • +
  • parseopt The parseopt module implements a command line option parser.
  • +
  • parsesql The parsesql module implements a simple high-performance SQL parser.
  • +
  • parseutils Helpers for parsing tokens, numbers, identifiers, etc.
  • +
  • parsexml 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.
  • +
  • pegs Procedures and operators for handling PEGs.
  • +
+ +

Docutils

  • packages/docutils/highlite 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 A reStructuredText parser. A large subset is implemented. Some features of the markdown wiki syntax are also supported.
  • +
  • packages/docutils/rstast An AST for the reStructuredText parser.
  • +
  • packages/docutils/rstgen A generator of HTML/Latex from reStructuredText.
  • +
+ +

XML Processing

  • xmltree A simple XML tree. More efficient and simpler than the DOM. It also contains a macro for XML/HTML code generation.
  • +
  • xmlparser XML document parser that creates a XML tree representation.
  • +
+ +

Generators

  • genasts AST generation using captured variables for macros.
  • +
  • htmlgen 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 A Base64 encoder and decoder.
  • +
  • hashes Efficient computations of hash values for diverse Nim types.
  • +
  • md5 The MD5 checksum algorithm.
  • +
  • oids 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.
  • +
  • sha1 The SHA-1 checksum algorithm.
  • +
+ +

Serialization

  • jsonutils Hookable (de)serialization for arbitrary types using JSON.
  • +
  • marshal Contains procs for serialization and deserialization of arbitrary Nim data structures.
  • +
+ +

Miscellaneous

  • assertions Assertion handling.
  • +
  • browsers Procs for opening URLs with the user's default browser.
  • +
  • colors Color handling.
  • +
  • coro Experimental coroutines in Nim.
  • +
  • decls Syntax sugar for some declarations.
  • +
  • enumerate enumerate syntactic sugar based on Nim's macro system.
  • +
  • importutils Utilities related to import and symbol resolution.
  • +
  • logging A simple logger.
  • +
  • segfaults Turns access violations or segfaults into a NilAccessDefect exception.
  • +
  • sugar Nice syntactic sugar based on Nim's macro system.
  • +
  • unittest Implements a Unit testing DSL.
  • +
  • varints Decode variable-length integers that are compatible with SQLite.
  • +
  • with The with macro for easy function chaining.
  • +
  • wrapnils Allows evaluating expressions safely against nil dereferences.
  • +
+ +

Modules for the JavaScript backend

  • asyncjs Types and macros for writing asynchronous procedures in JavaScript.
  • +
  • dom Declaration of the Document Object Model for the JS backend.
  • +
  • jsbigints Arbitrary precision integers.
  • +
  • jsconsole Wrapper for the console object.
  • +
  • jscore The wrapper of core JavaScript functions. For most purposes, you should be using the math, json, and times stdlib modules instead of this module.
  • +
  • jsfetch Wrapper for fetch.
  • +
  • jsffi Types and macros for easier interaction with JavaScript.
  • +
  • jsre Regular Expressions for the JavaScript target.
  • +
+ +

Impure libraries

+

Regular expressions

  • re Procedures and operators for handling regular expressions. The current implementation uses PCRE.
  • +
  • nre

    +

    Many help functions for handling regular expressions. The current implementation uses PCRE.

    +
  • +
+ +

Database support

  • db_mysql A higher level MySQL database wrapper. The same interface is implemented for other databases too.
  • +
  • db_odbc A higher level ODBC database wrapper. The same interface is implemented for other databases too.
  • +
  • db_postgres A higher level PostgreSQL database wrapper. The same interface is implemented for other databases too.
  • +
  • db_sqlite A higher level SQLite database wrapper. The same interface is implemented for other databases too.
  • +
+ +

Generic Operating System Services

  • rdstdin Code for reading user input 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 Wrapper for a small subset of the Win32 API.
  • +
  • registry Windows registry support.
  • +
+ +

UNIX specific

  • posix Wrapper for the POSIX standard.
  • +
  • posix_utils Contains helpers for the POSIX standard or specialized for Linux and BSDs.
  • +
+ +

Regular expressions

  • pcre Wrapper for the PCRE library.
  • +
+ +

Database support

  • mysql Wrapper for the mySQL API.
  • +
  • odbcsql interface to the ODBC driver.
  • +
  • postgres Wrapper for the PostgreSQL API.
  • +
  • sqlite3 Wrapper for the SQLite 3 API.
  • +
+ +

Network Programming and Internet Protocols

+

+ +
+
+ + +
+
+ + + + diff --git a/lib.idx b/lib.idx new file mode 100644 index 0000000000000..260f7ec0ba578 --- /dev/null +++ b/lib.idx @@ -0,0 +1,31 @@ +markupTitle Nim Standard Library lib.html Nim Standard Library 0 +heading Nimble lib.html#nimble Nimble 0 +heading Pure libraries lib.html#pure-libraries Pure libraries 0 +heading Automatic imports lib.html#pure-libraries-automatic-imports Automatic imports 0 +heading Core lib.html#pure-libraries-core Core 0 +heading Algorithms lib.html#pure-libraries-algorithms Algorithms 0 +heading Collections lib.html#pure-libraries-collections Collections 0 +heading String handling lib.html#pure-libraries-string-handling String handling 0 +heading Time handling lib.html#pure-libraries-time-handling Time handling 0 +heading Generic Operating System Services lib.html#pure-libraries-generic-operating-system-services Generic Operating System Services 0 +heading Math libraries lib.html#pure-libraries-math-libraries Math libraries 0 +heading Internet Protocols and Support lib.html#pure-libraries-internet-protocols-and-support Internet Protocols and Support 0 +heading Threading lib.html#pure-libraries-threading Threading 0 +heading Parsers lib.html#pure-libraries-parsers Parsers 0 +heading Docutils lib.html#pure-libraries-docutils Docutils 0 +heading XML Processing lib.html#pure-libraries-xml-processing XML Processing 0 +heading Generators lib.html#pure-libraries-generators Generators 0 +heading Hashing lib.html#pure-libraries-hashing Hashing 0 +heading Serialization lib.html#pure-libraries-serialization Serialization 0 +heading Miscellaneous lib.html#pure-libraries-miscellaneous Miscellaneous 0 +heading Modules for the JavaScript backend lib.html#pure-libraries-modules-for-the-javascript-backend Modules for the JavaScript backend 0 +heading Impure libraries lib.html#impure-libraries Impure libraries 0 +heading Regular expressions lib.html#impure-libraries-regular-expressions Regular expressions 0 +heading Database support lib.html#impure-libraries-database-support Database support 0 +heading Generic Operating System Services lib.html#impure-libraries-generic-operating-system-services Generic Operating System Services 0 +heading Wrappers lib.html#wrappers Wrappers 0 +heading Windows-specific lib.html#wrappers-windowsminusspecific Windows-specific 0 +heading UNIX specific lib.html#wrappers-unix-specific UNIX specific 0 +heading Regular expressions lib.html#wrappers-regular-expressions Regular expressions 0 +heading Database support lib.html#wrappers-database-support Database support 0 +heading Network Programming and Internet Protocols lib.html#wrappers-network-programming-and-internet-protocols Network Programming and Internet Protocols 0 diff --git a/linenoise.html b/linenoise.html new file mode 100644 index 0000000000000..5f9dd78ef751f --- /dev/null +++ b/linenoise.html @@ -0,0 +1,396 @@ + + + + + + + +std/linenoise + + + + + + + + + + + + + + + + +
+
+

std/linenoise

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
+

Types

+
+
+
CompletionCallback = proc (a2: cstring; a3: ptr Completions) {.cdecl.}
+
+ + + Source   +Edit   + +
+
+
+
Completions = object
+  len*: csize_t
+  cvec*: cstringArray
+
+ + + Source   +Edit   + +
+
+
+
LinenoiseData = object
+
+ + + Source   +Edit   + +
+
+
+
ReadLineResult = object
+  line*: string
+  status*: Status
+
+ + + Source   +Edit   + +
+
+
+
Status = enum
+  lnCtrlUnkown, lnCtrlC, lnCtrlD
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc addCompletion(a2: ptr Completions; a3: cstring) {.
+    importc: "linenoiseAddCompletion", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clearScreen() {.importc: "linenoiseClearScreen", ...raises: [], tags: [],
+                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc free(s: cstring) {.importc: "free", header: "<stdlib.h>", ...raises: [],
+                        tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc historyAdd(line: cstring): cint {.importc: "linenoiseHistoryAdd",
+                                       discardable, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc historyLoad(filename: cstring): cint {.importc: "linenoiseHistoryLoad",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc historySave(filename: cstring): cint {.importc: "linenoiseHistorySave",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc historySetMaxLen(len: cint): cint {.importc: "linenoiseHistorySetMaxLen",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc printKeyCodes() {.importc: "linenoisePrintKeyCodes", ...raises: [], tags: [],
+                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc readLine(prompt: cstring): cstring {.importc: "linenoise", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc readLineStatus(prompt: string; result: var ReadLineResult) {....raises: [],
+    tags: [], forbids: [].}
+
+ + line editing API that allows returning the line entered and an indicator of which control key was entered, allowing user to distinguish between for example ctrl-C vs ctrl-D. +

Example: cmd: -r:off

+
var ret: ReadLineResult
+while true:
+  readLineStatus("name: ", ret) # ctrl-D will exit, ctrl-C will go to next prompt
+  if ret.line.len > 0: echo ret.line
+  if ret.status == lnCtrlD: break
+echo "exiting"
+ Source   +Edit   + +
+
+ +
+
+
+
proc setCompletionCallback(a2: CompletionCallback) {.
+    importc: "linenoiseSetCompletionCallback", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setMultiLine(ml: cint) {.importc: "linenoiseSetMultiLine", ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/linenoise.idx b/linenoise.idx new file mode 100644 index 0000000000000..150f1eb40b04e --- /dev/null +++ b/linenoise.idx @@ -0,0 +1,21 @@ +nimTitle linenoise linenoise.html module std/linenoise 0 +nim Completions linenoise.html#Completions object Completions 11 +nim CompletionCallback linenoise.html#CompletionCallback type CompletionCallback 15 +nim setCompletionCallback linenoise.html#setCompletionCallback,CompletionCallback proc setCompletionCallback(a2: CompletionCallback) 19 +nim addCompletion linenoise.html#addCompletion,ptr.Completions,cstring proc addCompletion(a2: ptr Completions; a3: cstring) 21 +nim readLine linenoise.html#readLine,cstring proc readLine(prompt: cstring): cstring 23 +nim historyAdd linenoise.html#historyAdd,cstring proc historyAdd(line: cstring): cint 24 +nim historySetMaxLen linenoise.html#historySetMaxLen,cint proc historySetMaxLen(len: cint): cint 26 +nim historySave linenoise.html#historySave,cstring proc historySave(filename: cstring): cint 27 +nim historyLoad linenoise.html#historyLoad,cstring proc historyLoad(filename: cstring): cint 28 +nim clearScreen linenoise.html#clearScreen proc clearScreen() 29 +nim setMultiLine linenoise.html#setMultiLine,cint proc setMultiLine(ml: cint) 30 +nim printKeyCodes linenoise.html#printKeyCodes proc printKeyCodes() 31 +nim free linenoise.html#free,cstring proc free(s: cstring) 33 +nim LinenoiseData linenoise.html#LinenoiseData object LinenoiseData 42 +nim lnCtrlUnkown linenoise.html#lnCtrlUnkown Status.lnCtrlUnkown 48 +nim lnCtrlC linenoise.html#lnCtrlC Status.lnCtrlC 48 +nim lnCtrlD linenoise.html#lnCtrlD Status.lnCtrlD 48 +nim Status linenoise.html#Status enum Status 48 +nim ReadLineResult linenoise.html#ReadLineResult object ReadLineResult 53 +nim readLineStatus linenoise.html#readLineStatus,string,ReadLineResult proc readLineStatus(prompt: string; result: var ReadLineResult) 57 diff --git a/linux.html b/linux.html new file mode 100644 index 0000000000000..61f24b937655a --- /dev/null +++ b/linux.html @@ -0,0 +1,430 @@ + + + + + + + +std/linux + + + + + + + + + + + + + + + + +
+
+

std/linux

+
+ +
+ Source   +Edit   + +
+ +

Flags of clone syscall. See clone syscall manual for more information.

+
+

Imports

+
+ posix +
+
+
+

Consts

+
+
+
CLONE_CHILD_CLEARTID = 0x00200000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_CHILD_SETTID = 0x01000000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_DETACHED = 0x00400000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_FILES = 0x00000400'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_FS = 0x00000200'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_IO = 0x80000000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_NEWCGROUP = 0x02000000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_NEWIPC = 0x08000000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_NEWNET = 0x40000000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_NEWNS = 0x00020000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_NEWPID = 0x20000000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_NEWUSER = 0x10000000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_NEWUTS = 0x04000000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_PARENT = 0x00008000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_PARENT_SETTID = 0x00100000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_PIDFD = 0x00001000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_PTRACE = 0x00002000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_SETTLS = 0x00080000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_SIGHAND = 0x00000800'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_SYSVSEM = 0x00040000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_THREAD = 0x00010000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_UNTRACED = 0x00800000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_VFORK = 0x00004000'i32
+
+ + + Source   +Edit   + +
+
+
+
CLONE_VM = 0x00000100'i32
+
+ + + Source   +Edit   + +
+
+
+
CSIGNAL = 0x000000FF'i32
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc clone(fn: pointer; child_stack: pointer; flags: cint; arg: pointer;
+           ptid: ptr Pid; tls: pointer; ctid: ptr Pid): cint {.importc,
+    header: "<sched.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pipe2(a: array[0 .. 1, cint]; flags: cint): cint {.importc,
+    header: "<unistd.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/lists.html b/lists.html new file mode 100644 index 0000000000000..a80e6dfd52b74 --- /dev/null +++ b/lists.html @@ -0,0 +1,1519 @@ + + + + + + + +std/lists + + + + + + + + + + + + + + + + +
+
+

std/lists

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Implementation of:

+ +

Basic Usage

Because it makes no sense to do otherwise, the next and prev pointers are not hidden from you and can be manipulated directly for efficiency.

+ +

Lists

+

Example:

+
import std/lists
+var list = initDoublyLinkedList[int]()
+let
+  a = newDoublyLinkedNode[int](3)
+  b = newDoublyLinkedNode[int](7)
+  c = newDoublyLinkedNode[int](9)
+
+list.add(a)
+list.add(b)
+list.prepend(c)
+
+assert a.next == b
+assert a.prev == c
+assert c.next == a
+assert c.next.next == b
+assert c.prev == nil
+assert b.next == nil
+

Rings

+

Example:

+
import std/lists
+var ring = initSinglyLinkedRing[int]()
+let
+  a = newSinglyLinkedNode[int](3)
+  b = newSinglyLinkedNode[int](7)
+  c = newSinglyLinkedNode[int](9)
+
+ring.add(a)
+ring.add(b)
+ring.prepend(c)
+
+assert c.next == a
+assert a.next == b
+assert c.next.next == b
+assert b.next == c
+assert c.next.next.next == c
+

See also

+

+ +
+

Types

+
+
+
DoublyLinkedList[T] = object
+  head*: DoublyLinkedNode[T]
+  tail* {.cursor.}: DoublyLinkedNode[T]
+
+ + A doubly linked list. + Source   +Edit   + +
+
+
+
DoublyLinkedNode[T] = ref DoublyLinkedNodeObj[T]
+
+ + + Source   +Edit   + +
+
+
+
DoublyLinkedNodeObj[T] = object
+  next*: DoublyLinkedNode[T]
+  prev* {.cursor.}: DoublyLinkedNode[T]
+  value*: T
+
+ +

A node of a doubly linked list.

+

It consists of a value field, and pointers to next and prev.

+ + Source   +Edit   + +
+
+
+
DoublyLinkedRing[T] = object
+  head*: DoublyLinkedNode[T]
+
+ + A doubly linked ring. + Source   +Edit   + +
+
+
+
SinglyLinkedList[T] = object
+  head*: SinglyLinkedNode[T]
+  tail* {.cursor.}: SinglyLinkedNode[T]
+
+ + A singly linked list. + Source   +Edit   + +
+
+
+
SinglyLinkedNode[T] = ref SinglyLinkedNodeObj[T]
+
+ + + Source   +Edit   + +
+
+
+
SinglyLinkedNodeObj[T] = object
+  next*: SinglyLinkedNode[T]
+  value*: T
+
+ +

A node of a singly linked list.

+

It consists of a value field, and a pointer to next.

+ + Source   +Edit   + +
+
+
+
SinglyLinkedRing[T] = object
+  head*: SinglyLinkedNode[T]
+  tail* {.cursor.}: SinglyLinkedNode[T]
+
+ + A singly linked ring. + Source   +Edit   + +
+
+
+
SomeLinkedCollection[T] = SomeLinkedList[T] | SomeLinkedRing[T]
+
+ + + Source   +Edit   + +
+
+
+
SomeLinkedList[T] = SinglyLinkedList[T] | DoublyLinkedList[T]
+
+ + + Source   +Edit   + +
+
+
+
SomeLinkedNode[T] = SinglyLinkedNode[T] | DoublyLinkedNode[T]
+
+ + + Source   +Edit   + +
+
+
+
SomeLinkedRing[T] = SinglyLinkedRing[T] | DoublyLinkedRing[T]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`[T](L: SomeLinkedCollection[T]): string
+
+ + Turns a list into its string representation for logging and printing. +

Example:

+
let a = [1, 2, 3, 4].toSinglyLinkedList
+assert $a == "[1, 2, 3, 4]"
+ Source   +Edit   + +
+
+ +
+
+
+
proc add[T: SomeLinkedList](a: var T; b: T)
+
+ +

Appends a shallow copy of b to the end of a.

+

See also:

+ + +

Example:

+
from std/sequtils import toSeq
+var a = [1, 2, 3].toSinglyLinkedList
+let b = [4, 5].toSinglyLinkedList
+a.add(b)
+assert a.toSeq == [1, 2, 3, 4, 5]
+assert b.toSeq == [4, 5]
+a.add(a)
+assert a.toSeq == [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
+ Source   +Edit   + +
+
+
+
proc add[T](L: var DoublyLinkedList[T]; n: DoublyLinkedNode[T])
+
+ +

Appends (adds to the end) a node n to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initDoublyLinkedList[int]()
+let n = newDoublyLinkedNode[int](9)
+a.add(n)
+assert a.contains(9)
+ Source   +Edit   + +
+
+
+
proc add[T](L: var DoublyLinkedList[T]; value: T)
+
+ +

Appends (adds to the end) a value to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initDoublyLinkedList[int]()
+a.add(9)
+a.add(8)
+assert a.contains(9)
+ Source   +Edit   + +
+
+
+
proc add[T](L: var DoublyLinkedRing[T]; n: DoublyLinkedNode[T])
+
+ +

Appends (adds to the end) a node n to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initDoublyLinkedRing[int]()
+let n = newDoublyLinkedNode[int](9)
+a.add(n)
+assert a.contains(9)
+ Source   +Edit   + +
+
+
+
proc add[T](L: var DoublyLinkedRing[T]; value: T)
+
+ +

Appends (adds to the end) a value to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initDoublyLinkedRing[int]()
+a.add(9)
+a.add(8)
+assert a.contains(9)
+ Source   +Edit   + +
+
+
+
proc add[T](L: var SinglyLinkedList[T]; n: SinglyLinkedNode[T]) {.inline.}
+
+ +

Appends (adds to the end) a node n to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initSinglyLinkedList[int]()
+let n = newSinglyLinkedNode[int](9)
+a.add(n)
+assert a.contains(9)
+ Source   +Edit   + +
+
+
+
proc add[T](L: var SinglyLinkedList[T]; value: T) {.inline.}
+
+ +

Appends (adds to the end) a value to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initSinglyLinkedList[int]()
+a.add(9)
+a.add(8)
+assert a.contains(9)
+ Source   +Edit   + +
+
+
+
proc add[T](L: var SinglyLinkedRing[T]; n: SinglyLinkedNode[T])
+
+ +

Appends (adds to the end) a node n to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initSinglyLinkedRing[int]()
+let n = newSinglyLinkedNode[int](9)
+a.add(n)
+assert a.contains(9)
+ Source   +Edit   + +
+
+
+
proc add[T](L: var SinglyLinkedRing[T]; value: T)
+
+ +

Appends (adds to the end) a value to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initSinglyLinkedRing[int]()
+a.add(9)
+a.add(8)
+assert a.contains(9)
+ Source   +Edit   + +
+
+ +
+
+
+
proc addMoved[T](a, b: var DoublyLinkedList[T])
+
+ +

Moves b to the end of a. Efficiency: O(1). Note that b becomes empty after the operation unless it has the same address as a. Self-adding results in a cycle.

+

See also:

+ + +

Example:

+
import std/[sequtils, enumerate, sugar]
+var
+  a = [1, 2, 3].toDoublyLinkedList
+  b = [4, 5].toDoublyLinkedList
+  c = [0, 1].toDoublyLinkedList
+a.addMoved(b)
+assert a.toSeq == [1, 2, 3, 4, 5]
+assert b.toSeq == []
+c.addMoved(c)
+let s = collect:
+  for i, ci in enumerate(c):
+    if i == 6: break
+    ci
+assert s == [0, 1, 0, 1, 0, 1]
+ Source   +Edit   + +
+
+
+
proc addMoved[T](a, b: var SinglyLinkedList[T])
+
+ +

Moves b to the end of a. Efficiency: O(1). Note that b becomes empty after the operation unless it has the same address as a. Self-adding results in a cycle.

+

See also:

+ + +

Example:

+
import std/[sequtils, enumerate, sugar]
+var
+  a = [1, 2, 3].toSinglyLinkedList
+  b = [4, 5].toSinglyLinkedList
+  c = [0, 1].toSinglyLinkedList
+a.addMoved(b)
+assert a.toSeq == [1, 2, 3, 4, 5]
+assert b.toSeq == []
+c.addMoved(c)
+let s = collect:
+  for i, ci in enumerate(c):
+    if i == 6: break
+    ci
+assert s == [0, 1, 0, 1, 0, 1]
+ Source   +Edit   + +
+
+ +
+
+
+
proc append[T](a: var (DoublyLinkedList[T] | DoublyLinkedRing[T]);
+               b: DoublyLinkedList[T] | DoublyLinkedNode[T] | T)
+
+ +

Alias for a.add(b).

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc append[T](a: var (SinglyLinkedList[T] | SinglyLinkedRing[T]);
+               b: SinglyLinkedList[T] | SinglyLinkedNode[T] | T)
+
+ +

Alias for a.add(b).

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc appendMoved[T: SomeLinkedList](a, b: var T)
+
+ +

Alias for a.addMoved(b).

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc contains[T](L: SomeLinkedCollection[T]; value: T): bool {.inline.}
+
+ +

Searches in the list for a value. Returns false if the value does not exist, true otherwise. This allows the usage of the in and notin operators.

+

See also:

+ + +

Example:

+
let a = [9, 8].toSinglyLinkedList
+assert a.contains(9)
+assert 8 in a
+assert(not a.contains(1))
+assert 2 notin a
+ Source   +Edit   + +
+
+ +
+
+
+
func copy[T](a: DoublyLinkedList[T]): DoublyLinkedList[T]
+
+ + Creates a shallow copy of a. +

Example:

+
from std/sequtils import toSeq
+type Foo = ref object
+  x: int
+var
+  f = Foo(x: 1)
+  a = [f].toDoublyLinkedList
+let b = a.copy
+a.add([f].toDoublyLinkedList)
+assert a.toSeq == [f, f]
+assert b.toSeq == [f] # b isn't modified...
+f.x = 42
+assert a.head.value.x == 42
+assert b.head.value.x == 42 # ... but the elements are not deep copied
+
+let c = [1, 2, 3].toDoublyLinkedList
+assert $c == $c.copy
+ Source   +Edit   + +
+
+
+
func copy[T](a: SinglyLinkedList[T]): SinglyLinkedList[T]
+
+ + Creates a shallow copy of a. +

Example:

+
from std/sequtils import toSeq
+type Foo = ref object
+  x: int
+var
+  f = Foo(x: 1)
+  a = [f].toSinglyLinkedList
+let b = a.copy
+a.add([f].toSinglyLinkedList)
+assert a.toSeq == [f, f]
+assert b.toSeq == [f] # b isn't modified...
+f.x = 42
+assert a.head.value.x == 42
+assert b.head.value.x == 42 # ... but the elements are not deep copied
+
+let c = [1, 2, 3].toSinglyLinkedList
+assert $c == $c.copy
+ Source   +Edit   + +
+
+ +
+
+
+
proc find[T](L: SomeLinkedCollection[T]; value: T): SomeLinkedNode[T]
+
+ +

Searches in the list for a value. Returns nil if the value does not exist.

+

See also:

+ + +

Example:

+
let a = [9, 8].toSinglyLinkedList
+assert a.find(9).value == 9
+assert a.find(1) == nil
+ Source   +Edit   + +
+
+ +
+
+
+
proc initDoublyLinkedList[T](): DoublyLinkedList[T]
+
+ +

Creates a new doubly linked list that is empty.

+

Doubly linked lists are initialized by default, so it is not necessary to call this function explicitly.

+ +

Example:

+
let a = initDoublyLinkedList[int]()
+ Source   +Edit   + +
+
+ +
+
+
+
proc initDoublyLinkedRing[T](): DoublyLinkedRing[T]
+
+ +

Creates a new doubly linked ring that is empty.

+

Doubly linked rings are initialized by default, so it is not necessary to call this function explicitly.

+ +

Example:

+
let a = initDoublyLinkedRing[int]()
+ Source   +Edit   + +
+
+ +
+
+
+
proc initSinglyLinkedList[T](): SinglyLinkedList[T]
+
+ +

Creates a new singly linked list that is empty.

+

Singly linked lists are initialized by default, so it is not necessary to call this function explicitly.

+ +

Example:

+
let a = initSinglyLinkedList[int]()
+ Source   +Edit   + +
+
+ +
+
+
+
proc initSinglyLinkedRing[T](): SinglyLinkedRing[T]
+
+ +

Creates a new singly linked ring that is empty.

+

Singly linked rings are initialized by default, so it is not necessary to call this function explicitly.

+ +

Example:

+
let a = initSinglyLinkedRing[int]()
+ Source   +Edit   + +
+
+ +
+
+
+
proc newDoublyLinkedNode[T](value: T): DoublyLinkedNode[T]
+
+ + Creates a new doubly linked node with the given value. +

Example:

+
let n = newDoublyLinkedNode[int](5)
+assert n.value == 5
+ Source   +Edit   + +
+
+ +
+
+
+
proc newSinglyLinkedNode[T](value: T): SinglyLinkedNode[T]
+
+ + Creates a new singly linked node with the given value. +

Example:

+
let n = newSinglyLinkedNode[int](5)
+assert n.value == 5
+ Source   +Edit   + +
+
+ +
+
+
+
proc prepend[T: SomeLinkedList](a: var T; b: T)
+
+ +

Prepends a shallow copy of b to the beginning of a.

+

See also:

+ + +

Example:

+
from std/sequtils import toSeq
+var a = [4, 5].toSinglyLinkedList
+let b = [1, 2, 3].toSinglyLinkedList
+a.prepend(b)
+assert a.toSeq == [1, 2, 3, 4, 5]
+assert b.toSeq == [1, 2, 3]
+a.prepend(a)
+assert a.toSeq == [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
+ Source   +Edit   + +
+
+
+
proc prepend[T](L: var DoublyLinkedList[T]; n: DoublyLinkedNode[T])
+
+ +

Prepends (adds to the beginning) a node n to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initDoublyLinkedList[int]()
+let n = newDoublyLinkedNode[int](9)
+a.prepend(n)
+assert a.contains(9)
+ Source   +Edit   + +
+
+
+
proc prepend[T](L: var DoublyLinkedList[T]; value: T)
+
+ +

Prepends (adds to the beginning) a value to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initDoublyLinkedList[int]()
+a.prepend(9)
+a.prepend(8)
+assert a.contains(9)
+ Source   +Edit   + +
+
+
+
proc prepend[T](L: var DoublyLinkedRing[T]; n: DoublyLinkedNode[T])
+
+ +

Prepends (adds to the beginning) a node n to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initDoublyLinkedRing[int]()
+let n = newDoublyLinkedNode[int](9)
+a.prepend(n)
+assert a.contains(9)
+ Source   +Edit   + +
+
+
+
proc prepend[T](L: var DoublyLinkedRing[T]; value: T)
+
+ +

Prepends (adds to the beginning) a value to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initDoublyLinkedRing[int]()
+a.prepend(9)
+a.prepend(8)
+assert a.contains(9)
+ Source   +Edit   + +
+
+
+
proc prepend[T](L: var SinglyLinkedList[T]; n: SinglyLinkedNode[T]) {.inline.}
+
+ +

Prepends (adds to the beginning) a node to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initSinglyLinkedList[int]()
+let n = newSinglyLinkedNode[int](9)
+a.prepend(n)
+assert a.contains(9)
+ Source   +Edit   + +
+
+
+
proc prepend[T](L: var SinglyLinkedList[T]; value: T) {.inline.}
+
+ +

Prepends (adds to the beginning) a node to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initSinglyLinkedList[int]()
+a.prepend(9)
+a.prepend(8)
+assert a.contains(9)
+ Source   +Edit   + +
+
+
+
proc prepend[T](L: var SinglyLinkedRing[T]; n: SinglyLinkedNode[T])
+
+ +

Prepends (adds to the beginning) a node n to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initSinglyLinkedRing[int]()
+let n = newSinglyLinkedNode[int](9)
+a.prepend(n)
+assert a.contains(9)
+ Source   +Edit   + +
+
+
+
proc prepend[T](L: var SinglyLinkedRing[T]; value: T)
+
+ +

Prepends (adds to the beginning) a value to L. Efficiency: O(1).

+

See also:

+ + +

Example:

+
var a = initSinglyLinkedRing[int]()
+a.prepend(9)
+a.prepend(8)
+assert a.contains(9)
+ Source   +Edit   + +
+
+ +
+
+
+
proc prependMoved[T: SomeLinkedList](a, b: var T)
+
+ +

Moves b before the head of a. Efficiency: O(1). Note that b becomes empty after the operation unless it has the same address as a. Self-prepending results in a cycle.

+

See also:

+ + +

Example:

+
import std/[sequtils, enumerate, sugar]
+var
+  a = [4, 5].toSinglyLinkedList
+  b = [1, 2, 3].toSinglyLinkedList
+  c = [0, 1].toSinglyLinkedList
+a.prependMoved(b)
+assert a.toSeq == [1, 2, 3, 4, 5]
+assert b.toSeq == []
+c.prependMoved(c)
+let s = collect:
+  for i, ci in enumerate(c):
+    if i == 6: break
+    ci
+assert s == [0, 1, 0, 1, 0, 1]
+ Source   +Edit   + +
+
+ +
+
+
+
proc remove[T](L: var DoublyLinkedList[T]; n: DoublyLinkedNode[T])
+
+ + Removes a node n from L. Efficiency: O(1). This function assumes, for the sake of efficiency, that n is contained in L, otherwise the effects are undefined. When the list is cyclic, the cycle is preserved after removal. +

Example:

+
import std/[sequtils, enumerate, sugar]
+var a = [0, 1, 2].toSinglyLinkedList
+let n = a.head.next
+assert n.value == 1
+a.remove(n)
+assert a.toSeq == [0, 2]
+a.remove(n)
+assert a.toSeq == [0, 2]
+a.addMoved(a) # cycle: [0, 2, 0, 2, ...]
+a.remove(a.head)
+let s = collect:
+  for i, ai in enumerate(a):
+    if i == 4: break
+    ai
+assert s == [2, 2, 2, 2]
+ Source   +Edit   + +
+
+
+
proc remove[T](L: var DoublyLinkedRing[T]; n: DoublyLinkedNode[T])
+
+ + Removes n from L. Efficiency: O(1). This function assumes, for the sake of efficiency, that n is contained in L, otherwise the effects are undefined. +

Example:

+
var a = initDoublyLinkedRing[int]()
+let n = newDoublyLinkedNode[int](5)
+a.add(n)
+assert 5 in a
+a.remove(n)
+assert 5 notin a
+ Source   +Edit   + +
+
+
+
proc remove[T](L: var SinglyLinkedList[T]; n: SinglyLinkedNode[T]): bool {.
+    discardable.}
+
+ + Removes a node n from L. Returns true if n was found in L. Efficiency: O(n); the list is traversed until n is found. Attempting to remove an element not contained in the list is a no-op. When the list is cyclic, the cycle is preserved after removal. +

Example:

+
import std/[sequtils, enumerate, sugar]
+var a = [0, 1, 2].toSinglyLinkedList
+let n = a.head.next
+assert n.value == 1
+assert a.remove(n) == true
+assert a.toSeq == [0, 2]
+assert a.remove(n) == false
+assert a.toSeq == [0, 2]
+a.addMoved(a) # cycle: [0, 2, 0, 2, ...]
+a.remove(a.head)
+let s = collect:
+  for i, ai in enumerate(a):
+    if i == 4: break
+    ai
+assert s == [2, 2, 2, 2]
+ Source   +Edit   + +
+
+ +
+
+
+
func toDoublyLinkedList[T](elems: openArray[T]): DoublyLinkedList[T]
+
+ + Creates a new DoublyLinkedList from the members of elems. +

Example:

+
from std/sequtils import toSeq
+let a = [1, 2, 3, 4, 5].toDoublyLinkedList
+assert a.toSeq == [1, 2, 3, 4, 5]
+ Source   +Edit   + +
+
+ +
+
+
+
func toDoublyLinkedRing[T](elems: openArray[T]): DoublyLinkedRing[T]
+
+ + Creates a new DoublyLinkedRing from the members of elems. +

Example:

+
from std/sequtils import toSeq
+let a = [1, 2, 3, 4, 5].toDoublyLinkedRing
+assert a.toSeq == [1, 2, 3, 4, 5]
+ Source   +Edit   + +
+
+ +
+
+
+
func toSinglyLinkedList[T](elems: openArray[T]): SinglyLinkedList[T]
+
+ + Creates a new SinglyLinkedList from the members of elems. +

Example:

+
from std/sequtils import toSeq
+let a = [1, 2, 3, 4, 5].toSinglyLinkedList
+assert a.toSeq == [1, 2, 3, 4, 5]
+ Source   +Edit   + +
+
+ +
+
+
+
func toSinglyLinkedRing[T](elems: openArray[T]): SinglyLinkedRing[T]
+
+ + Creates a new SinglyLinkedRing from the members of elems. +

Example:

+
from std/sequtils import toSeq
+let a = [1, 2, 3, 4, 5].toSinglyLinkedRing
+assert a.toSeq == [1, 2, 3, 4, 5]
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator items[T](L: SomeLinkedList[T]): T
+
+ +

Yields every value of L.

+

See also:

+ + +

Example:

+
from std/sugar import collect
+from std/sequtils import toSeq
+let a = collect(initSinglyLinkedList):
+  for i in 1..3: 10 * i
+assert toSeq(items(a)) == toSeq(a)
+assert toSeq(a) == @[10, 20, 30]
+ Source   +Edit   + +
+
+
+
iterator items[T](L: SomeLinkedRing[T]): T
+
+ +

Yields every value of L.

+

See also:

+ + +

Example:

+
from std/sugar import collect
+from std/sequtils import toSeq
+let a = collect(initSinglyLinkedRing):
+  for i in 1..3: 10 * i
+assert toSeq(items(a)) == toSeq(a)
+assert toSeq(a) == @[10, 20, 30]
+ Source   +Edit   + +
+
+ +
+
+
+
iterator mitems[T](L: var SomeLinkedList[T]): var T
+
+ +

Yields every value of L so that you can modify it.

+

See also:

+ + +

Example:

+
var a = initSinglyLinkedList[int]()
+for i in 1..5:
+  a.add(10 * i)
+assert $a == "[10, 20, 30, 40, 50]"
+for x in mitems(a):
+  x = 5 * x - 1
+assert $a == "[49, 99, 149, 199, 249]"
+ Source   +Edit   + +
+
+
+
iterator mitems[T](L: var SomeLinkedRing[T]): var T
+
+ +

Yields every value of L so that you can modify it.

+

See also:

+ + +

Example:

+
var a = initSinglyLinkedRing[int]()
+for i in 1..5:
+  a.add(10 * i)
+assert $a == "[10, 20, 30, 40, 50]"
+for x in mitems(a):
+  x = 5 * x - 1
+assert $a == "[49, 99, 149, 199, 249]"
+ Source   +Edit   + +
+
+ +
+
+
+
iterator nodes[T](L: SomeLinkedList[T]): SomeLinkedNode[T]
+
+ +

Iterates over every node of x. Removing the current node from the list during traversal is supported.

+

See also:

+ + +

Example:

+
var a = initDoublyLinkedList[int]()
+for i in 1..5:
+  a.add(10 * i)
+assert $a == "[10, 20, 30, 40, 50]"
+for x in nodes(a):
+  if x.value == 30:
+    a.remove(x)
+  else:
+    x.value = 5 * x.value - 1
+assert $a == "[49, 99, 199, 249]"
+ Source   +Edit   + +
+
+
+
iterator nodes[T](L: SomeLinkedRing[T]): SomeLinkedNode[T]
+
+ +

Iterates over every node of x. Removing the current node from the list during traversal is supported.

+

See also:

+ + +

Example:

+
var a = initDoublyLinkedRing[int]()
+for i in 1..5:
+  a.add(10 * i)
+assert $a == "[10, 20, 30, 40, 50]"
+for x in nodes(a):
+  if x.value == 30:
+    a.remove(x)
+  else:
+    x.value = 5 * x.value - 1
+assert $a == "[49, 99, 199, 249]"
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/lists.idx b/lists.idx new file mode 100644 index 0000000000000..e7d0792368ac2 --- /dev/null +++ b/lists.idx @@ -0,0 +1,74 @@ +nimTitle lists lists.html module std/lists 0 +nim DoublyLinkedNodeObj lists.html#DoublyLinkedNodeObj object DoublyLinkedNodeObj 66 +nim DoublyLinkedNode lists.html#DoublyLinkedNode type DoublyLinkedNode 73 +nim SinglyLinkedNodeObj lists.html#SinglyLinkedNodeObj object SinglyLinkedNodeObj 75 +nim SinglyLinkedNode lists.html#SinglyLinkedNode type SinglyLinkedNode 81 +nim SinglyLinkedList lists.html#SinglyLinkedList object SinglyLinkedList 83 +nim DoublyLinkedList lists.html#DoublyLinkedList object DoublyLinkedList 88 +nim SinglyLinkedRing lists.html#SinglyLinkedRing object SinglyLinkedRing 93 +nim DoublyLinkedRing lists.html#DoublyLinkedRing object DoublyLinkedRing 98 +nim SomeLinkedList lists.html#SomeLinkedList type SomeLinkedList 102 +nim SomeLinkedRing lists.html#SomeLinkedRing type SomeLinkedRing 104 +nim SomeLinkedCollection lists.html#SomeLinkedCollection type SomeLinkedCollection 106 +nim SomeLinkedNode lists.html#SomeLinkedNode type SomeLinkedNode 108 +nim initSinglyLinkedList lists.html#initSinglyLinkedList proc initSinglyLinkedList[T](): SinglyLinkedList[T] 110 +nim initDoublyLinkedList lists.html#initDoublyLinkedList proc initDoublyLinkedList[T](): DoublyLinkedList[T] 120 +nim initSinglyLinkedRing lists.html#initSinglyLinkedRing proc initSinglyLinkedRing[T](): SinglyLinkedRing[T] 130 +nim initDoublyLinkedRing lists.html#initDoublyLinkedRing proc initDoublyLinkedRing[T](): DoublyLinkedRing[T] 140 +nim newDoublyLinkedNode lists.html#newDoublyLinkedNode,T proc newDoublyLinkedNode[T](value: T): DoublyLinkedNode[T] 150 +nim newSinglyLinkedNode lists.html#newSinglyLinkedNode,T proc newSinglyLinkedNode[T](value: T): SinglyLinkedNode[T] 159 +nim items lists.html#items.i,SomeLinkedList[T] iterator items[T](L: SomeLinkedList[T]): T 182 +nim items lists.html#items.i,SomeLinkedRing[T] iterator items[T](L: SomeLinkedRing[T]): T 198 +nim mitems lists.html#mitems.i,SomeLinkedList[T] iterator mitems[T](L: var SomeLinkedList[T]): var T 214 +nim mitems lists.html#mitems.i,SomeLinkedRing[T] iterator mitems[T](L: var SomeLinkedRing[T]): var T 231 +nim nodes lists.html#nodes.i,SomeLinkedList[T] iterator nodes[T](L: SomeLinkedList[T]): SomeLinkedNode[T] 248 +nim nodes lists.html#nodes.i,SomeLinkedRing[T] iterator nodes[T](L: SomeLinkedRing[T]): SomeLinkedNode[T] 273 +nim `$` lists.html#$,SomeLinkedCollection[T] proc `$`[T](L: SomeLinkedCollection[T]): string 300 +nim find lists.html#find,SomeLinkedCollection[T],T proc find[T](L: SomeLinkedCollection[T]; value: T): SomeLinkedNode[T] 312 +nim contains lists.html#contains,SomeLinkedCollection[T],T proc contains[T](L: SomeLinkedCollection[T]; value: T): bool 330 +nim prepend lists.html#prepend,T,T proc prepend[T: SomeLinkedList](a: var T; b: T) 346 +nim prependMoved lists.html#prependMoved,T,T proc prependMoved[T: SomeLinkedList](a, b: var T) 366 +nim add lists.html#add,SinglyLinkedList[T],SinglyLinkedNode[T] proc add[T](L: var SinglyLinkedList[T]; n: SinglyLinkedNode[T]) 393 +nim add lists.html#add,SinglyLinkedList[T],T proc add[T](L: var SinglyLinkedList[T]; value: T) 414 +nim prepend lists.html#prepend,SinglyLinkedList[T],SinglyLinkedNode[T] proc prepend[T](L: var SinglyLinkedList[T]; n: SinglyLinkedNode[T]) 430 +nim prepend lists.html#prepend,SinglyLinkedList[T],T proc prepend[T](L: var SinglyLinkedList[T]; value: T) 449 +nim copy lists.html#copy,SinglyLinkedList[T] proc copy[T](a: SinglyLinkedList[T]): SinglyLinkedList[T] 466 +nim addMoved lists.html#addMoved,SinglyLinkedList[T],SinglyLinkedList[T] proc addMoved[T](a, b: var SinglyLinkedList[T]) 490 +nim add lists.html#add,DoublyLinkedList[T],DoublyLinkedNode[T] proc add[T](L: var DoublyLinkedList[T]; n: DoublyLinkedNode[T]) 523 +nim add lists.html#add,DoublyLinkedList[T],T proc add[T](L: var DoublyLinkedList[T]; value: T) 547 +nim prepend lists.html#prepend,DoublyLinkedList[T],DoublyLinkedNode[T] proc prepend[T](L: var DoublyLinkedList[T]; n: DoublyLinkedNode[T]) 566 +nim prepend lists.html#prepend,DoublyLinkedList[T],T proc prepend[T](L: var DoublyLinkedList[T]; value: T) 590 +nim copy lists.html#copy,DoublyLinkedList[T] proc copy[T](a: DoublyLinkedList[T]): DoublyLinkedList[T] 609 +nim addMoved lists.html#addMoved,DoublyLinkedList[T],DoublyLinkedList[T] proc addMoved[T](a, b: var DoublyLinkedList[T]) 633 +nim add lists.html#add,T,T proc add[T: SomeLinkedList](a: var T; b: T) 668 +nim remove lists.html#remove,SinglyLinkedList[T],SinglyLinkedNode[T] proc remove[T](L: var SinglyLinkedList[T]; n: SinglyLinkedNode[T]): bool 688 +nim remove lists.html#remove,DoublyLinkedList[T],DoublyLinkedNode[T] proc remove[T](L: var DoublyLinkedList[T]; n: DoublyLinkedNode[T]) 726 +nim add lists.html#add,SinglyLinkedRing[T],SinglyLinkedNode[T] proc add[T](L: var SinglyLinkedRing[T]; n: SinglyLinkedNode[T]) 755 +nim add lists.html#add,SinglyLinkedRing[T],T proc add[T](L: var SinglyLinkedRing[T]; value: T) 778 +nim prepend lists.html#prepend,SinglyLinkedRing[T],SinglyLinkedNode[T] proc prepend[T](L: var SinglyLinkedRing[T]; n: SinglyLinkedNode[T]) 795 +nim prepend lists.html#prepend,SinglyLinkedRing[T],T proc prepend[T](L: var SinglyLinkedRing[T]; value: T) 818 +nim add lists.html#add,DoublyLinkedRing[T],DoublyLinkedNode[T] proc add[T](L: var DoublyLinkedRing[T]; n: DoublyLinkedNode[T]) 837 +nim add lists.html#add,DoublyLinkedRing[T],T proc add[T](L: var DoublyLinkedRing[T]; value: T) 863 +nim prepend lists.html#prepend,DoublyLinkedRing[T],DoublyLinkedNode[T] proc prepend[T](L: var DoublyLinkedRing[T]; n: DoublyLinkedNode[T]) 882 +nim prepend lists.html#prepend,DoublyLinkedRing[T],T proc prepend[T](L: var DoublyLinkedRing[T]; value: T) 908 +nim remove lists.html#remove,DoublyLinkedRing[T],DoublyLinkedNode[T] proc remove[T](L: var DoublyLinkedRing[T]; n: DoublyLinkedNode[T]) 927 +nim append lists.html#append,, proc append[T](a: var (SinglyLinkedList[T] | SinglyLinkedRing[T]);\n b: SinglyLinkedList[T] | SinglyLinkedNode[T] | T) 949 +nim append lists.html#append,,_2 proc append[T](a: var (DoublyLinkedList[T] | DoublyLinkedRing[T]);\n b: DoublyLinkedList[T] | DoublyLinkedNode[T] | T) 959 +nim appendMoved lists.html#appendMoved,T,T proc appendMoved[T: SomeLinkedList](a, b: var T) 969 +nim toSinglyLinkedList lists.html#toSinglyLinkedList,openArray[T] proc toSinglyLinkedList[T](elems: openArray[T]): SinglyLinkedList[T] 977 +nim toSinglyLinkedRing lists.html#toSinglyLinkedRing,openArray[T] proc toSinglyLinkedRing[T](elems: openArray[T]): SinglyLinkedRing[T] 988 +nim toDoublyLinkedList lists.html#toDoublyLinkedList,openArray[T] proc toDoublyLinkedList[T](elems: openArray[T]): DoublyLinkedList[T] 999 +nim toDoublyLinkedRing lists.html#toDoublyLinkedRing,openArray[T] proc toDoublyLinkedRing[T](elems: openArray[T]): DoublyLinkedRing[T] 1010 +heading Basic Usage lists.html#basic-usage Basic Usage 0 +heading Lists lists.html#basic-usage-lists Lists 0 +heading Rings lists.html#basic-usage-rings Rings 0 +heading See also lists.html#see-also See also 0 +nimgrp remove lists.html#remove-procs-all proc 688 +nimgrp copy lists.html#copy-procs-all proc 466 +nimgrp prepend lists.html#prepend-procs-all proc 346 +nimgrp add lists.html#add-procs-all proc 393 +nimgrp addmoved lists.html#addMoved-procs-all proc 490 +nimgrp append lists.html#append-procs-all proc 949 +nimgrp items lists.html#items-iterators-all iterator 182 +nimgrp mitems lists.html#mitems-iterators-all iterator 214 +nimgrp nodes lists.html#nodes-iterators-all iterator 248 diff --git a/locks.html b/locks.html new file mode 100644 index 0000000000000..8f923cb951664 --- /dev/null +++ b/locks.html @@ -0,0 +1,358 @@ + + + + + + + +std/locks + + + + + + + + + + + + + + + + +
+
+

std/locks

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module contains Nim's support for locks and condition vars.

+
+

Imports

+
+ syslocks +
+
+
+

Types

+
+
+
Cond = SysCond
+
+ + Nim condition variable + Source   +Edit   + +
+
+
+
Lock = SysLock
+
+ + Nim lock; whether this is re-entrant or not is unspecified! + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(lock: Lock): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc acquire(lock: var Lock) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Acquires the given lock. + Source   +Edit   + +
+
+ +
+
+
+
proc broadcast(cond: var Cond) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Unblocks all threads currently blocked on the specified condition variable cond. + Source   +Edit   + +
+
+ +
+
+
+
proc deinitCond(cond: Cond) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Frees the resources associated with the condition variable. + Source   +Edit   + +
+
+ +
+
+
+
proc deinitLock(lock: Lock) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Frees the resources associated with the lock. + Source   +Edit   + +
+
+ +
+
+
+
proc initCond(cond: var Cond) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Initializes the given condition variable. + Source   +Edit   + +
+
+ +
+
+
+
proc initLock(lock: var Lock) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Initializes the given lock. + Source   +Edit   + +
+
+ +
+
+
+
proc release(lock: var Lock) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Releases the given lock. + Source   +Edit   + +
+
+ +
+
+
+
proc signal(cond: var Cond) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Sends a signal to the condition variable cond. + Source   +Edit   + +
+
+ +
+
+
+
proc tryAcquire(lock: var Lock): bool {.inline, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + Tries to acquire the given lock. Returns true on success. + Source   +Edit   + +
+
+ +
+
+
+
proc wait(cond: var Cond; lock: var Lock) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Waits on the condition variable cond. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template withLock(a: Lock; body: untyped)
+
+ + Acquires the given lock, executes the statements in body and releases the lock after the statements finish executing. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/locks.idx b/locks.idx new file mode 100644 index 0000000000000..4bebe6e4d286f --- /dev/null +++ b/locks.idx @@ -0,0 +1,15 @@ +nimTitle locks locks.html module std/locks 0 +nim Lock locks.html#Lock type Lock 24 +nim Cond locks.html#Cond type Cond 26 +nim `$` locks.html#$,SysLockObj proc `$`(lock: Lock): string 31 +nim initLock locks.html#initLock,SysLockObj proc initLock(lock: var Lock) 35 +nim deinitLock locks.html#deinitLock,SysLockObj proc deinitLock(lock: Lock) 40 +nim tryAcquire locks.html#tryAcquire,SysLockObj proc tryAcquire(lock: var Lock): bool 44 +nim acquire locks.html#acquire,SysLockObj proc acquire(lock: var Lock) 48 +nim release locks.html#release,SysLockObj proc release(lock: var Lock) 53 +nim initCond locks.html#initCond,SysCondObj proc initCond(cond: var Cond) 59 +nim deinitCond locks.html#deinitCond,SysCondObj proc deinitCond(cond: Cond) 63 +nim wait locks.html#wait,SysCondObj,SysLockObj proc wait(cond: var Cond; lock: var Lock) 67 +nim signal locks.html#signal,SysCondObj proc signal(cond: var Cond) 71 +nim broadcast locks.html#broadcast,SysCondObj proc broadcast(cond: var Cond) 75 +nim withLock locks.html#withLock.t,SysLockObj,untyped template withLock(a: Lock; body: untyped) 80 diff --git a/logging.html b/logging.html new file mode 100644 index 0000000000000..bcb0015382dd1 --- /dev/null +++ b/logging.html @@ -0,0 +1,1023 @@ + + + + + + + +std/logging + + + + + + + + + + + + + + + + +
+
+

std/logging

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a simple logger.

+

It has been designed to be as simple as possible to avoid bloat. If this library does not fulfill your needs, write your own.

+ +

Basic usage

To get started, first create a logger:

+

import std/logging
+
+var logger = newConsoleLogger()

+

The logger that was created above logs to the console, but this module also provides loggers that log to files, such as the FileLogger. Creating custom loggers is also possible by inheriting from the Logger type.

+

Once a logger has been created, call its log proc to log a message:

+

logger.log(lvlInfo, "a log message")
+# Output: INFO a log message

+

The INFO within the output is the result of a format string being prepended to the message, and it will differ depending on the message's level. Format strings are explained in more detail here.

+

There are six logging levels: debug, info, notice, warn, error, and fatal. They are described in more detail within the Level enum's documentation. A message is logged if its level is at or above both the logger's levelThreshold field and the global log filter. The latter can be changed with the setLogFilter proc.

+
Warning: +For loggers that log to a console or to files, only error and fatal messages will cause their output buffers to be flushed immediately by default. set flushThreshold when creating the logger to change this.
+ +

Handlers

When using multiple loggers, calling the log proc for each logger can become repetitive. Instead of doing that, register each logger that will be used with the addHandler proc, which is demonstrated in the following example:

+

import std/logging
+
+var consoleLog = newConsoleLogger()
+var fileLog = newFileLogger("errors.log", levelThreshold=lvlError)
+var rollingLog = newRollingFileLogger("rolling.log")
+
+addHandler(consoleLog)
+addHandler(fileLog)
+addHandler(rollingLog)

+

After doing this, use either the log template or one of the level-specific templates, such as the error template, to log messages to all registered handlers at once.

+

# This example uses the loggers created above
+log(lvlError, "an error occurred")
+error("an error occurred")  # Equivalent to the above line
+info("something normal happened")  # Will not be written to errors.log

+

Note that a message's level is still checked against each handler's levelThreshold and the global log filter.

+ +

Format strings

Log messages are prefixed with format strings. These strings contain placeholders for variables, such as $time, that are replaced with their corresponding values, such as the current time, before they are prepended to a log message. Characters that are not part of variables are unaffected.

+

The format string used by a logger can be specified by providing the fmtStr argument when creating the logger or by setting its fmtStr field afterward. If not specified, the default format string is used.

+

The following variables, which must be prefixed with a dollar sign ($), are available:

+ + + + + + + + + +
VariableOutput
$dateCurrent date
$timeCurrent time
$datetime$dateT$time
$appos.getAppFilename()
$appnameBase name of $app
$appdirDirectory name of $app
$levelidFirst letter of log level
$levelnameLog level name

Note that $app, $appname, and $appdir are not supported when using the JavaScript backend.

+

The following example illustrates how to use format strings:

+

import std/logging
+
+var logger = newConsoleLogger(fmtStr="[$time] - $levelname: ")
+logger.log(lvlInfo, "this is a message")
+# Output: [19:50:13] - INFO: this is a message

+ +

Notes when using multiple threads

There are a few details to keep in mind when using this module within multiple threads:

+
  • The global log filter is actually a thread-local variable, so it needs to be set in each thread that uses this module.
  • +
  • The list of registered handlers is also a thread-local variable. If a handler will be used in multiple threads, it needs to be registered in each of those threads.
  • +
+ +

See also

+

+ +
+

Types

+
+
+
ConsoleLogger = ref object of Logger
+  useStderr*: bool           ## If true, writes to stderr; otherwise, writes to stdout
+  flushThreshold*: Level     ## Only messages that are at or above this
+                             ## threshold will be flushed immediately
+
+ +

A logger that writes log messages to the console.

+

Create a new ConsoleLogger with the newConsoleLogger proc.

+

See also:

+ + + Source   +Edit   + +
+
+
+
FileLogger = ref object of Logger
+  file*: File                ## The wrapped file
+  flushThreshold*: Level     ## Only messages that are at or above this
+                             ## threshold will be flushed immediately
+
+ +

A logger that writes log messages to a file.

+

Create a new FileLogger with the newFileLogger proc.

+

Note: This logger is not available for the JavaScript backend.

+

See also:

+ + + Source   +Edit   + +
+
+
+
Level = enum
+  lvlAll,                   ## All levels active
+  lvlDebug,                 ## Debug level and above are active
+  lvlInfo,                  ## Info level and above are active
+  lvlNotice,                ## Notice level and above are active
+  lvlWarn,                  ## Warn level and above are active
+  lvlError,                 ## Error level and above are active
+  lvlFatal,                 ## Fatal level and above are active
+  lvlNone                    ## No levels active; nothing is logged
+
+ +

+Enumeration of logging levels.

+

Debug messages represent the lowest logging level, and fatal error messages represent the highest logging level. lvlAll can be used to enable all messages, while lvlNone can be used to disable all messages.

+

Typical usage for each logging level, from lowest to highest, is described below:

+
  • Debug - debugging information helpful only to developers
  • +
  • Info - anything associated with normal operation and without any particular importance
  • +
  • Notice - more important information that users should be notified about
  • +
  • Warn - impending problems that require some attention
  • +
  • Error - error conditions that the application can recover from
  • +
  • Fatal - fatal errors that prevent the application from continuing
  • +
+

It is completely up to the application how to utilize each level.

+

Individual loggers have a levelThreshold field that filters out any messages with a level lower than the threshold. There is also a global filter that applies to all log messages, and it can be changed using the setLogFilter proc.

+ + Source   +Edit   + +
+
+
+
Logger = ref object of RootObj
+  levelThreshold*: Level     ## Only messages that are at or above this
+                             ## threshold will be logged
+  fmtStr*: string            ## Format string to prepend to each log message;
+                             ## defaultFmtStr is the default
+
+ +

The abstract base type of all loggers.

+

Custom loggers should inherit from this type. They should also provide their own implementation of the log method.

+

See also:

+ + + Source   +Edit   + +
+
+
+
RollingFileLogger = ref object of FileLogger
+
+ +

A logger that writes log messages to a file while performing log rotation.

+

Create a new RollingFileLogger with the newRollingFileLogger proc.

+

Note: This logger is not available for the JavaScript backend.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
defaultFmtStr = "$levelname "
+
+ + The default format string. + Source   +Edit   + +
+
+
+
LevelNames: array[Level, string] = ["DEBUG", "DEBUG", "INFO", "NOTICE", "WARN",
+                                    "ERROR", "FATAL", "NONE"]
+
+ + Array of strings representing each logging level. + Source   +Edit   + +
+
+
+
verboseFmtStr = "$levelid, [$datetime] -- $appname: "
+
+ +

+A more verbose format string.

+

This string can be passed as the frmStr argument to procs that create new loggers, such as the newConsoleLogger proc.

+

If a different format string is preferred, refer to the documentation about format strings for more information, including a list of available variables.

+ + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc addHandler(handler: Logger) {....raises: [], tags: [], forbids: [].}
+
+ + Adds a logger to the list of registered handlers.
Warning: +The list of handlers is a thread-local variable. If the given handler will be used in multiple threads, this proc should be called in each of those threads.
+

See also:

+ + +

Example:

+
var logger = newConsoleLogger()
+addHandler(logger)
+doAssert logger in getHandlers()
+ Source   +Edit   + +
+
+ +
+
+
+
proc defaultFilename(): string {....raises: [], tags: [ReadIOEffect], forbids: [].}
+
+ +

Returns the filename that is used by default when naming log files.

+

Note: This proc is not available for the JavaScript backend.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getHandlers(): seq[Logger] {....raises: [], tags: [], forbids: [].}
+
+ +

Returns a list of all the registered handlers.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getLogFilter(): Level {....raises: [], tags: [], forbids: [].}
+
+ +

Gets the global log filter.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newConsoleLogger(levelThreshold = lvlAll; fmtStr = defaultFmtStr;
+                      useStderr = false; flushThreshold = defaultFlushThreshold): ConsoleLogger {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new ConsoleLogger.

+

By default, log messages are written to stdout. If useStderr is true, they are written to stderr instead.

+

For the JavaScript backend, log messages are written to the console, and useStderr is ignored.

+

See also:

+ +

Examples:

+

var normalLog = newConsoleLogger()
+var formatLog = newConsoleLogger(fmtStr=verboseFmtStr)
+var errorLog = newConsoleLogger(levelThreshold=lvlError, useStderr=true)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newFileLogger(file: File; levelThreshold = lvlAll; fmtStr = defaultFmtStr;
+                   flushThreshold = defaultFlushThreshold): FileLogger {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new FileLogger that uses the given file handle.

+

Note: This proc is not available for the JavaScript backend.

+

See also:

+ +

Examples:

+

var messages = open("messages.log", fmWrite)
+var formatted = open("formatted.log", fmWrite)
+var errors = open("errors.log", fmWrite)
+
+var normalLog = newFileLogger(messages)
+var formatLog = newFileLogger(formatted, fmtStr=verboseFmtStr)
+var errorLog = newFileLogger(errors, levelThreshold=lvlError)

+ + Source   +Edit   + +
+
+
+
proc newFileLogger(filename = defaultFilename(); mode: FileMode = fmAppend;
+                   levelThreshold = lvlAll; fmtStr = defaultFmtStr;
+                   bufSize: int = -1; flushThreshold = defaultFlushThreshold): FileLogger {.
+    ...raises: [IOError], tags: [], forbids: [].}
+
+ +

Creates a new FileLogger that logs to a file with the given filename.

+

bufSize controls the size of the output buffer that is used when writing to the log file. The following values can be provided:

+
  • -1 - use system defaults
  • +
  • 0 - unbuffered
  • +
  • > 0 - fixed buffer size
  • +
+

Note: This proc is not available for the JavaScript backend.

+

See also:

+ +

Examples:

+

var normalLog = newFileLogger("messages.log")
+var formatLog = newFileLogger("formatted.log", fmtStr=verboseFmtStr)
+var errorLog = newFileLogger("errors.log", levelThreshold=lvlError)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newRollingFileLogger(filename = defaultFilename();
+                          mode: FileMode = fmReadWrite; levelThreshold = lvlAll;
+                          fmtStr = defaultFmtStr; maxLines: Positive = 1000;
+                          bufSize: int = -1;
+                          flushThreshold = defaultFlushThreshold): RollingFileLogger {.
+    ...raises: [IOError, OSError], tags: [ReadDirEffect, ReadIOEffect], forbids: [].}
+
+ +

Creates a new RollingFileLogger.

+

Once the current log file being written to contains maxLines lines, a new log file will be created, and the old log file will be renamed.

+

bufSize controls the size of the output buffer that is used when writing to the log file. The following values can be provided:

+
  • -1 - use system defaults
  • +
  • 0 - unbuffered
  • +
  • > 0 - fixed buffer size
  • +
+

Note: This proc is not available in the JavaScript backend.

+

See also:

+ +

Examples:

+

var normalLog = newRollingFileLogger("messages.log")
+var formatLog = newRollingFileLogger("formatted.log", fmtStr=verboseFmtStr)
+var shortLog = newRollingFileLogger("short.log", maxLines=200)
+var errorLog = newRollingFileLogger("errors.log", levelThreshold=lvlError)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc removeHandler(handler: Logger) {....raises: [], tags: [], forbids: [].}
+
+ +

Removes a logger from the list of registered handlers.

+

Note that for n times a logger is registered, n calls to this proc are required to remove that logger.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc setLogFilter(lvl: Level) {....raises: [], tags: [], forbids: [].}
+
+ +

Sets the global log filter.

+

Messages below the provided level will not be logged regardless of an individual logger's levelThreshold. By default, all messages are logged.

+
Warning: +The global log filter is a thread-local variable. If logging is being performed in multiple threads, this proc should be called in each thread unless it is intended that different threads should log at different logging levels.
+

See also:

+ + +

Example:

+
setLogFilter(lvlError)
+doAssert getLogFilter() == lvlError
+ Source   +Edit   + +
+
+ +
+
+
+
proc substituteLog(frmt: string; level: Level; args: varargs[string, `$`]): string {.
+    ...raises: [], tags: [ReadIOEffect, TimeEffect], forbids: [].}
+
+ +

Formats a log message at the specified level with the given format string.

+

The format variables present within frmt will be replaced with the corresponding values before being prepended to args and returned.

+

Unless you are implementing a custom logger, there is little need to call this directly. Use either a logger's log method or one of the logging templates.

+

See also:

+ + +

Example:

+
doAssert substituteLog(defaultFmtStr, lvlInfo, "a message") == "INFO a message"
+doAssert substituteLog("$levelid - ", lvlError, "an error") == "E - an error"
+doAssert substituteLog("$levelid", lvlDebug, "error") == "Derror"
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Methods

+
+
+
+
method log(logger: ConsoleLogger; level: Level; args: varargs[string, `$`]) {.
+    ...raises: [], tags: [ReadIOEffect, TimeEffect, WriteIOEffect], forbids: [].}
+
+ +

Logs to the console with the given ConsoleLogger only.

+

This method ignores the list of registered handlers.

+

Whether the message is logged depends on both the ConsoleLogger's levelThreshold field and the global log filter set using the setLogFilter proc.

+

Note: Only error and fatal messages will cause the output buffer to be flushed immediately by default. Set flushThreshold when creating the logger to change this.

+

See also:

+ +

Examples:

+

var consoleLog = newConsoleLogger()
+consoleLog.log(lvlInfo, "this is a message")
+consoleLog.log(lvlError, "error code is: ", 404)

+ + Source   +Edit   + +
+
+
+
method log(logger: FileLogger; level: Level; args: varargs[string, `$`]) {.
+    ...raises: [IOError], tags: [WriteIOEffect, ReadIOEffect, TimeEffect],
+    forbids: [].}
+
+ +

Logs a message at the specified level using the given FileLogger only.

+

This method ignores the list of registered handlers.

+

Whether the message is logged depends on both the FileLogger's levelThreshold field and the global log filter set using the setLogFilter proc.

+

Notes:

+
  • Only error and fatal messages will cause the output buffer to be flushed immediately by default. Set flushThreshold when creating the logger to change this.
  • +
  • This method is not available for the JavaScript backend.
  • +
+

See also:

+ +

Examples:

+

var fileLog = newFileLogger("messages.log")
+fileLog.log(lvlInfo, "this is a message")
+fileLog.log(lvlError, "error code is: ", 404)

+ + Source   +Edit   + +
+
+
+
method log(logger: Logger; level: Level; args: varargs[string, `$`]) {.
+    ...raises: [Exception], gcsafe, tags: [RootEffect], base, ...forbids: [].}
+
+ +

Override this method in custom loggers. The default implementation does nothing.

+

See also:

+ + + Source   +Edit   + +
+
+
+
method log(logger: RollingFileLogger; level: Level; args: varargs[string, `$`]) {.
+    ...raises: [OSError, IOError, Exception],
+    tags: [ReadDirEffect, ReadIOEffect, WriteIOEffect, TimeEffect], forbids: [].}
+
+ +

Logs a message at the specified level using the given RollingFileLogger only.

+

This method ignores the list of registered handlers.

+

Whether the message is logged depends on both the RollingFileLogger's levelThreshold field and the global log filter set using the setLogFilter proc.

+

Notes:

+
  • Only error and fatal messages will cause the output buffer to be flushed immediately by default. Set flushThreshold when creating the logger to change this.
  • +
  • This method is not available for the JavaScript backend.
  • +
+

See also:

+ +

Examples:

+

var rollingLog = newRollingFileLogger("messages.log")
+rollingLog.log(lvlInfo, "this is a message")
+rollingLog.log(lvlError, "error code is: ", 404)

+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template debug(args: varargs[string, `$`])
+
+ +

Logs a debug message to all registered handlers.

+

Debug messages are typically useful to the application developer only, and they are usually disabled in release builds, although this template does not make that distinction.

+

Examples:

+

var logger = newConsoleLogger()
+addHandler(logger)
+
+debug("myProc called with arguments: foo, 5")

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
template error(args: varargs[string, `$`])
+
+ +

Logs an error message to all registered handlers.

+

Error messages are for application-level error conditions, such as when some user input generated an exception. Typically, the application will continue to run, but with degraded functionality or loss of data, and these effects might be visible to users.

+

Examples:

+

var logger = newConsoleLogger()
+addHandler(logger)
+
+error("An exception occurred while processing the form.")

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
template fatal(args: varargs[string, `$`])
+
+ +

Logs a fatal error message to all registered handlers.

+

Fatal error messages usually indicate that the application cannot continue to run and will exit due to a fatal condition. This template only logs the message, and it is the application's responsibility to exit properly.

+

Examples:

+

var logger = newConsoleLogger()
+addHandler(logger)
+
+fatal("Can't open database -- exiting.")

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
template info(args: varargs[string, `$`])
+
+ +

Logs an info message to all registered handlers.

+

Info messages are typically generated during the normal operation of an application and are of no particular importance. It can be useful to aggregate these messages for later analysis.

+

Examples:

+

var logger = newConsoleLogger()
+addHandler(logger)
+
+info("Application started successfully.")

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
template log(level: Level; args: varargs[string, `$`])
+
+ +

Logs a message at the specified level to all registered handlers.

+

Whether the message is logged depends on both the FileLogger's levelThreshold field and the global log filter set using the setLogFilter proc.

+

Examples:

+

var logger = newConsoleLogger()
+addHandler(logger)
+
+log(lvlInfo, "This is an example.")

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
template notice(args: varargs[string, `$`])
+
+ +

Logs an notice to all registered handlers.

+

Notices are semantically very similar to info messages, but they are meant to be messages that the user should be actively notified about, depending on the application.

+

Examples:

+

var logger = newConsoleLogger()
+addHandler(logger)
+
+notice("An important operation has completed.")

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
template warn(args: varargs[string, `$`])
+
+ +

Logs a warning message to all registered handlers.

+

A warning is a non-error message that may indicate impending problems or degraded performance.

+

Examples:

+

var logger = newConsoleLogger()
+addHandler(logger)
+
+warn("The previous operation took too long to process.")

+

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/logging.idx b/logging.idx new file mode 100644 index 0000000000000..dad419df940a0 --- /dev/null +++ b/logging.idx @@ -0,0 +1,46 @@ +nimTitle logging logging.html module std/logging 0 +nim lvlAll logging.html#lvlAll Level.lvlAll 157 +nim lvlDebug logging.html#lvlDebug Level.lvlDebug 157 +nim lvlInfo logging.html#lvlInfo Level.lvlInfo 157 +nim lvlNotice logging.html#lvlNotice Level.lvlNotice 157 +nim lvlWarn logging.html#lvlWarn Level.lvlWarn 157 +nim lvlError logging.html#lvlError Level.lvlError 157 +nim lvlFatal logging.html#lvlFatal Level.lvlFatal 157 +nim lvlNone logging.html#lvlNone Level.lvlNone 157 +nim Level logging.html#Level enum Level 157 +nim LevelNames logging.html#LevelNames const LevelNames 193 +nim defaultFmtStr logging.html#defaultFmtStr const defaultFmtStr 197 +nim verboseFmtStr logging.html#verboseFmtStr const verboseFmtStr 198 +nim Logger logging.html#Logger type Logger 218 +nim ConsoleLogger logging.html#ConsoleLogger type ConsoleLogger 234 +nim FileLogger logging.html#FileLogger type FileLogger 249 +nim RollingFileLogger logging.html#RollingFileLogger type RollingFileLogger 264 +nim substituteLog logging.html#substituteLog,string,Level,varargs[string,] proc substituteLog(frmt: string; level: Level; args: varargs[string, `$`]): string 287 +nim log logging.html#log.e,Logger,Level,varargs[string,] method log(logger: Logger; level: Level; args: varargs[string, `$`]) 342 +nim log logging.html#log.e,ConsoleLogger,Level,varargs[string,] method log(logger: ConsoleLogger; level: Level; args: varargs[string, `$`]) 358 +nim newConsoleLogger logging.html#newConsoleLogger proc newConsoleLogger(levelThreshold = lvlAll; fmtStr = defaultFmtStr;\n useStderr = false; flushThreshold = defaultFlushThreshold): ConsoleLogger 405 +nim log logging.html#log.e,FileLogger,Level,varargs[string,] method log(logger: FileLogger; level: Level; args: varargs[string, `$`]) 435 +nim defaultFilename logging.html#defaultFilename proc defaultFilename(): string 469 +nim newFileLogger logging.html#newFileLogger,File proc newFileLogger(file: File; levelThreshold = lvlAll; fmtStr = defaultFmtStr;\n flushThreshold = defaultFlushThreshold): FileLogger 476 +nim newFileLogger logging.html#newFileLogger,FileMode,int proc newFileLogger(filename = defaultFilename(); mode: FileMode = fmAppend;\n levelThreshold = lvlAll; fmtStr = defaultFmtStr;\n bufSize: int = -1; flushThreshold = defaultFlushThreshold): FileLogger 507 +nim newRollingFileLogger logging.html#newRollingFileLogger,FileMode,Positive,int proc newRollingFileLogger(filename = defaultFilename(); mode: FileMode = fmReadWrite;\n levelThreshold = lvlAll; fmtStr = defaultFmtStr;\n maxLines: Positive = 1000; bufSize: int = -1;\n flushThreshold = defaultFlushThreshold): RollingFileLogger 564 +nim log logging.html#log.e,RollingFileLogger,Level,varargs[string,] method log(logger: RollingFileLogger; level: Level; args: varargs[string, `$`]) 622 +nim log logging.html#log.t,Level,varargs[string,] template log(level: Level; args: varargs[string, `$`]) 672 +nim debug logging.html#debug.t,varargs[string,] template debug(args: varargs[string, `$`]) 702 +nim info logging.html#info.t,varargs[string,] template info(args: varargs[string, `$`]) 724 +nim notice logging.html#notice.t,varargs[string,] template notice(args: varargs[string, `$`]) 746 +nim warn logging.html#warn.t,varargs[string,] template warn(args: varargs[string, `$`]) 768 +nim error logging.html#error.t,varargs[string,] template error(args: varargs[string, `$`]) 789 +nim fatal logging.html#fatal.t,varargs[string,] template fatal(args: varargs[string, `$`]) 812 +nim addHandler logging.html#addHandler,Logger proc addHandler(handler: Logger) 834 +nim removeHandler logging.html#removeHandler,Logger proc removeHandler(handler: Logger) 850 +nim getHandlers logging.html#getHandlers proc getHandlers(): seq[Logger] 860 +nim setLogFilter logging.html#setLogFilter,Level proc setLogFilter(lvl: Level) 867 +nim getLogFilter logging.html#getLogFilter proc getLogFilter(): Level 886 +heading Basic usage logging.html#basic-usage Basic usage 0 +heading Handlers logging.html#basic-usage-handlers Handlers 0 +heading Format strings logging.html#basic-usage-format-strings Format strings 0 +heading Notes when using multiple threads logging.html#basic-usage-notes-when-using-multiple-threads Notes when using multiple threads 0 +heading See also logging.html#see-also See also 0 +nimgrp newfilelogger logging.html#newFileLogger-procs-all proc 476 +nimgrp log logging.html#log-methods-all method 342 diff --git a/logic.html b/logic.html new file mode 100644 index 0000000000000..cddff28c1849a --- /dev/null +++ b/logic.html @@ -0,0 +1,181 @@ + + + + + + + +std/logic + + + + + + + + + + + + + + + + +
+
+

std/logic

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module provides further logic operators like 'forall' and 'exists' They are only supported in .ensures etc pragmas.

+
+

Procs

+
+
+
+
proc `->`(a, b: bool): bool {.magic: "Implies", ...raises: [], tags: [],
+                              forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `<->`(a, b: bool): bool {.magic: "Iff", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc exists(args: varargs[untyped]): bool {.magic: "Exists", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc forall(args: varargs[untyped]): bool {.magic: "Forall", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc old[T](x: T): T {.magic: "Old", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/logic.idx b/logic.idx new file mode 100644 index 0000000000000..aa27c4c0d9cd9 --- /dev/null +++ b/logic.idx @@ -0,0 +1,6 @@ +nimTitle logic logic.html module std/logic 0 +nim `->` logic.html#->,bool,bool proc `->`(a, b: bool): bool 4 +nim `<->` logic.html#<->,bool,bool proc `<->`(a, b: bool): bool 5 +nim forall logic.html#forall,varargs[untyped] proc forall(args: varargs[untyped]): bool 7 +nim exists logic.html#exists,varargs[untyped] proc exists(args: varargs[untyped]): bool 8 +nim old logic.html#old,T proc old[T](x: T): T 10 diff --git a/macrocache.html b/macrocache.html new file mode 100644 index 0000000000000..40d98d6f9e759 --- /dev/null +++ b/macrocache.html @@ -0,0 +1,552 @@ + + + + + + + +std/macrocache + + + + + + + + + + + + + + + + +
+
+

std/macrocache

+
+ +
+ Source   +Edit   + +
+ +

This module provides an API for macros to collect compile-time information across module boundaries. It should be used instead of global {.compileTime.} variables as those break incremental compilation.

+

The main feature of this module is that if you create CacheTables or any other Cache types with the same name in different modules, their content will be shared, meaning that you can fill a CacheTable in one module, and iterate over its contents in another.

+ +

Example:

+
import std/macrocache
+import std/macros
+
+const mcTable = CacheTable"myTable"
+const mcSeq = CacheSeq"mySeq"
+const mcCounter = CacheCounter"myCounter"
+
+static:
+  # add new key "val" with the value `myval`
+  let myval = newLit("hello ic")
+  mcTable["val"] = myval
+  assert mcTable["val"].kind == nnkStrLit
+
+# Can access the same cache from different static contexts
+# All the information is retained
+static:
+  # get value from `mcTable` and add it to `mcSeq`
+  mcSeq.add(mcTable["val"])
+  assert mcSeq.len == 1
+
+static:
+  assert mcSeq[0].strVal == "hello ic"
+
+  # increase `mcCounter` by 3
+  mcCounter.inc(3)
+  assert mcCounter.value == 3

+
+

Types

+
+
+
CacheCounter = distinct string
+
+ + Compile-time counter, uses int for storing the count. + Source   +Edit   + +
+
+
+
CacheSeq = distinct string
+
+ + Compile-time sequence of NimNodes. + Source   +Edit   + +
+
+
+
CacheTable = distinct string
+
+ +

Compile-time table of key-value pairs.

+

Keys are strings and values are NimNodes.

+ + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `[]`(s: CacheSeq; i: BackwardsIndex): NimNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Returns the ith last value from s. +

Example:

+
import std/macros
+
+const mySeq = CacheSeq"backTest"
+static:
+  mySeq &= newLit(42)
+  mySeq &= newLit(7)
+  assert mySeq[^1].intVal == 7  # Last item
+  assert mySeq[^2].intVal == 42 # Second last item
+ Source   +Edit   + +
+
+
+
proc `[]`(s: CacheSeq; i: int): NimNode {.magic: "NcsAt", ...raises: [], tags: [],
+    forbids: [].}
+
+ + Returns the ith value from s. +

Example:

+
import std/macros
+
+const mySeq = CacheSeq"subTest"
+static:
+  mySeq.add(newLit(42))
+  assert mySeq[0].intVal == 42
+ Source   +Edit   + +
+
+
+
proc `[]`(t: CacheTable; key: string): NimNode {.magic: "NctGet", ...raises: [],
+    tags: [], forbids: [].}
+
+ + Retrieves the NimNode value at t[key]. +

Example:

+
import std/macros
+
+const mcTable = CacheTable"subTest"
+static:
+  mcTable["toAdd"] = newStmtList()
+
+  # get the NimNode back
+  assert mcTable["toAdd"].kind == nnkStmtList
+ Source   +Edit   + +
+
+ +
+
+
+
proc `[]=`(t: CacheTable; key: string; value: NimNode) {.magic: "NctPut",
+    ...raises: [], tags: [], forbids: [].}
+
+ + Inserts a (key, value) pair into t.
Warning: +key has to be unique! Assigning value to a key that is already in the table will result in a compiler error.
+ +

Example:

+
import std/macros
+
+const mcTable = CacheTable"subTest"
+static:
+  # assign newLit(5) to the key "value"
+  mcTable["value"] = newLit(5)
+
+  # check that we can get the value back
+  assert mcTable["value"].kind == nnkIntLit
+ Source   +Edit   + +
+
+ +
+
+
+
proc add(s: CacheSeq; value: NimNode) {.magic: "NcsAdd", ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + Adds value to s. +

Example:

+
import std/macros
+const mySeq = CacheSeq"addTest"
+
+static:
+  mySeq.add(newLit(5))
+  mySeq.add(newLit("hello ic"))
+
+  assert mySeq.len == 2
+  assert mySeq[1].strVal == "hello ic"
+ Source   +Edit   + +
+
+ +
+
+
+
proc contains(t: CacheTable; key: string): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Alias of hasKey for use with the in operator. +

Example:

+
import std/macros
+const mcTable = CacheTable"containsEx"
+static:
+  mcTable["foo"] = newEmptyNode()
+  # Will be true since we gave it a value before
+  assert "foo" in mcTable
+ Source   +Edit   + +
+
+ +
+
+
+
proc hasKey(t: CacheTable; key: string): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Returns true if key is in the table t.

+

See also:

+ + +

Example:

+
import std/macros
+const mcTable = CacheTable"hasKeyEx"
+static:
+  assert not mcTable.hasKey("foo")
+  mcTable["foo"] = newEmptyNode()
+  # Will now be true since we inserted a value
+  assert mcTable.hasKey("foo")
+ Source   +Edit   + +
+
+ +
+
+
+
proc inc(c: CacheCounter; by = 1) {.magic: "NccInc", ...raises: [], tags: [],
+                                    forbids: [].}
+
+ + Increments the counter c with the value by. +

Example:

+
static:
+  let counter = CacheCounter"incTest"
+  inc counter
+  inc counter, 5
+
+  assert counter.value == 6
+ Source   +Edit   + +
+
+ +
+
+
+
proc incl(s: CacheSeq; value: NimNode) {.magic: "NcsIncl", ...raises: [], tags: [],
+    forbids: [].}
+
+ + Adds value to s.
Hint: +This doesn't do anything if value is already in s.
+ +

Example:

+
import std/macros
+const mySeq = CacheSeq"inclTest"
+
+static:
+  mySeq.incl(newLit(5))
+  mySeq.incl(newLit(5))
+
+  # still one element
+  assert mySeq.len == 1
+ Source   +Edit   + +
+
+ +
+
+
+
proc len(s: CacheSeq): int {.magic: "NcsLen", ...raises: [], tags: [], forbids: [].}
+
+ + Returns the length of s. +

Example:

+
import std/macros
+
+const mySeq = CacheSeq"lenTest"
+static:
+  let val = newLit("helper")
+  mySeq.add(val)
+  assert mySeq.len == 1
+
+  mySeq.add(val)
+  assert mySeq.len == 2
+ Source   +Edit   + +
+
+
+
proc len(t: CacheTable): int {.magic: "NctLen", ...raises: [], tags: [],
+                               forbids: [].}
+
+ + Returns the number of elements in t. +

Example:

+
import std/macros
+
+const dataTable = CacheTable"lenTest"
+static:
+  dataTable["key"] = newLit(5)
+  assert dataTable.len == 1
+ Source   +Edit   + +
+
+ +
+
+
+
proc value(c: CacheCounter): int {.magic: "NccValue", ...raises: [], tags: [],
+                                   forbids: [].}
+
+ + Returns the value of a counter c. +

Example:

+
static:
+  let counter = CacheCounter"valTest"
+  # default value is 0
+  assert counter.value == 0
+
+  inc counter
+  assert counter.value == 1
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator items(s: CacheSeq): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Iterates over each item in s. +

Example:

+
import std/macros
+const myseq = CacheSeq"itemsTest"
+
+static:
+  myseq.add(newLit(5))
+  myseq.add(newLit(42))
+
+  for val in myseq:
+    # check that all values in `myseq` are int literals
+    assert val.kind == nnkIntLit
+ Source   +Edit   + +
+
+ +
+
+
+
iterator pairs(t: CacheTable): (string, NimNode) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Iterates over all (key, value) pairs in t. +

Example:

+
import std/macros
+const mytabl = CacheTable"values"
+
+static:
+  mytabl["intVal"] = newLit(5)
+  mytabl["otherVal"] = newLit(6)
+  for key, val in mytabl:
+    # make sure that we actually get the same keys
+    assert key in ["intVal", "otherVal"]
+
+    # all vals are int literals
+    assert val.kind == nnkIntLit
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/macrocache.idx b/macrocache.idx new file mode 100644 index 0000000000000..90897d88f191f --- /dev/null +++ b/macrocache.idx @@ -0,0 +1,20 @@ +nimTitle macrocache macrocache.html module std/macrocache 0 +nim CacheSeq macrocache.html#CacheSeq type CacheSeq 48 +nim CacheTable macrocache.html#CacheTable type CacheTable 50 +nim CacheCounter macrocache.html#CacheCounter type CacheCounter 54 +nim value macrocache.html#value,CacheCounter proc value(c: CacheCounter): int 57 +nim inc macrocache.html#inc,CacheCounter,int proc inc(c: CacheCounter; by = 1) 68 +nim add macrocache.html#add,CacheSeq,NimNode proc add(s: CacheSeq; value: NimNode) 78 +nim incl macrocache.html#incl,CacheSeq,NimNode proc incl(s: CacheSeq; value: NimNode) 91 +nim len macrocache.html#len,CacheSeq proc len(s: CacheSeq): int 106 +nim `[]` macrocache.html#[],CacheSeq,int proc `[]`(s: CacheSeq; i: int): NimNode 120 +nim `[]` macrocache.html#[],CacheSeq,BackwardsIndex proc `[]`(s: CacheSeq; i: BackwardsIndex): NimNode 130 +nim items macrocache.html#items.i,CacheSeq iterator items(s: CacheSeq): NimNode 143 +nim `[]=` macrocache.html#[]=,CacheTable,string,NimNode proc `[]=`(t: CacheTable; key: string; value: NimNode) 159 +nim len macrocache.html#len,CacheTable proc len(t: CacheTable): int 175 +nim `[]` macrocache.html#[],CacheTable,string proc `[]`(t: CacheTable; key: string): NimNode 185 +nim hasKey macrocache.html#hasKey,CacheTable,string proc hasKey(t: CacheTable; key: string): bool 197 +nim contains macrocache.html#contains,CacheTable,string proc contains(t: CacheTable; key: string): bool 212 +nim pairs macrocache.html#pairs.i,CacheTable iterator pairs(t: CacheTable): (string, NimNode) 226 +nimgrp [] macrocache.html#[]-procs-all proc 120 +nimgrp len macrocache.html#len-procs-all proc 106 diff --git a/macros.html b/macros.html new file mode 100644 index 0000000000000..87f856a0bf4f7 --- /dev/null +++ b/macros.html @@ -0,0 +1,4449 @@ + + + + + + + +std/macros + + + + + + + + + + + + + + + + +
+
+

std/macros

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module contains the interface to the compiler's abstract syntax tree (AST). Macros operate on this tree.

+

See also:

+ + +

The AST in Nim

This section describes how the AST is modelled with Nim's type system. The AST consists of nodes (NimNode) with a variable number of children. Each node has a field named kind which describes what the node contains:

+

type
+  NimNodeKind = enum     ## kind of a node; only explanatory
+    nnkNone,             ## invalid node kind
+    nnkEmpty,            ## empty node
+    nnkIdent,            ## node contains an identifier
+    nnkIntLit,           ## node contains an int literal (example: 10)
+    nnkStrLit,           ## node contains a string literal (example: "abc")
+    nnkNilLit,           ## node contains a nil literal (example: nil)
+    nnkCaseStmt,         ## node represents a case statement
+    ...                  ## many more
+  
+  NimNode = ref NimNodeObj
+  NimNodeObj = object
+    case kind: NimNodeKind           ## the node's kind
+    of nnkNone, nnkEmpty, nnkNilLit:
+      discard                        ## node contains no additional fields
+    of nnkCharLit..nnkUInt64Lit:
+      intVal: BiggestInt             ## the int literal
+    of nnkFloatLit..nnkFloat64Lit:
+      floatVal: BiggestFloat         ## the float literal
+    of nnkStrLit..nnkTripleStrLit, nnkCommentStmt, nnkIdent, nnkSym:
+      strVal: string                 ## the string literal
+    else:
+      sons: seq[NimNode]             ## the node's sons (or children)

+

For the NimNode type, the [] operator has been overloaded: n[i] is n's i-th child.

+

To specify the AST for the different Nim constructs, the notation nodekind(son1, son2, ...) or nodekind(value) or nodekind(field=value) is used.

+

Some child may be missing. A missing child is a node of kind nnkEmpty; a child can never be nil.

+ +

Leaf nodes/Atoms

A leaf of the AST often corresponds to a terminal symbol in the concrete syntax. Note that the default float in Nim maps to float64 such that the default AST for a float is nnkFloat64Lit as below.

+ + + + + + + + + + + + + + + + + + + + +
Nim expressionCorresponding AST
42nnkIntLit(intVal = 42)
42'i8nnkInt8Lit(intVal = 42)
42'i16nnkInt16Lit(intVal = 42)
42'i32nnkInt32Lit(intVal = 42)
42'i64nnkInt64Lit(intVal = 42)
42'u8nnkUInt8Lit(intVal = 42)
42'u16nnkUInt16Lit(intVal = 42)
42'u32nnkUInt32Lit(intVal = 42)
42'u64nnkUInt64Lit(intVal = 42)
42.0nnkFloat64Lit(floatVal = 42.0)
42.0'f32nnkFloat32Lit(floatVal = 42.0)
42.0'f64nnkFloat64Lit(floatVal = 42.0)
"abc"nnkStrLit(strVal = "abc")
r"abc"nnkRStrLit(strVal = "abc")
"""abc"""nnkTripleStrLit(strVal = "abc")
' 'nnkCharLit(intVal = 32)
nilnnkNilLit()
myIdentifiernnkIdent(strVal = "myIdentifier")
myIdentifierafter lookup pass: nnkSym(strVal = "myIdentifier", ...)

Identifiers are nnkIdent nodes. After the name lookup pass these nodes get transferred into nnkSym nodes.

+ +

Calls/expressions

+

Command call

Concrete syntax:

+

echo "abc", "xyz"

+

AST:

+

nnkCommand(
+  nnkIdent("echo"),
+  nnkStrLit("abc"),
+  nnkStrLit("xyz")
+)

+ +

Call with ()

Concrete syntax:

+

echo("abc", "xyz")

+

AST:

+

nnkCall(
+  nnkIdent("echo"),
+  nnkStrLit("abc"),
+  nnkStrLit("xyz")
+)

+ +

Infix operator call

Concrete syntax:

+

"abc" & "xyz"

+

AST:

+

nnkInfix(
+  nnkIdent("&"),
+  nnkStrLit("abc"),
+  nnkStrLit("xyz")
+)

+

Note that with multiple infix operators, the command is parsed by operator precedence.

+

Concrete syntax:

+

5 + 3 * 4

+

AST:

+

nnkInfix(
+  nnkIdent("+"),
+  nnkIntLit(5),
+  nnkInfix(
+    nnkIdent("*"),
+    nnkIntLit(3),
+    nnkIntLit(4)
+  )
+)

+

As a side note, if you choose to use infix operators in a prefix form, the AST behaves as a parenthetical function call with nnkAccQuoted, as follows:

+

Concrete syntax:

+

`+`(3, 4)

+

AST:

+

nnkCall(
+  nnkAccQuoted(
+    nnkIdent("+")
+  ),
+  nnkIntLit(3),
+  nnkIntLit(4)
+)

+ +

Prefix operator call

Concrete syntax:

+

? "xyz"

+

AST:

+

nnkPrefix(
+  nnkIdent("?"),
+  nnkStrLit("abc")
+)

+ +

Postfix operator call

Note: There are no postfix operators in Nim. However, the nnkPostfix node is used for the asterisk export marker *:

+

Concrete syntax:

+

identifier*

+

AST:

+

nnkPostfix(
+  nnkIdent("*"),
+  nnkIdent("identifier")
+)

+ +

Call with named arguments

Concrete syntax:

+

writeLine(file=stdout, "hallo")

+

AST:

+

nnkCall(
+  nnkIdent("writeLine"),
+  nnkExprEqExpr(
+    nnkIdent("file"),
+    nnkIdent("stdout")
+  ),
+  nnkStrLit("hallo")
+)

+ +

Call with raw string literal

This is used, for example, in the bindSym examples here and with re"some regexp" in the regular expression module.

+

Concrete syntax:

+

echo"abc"

+

AST:

+

nnkCallStrLit(
+  nnkIdent("echo"),
+  nnkRStrLit("hello")
+)

+ +

Dereference operator []

Concrete syntax:

+

x[]

+

AST:

+

nnkDerefExpr(nnkIdent("x"))

+ +

Addr operator

Concrete syntax:

+

addr(x)

+

AST:

+

nnkAddr(nnkIdent("x"))

+ +

Cast operator

Concrete syntax:

+

cast[T](x)

+

AST:

+

nnkCast(nnkIdent("T"), nnkIdent("x"))

+ +

Object access operator .

Concrete syntax:

+

x.y

+

AST:

+

nnkDotExpr(nnkIdent("x"), nnkIdent("y"))

+

If you use Nim's flexible calling syntax (as in x.len()), the result is the same as above but wrapped in an nnkCall.

+ +

Array access operator []

Concrete syntax:

+

x[y]

+

AST:

+

nnkBracketExpr(nnkIdent("x"), nnkIdent("y"))

+ +

Parentheses

Parentheses for affecting operator precedence use the nnkPar node.

+

Concrete syntax:

+

(a + b) * c

+

AST:

+

nnkInfix(nnkIdent("*"),
+  nnkPar(
+    nnkInfix(nnkIdent("+"), nnkIdent("a"), nnkIdent("b"))),
+  nnkIdent("c"))

+ +

Tuple Constructors

Nodes for tuple construction are built with the nnkTupleConstr node.

+

Concrete syntax:

+

(1, 2, 3)
+(a: 1, b: 2, c: 3)
+()

+

AST:

+

nnkTupleConstr(nnkIntLit(1), nnkIntLit(2), nnkIntLit(3))
+nnkTupleConstr(
+  nnkExprColonExpr(nnkIdent("a"), nnkIntLit(1)),
+  nnkExprColonExpr(nnkIdent("b"), nnkIntLit(2)),
+  nnkExprColonExpr(nnkIdent("c"), nnkIntLit(3)))
+nnkTupleConstr()

+

Since the one tuple would be syntactically identical to parentheses with an expression in them, the parser expects a trailing comma for them. For tuple constructors with field names, this is not necessary.

+

(1,)
+(a: 1)

+

AST:

+

nnkTupleConstr(nnkIntLit(1))
+nnkTupleConstr(
+  nnkExprColonExpr(nnkIdent("a"), nnkIntLit(1)))

+ +

Curly braces

Curly braces are used as the set constructor.

+

Concrete syntax:

+

{1, 2, 3}

+

AST:

+

nnkCurly(nnkIntLit(1), nnkIntLit(2), nnkIntLit(3))

+

When used as a table constructor, the syntax is different.

+

Concrete syntax:

+

{a: 3, b: 5}

+

AST:

+

nnkTableConstr(
+  nnkExprColonExpr(nnkIdent("a"), nnkIntLit(3)),
+  nnkExprColonExpr(nnkIdent("b"), nnkIntLit(5))
+)

+ +

Brackets

Brackets are used as the array constructor.

+

Concrete syntax:

+

[1, 2, 3]

+

AST:

+

nnkBracket(nnkIntLit(1), nnkIntLit(2), nnkIntLit(3))

+ +

Ranges

Ranges occur in set constructors, case statement branches, or array slices. Internally, the node kind nnkRange is used, but when constructing the AST, construction with .. as an infix operator should be used instead.

+

Concrete syntax:

+

1..3

+

AST:

+

nnkInfix(
+  nnkIdent(".."),
+  nnkIntLit(1),
+  nnkIntLit(3)
+)

+

Example code:

+

macro genRepeatEcho() =
+  result = newNimNode(nnkStmtList)
+  
+  var forStmt = newNimNode(nnkForStmt) # generate a for statement
+  forStmt.add(ident("i")) # use the variable `i` for iteration
+  
+  var rangeDef = newNimNode(nnkInfix).add(
+    ident("..")).add(
+    newIntLitNode(3),newIntLitNode(5)) # iterate over the range 3..5
+  
+  forStmt.add(rangeDef)
+  forStmt.add(newCall(ident("echo"), newIntLitNode(3))) # meat of the loop
+  result.add(forStmt)
+
+genRepeatEcho() # gives:
+                # 3
+                # 3
+                # 3

+ +

If expression

The representation of the if expression is subtle, but easy to traverse.

+

Concrete syntax:

+

if cond1: expr1 elif cond2: expr2 else: expr3

+

AST:

+

nnkIfExpr(
+  nnkElifExpr(cond1, expr1),
+  nnkElifExpr(cond2, expr2),
+  nnkElseExpr(expr3)
+)

+ +

Documentation Comments

Double-hash (##) comments in the code actually have their own format, using strVal to get and set the comment text. Single-hash (#) comments are ignored.

+

Concrete syntax:

+

## This is a comment
+## This is part of the first comment
+stmt1
+## Yet another

+

AST:

+

nnkCommentStmt() # only appears once for the first two lines!
+stmt1
+nnkCommentStmt() # another nnkCommentStmt because there is another comment
+                 # (separate from the first)

+ +

Pragmas

One of Nim's cool features is pragmas, which allow fine-tuning of various aspects of the language. They come in all types, such as adorning procs and objects, but the standalone emit pragma shows the basics with the AST.

+

Concrete syntax:

+

{.emit: "#include <stdio.h>".}

+

AST:

+

nnkPragma(
+  nnkExprColonExpr(
+    nnkIdent("emit"),
+    nnkStrLit("#include <stdio.h>") # the "argument"
+  )
+)

+

As many nnkIdent appear as there are pragmas between {..}. Note that the declaration of new pragmas is essentially the same:

+

Concrete syntax:

+

{.pragma: cdeclRename, cdecl.}

+

AST:

+

nnkPragma(
+  nnkExprColonExpr(
+    nnkIdent("pragma"), # this is always first when declaring a new pragma
+    nnkIdent("cdeclRename") # the name of the pragma
+  ),
+  nnkIdent("cdecl")
+)

+ +

Statements

+

If statement

The representation of the if statement is subtle, but easy to traverse. If there is no else branch, no nnkElse child exists.

+

Concrete syntax:

+

if cond1:
+  stmt1
+elif cond2:
+  stmt2
+elif cond3:
+  stmt3
+else:
+  stmt4

+

AST:

+

nnkIfStmt(
+  nnkElifBranch(cond1, stmt1),
+  nnkElifBranch(cond2, stmt2),
+  nnkElifBranch(cond3, stmt3),
+  nnkElse(stmt4)
+)

+ +

When statement

Like the if statement, but the root has the kind nnkWhenStmt.

+ +

Assignment

Concrete syntax:

+

x = 42

+

AST:

+

nnkAsgn(nnkIdent("x"), nnkIntLit(42))

+

This is not the syntax for assignment when combined with var, let, or const.

+ +

Statement list

Concrete syntax:

+

stmt1
+stmt2
+stmt3

+

AST:

+

nnkStmtList(stmt1, stmt2, stmt3)

+ +

Case statement

Concrete syntax:

+

case expr1
+of expr2, expr3..expr4:
+  stmt1
+of expr5:
+  stmt2
+elif cond1:
+  stmt3
+else:
+  stmt4

+

AST:

+

nnkCaseStmt(
+  expr1,
+  nnkOfBranch(expr2, nnkRange(expr3, expr4), stmt1),
+  nnkOfBranch(expr5, stmt2),
+  nnkElifBranch(cond1, stmt3),
+  nnkElse(stmt4)
+)

+

The nnkElifBranch and nnkElse parts may be missing.

+ +

While statement

Concrete syntax:

+

while expr1:
+  stmt1

+

AST:

+

nnkWhileStmt(expr1, stmt1)

+ +

For statement

Concrete syntax:

+

for ident1, ident2 in expr1:
+  stmt1

+

AST:

+

nnkForStmt(ident1, ident2, expr1, stmt1)

+ +

Try statement

Concrete syntax:

+

try:
+  stmt1
+except e1, e2:
+  stmt2
+except e3:
+  stmt3
+except:
+  stmt4
+finally:
+  stmt5

+

AST:

+

nnkTryStmt(
+  stmt1,
+  nnkExceptBranch(e1, e2, stmt2),
+  nnkExceptBranch(e3, stmt3),
+  nnkExceptBranch(stmt4),
+  nnkFinally(stmt5)
+)

+ +

Return statement

Concrete syntax:

+

return expr1

+

AST:

+

nnkReturnStmt(expr1)

+ +

Yield statement

Like return, but with nnkYieldStmt kind.

+

nnkYieldStmt(expr1)

+ +

Discard statement

Like return, but with nnkDiscardStmt kind.

+

nnkDiscardStmt(expr1)

+ +

Continue statement

Concrete syntax:

+

continue

+

AST:

+

nnkContinueStmt()

+ +

Break statement

Concrete syntax:

+

break otherLocation

+

AST:

+

nnkBreakStmt(nnkIdent("otherLocation"))

+

If break is used without a jump-to location, nnkEmpty replaces nnkIdent.

+ +

Block statement

Concrete syntax:

+

block name:

+

AST:

+

nnkBlockStmt(nnkIdent("name"), nnkStmtList(...))

+

A block doesn't need an name, in which case nnkEmpty is used.

+ +

Asm statement

Concrete syntax:

+

asm """
+  some asm
+"""

+

AST:

+

nnkAsmStmt(
+  nnkEmpty(), # for pragmas
+  nnkTripleStrLit("some asm"),
+)

+ +

Import section

Nim's import statement actually takes different variations depending on what keywords are present. Let's start with the simplest form.

+

Concrete syntax:

+

import std/math

+

AST:

+

nnkImportStmt(nnkIdent("math"))

+

With except, we get nnkImportExceptStmt.

+

Concrete syntax:

+

import std/math except pow

+

AST:

+

nnkImportExceptStmt(nnkIdent("math"),nnkIdent("pow"))

+

Note that import std/math as m does not use a different node; rather, we use nnkImportStmt with as as an infix operator.

+

Concrete syntax:

+

import std/strutils as su

+

AST:

+

nnkImportStmt(
+  nnkInfix(
+    nnkIdent("as"),
+    nnkIdent("strutils"),
+    nnkIdent("su")
+  )
+)

+ +

From statement

If we use from ... import, the result is different, too.

+

Concrete syntax:

+

from std/math import pow

+

AST:

+

nnkFromStmt(nnkIdent("math"), nnkIdent("pow"))

+

Using from std/math as m import pow works identically to the as modifier with the import statement, but wrapped in nnkFromStmt.

+ +

Export statement

When you are making an imported module accessible by modules that import yours, the export syntax is pretty straightforward.

+

Concrete syntax:

+

export unsigned

+

AST:

+

nnkExportStmt(nnkIdent("unsigned"))

+

Similar to the import statement, the AST is different for export ... except.

+

Concrete syntax:

+

export math except pow # we're going to implement our own exponentiation

+

AST:

+

nnkExportExceptStmt(nnkIdent("math"),nnkIdent("pow"))

+ +

Include statement

Like a plain import statement but with nnkIncludeStmt.

+

Concrete syntax:

+

include blocks

+

AST:

+

nnkIncludeStmt(nnkIdent("blocks"))

+ +

Var section

Concrete syntax:

+

var a = 3

+

AST:

+

nnkVarSection(
+  nnkIdentDefs(
+    nnkIdent("a"),
+    nnkEmpty(), # or nnkIdent(...) if the variable declares the type
+    nnkIntLit(3),
+  )
+)

+

Note that either the second or third (or both) parameters above must exist, as the compiler needs to know the type somehow (which it can infer from the given assignment).

+

This is not the same AST for all uses of var. See Procedure declaration for details.

+ +

Let section

This is equivalent to var, but with nnkLetSection rather than nnkVarSection.

+

Concrete syntax:

+

let a = 3

+

AST:

+

nnkLetSection(
+  nnkIdentDefs(
+    nnkIdent("a"),
+    nnkEmpty(), # or nnkIdent(...) for the type
+    nnkIntLit(3),
+  )
+)

+ +

Const section

Concrete syntax:

+

const a = 3

+

AST:

+

nnkConstSection(
+  nnkConstDef( # not nnkConstDefs!
+    nnkIdent("a"),
+    nnkEmpty(), # or nnkIdent(...) if the variable declares the type
+    nnkIntLit(3), # required in a const declaration!
+  )
+)

+ +

Type section

Starting with the simplest case, a type section appears much like var and const.

+

Concrete syntax:

+

type A = int

+

AST:

+

nnkTypeSection(
+  nnkTypeDef(
+    nnkIdent("A"),
+    nnkEmpty(),
+    nnkIdent("int")
+  )
+)

+

Declaring distinct types is similar, with the last nnkIdent wrapped in nnkDistinctTy.

+

Concrete syntax:

+

type MyInt = distinct int

+

AST:

+

# ...
+nnkTypeDef(
+  nnkIdent("MyInt"),
+  nnkEmpty(),
+  nnkDistinctTy(
+    nnkIdent("int")
+  )
+)

+

If a type section uses generic parameters, they are treated here:

+

Concrete syntax:

+

type A[T] = expr1

+

AST:

+

nnkTypeSection(
+  nnkTypeDef(
+    nnkIdent("A"),
+    nnkGenericParams(
+      nnkIdentDefs(
+        nnkIdent("T"),
+        nnkEmpty(), # if the type is declared with options, like
+                    # ``[T: SomeInteger]``, they are given here
+        nnkEmpty(),
+      )
+    )
+    expr1,
+  )
+)

+

Note that not all nnkTypeDef utilize nnkIdent as their parameter. One of the most common uses of type declarations is to work with objects.

+

Concrete syntax:

+

type IO = object of RootObj

+

AST:

+

# ...
+nnkTypeDef(
+  nnkIdent("IO"),
+  nnkEmpty(),
+  nnkObjectTy(
+    nnkEmpty(), # no pragmas here
+    nnkOfInherit(
+      nnkIdent("RootObj") # inherits from RootObj
+    ),
+    nnkEmpty()
+  )
+)

+

Nim's object syntax is rich. Let's take a look at an involved example in its entirety to see some of the complexities.

+

Concrete syntax:

+

type Obj[T] {.inheritable.} = object
+  name: string
+  case isFat: bool
+  of true:
+    m: array[100_000, T]
+  of false:
+    m: array[10, T]

+

AST:

+

# ...
+nnkPragmaExpr(
+  nnkIdent("Obj"),
+  nnkPragma(nnkIdent("inheritable"))
+),
+nnkGenericParams(
+nnkIdentDefs(
+  nnkIdent("T"),
+  nnkEmpty(),
+  nnkEmpty())
+),
+nnkObjectTy(
+  nnkEmpty(),
+  nnkEmpty(),
+  nnkRecList( # list of object parameters
+    nnkIdentDefs(
+      nnkIdent("name"),
+      nnkIdent("string"),
+      nnkEmpty()
+    ),
+    nnkRecCase( # case statement within object (not nnkCaseStmt)
+      nnkIdentDefs(
+        nnkIdent("isFat"),
+        nnkIdent("bool"),
+        nnkEmpty()
+      ),
+      nnkOfBranch(
+        nnkIdent("true"),
+        nnkRecList( # again, a list of object parameters
+          nnkIdentDefs(
+            nnkIdent("m"),
+            nnkBracketExpr(
+              nnkIdent("array"),
+              nnkIntLit(100000),
+              nnkIdent("T")
+            ),
+            nnkEmpty()
+        )
+      ),
+      nnkOfBranch(
+        nnkIdent("false"),
+        nnkRecList(
+          nnkIdentDefs(
+            nnkIdent("m"),
+            nnkBracketExpr(
+              nnkIdent("array"),
+              nnkIntLit(10),
+              nnkIdent("T")
+            ),
+            nnkEmpty()
+          )
+        )
+      )
+    )
+  )
+)

+

Using an enum is similar to using an object.

+

Concrete syntax:

+

type X = enum
+  First

+

AST:

+

# ...
+nnkEnumTy(
+  nnkEmpty(),
+  nnkIdent("First") # you need at least one nnkIdent or the compiler complains
+)

+

The usage of concept (experimental) is similar to objects.

+

Concrete syntax:

+

type Con = concept x,y,z
+  (x & y & z) is string

+

AST:

+

# ...
+nnkTypeClassTy( # note this isn't nnkConceptTy!
+  nnkArgList(
+    # ... idents for x, y, z
+  )
+  # ...
+)

+

Static types, like static[int], use nnkIdent wrapped in nnkStaticTy.

+

Concrete syntax:

+

type A[T: static[int]] = object

+

AST:

+

# ... within nnkGenericParams
+nnkIdentDefs(
+  nnkIdent("T"),
+  nnkStaticTy(
+    nnkIdent("int")
+  ),
+  nnkEmpty()
+)
+# ...

+

In general, declaring types mirrors this syntax (i.e., nnkStaticTy for static, etc.). Examples follow (exceptions marked by *):

+ + + + + + + + + + + + + +
Nim typeCorresponding AST
staticnnkStaticTy
tuplennkTupleTy
varnnkVarTy
ptrnnkPtrTy
refnnkRefTy
distinctnnkDistinctTy
enumnnkEnumTy
conceptnnkTypeClassTy*
arraynnkBracketExpr(nnkIdent("array"),...*
procnnkProcTy
iteratornnkIteratorTy
objectnnkObjectTy

Take special care when declaring types as proc. The behavior is similar to Procedure declaration, below, but does not treat nnkGenericParams. Generic parameters are treated in the type, not the proc itself.

+

Concrete syntax:

+

type MyProc[T] = proc(x: T) {.nimcall.}

+

AST:

+

# ...
+nnkTypeDef(
+  nnkIdent("MyProc"),
+  nnkGenericParams( # here, not with the proc
+    # ...
+  )
+  nnkProcTy( # behaves like a procedure declaration from here on
+    nnkFormalParams(
+      # ...
+    ),
+    nnkPragma(nnkIdent("nimcall"))
+  )
+)

+

The same syntax applies to iterator (with nnkIteratorTy), but does not apply to converter or template.

+

Type class versions of these nodes generally share the same node kind but without any child nodes. The tuple type class is represented by nnkTupleClassTy, while a proc or iterator type class with pragmas has an nnkEmpty node in place of the nnkFormalParams node of a concrete proc or iterator type node.

+

type TypeClass = proc {.nimcall.} | ref | tuple

+

AST:

+

nnkTypeDef(
+  nnkIdent("TypeClass"),
+  nnkEmpty(),
+  nnkInfix(
+    nnkIdent("|"),
+    nnkProcTy(
+      nnkEmpty(),
+      nnkPragma(nnkIdent("nimcall"))
+    ),
+    nnkInfix(
+      nnkIdent("|"),
+      nnkRefTy(),
+      nnkTupleClassTy()
+    )
+  )
+)

+ +

Mixin statement

Concrete syntax:

+

mixin x

+

AST:

+

nnkMixinStmt(nnkIdent("x"))

+ +

Bind statement

Concrete syntax:

+

bind x

+

AST:

+

nnkBindStmt(nnkIdent("x"))

+ +

Procedure declaration

Let's take a look at a procedure with a lot of interesting aspects to get a feel for how procedure calls are broken down.

+

Concrete syntax:

+

proc hello*[T: SomeInteger](x: int = 3, y: float32): int {.inline.} = discard

+

AST:

+

nnkProcDef(
+  nnkPostfix(nnkIdent("*"), nnkIdent("hello")), # the exported proc name
+  nnkEmpty(), # patterns for term rewriting in templates and macros (not procs)
+  nnkGenericParams( # generic type parameters, like with type declaration
+    nnkIdentDefs(
+      nnkIdent("T"),
+      nnkIdent("SomeInteger"),
+      nnkEmpty()
+    )
+  ),
+  nnkFormalParams(
+    nnkIdent("int"), # the first FormalParam is the return type. nnkEmpty() if there is none
+    nnkIdentDefs(
+      nnkIdent("x"),
+      nnkIdent("int"), # type type (required for procs, not for templates)
+      nnkIntLit(3) # a default value
+    ),
+    nnkIdentDefs(
+      nnkIdent("y"),
+      nnkIdent("float32"),
+      nnkEmpty()
+    )
+  ),
+  nnkPragma(nnkIdent("inline")),
+  nnkEmpty(), # reserved slot for future use
+  nnkStmtList(nnkDiscardStmt(nnkEmpty())) # the meat of the proc
+)

+

There is another consideration. Nim has flexible type identification for its procs. Even though proc(a: int, b: int) and proc(a, b: int) are equivalent in the code, the AST is a little different for the latter.

+

Concrete syntax:

+

proc(a, b: int)

+

AST:

+

# ...AST as above...
+nnkFormalParams(
+  nnkEmpty(), # no return here
+  nnkIdentDefs(
+    nnkIdent("a"), # the first parameter
+    nnkIdent("b"), # directly to the second parameter
+    nnkIdent("int"), # their shared type identifier
+    nnkEmpty(), # default value would go here
+  )
+),
+# ...

+

When a procedure uses the special var type return variable, the result is different from that of a var section.

+

Concrete syntax:

+

proc hello(): var int

+

AST:

+

# ...
+nnkFormalParams(
+  nnkVarTy(
+    nnkIdent("int")
+  )
+)

+ +

Iterator declaration

The syntax for iterators is similar to procs, but with nnkIteratorDef replacing nnkProcDef.

+

Concrete syntax:

+

iterator nonsense[T](x: seq[T]): float {.closure.} = ...

+

AST:

+

nnkIteratorDef(
+  nnkIdent("nonsense"),
+  nnkEmpty(),
+  ...
+)

+ +

Converter declaration

A converter is similar to a proc.

+

Concrete syntax:

+

converter toBool(x: float): bool

+

AST:

+

nnkConverterDef(
+  nnkIdent("toBool"),
+  # ...
+)

+ +

Template declaration

Templates (as well as macros, as we'll see) have a slightly expanded AST when compared to procs and iterators. The reason for this is term-rewriting macros. Notice the nnkEmpty() as the second argument to nnkProcDef and nnkIteratorDef above? That's where the term-rewriting macros go.

+

Concrete syntax:

+

template optOpt{expr1}(a: int): int

+

AST:

+

nnkTemplateDef(
+  nnkIdent("optOpt"),
+  nnkStmtList( # instead of nnkEmpty()
+    expr1
+  ),
+  # follows like a proc or iterator
+)

+

If the template does not have types for its parameters, the type identifiers inside nnkFormalParams just becomes nnkEmpty.

+ +

Macro declaration

Macros behave like templates, but nnkTemplateDef is replaced with nnkMacroDef.

+ +

Hidden Standard Conversion

var f: float = 1

+

The type of "f" is float but the type of "1" is actually int. Inserting int into a float is a type error. Nim inserts the nnkHiddenStdConv node around the nnkIntLit node so that the new node has the correct type of float. This works for any auto converted nodes and makes the conversion explicit.

+ +

Special node kinds

There are several node kinds that are used for semantic checking or code generation. These are accessible from this module, but should not be used. Other node kinds are especially designed to make AST manipulations easier. These are explained here.

+

To be written.

+

+ +
+

Types

+
+
+
BindSymRule = enum
+  brClosed,                 ## only the symbols in current scope are bound
+  brOpen,                   ## open for overloaded symbols, but may be a single
+                             ## symbol if not ambiguous (the rules match that of
+                             ## binding in generics)
+  brForceOpen                ## same as brOpen, but it will always be open even
+                             ## if not ambiguous (this cannot be achieved with
+                             ## any other means in the language currently)
+
+ + Specifies how bindSym behaves. The difference between open and closed symbols can be found in manual.html#symbol-lookup-in-generics-open-and-closed-symbols + Source   +Edit   + +
+
+
+
LineInfo = object
+  filename*: string
+  line*, column*: int
+
+ + + Source   +Edit   + +
+
+
+
NimIdent {....deprecated.} = object of RootObj
+
+
+ Deprecated +
+ + Represents a Nim identifier in the AST. Note: This is only rarely useful, for identifier construction from a string use ident"abc". + Source   +Edit   + +
+
+
+
NimNodeKind = enum
+  nnkNone, nnkEmpty, nnkIdent, nnkSym, nnkType, nnkCharLit, nnkIntLit,
+  nnkInt8Lit, nnkInt16Lit, nnkInt32Lit, nnkInt64Lit, nnkUIntLit, nnkUInt8Lit,
+  nnkUInt16Lit, nnkUInt32Lit, nnkUInt64Lit, nnkFloatLit, nnkFloat32Lit,
+  nnkFloat64Lit, nnkFloat128Lit, nnkStrLit, nnkRStrLit, nnkTripleStrLit,
+  nnkNilLit, nnkComesFrom, nnkDotCall, nnkCommand, nnkCall, nnkCallStrLit,
+  nnkInfix, nnkPrefix, nnkPostfix, nnkHiddenCallConv, nnkExprEqExpr,
+  nnkExprColonExpr, nnkIdentDefs, nnkVarTuple, nnkPar, nnkObjConstr, nnkCurly,
+  nnkCurlyExpr, nnkBracket, nnkBracketExpr, nnkPragmaExpr, nnkRange, nnkDotExpr,
+  nnkCheckedFieldExpr, nnkDerefExpr, nnkIfExpr, nnkElifExpr, nnkElseExpr,
+  nnkLambda, nnkDo, nnkAccQuoted, nnkTableConstr, nnkBind, nnkClosedSymChoice,
+  nnkOpenSymChoice, nnkHiddenStdConv, nnkHiddenSubConv, nnkConv, nnkCast,
+  nnkStaticExpr, nnkAddr, nnkHiddenAddr, nnkHiddenDeref, nnkObjDownConv,
+  nnkObjUpConv, nnkChckRangeF, nnkChckRange64, nnkChckRange, nnkStringToCString,
+  nnkCStringToString, nnkAsgn, nnkFastAsgn, nnkGenericParams, nnkFormalParams,
+  nnkOfInherit, nnkImportAs, nnkProcDef, nnkMethodDef, nnkConverterDef,
+  nnkMacroDef, nnkTemplateDef, nnkIteratorDef, nnkOfBranch, nnkElifBranch,
+  nnkExceptBranch, nnkElse, nnkAsmStmt, nnkPragma, nnkPragmaBlock, nnkIfStmt,
+  nnkWhenStmt, nnkForStmt, nnkParForStmt, nnkWhileStmt, nnkCaseStmt,
+  nnkTypeSection, nnkVarSection, nnkLetSection, nnkConstSection, nnkConstDef,
+  nnkTypeDef, nnkYieldStmt, nnkDefer, nnkTryStmt, nnkFinally, nnkRaiseStmt,
+  nnkReturnStmt, nnkBreakStmt, nnkContinueStmt, nnkBlockStmt, nnkStaticStmt,
+  nnkDiscardStmt, nnkStmtList, nnkImportStmt, nnkImportExceptStmt,
+  nnkExportStmt, nnkExportExceptStmt, nnkFromStmt, nnkIncludeStmt, nnkBindStmt,
+  nnkMixinStmt, nnkUsingStmt, nnkCommentStmt, nnkStmtListExpr, nnkBlockExpr,
+  nnkStmtListType, nnkBlockType, nnkWith, nnkWithout, nnkTypeOfExpr,
+  nnkObjectTy, nnkTupleTy, nnkTupleClassTy, nnkTypeClassTy, nnkStaticTy,
+  nnkRecList, nnkRecCase, nnkRecWhen, nnkRefTy, nnkPtrTy, nnkVarTy, nnkConstTy,
+  nnkOutTy, nnkDistinctTy, nnkProcTy, nnkIteratorTy, nnkSinkAsgn, nnkEnumTy,
+  nnkEnumFieldDef, nnkArgList, nnkPattern, nnkHiddenTryStmt, nnkClosure,
+  nnkGotoState, nnkState, nnkBreakState, nnkFuncDef, nnkTupleConstr, nnkError, ## erroneous AST node
+  nnkModuleRef, nnkReplayAction, nnkNilRodNode, ## internal IC nodes
+  nnkOpenSym
+
+ + + Source   +Edit   + +
+
+
+
NimNodeKinds = set[NimNodeKind]
+
+ + + Source   +Edit   + +
+
+
+
NimSym {....deprecated.} = ref NimSymObj
+
+
+ Deprecated +
+ + Represents a Nim symbol in the compiler; a symbol is a looked-up ident. + Source   +Edit   + +
+
+
+
NimSymKind = enum
+  nskUnknown, nskConditional, nskDynLib, nskParam, nskGenericParam, nskTemp,
+  nskModule, nskType, nskVar, nskLet, nskConst, nskResult, nskProc, nskFunc,
+  nskMethod, nskIterator, nskConverter, nskMacro, nskTemplate, nskField,
+  nskEnumField, nskForVar, nskLabel, nskStub
+
+ + + Source   +Edit   + +
+
+
+
NimTypeKind = enum
+  ntyNone, ntyBool, ntyChar, ntyEmpty, ntyAlias, ntyNil, ntyExpr, ntyStmt,
+  ntyTypeDesc, ntyGenericInvocation, ntyGenericBody, ntyGenericInst,
+  ntyGenericParam, ntyDistinct, ntyEnum, ntyOrdinal, ntyArray, ntyObject,
+  ntyTuple, ntySet, ntyRange, ntyPtr, ntyRef, ntyVar, ntySequence, ntyProc,
+  ntyPointer, ntyOpenArray, ntyString, ntyCString, ntyForward, ntyInt, ntyInt8,
+  ntyInt16, ntyInt32, ntyInt64, ntyFloat, ntyFloat32, ntyFloat64, ntyFloat128,
+  ntyUInt, ntyUInt8, ntyUInt16, ntyUInt32, ntyUInt64, ntyUnused0, ntyUnused1,
+  ntyUnused2, ntyVarargs, ntyUncheckedArray, ntyError, ntyBuiltinTypeClass,
+  ntyUserTypeClass, ntyUserTypeClassInst, ntyCompositeTypeClass, ntyInferred,
+  ntyAnd, ntyOr, ntyNot, ntyAnything, ntyStatic, ntyFromExpr, ntyOptDeprecated,
+  ntyVoid
+
+ + + Source   +Edit   + +
+
+
+
TNimSymKinds {....deprecated.} = set[NimSymKind]
+
+
+ Deprecated +
+ + + Source   +Edit   + +
+
+
+
TNimTypeKinds {....deprecated.} = set[NimTypeKind]
+
+
+ Deprecated +
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
AtomicNodes = {nnkNone..nnkNilLit}
+
+ + + Source   +Edit   + +
+
+
+
CallNodes = {nnkCall, nnkInfix, nnkPrefix, nnkPostfix, nnkCommand,
+             nnkCallStrLit, nnkHiddenCallConv}
+
+ + + Source   +Edit   + +
+
+
+
nnkCallKinds = {nnkCall, nnkInfix, nnkPrefix, nnkPostfix, nnkCommand,
+                nnkCallStrLit, nnkHiddenCallConv}
+
+ + + Source   +Edit   + +
+
+
+
nnkLiterals = {nnkCharLit..nnkNilLit}
+
+ + + Source   +Edit   + +
+
+
+
nnkMutableTy {....deprecated.} = nnkOutTy
+
+ + + Source   +Edit   + +
+
+
+
nnkSharedTy {....deprecated.} = nnkSinkAsgn
+
+ + + Source   +Edit   + +
+
+
+
RoutineNodes = {nnkProcDef, nnkFuncDef, nnkMethodDef, nnkDo, nnkLambda,
+                nnkIteratorDef, nnkTemplateDef, nnkConverterDef, nnkMacroDef}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(arg: LineInfo): string {....raises: [], tags: [], forbids: [].}
+
+ + Return a string representation in the form filepath(line, column). + Source   +Edit   + +
+
+
+
proc `$`(i: NimIdent): string {.magic: "NStrVal", noSideEffect, ...deprecated: "Deprecated since version 0.18.1; Use \'strVal\' instead.",
+                                raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since version 0.18.1; Use 'strVal' instead. +
+ + Converts a Nim identifier to a string. + Source   +Edit   + +
+
+
+
proc `$`(node: NimNode): string {....raises: [], tags: [], forbids: [].}
+
+ + Get the string of an identifier node. + Source   +Edit   + +
+
+
+
proc `$`(s: NimSym): string {.magic: "NStrVal", noSideEffect, ...deprecated: "Deprecated since version 0.18.1; Use \'strVal\' instead.",
+                              raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since version 0.18.1; Use 'strVal' instead. +
+ + Converts a Nim symbol to a string. + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(a, b: NimIdent): bool {.magic: "EqIdent", noSideEffect, ...deprecated: "Deprecated since version 0.18.1; Use \'==\' on \'NimNode\' instead.",
+                                  raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since version 0.18.1; Use '==' on 'NimNode' instead. +
+ + Compares two Nim identifiers. + Source   +Edit   + +
+
+
+
proc `==`(a, b: NimNode): bool {.magic: "EqNimrodNode", noSideEffect,
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + Compare two Nim nodes. Return true if nodes are structurally equivalent. This means two independently created nodes can be equal. + Source   +Edit   + +
+
+
+
proc `==`(a, b: NimSym): bool {.magic: "EqNimrodNode", noSideEffect, ...deprecated: "Deprecated since version 0.18.1; Use \'==(NimNode, NimNode)\' instead.",
+                                raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since version 0.18.1; Use '==(NimNode, NimNode)' instead. +
+ + Compares two Nim symbols. + Source   +Edit   + +
+
+ +
+
+
+
proc `[]`(n: NimNode; i: BackwardsIndex): NimNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Get n's i'th child. + Source   +Edit   + +
+
+
+
proc `[]`(n: NimNode; i: int): NimNode {.magic: "NChild", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Get n's i'th child. + Source   +Edit   + +
+
+
+
proc `[]`[T, U: Ordinal](n: NimNode; x: HSlice[T, U]): seq[NimNode]
+
+ + Slice operation for NimNode. Returns a seq of child of n who inclusive range [n[x.a], n[x.b]]. + Source   +Edit   + +
+
+ +
+
+
+
proc `[]=`(n: NimNode; i: BackwardsIndex; child: NimNode) {....raises: [],
+    tags: [], forbids: [].}
+
+ + Set n's i'th child to child. + Source   +Edit   + +
+
+
+
proc `[]=`(n: NimNode; i: int; child: NimNode) {.magic: "NSetChild",
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + Set n's i'th child to child. + Source   +Edit   + +
+
+ +
+
+
+
proc add(father, child: NimNode): NimNode {.magic: "NAdd", discardable,
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + Adds the child to the father node. Returns the father node so that calls can be nested. + Source   +Edit   + +
+
+
+
proc add(father: NimNode; children: varargs[NimNode]): NimNode {.
+    magic: "NAddMultiple", discardable, noSideEffect, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Adds each child of children to the father node. Returns the father node so that calls can be nested. + Source   +Edit   + +
+
+ +
+
+
+
proc addIdentIfAbsent(dest: NimNode; ident: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Add ident to dest if it is not present. This is intended for use with pragmas. + Source   +Edit   + +
+
+ +
+
+
+
proc addPragma(someProc, pragma: NimNode) {....raises: [], tags: [], forbids: [].}
+
+ + Adds pragma to routine definition. + Source   +Edit   + +
+
+ +
+
+
+
proc astGenRepr(n: NimNode): string {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ +

Convert the AST n to the code required to generate that AST.

+

See also system: repr, treeRepr, and lispRepr.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc basename(a: NimNode): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Pull an identifier from prefix/postfix expressions. + Source   +Edit   + +
+
+ +
+
+
+
proc basename=(a: NimNode; val: string) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bindSym(ident: string | NimNode; rule: BindSymRule = brClosed): NimNode {.
+    magic: "NBindSym", noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a node that binds ident to a symbol node. The bound symbol may be an overloaded symbol. if ident is a NimNode, it must have nnkIdent kind. If rule == brClosed either an nnkClosedSymChoice tree is returned or nnkSym if the symbol is not ambiguous. If rule == brOpen either an nnkOpenSymChoice tree is returned or nnkSym if the symbol is not ambiguous. If rule == brForceOpen always an nnkOpenSymChoice tree is returned even if the symbol is not ambiguous.

+

See the manual for more details.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc body(someProc: NimNode): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc body=(someProc: NimNode; val: NimNode) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc boolVal(n: NimNode): bool {.noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc callsite(): NimNode {.magic: "NCallSite", ...gcsafe, deprecated: "Deprecated since v0.18.1; use `varargs[untyped]` in the macro prototype instead",
+                           raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v0.18.1; use `varargs[untyped]` in the macro prototype instead +
+ + Returns the AST of the invocation expression that invoked this macro. + Source   +Edit   + +
+
+ +
+
+
+
proc copy(node: NimNode): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + An alias for copyNimTree. + Source   +Edit   + +
+
+ +
+
+
+
proc copyChildrenTo(src, dest: NimNode) {....raises: [], tags: [], forbids: [].}
+
+ + Copy all children from src to dest. + Source   +Edit   + +
+
+ +
+
+
+
proc copyLineInfo(arg: NimNode; info: NimNode) {.magic: "NLineInfo",
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + Copy lineinfo from info. + Source   +Edit   + +
+
+ +
+
+
+
proc copyNimNode(n: NimNode): NimNode {.magic: "NCopyNimNode", noSideEffect,
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + Creates a new AST node by copying the node n. Note that unlike copyNimTree, child nodes of n are not copied. +

Example:

+
macro foo(x: typed) =
+  var s = copyNimNode(x)
+  doAssert s.len == 0
+  doAssert s.kind == nnkStmtList
+
+foo:
+  let x = 12
+  echo x
+ Source   +Edit   + +
+
+ +
+
+
+
proc copyNimTree(n: NimNode): NimNode {.magic: "NCopyNimTree", noSideEffect,
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + Creates a new AST node by recursively copying the node n. Note that unlike copyNimNode, this copies n, the children of n, etc. +

Example:

+
macro foo(x: typed) =
+  var s = copyNimTree(x)
+  doAssert s.len == 2
+  doAssert s.kind == nnkStmtList
+
+foo:
+  let x = 12
+  echo x
+ Source   +Edit   + +
+
+ +
+
+
+
proc del(father: NimNode; idx = 0; n = 1) {.magic: "NDel", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Deletes n children of father starting at index idx. + Source   +Edit   + +
+
+ +
+
+
+
proc eqIdent(a: NimNode; b: NimNode): bool {.magic: "EqIdent", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Style insensitive comparison. a and b can be an identifier or a symbol. Both may be wrapped in an export marker (nnkPostfix) or quoted with backticks (nnkAccQuoted), these nodes will be unwrapped. + Source   +Edit   + +
+
+
+
proc eqIdent(a: NimNode; b: string): bool {.magic: "EqIdent", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Style insensitive comparison. a can be an identifier or a symbol. a may be wrapped in an export marker (nnkPostfix) or quoted with backticks (nnkAccQuoted), these nodes will be unwrapped. + Source   +Edit   + +
+
+
+
proc eqIdent(a: string; b: NimNode): bool {.magic: "EqIdent", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Style insensitive comparison. b can be an identifier or a symbol. b may be wrapped in an export marker (nnkPostfix) or quoted with backticks (nnkAccQuoted), these nodes will be unwrapped. + Source   +Edit   + +
+
+
+
proc eqIdent(a: string; b: string): bool {.magic: "EqIdent", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Style insensitive comparison. + Source   +Edit   + +
+
+ +
+
+
+
proc error(msg: string; n: NimNode = nil) {.magic: "NError", ...gcsafe, noreturn,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Writes an error message at compile time. The optional n: NimNode parameter is used as the source for file and line number information in the compilation error message. + Source   +Edit   + +
+
+ +
+
+
+
proc expectIdent(n: NimNode; name: string) {....raises: [], tags: [], forbids: [].}
+
+ + Check that eqIdent(n,name) holds true. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check the AST that is passed to them. + Source   +Edit   + +
+
+ +
+
+
+
proc expectKind(n: NimNode; k: NimNodeKind) {....raises: [], tags: [], forbids: [].}
+
+ + Checks that n is of kind k. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check the AST that is passed to them. + Source   +Edit   + +
+
+
+
proc expectKind(n: NimNode; k: set[NimNodeKind]) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Checks that n is of kind k. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check the AST that is passed to them. + Source   +Edit   + +
+
+ +
+
+
+
proc expectLen(n: NimNode; len: int) {....raises: [], tags: [], forbids: [].}
+
+ + Checks that n has exactly len children. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check its number of arguments. + Source   +Edit   + +
+
+
+
proc expectLen(n: NimNode; min, max: int) {....raises: [], tags: [], forbids: [].}
+
+ + Checks that n has a number of children in the range min..max. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check its number of arguments. + Source   +Edit   + +
+
+ +
+
+
+
proc expectMinLen(n: NimNode; min: int) {....raises: [], tags: [], forbids: [].}
+
+ + Checks that n has at least min children. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check its number of arguments. + Source   +Edit   + +
+
+ +
+
+
+
proc extractDocCommentsAndRunnables(n: NimNode): NimNode {....raises: [], tags: [],
+    forbids: [].}
+
+ +

returns a nnkStmtList containing the top-level doc comments and runnableExamples in a, stopping at the first child that is neither. Example:

+

import std/macros
+macro transf(a): untyped =
+  result = quote do:
+    proc fun2*() = discard
+  let header = extractDocCommentsAndRunnables(a.body)
+  # correct usage: rest is appended
+  result.body = header
+  result.body.add quote do: discard # just an example
+  # incorrect usage: nesting inside a nnkStmtList:
+  # result.body = quote do: (`header`; discard)
+
+proc fun*() {.transf.} =
+  ## first comment
+  runnableExamples: discard
+  runnableExamples: discard
+  ## last comment
+  discard # first statement after doc comments + runnableExamples
+  ## not docgen'd

+ + Source   +Edit   + +
+
+ +
+
+
+
proc floatVal(n: NimNode): BiggestFloat {.magic: "NFloatVal", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Returns a float from any floating point literal. + Source   +Edit   + +
+
+ +
+
+
+
proc floatVal=(n: NimNode; val: BiggestFloat) {.magic: "NSetFloatVal",
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc genSym(kind: NimSymKind = nskLet; ident = ""): NimNode {.magic: "NGenSym",
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + Generates a fresh symbol that is guaranteed to be unique. The symbol needs to occur in a declaration context. + Source   +Edit   + +
+
+ +
+
+
+
proc getAlign(arg: NimNode): int {.magic: "NSizeOf", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + Returns the same result as system.alignof if the alignment is known by the Nim compiler. It works on NimNode for use in macro context. Returns a negative value if the Nim compiler does not know the alignment. + Source   +Edit   + +
+
+ +
+
+
+
proc getAst(macroOrTemplate: untyped): NimNode {.magic: "ExpandToAst",
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Obtains the AST nodes returned from a macro or template invocation. See also genasts.genAst. Example:

+

macro FooMacro() =
+  var ast = getAst(BarTemplate())

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getImpl(s: NimSym): NimNode {.magic: "GetImpl", noSideEffect, ...deprecated: "use `getImpl: NimNode -> NimNode` instead",
+                                   raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: use `getImpl: NimNode -> NimNode` instead +
+ + + Source   +Edit   + +
+
+
+
proc getImpl(symbol: NimNode): NimNode {.magic: "GetImpl", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Returns a copy of the declaration of a symbol or nil. + Source   +Edit   + +
+
+ +
+
+
+
proc getImplTransformed(symbol: NimNode): NimNode {.magic: "GetImplTransf",
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + For a typed proc returns the AST after transformation pass; this is useful for debugging how the compiler transforms code (e.g.: defer, for) but note that code transformations are implementation dependent and subject to change. See an example in tests/macros/tmacros_various.nim. + Source   +Edit   + +
+
+ +
+
+
+
proc getOffset(arg: NimNode): int {.magic: "NSizeOf", noSideEffect, ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + Returns the same result as system.offsetof if the offset is known by the Nim compiler. It expects a resolved symbol node from a field of a type. Therefore it only requires one argument instead of two. Returns a negative value if the Nim compiler does not know the offset. + Source   +Edit   + +
+
+ +
+
+
+
proc getProjectPath(): string {....raises: [], tags: [], forbids: [].}
+
+ +

Returns the path to the currently compiling project.

+

This is not to be confused with system.currentSourcePath which returns the path of the source file containing that template call.

+

For example, assume a dir1/foo.nim that imports a dir2/bar.nim, have the bar.nim print out both getProjectPath and currentSourcePath outputs.

+

Now when foo.nim is compiled, the getProjectPath from bar.nim will return the dir1/ path, while the currentSourcePath will return the path to the bar.nim source file.

+

Now when bar.nim is compiled directly, the getProjectPath will now return the dir2/ path, and the currentSourcePath will still return the same path, the path to the bar.nim source file.

+

The path returned by this proc is set at compile time.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getSize(arg: NimNode): int {.magic: "NSizeOf", noSideEffect, ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + Returns the same result as system.sizeof if the size is known by the Nim compiler. Returns a negative value if the Nim compiler does not know the size. + Source   +Edit   + +
+
+ +
+
+
+
proc getType(n: NimNode): NimNode {.magic: "NGetType", noSideEffect, ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + With 'getType' you can access the node's type. A Nim type is mapped to a Nim AST too, so it's slightly confusing but it means the same API can be used to traverse types. Recursive types are flattened for you so there is no danger of infinite recursions during traversal. To resolve recursive types, you have to call 'getType' again. To see what kind of type it is, call typeKind on getType's result. + Source   +Edit   + +
+
+
+
proc getType(n: typedesc): NimNode {.magic: "NGetType", noSideEffect,
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + Version of getType which takes a typedesc. + Source   +Edit   + +
+
+ +
+
+
+
proc getTypeImpl(n: NimNode): NimNode {.magic: "NGetType", noSideEffect,
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + Returns the type of a node in a form matching the implementation of the type. Any intermediate aliases are expanded to arrive at the final type implementation. You can instead use getImpl on a symbol if you want to find the intermediate aliases. +

Example:

+
type
+  Vec[N: static[int], T] = object
+    arr: array[N, T]
+  Vec4[T] = Vec[4, T]
+  Vec4f = Vec4[float32]
+var a: Vec4f
+var b: Vec4[float32]
+var c: Vec[4, float32]
+macro dumpTypeImpl(x: typed): untyped =
+  newLit(x.getTypeImpl.repr)
+let t = """
+object
+  arr: array[0 .. 3, float32]"""
+doAssert(dumpTypeImpl(a) == t)
+doAssert(dumpTypeImpl(b) == t)
+doAssert(dumpTypeImpl(c) == t)
+ Source   +Edit   + +
+
+
+
proc getTypeImpl(n: typedesc): NimNode {.magic: "NGetType", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Version of getTypeImpl which takes a typedesc. + Source   +Edit   + +
+
+ +
+
+
+
proc getTypeInst(n: NimNode): NimNode {.magic: "NGetType", noSideEffect,
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + Returns the type of a node in a form matching the way the type instance was declared in the code. +

Example:

+
type
+  Vec[N: static[int], T] = object
+    arr: array[N, T]
+  Vec4[T] = Vec[4, T]
+  Vec4f = Vec4[float32]
+var a: Vec4f
+var b: Vec4[float32]
+var c: Vec[4, float32]
+macro dumpTypeInst(x: typed): untyped =
+  newLit(x.getTypeInst.repr)
+doAssert(dumpTypeInst(a) == "Vec4f")
+doAssert(dumpTypeInst(b) == "Vec4[float32]")
+doAssert(dumpTypeInst(c) == "Vec[4, float32]")
+ Source   +Edit   + +
+
+
+
proc getTypeInst(n: typedesc): NimNode {.magic: "NGetType", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Version of getTypeInst which takes a typedesc. + Source   +Edit   + +
+
+ +
+
+
+
proc hasArgOfName(params: NimNode; name: string): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + Search nnkFormalParams for an argument. + Source   +Edit   + +
+
+ +
+
+
+
proc hint(msg: string; n: NimNode = nil) {.magic: "NHint", ...gcsafe, raises: [],
+    tags: [], forbids: [].}
+
+ + Writes a hint message at compile time. + Source   +Edit   + +
+
+ +
+
+
+
proc ident(n: NimNode): NimIdent {.magic: "NIdent", noSideEffect, ...deprecated: "Deprecated since version 0.18.1; All functionality is defined on \'NimNode\'.",
+                                   raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since version 0.18.1; All functionality is defined on 'NimNode'. +
+ + + Source   +Edit   + +
+
+
+
proc ident(name: string): NimNode {.magic: "StrToIdent", noSideEffect,
+                                    ...raises: [], tags: [], forbids: [].}
+
+ + Create a new ident node from a string. + Source   +Edit   + +
+
+ +
+
+
+
proc ident=(n: NimNode; val: NimIdent) {.magic: "NSetIdent", noSideEffect, ...deprecated: "Deprecated since version 0.18.1; Generate a new \'NimNode\' with \'ident(string)\' instead.",
+    raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since version 0.18.1; Generate a new 'NimNode' with 'ident(string)' instead. +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc infix(a: NimNode; op: string; b: NimNode): NimNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc insert(a: NimNode; pos: int; b: NimNode) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Insert node b into node a at pos. + Source   +Edit   + +
+
+ +
+
+
+
proc internalErrorFlag(): string {.magic: "NError", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + Some builtins set an error flag. This is then turned into a proper exception. Note: Ordinary application code should not call this. + Source   +Edit   + +
+
+ +
+
+
+
proc intVal(n: NimNode): BiggestInt {.magic: "NIntVal", noSideEffect,
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + Returns an integer value from any integer literal or enum field symbol. + Source   +Edit   + +
+
+ +
+
+
+
proc intVal=(n: NimNode; val: BiggestInt) {.magic: "NSetIntVal", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isExported(n: NimNode): bool {.noSideEffect, ...raises: [], tags: [],
+                                    forbids: [].}
+
+ + Returns whether the symbol is exported or not. + Source   +Edit   + +
+
+ +
+
+
+
proc isInstantiationOf(instanceProcSym, genProcSym: NimNode): bool {.
+    magic: "SymIsInstantiationOf", noSideEffect, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Checks if a proc symbol is an instance of the generic proc symbol. Useful to check proc symbols against generic symbols returned by bindSym. + Source   +Edit   + +
+
+ +
+
+
+
proc kind(n: NimNode): NimNodeKind {.magic: "NKind", noSideEffect, ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + Returns the kind of the node n. + Source   +Edit   + +
+
+ +
+
+
+
proc last(node: NimNode): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Return the last item in nodes children. Same as node[^1]. + Source   +Edit   + +
+
+ +
+
+
+
proc len(n: NimNode): int {.magic: "NLen", noSideEffect, ...raises: [], tags: [],
+                            forbids: [].}
+
+ + Returns the number of children of n. + Source   +Edit   + +
+
+ +
+
+
+
proc lineInfo(arg: NimNode): string {....raises: [], tags: [], forbids: [].}
+
+ + Return line info in the form filepath(line, column). + Source   +Edit   + +
+
+ +
+
+
+
proc lineInfoObj(n: NimNode): LineInfo {....raises: [], tags: [], forbids: [].}
+
+ + Returns LineInfo of n, using absolute path for filename. + Source   +Edit   + +
+
+ +
+
+
+
proc lispRepr(n: NimNode; indented = false): string {....gcsafe, raises: [],
+    tags: [], forbids: [].}
+
+ +

Convert the AST n to a human-readable lisp-like string.

+

See also repr, treeRepr, and astGenRepr.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc name(someProc: NimNode): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc name=(someProc: NimNode; val: NimNode) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nestList(op: NimNode; pack: NimNode): NimNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Nests the list pack into a tree of call expressions: [a, b, c] is transformed into op(a, op(c, d)). This is also known as fold expression. + Source   +Edit   + +
+
+
+
proc nestList(op: NimNode; pack: NimNode; init: NimNode): NimNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + Nests the list pack into a tree of call expressions: [a, b, c] is transformed into op(a, op(c, d)). This is also known as fold expression. + Source   +Edit   + +
+
+ +
+
+
+
proc newAssignment(lhs, rhs: NimNode): NimNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newBlockStmt(body: NimNode): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Create a new block: stmt. + Source   +Edit   + +
+
+
+
proc newBlockStmt(label, body: NimNode): NimNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Create a new block statement with label. + Source   +Edit   + +
+
+ +
+
+
+
proc newCall(theProc: NimIdent; args: varargs[NimNode]): NimNode {....deprecated: "Deprecated since v0.18.1; use \'newCall(string, ...)\' or \'newCall(NimNode, ...)\' instead",
+    raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v0.18.1; use 'newCall(string, ...)' or 'newCall(NimNode, ...)' instead +
+ + Produces a new call node. theProc is the proc that is called with the arguments args[0..]. + Source   +Edit   + +
+
+
+
proc newCall(theProc: NimNode; args: varargs[NimNode]): NimNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + Produces a new call node. theProc is the proc that is called with the arguments args[0..]. + Source   +Edit   + +
+
+
+
proc newCall(theProc: string; args: varargs[NimNode]): NimNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + Produces a new call node. theProc is the proc that is called with the arguments args[0..]. + Source   +Edit   + +
+
+ +
+
+
+
proc newColonExpr(a, b: NimNode): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Create new colon expression. newColonExpr(a, b) -> a: b + Source   +Edit   + +
+
+ +
+
+
+
proc newCommentStmtNode(s: string): NimNode {.noSideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Creates a comment statement node. + Source   +Edit   + +
+
+ +
+
+
+
proc newConstStmt(name, value: NimNode): NimNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Create a new const stmt. + Source   +Edit   + +
+
+ +
+
+
+
proc newDotExpr(a, b: NimNode): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Create new dot expression. a.dot(b) -> a.b + Source   +Edit   + +
+
+ +
+
+
+
proc newEmptyNode(): NimNode {.noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + Create a new empty node. + Source   +Edit   + +
+
+ +
+
+
+
proc newEnum(name: NimNode; fields: openArray[NimNode]; public, pure: bool): NimNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new enum. name must be an ident. Fields are allowed to be either idents or EnumFieldDef:

+

newEnum(
+  name    = ident("Colors"),
+  fields  = [ident("Blue"), ident("Red")],
+  public  = true, pure = false)
+
+# type Colors* = Blue Red

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newFloatLitNode(f: BiggestFloat): NimNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Creates a float literal node from f. + Source   +Edit   + +
+
+ +
+
+
+
proc newIdentDefs(name, kind: NimNode; default = newEmptyNode()): NimNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new nnkIdentDefs node of a specific kind and value.

+

nnkIdentDefs need to have at least three children, but they can have more: first comes a list of identifiers followed by a type and value nodes. This helper proc creates a three node subtree, the first subnode being a single identifier name. Both the kind node and default (value) nodes may be empty depending on where the nnkIdentDefs appears: tuple or object definitions will have an empty default node, let or var blocks may have an empty kind node if the identifier is being assigned a value. Example:

+

var varSection = newNimNode(nnkVarSection).add(
+  newIdentDefs(ident("a"), ident("string")),
+  newIdentDefs(ident("b"), newEmptyNode(), newLit(3)))
+# --> var
+#       a: string
+#       b = 3

+

If you need to create multiple identifiers you need to use the lower level newNimNode:

+

result = newNimNode(nnkIdentDefs).add(
+  ident("a"), ident("b"), ident("c"), ident("string"),
+    newStrLitNode("Hello"))

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newIdentNode(i: NimIdent): NimNode {....deprecated: "use ident(string)",
+    raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: use ident(string) +
+ + Creates an identifier node from i. + Source   +Edit   + +
+
+
+
proc newIdentNode(i: string): NimNode {.magic: "StrToIdent", noSideEffect,
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + Creates an identifier node from i. It is simply an alias for ident(string). Use that, it's shorter. + Source   +Edit   + +
+
+ +
+
+
+
proc newIfStmt(branches: varargs[tuple[cond, body: NimNode]]): NimNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Constructor for if statements.

+

newIfStmt(
+  (Ident, StmtList),
+  ...
+)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newIntLitNode(i: BiggestInt): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates an int literal node from i. + Source   +Edit   + +
+
+ +
+
+
+
proc newLetStmt(name, value: NimNode): NimNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Create a new let stmt. + Source   +Edit   + +
+
+ +
+
+
+
proc newLit(arg: enum): NimNode
+
+ + + Source   +Edit   + +
+
+
+
proc newLit(arg: object): NimNode
+
+ + + Source   +Edit   + +
+
+
+
proc newLit(arg: ref object): NimNode
+
+ + produces a new ref type literal node. + Source   +Edit   + +
+
+
+
proc newLit(b: bool): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Produces a new boolean literal node. + Source   +Edit   + +
+
+
+
proc newLit(c: char): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Produces a new character literal node. + Source   +Edit   + +
+
+
+
proc newLit(f: float32): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Produces a new float literal node. + Source   +Edit   + +
+
+
+
proc newLit(f: float64): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Produces a new float literal node. + Source   +Edit   + +
+
+
+
proc newLit(i: int): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Produces a new integer literal node. + Source   +Edit   + +
+
+
+
proc newLit(i: int8): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Produces a new integer literal node. + Source   +Edit   + +
+
+
+
proc newLit(i: int16): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Produces a new integer literal node. + Source   +Edit   + +
+
+
+
proc newLit(i: int32): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Produces a new integer literal node. + Source   +Edit   + +
+
+
+
proc newLit(i: int64): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Produces a new integer literal node. + Source   +Edit   + +
+
+
+
proc newLit(i: uint): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Produces a new unsigned integer literal node. + Source   +Edit   + +
+
+
+
proc newLit(i: uint8): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Produces a new unsigned integer literal node. + Source   +Edit   + +
+
+
+
proc newLit(i: uint16): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Produces a new unsigned integer literal node. + Source   +Edit   + +
+
+
+
proc newLit(i: uint32): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Produces a new unsigned integer literal node. + Source   +Edit   + +
+
+
+
proc newLit(i: uint64): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Produces a new unsigned integer literal node. + Source   +Edit   + +
+
+
+
proc newLit(s: string): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Produces a new string literal node. + Source   +Edit   + +
+
+
+
proc newLit[N, T](arg: array[N, T]): NimNode
+
+ + + Source   +Edit   + +
+
+
+
proc newLit[T: tuple](arg: T): NimNode
+
+ + + Source   +Edit   + +
+
+
+
proc newLit[T](arg: seq[T]): NimNode
+
+ + + Source   +Edit   + +
+
+
+
proc newLit[T](s: set[T]): NimNode
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newNilLit(): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + New nil literal shortcut. + Source   +Edit   + +
+
+ +
+
+
+
proc newNimNode(kind: NimNodeKind; lineInfoFrom: NimNode = nil): NimNode {.
+    magic: "NNewNimNode", noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new AST node of the specified kind.

+

The lineInfoFrom parameter is used for line information when the produced code crashes. You should ensure that it is set to a node that you are transforming.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newPar(exprs: NimNode): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Create a new parentheses-enclosed expression. + Source   +Edit   + +
+
+
+
proc newPar(exprs: varargs[NimNode]): NimNode {....deprecated: "don\'t use newPar/nnkPar to construct tuple expressions; use nnkTupleConstr instead",
+    raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: don't use newPar/nnkPar to construct tuple expressions; use nnkTupleConstr instead +
+ + Create a new parentheses-enclosed expression. + Source   +Edit   + +
+
+ +
+
+
+
proc newProc(name = newEmptyNode();
+             params: openArray[NimNode] = [newEmptyNode()];
+             body: NimNode = newStmtList(); procType = nnkProcDef;
+             pragmas: NimNode = newEmptyNode()): NimNode {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Shortcut for creating a new proc.

+

The params array must start with the return type of the proc, followed by a list of IdentDefs which specify the params.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newStmtList(stmts: varargs[NimNode]): NimNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Create a new statement list. + Source   +Edit   + +
+
+ +
+
+
+
proc newStrLitNode(s: string): NimNode {.noSideEffect, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Creates a string literal node from s. + Source   +Edit   + +
+
+ +
+
+
+
proc newTree(kind: NimNodeKind; children: varargs[NimNode]): NimNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Produces a new node with children. + Source   +Edit   + +
+
+ +
+
+
+
proc newVarStmt(name, value: NimNode): NimNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Create a new var stmt. + Source   +Edit   + +
+
+ +
+
+
+
proc nodeID(n: NimNode): int {.magic: "NodeId", ...raises: [], tags: [],
+                               forbids: [].}
+
+ + Returns the id of n, when the compiler has been compiled with the flag -d:useNodeids, otherwise returns -1. This proc is for the purpose to debug the compiler only. + Source   +Edit   + +
+
+ +
+
+
+
proc owner(sym: NimNode): NimNode {.magic: "SymOwner", noSideEffect, ...deprecated,
+                                    raises: [], tags: [], forbids: [].}
+
+
+ Deprecated +
+ +

Accepts a node of kind nnkSym and returns its owner's symbol. The meaning of 'owner' depends on sym's NimSymKind and declaration context. For top level declarations this is an nskModule symbol, for proc local variables an nskProc symbol, for enum/object fields an nskType symbol, etc. For symbols without an owner, nil is returned.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc params(someProc: NimNode): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc params=(someProc: NimNode; params: NimNode) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc parseExpr(s: string; filename: string = ""): NimNode {.noSideEffect,
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ + Compiles the passed string to its AST representation. Expects a single expression. Raises ValueError for parsing errors. A filename can be given for more informative errors. + Source   +Edit   + +
+
+ +
+
+
+
proc parseStmt(s: string; filename: string = ""): NimNode {.noSideEffect,
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ + Compiles the passed string to its AST representation. Expects one or more statements. Raises ValueError for parsing errors. A filename can be given for more informative errors. + Source   +Edit   + +
+
+ +
+
+
+
proc postfix(node: NimNode; op: string): NimNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pragma(someProc: NimNode): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Get the pragma of a proc type. These will be expanded. + Source   +Edit   + +
+
+ +
+
+
+
proc pragma=(someProc: NimNode; val: NimNode) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Set the pragma of a proc type. + Source   +Edit   + +
+
+ +
+
+
+
proc prefix(node: NimNode; op: string): NimNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc quote(bl: typed; op = "``"): NimNode {.magic: "QuoteAst", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Quasi-quoting operator. Accepts an expression or a block and returns the AST that represents it. Within the quoted AST, you are able to interpolate NimNode expressions from the surrounding scope. If no operator is given, quoting is done using backticks. Otherwise, the given operator must be used as a prefix operator for any interpolated expression. The original meaning of the interpolation operator may be obtained by escaping it (by prefixing it with itself) when used as a unary operator: e.g. @ is escaped as @@, &% is escaped as &%&% and so on; see examples.

+

A custom operator interpolation needs accent quoted (``) whenever it resolves to a symbol.

+

See also genasts which avoids some issues with quote.

+ +

Example:

+
macro check(ex: untyped) =
+  # this is a simplified version of the check macro from the
+  # unittest module.
+
+  # If there is a failed check, we want to make it easy for
+  # the user to jump to the faulty line in the code, so we
+  # get the line info here:
+  var info = ex.lineinfo
+
+  # We will also display the code string of the failed check:
+  var expString = ex.toStrLit
+
+  # Finally we compose the code to implement the check:
+  result = quote do:
+    if not `ex`:
+      echo `info` & ": Check failed: " & `expString`
+check 1 + 1 == 2
+

Example:

+
# example showing how to define a symbol that requires backtick without
+# quoting it.
+var destroyCalled = false
+macro bar() =
+  let s = newTree(nnkAccQuoted, ident"=destroy")
+  # let s = ident"`=destroy`" # this would not work
+  result = quote do:
+    type Foo = object
+    # proc `=destroy`(a: var Foo) = destroyCalled = true # this would not work
+    proc `s`(a: var Foo) = destroyCalled = true
+    block:
+      let a = Foo()
+bar()
+doAssert destroyCalled
+

Example:

+
# custom `op`
+var destroyCalled = false
+macro bar(ident) =
+  var x = 1.5
+  result = quote("@") do:
+    type Foo = object
+    let `@ident` = 0 # custom op interpolated symbols need quoted (``)
+    proc `=destroy`(a: var Foo) =
+      doAssert @x == 1.5
+      doAssert compiles(@x == 1.5)
+      let b1 = @[1,2]
+      let b2 = @@[1,2]
+      doAssert $b1 == "[1, 2]"
+      doAssert $b2 == "@[1, 2]"
+      destroyCalled = true
+    block:
+      let a = Foo()
+bar(someident)
+doAssert destroyCalled
+
+proc `&%`(x: int): int = 1
+proc `&%`(x, y: int): int = 2
+
+macro bar2() =
+  var x = 3
+  result = quote("&%") do:
+    var y = &%x # quoting operator
+    doAssert &%&%y == 1 # unary operator => need to escape
+    doAssert y &% y == 2 # binary operator => no need to escape
+    doAssert y == 3
+bar2()
+ Source   +Edit   + +
+
+ +
+
+
+
proc sameType(a, b: NimNode): bool {.magic: "SameNodeType", noSideEffect,
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + Compares two Nim nodes' types. Return true if the types are the same, e.g. true when comparing alias with original type. + Source   +Edit   + +
+
+ +
+
+
+
proc setLineInfo(arg: NimNode; file: string; line: int; column: int) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Sets the line info on the NimNode. The file needs to exists, but can be a relative path. If you want to attach line info to a block using quote you'll need to add the line information after the quote block. + Source   +Edit   + +
+
+
+
proc setLineInfo(arg: NimNode; lineInfo: LineInfo) {....raises: [], tags: [],
+    forbids: [].}
+
+ + See setLineInfo proc + Source   +Edit   + +
+
+ +
+
+
+
proc signatureHash(n: NimNode): string {.magic: "NSigHash", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Returns a stable identifier derived from the signature of a symbol. The signature combines many factors such as the type of the symbol, the owning module of the symbol and others. The same identifier is used in the back-end to produce the mangled symbol name. + Source   +Edit   + +
+
+ +
+
+
+
proc strVal(n: NimNode): string {.magic: "NStrVal", noSideEffect, ...raises: [],
+                                  tags: [], forbids: [].}
+
+ +

Returns the string value of an identifier, symbol, comment, or string literal.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc strVal=(n: NimNode; val: string) {.magic: "NSetStrVal", noSideEffect,
+                                        ...raises: [], tags: [], forbids: [].}
+
+ +

Sets the string value of a string literal or comment. Setting strVal is disallowed for nnkIdent and nnkSym nodes; a new node must be created using ident or bindSym instead.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc symBodyHash(s: NimNode): string {.noSideEffect, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + Returns a stable digest for symbols derived not only from type signature and owning module, but also implementation body. All procs/variables used in the implementation of this symbol are hashed recursively as well, including magics from system module. + Source   +Edit   + +
+
+ +
+
+
+
proc symbol(n: NimNode): NimSym {.magic: "NSymbol", noSideEffect, ...deprecated: "Deprecated since version 0.18.1; All functionality is defined on \'NimNode\'.",
+                                  raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since version 0.18.1; All functionality is defined on 'NimNode'. +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc symbol=(n: NimNode; val: NimSym) {.magic: "NSetSymbol", noSideEffect, ...deprecated: "Deprecated since version 0.18.1; Generate a new \'NimNode\' with \'genSym\' instead.",
+                                        raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since version 0.18.1; Generate a new 'NimNode' with 'genSym' instead. +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc symKind(symbol: NimNode): NimSymKind {.magic: "NSymKind", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toNimIdent(s: string): NimIdent {.magic: "StrToIdent", noSideEffect, ...deprecated: "Deprecated since version 0.18.0: Use \'ident\' or \'newIdentNode\' instead.",
+                                       raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since version 0.18.0: Use 'ident' or 'newIdentNode' instead. +
+ + Constructs an identifier from the string s. + Source   +Edit   + +
+
+ +
+
+
+
proc toStrLit(n: NimNode): NimNode {....raises: [], tags: [], forbids: [].}
+
+ + Converts the AST n to the concrete Nim code and wraps that in a string literal node. + Source   +Edit   + +
+
+ +
+
+
+
proc treeRepr(n: NimNode): string {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ +

Convert the AST n to a human-readable tree-like string.

+

See also repr, lispRepr, and astGenRepr.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc typeKind(n: NimNode): NimTypeKind {.magic: "NGetType", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Returns the type kind of the node 'n' that should represent a type, that means the node should have been obtained via getType. + Source   +Edit   + +
+
+ +
+
+
+
proc unpackInfix(node: NimNode): tuple[left: NimNode, op: string, right: NimNode] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc unpackPostfix(node: NimNode): tuple[node: NimNode, op: string] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc unpackPrefix(node: NimNode): tuple[node: NimNode, op: string] {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc warning(msg: string; n: NimNode = nil) {.magic: "NWarning", ...gcsafe,
+    raises: [], tags: [], forbids: [].}
+
+ + Writes a warning message at compile time. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator children(n: NimNode): NimNode {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Iterates over the children of the NimNode n. + Source   +Edit   + +
+
+ +
+
+
+
iterator items(n: NimNode): NimNode {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Iterates over the children of the NimNode n. + Source   +Edit   + +
+
+ +
+
+
+
iterator pairs(n: NimNode): (int, NimNode) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Iterates over the children of the NimNode n and its indices. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro dumpAstGen(s: untyped): untyped
+
+ +

Accepts a block of nim code and prints the parsed abstract syntax tree using the astGenRepr proc. Printing is done at compile time.

+

You can use this as a tool to write macros quicker by writing example outputs and then copying the snippets into the macro for modification.

+

For example:

+

dumpAstGen:
+  echo "Hello, World!"

+

Outputs:

+

nnkStmtList.newTree(
+  nnkCommand.newTree(
+    newIdentNode("echo"),
+    newLit("Hello, World!")
+  )
+)

+

Also see dumpTree and dumpLisp.

+ + Source   +Edit   + +
+
+ +
+
+
+
macro dumpLisp(s: untyped): untyped
+
+ +

Accepts a block of nim code and prints the parsed abstract syntax tree using the lispRepr proc. Printing is done at compile time.

+

You can use this as a tool to explore the Nim's abstract syntax tree and to discover what kind of nodes must be created to represent a certain expression/statement.

+

For example:

+

dumpLisp:
+  echo "Hello, World!"

+

Outputs:

+

(StmtList
+ (Command
+  (Ident "echo")
+  (StrLit "Hello, World!")))

+

Also see dumpAstGen and dumpTree.

+ + Source   +Edit   + +
+
+ +
+
+
+
macro dumpTree(s: untyped): untyped
+
+ +

Accepts a block of nim code and prints the parsed abstract syntax tree using the treeRepr proc. Printing is done at compile time.

+

You can use this as a tool to explore the Nim's abstract syntax tree and to discover what kind of nodes must be created to represent a certain expression/statement.

+

For example:

+

dumpTree:
+  echo "Hello, World!"

+

Outputs:

+

StmtList
+  Command
+    Ident "echo"
+    StrLit "Hello, World!"

+

Also see dumpAstGen and dumpLisp.

+ + Source   +Edit   + +
+
+ +
+
+
+
macro expandMacros(body: typed): untyped
+
+ +

Expands one level of macro - useful for debugging. Can be used to inspect what happens when a macro call is expanded, without altering its result.

+

For instance,

+

import std/[sugar, macros]
+
+let
+  x = 10
+  y = 20
+expandMacros:
+  dump(x + y)

+

will actually dump x + y, but at the same time will print at compile time the expansion of the dump macro, which in this case is debugEcho ["x + y", " = ", x + y].

+ + Source   +Edit   + +
+
+ +
+
+
+
macro getCustomPragmaVal(n: typed; cp: typed{nkSym}): untyped
+
+ +

Expands to value of custom pragma cp of expression n which is expected to be nnkDotExpr, a proc or a type.

+

See also hasCustomPragma.

+

template serializationKey(key: string) {.pragma.}
+type
+  MyObj {.serializationKey: "mo".} = object
+    myField {.serializationKey: "mf".}: int
+var o: MyObj
+assert(o.myField.getCustomPragmaVal(serializationKey) == "mf")
+assert(o.getCustomPragmaVal(serializationKey) == "mo")
+assert(MyObj.getCustomPragmaVal(serializationKey) == "mo")

+ + Source   +Edit   + +
+
+ +
+
+
+
macro hasCustomPragma(n: typed; cp: typed{nkSym}): untyped
+
+ +

Expands to true if expression n which is expected to be nnkDotExpr (if checking a field), a proc or a type has custom pragma cp.

+

See also getCustomPragmaVal.

+

template myAttr() {.pragma.}
+type
+  MyObj = object
+    myField {.myAttr.}: int
+
+proc myProc() {.myAttr.} = discard
+
+var o: MyObj
+assert(o.myField.hasCustomPragma(myAttr))
+assert(myProc.hasCustomPragma(myAttr))

+ + Source   +Edit   + +
+
+ +
+
+
+
macro unpackVarargs(callee: untyped; args: varargs[untyped]): untyped
+
+ + Calls callee with args unpacked as individual arguments. This is useful in 2 cases:
  • when forwarding varargs[T] for some typed T
  • +
  • when forwarding varargs[untyped] when args can potentially be empty, due to a compiler limitation
  • +
+ +

Example:

+
template call1(fun: typed; args: varargs[untyped]): untyped =
+  unpackVarargs(fun, args)
+  # when varargsLen(args) > 0: fun(args) else: fun() # this would also work
+template call2(fun: typed; args: varargs[typed]): untyped =
+  unpackVarargs(fun, args)
+proc fn1(a = 0, b = 1) = discard (a, b)
+call1(fn1, 10, 11)
+call1(fn1) # `args` is empty in this case
+if false: call2(echo, 10, 11) # would print 1011
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template findChild(n: NimNode; cond: untyped): NimNode {.dirty.}
+
+ +

Find the first child node matching condition (or nil).

+

var res = findChild(n, it.kind == nnkPostfix and
+                       it.basename.ident == ident"foo")

+ + Source   +Edit   + +
+
+ +
+
+
+
template `or`(x, y: NimNode): NimNode
+
+ +

Evaluate x and when it is not an empty node, return it. Otherwise evaluate to y. Can be used to chain several expressions to get the first expression that is not empty.

+

let node = mightBeEmpty() or mightAlsoBeEmpty() or fallbackNode

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/macros.idx b/macros.idx new file mode 100644 index 0000000000000..443ec76ff325e --- /dev/null +++ b/macros.idx @@ -0,0 +1,527 @@ +nimTitle macros macros.html module std/macros 0 +nim nnkNone macros.html#nnkNone NimNodeKind.nnkNone 32 +nim nnkEmpty macros.html#nnkEmpty NimNodeKind.nnkEmpty 32 +nim nnkIdent macros.html#nnkIdent NimNodeKind.nnkIdent 32 +nim nnkSym macros.html#nnkSym NimNodeKind.nnkSym 32 +nim nnkType macros.html#nnkType NimNodeKind.nnkType 32 +nim nnkCharLit macros.html#nnkCharLit NimNodeKind.nnkCharLit 32 +nim nnkIntLit macros.html#nnkIntLit NimNodeKind.nnkIntLit 32 +nim nnkInt8Lit macros.html#nnkInt8Lit NimNodeKind.nnkInt8Lit 32 +nim nnkInt16Lit macros.html#nnkInt16Lit NimNodeKind.nnkInt16Lit 32 +nim nnkInt32Lit macros.html#nnkInt32Lit NimNodeKind.nnkInt32Lit 32 +nim nnkInt64Lit macros.html#nnkInt64Lit NimNodeKind.nnkInt64Lit 32 +nim nnkUIntLit macros.html#nnkUIntLit NimNodeKind.nnkUIntLit 32 +nim nnkUInt8Lit macros.html#nnkUInt8Lit NimNodeKind.nnkUInt8Lit 32 +nim nnkUInt16Lit macros.html#nnkUInt16Lit NimNodeKind.nnkUInt16Lit 32 +nim nnkUInt32Lit macros.html#nnkUInt32Lit NimNodeKind.nnkUInt32Lit 32 +nim nnkUInt64Lit macros.html#nnkUInt64Lit NimNodeKind.nnkUInt64Lit 32 +nim nnkFloatLit macros.html#nnkFloatLit NimNodeKind.nnkFloatLit 32 +nim nnkFloat32Lit macros.html#nnkFloat32Lit NimNodeKind.nnkFloat32Lit 32 +nim nnkFloat64Lit macros.html#nnkFloat64Lit NimNodeKind.nnkFloat64Lit 32 +nim nnkFloat128Lit macros.html#nnkFloat128Lit NimNodeKind.nnkFloat128Lit 32 +nim nnkStrLit macros.html#nnkStrLit NimNodeKind.nnkStrLit 32 +nim nnkRStrLit macros.html#nnkRStrLit NimNodeKind.nnkRStrLit 32 +nim nnkTripleStrLit macros.html#nnkTripleStrLit NimNodeKind.nnkTripleStrLit 32 +nim nnkNilLit macros.html#nnkNilLit NimNodeKind.nnkNilLit 32 +nim nnkComesFrom macros.html#nnkComesFrom NimNodeKind.nnkComesFrom 32 +nim nnkDotCall macros.html#nnkDotCall NimNodeKind.nnkDotCall 32 +nim nnkCommand macros.html#nnkCommand NimNodeKind.nnkCommand 32 +nim nnkCall macros.html#nnkCall NimNodeKind.nnkCall 32 +nim nnkCallStrLit macros.html#nnkCallStrLit NimNodeKind.nnkCallStrLit 32 +nim nnkInfix macros.html#nnkInfix NimNodeKind.nnkInfix 32 +nim nnkPrefix macros.html#nnkPrefix NimNodeKind.nnkPrefix 32 +nim nnkPostfix macros.html#nnkPostfix NimNodeKind.nnkPostfix 32 +nim nnkHiddenCallConv macros.html#nnkHiddenCallConv NimNodeKind.nnkHiddenCallConv 32 +nim nnkExprEqExpr macros.html#nnkExprEqExpr NimNodeKind.nnkExprEqExpr 32 +nim nnkExprColonExpr macros.html#nnkExprColonExpr NimNodeKind.nnkExprColonExpr 32 +nim nnkIdentDefs macros.html#nnkIdentDefs NimNodeKind.nnkIdentDefs 32 +nim nnkVarTuple macros.html#nnkVarTuple NimNodeKind.nnkVarTuple 32 +nim nnkPar macros.html#nnkPar NimNodeKind.nnkPar 32 +nim nnkObjConstr macros.html#nnkObjConstr NimNodeKind.nnkObjConstr 32 +nim nnkCurly macros.html#nnkCurly NimNodeKind.nnkCurly 32 +nim nnkCurlyExpr macros.html#nnkCurlyExpr NimNodeKind.nnkCurlyExpr 32 +nim nnkBracket macros.html#nnkBracket NimNodeKind.nnkBracket 32 +nim nnkBracketExpr macros.html#nnkBracketExpr NimNodeKind.nnkBracketExpr 32 +nim nnkPragmaExpr macros.html#nnkPragmaExpr NimNodeKind.nnkPragmaExpr 32 +nim nnkRange macros.html#nnkRange NimNodeKind.nnkRange 32 +nim nnkDotExpr macros.html#nnkDotExpr NimNodeKind.nnkDotExpr 32 +nim nnkCheckedFieldExpr macros.html#nnkCheckedFieldExpr NimNodeKind.nnkCheckedFieldExpr 32 +nim nnkDerefExpr macros.html#nnkDerefExpr NimNodeKind.nnkDerefExpr 32 +nim nnkIfExpr macros.html#nnkIfExpr NimNodeKind.nnkIfExpr 32 +nim nnkElifExpr macros.html#nnkElifExpr NimNodeKind.nnkElifExpr 32 +nim nnkElseExpr macros.html#nnkElseExpr NimNodeKind.nnkElseExpr 32 +nim nnkLambda macros.html#nnkLambda NimNodeKind.nnkLambda 32 +nim nnkDo macros.html#nnkDo NimNodeKind.nnkDo 32 +nim nnkAccQuoted macros.html#nnkAccQuoted NimNodeKind.nnkAccQuoted 32 +nim nnkTableConstr macros.html#nnkTableConstr NimNodeKind.nnkTableConstr 32 +nim nnkBind macros.html#nnkBind NimNodeKind.nnkBind 32 +nim nnkClosedSymChoice macros.html#nnkClosedSymChoice NimNodeKind.nnkClosedSymChoice 32 +nim nnkOpenSymChoice macros.html#nnkOpenSymChoice NimNodeKind.nnkOpenSymChoice 32 +nim nnkHiddenStdConv macros.html#nnkHiddenStdConv NimNodeKind.nnkHiddenStdConv 32 +nim nnkHiddenSubConv macros.html#nnkHiddenSubConv NimNodeKind.nnkHiddenSubConv 32 +nim nnkConv macros.html#nnkConv NimNodeKind.nnkConv 32 +nim nnkCast macros.html#nnkCast NimNodeKind.nnkCast 32 +nim nnkStaticExpr macros.html#nnkStaticExpr NimNodeKind.nnkStaticExpr 32 +nim nnkAddr macros.html#nnkAddr NimNodeKind.nnkAddr 32 +nim nnkHiddenAddr macros.html#nnkHiddenAddr NimNodeKind.nnkHiddenAddr 32 +nim nnkHiddenDeref macros.html#nnkHiddenDeref NimNodeKind.nnkHiddenDeref 32 +nim nnkObjDownConv macros.html#nnkObjDownConv NimNodeKind.nnkObjDownConv 32 +nim nnkObjUpConv macros.html#nnkObjUpConv NimNodeKind.nnkObjUpConv 32 +nim nnkChckRangeF macros.html#nnkChckRangeF NimNodeKind.nnkChckRangeF 32 +nim nnkChckRange64 macros.html#nnkChckRange64 NimNodeKind.nnkChckRange64 32 +nim nnkChckRange macros.html#nnkChckRange NimNodeKind.nnkChckRange 32 +nim nnkStringToCString macros.html#nnkStringToCString NimNodeKind.nnkStringToCString 32 +nim nnkCStringToString macros.html#nnkCStringToString NimNodeKind.nnkCStringToString 32 +nim nnkAsgn macros.html#nnkAsgn NimNodeKind.nnkAsgn 32 +nim nnkFastAsgn macros.html#nnkFastAsgn NimNodeKind.nnkFastAsgn 32 +nim nnkGenericParams macros.html#nnkGenericParams NimNodeKind.nnkGenericParams 32 +nim nnkFormalParams macros.html#nnkFormalParams NimNodeKind.nnkFormalParams 32 +nim nnkOfInherit macros.html#nnkOfInherit NimNodeKind.nnkOfInherit 32 +nim nnkImportAs macros.html#nnkImportAs NimNodeKind.nnkImportAs 32 +nim nnkProcDef macros.html#nnkProcDef NimNodeKind.nnkProcDef 32 +nim nnkMethodDef macros.html#nnkMethodDef NimNodeKind.nnkMethodDef 32 +nim nnkConverterDef macros.html#nnkConverterDef NimNodeKind.nnkConverterDef 32 +nim nnkMacroDef macros.html#nnkMacroDef NimNodeKind.nnkMacroDef 32 +nim nnkTemplateDef macros.html#nnkTemplateDef NimNodeKind.nnkTemplateDef 32 +nim nnkIteratorDef macros.html#nnkIteratorDef NimNodeKind.nnkIteratorDef 32 +nim nnkOfBranch macros.html#nnkOfBranch NimNodeKind.nnkOfBranch 32 +nim nnkElifBranch macros.html#nnkElifBranch NimNodeKind.nnkElifBranch 32 +nim nnkExceptBranch macros.html#nnkExceptBranch NimNodeKind.nnkExceptBranch 32 +nim nnkElse macros.html#nnkElse NimNodeKind.nnkElse 32 +nim nnkAsmStmt macros.html#nnkAsmStmt NimNodeKind.nnkAsmStmt 32 +nim nnkPragma macros.html#nnkPragma NimNodeKind.nnkPragma 32 +nim nnkPragmaBlock macros.html#nnkPragmaBlock NimNodeKind.nnkPragmaBlock 32 +nim nnkIfStmt macros.html#nnkIfStmt NimNodeKind.nnkIfStmt 32 +nim nnkWhenStmt macros.html#nnkWhenStmt NimNodeKind.nnkWhenStmt 32 +nim nnkForStmt macros.html#nnkForStmt NimNodeKind.nnkForStmt 32 +nim nnkParForStmt macros.html#nnkParForStmt NimNodeKind.nnkParForStmt 32 +nim nnkWhileStmt macros.html#nnkWhileStmt NimNodeKind.nnkWhileStmt 32 +nim nnkCaseStmt macros.html#nnkCaseStmt NimNodeKind.nnkCaseStmt 32 +nim nnkTypeSection macros.html#nnkTypeSection NimNodeKind.nnkTypeSection 32 +nim nnkVarSection macros.html#nnkVarSection NimNodeKind.nnkVarSection 32 +nim nnkLetSection macros.html#nnkLetSection NimNodeKind.nnkLetSection 32 +nim nnkConstSection macros.html#nnkConstSection NimNodeKind.nnkConstSection 32 +nim nnkConstDef macros.html#nnkConstDef NimNodeKind.nnkConstDef 32 +nim nnkTypeDef macros.html#nnkTypeDef NimNodeKind.nnkTypeDef 32 +nim nnkYieldStmt macros.html#nnkYieldStmt NimNodeKind.nnkYieldStmt 32 +nim nnkDefer macros.html#nnkDefer NimNodeKind.nnkDefer 32 +nim nnkTryStmt macros.html#nnkTryStmt NimNodeKind.nnkTryStmt 32 +nim nnkFinally macros.html#nnkFinally NimNodeKind.nnkFinally 32 +nim nnkRaiseStmt macros.html#nnkRaiseStmt NimNodeKind.nnkRaiseStmt 32 +nim nnkReturnStmt macros.html#nnkReturnStmt NimNodeKind.nnkReturnStmt 32 +nim nnkBreakStmt macros.html#nnkBreakStmt NimNodeKind.nnkBreakStmt 32 +nim nnkContinueStmt macros.html#nnkContinueStmt NimNodeKind.nnkContinueStmt 32 +nim nnkBlockStmt macros.html#nnkBlockStmt NimNodeKind.nnkBlockStmt 32 +nim nnkStaticStmt macros.html#nnkStaticStmt NimNodeKind.nnkStaticStmt 32 +nim nnkDiscardStmt macros.html#nnkDiscardStmt NimNodeKind.nnkDiscardStmt 32 +nim nnkStmtList macros.html#nnkStmtList NimNodeKind.nnkStmtList 32 +nim nnkImportStmt macros.html#nnkImportStmt NimNodeKind.nnkImportStmt 32 +nim nnkImportExceptStmt macros.html#nnkImportExceptStmt NimNodeKind.nnkImportExceptStmt 32 +nim nnkExportStmt macros.html#nnkExportStmt NimNodeKind.nnkExportStmt 32 +nim nnkExportExceptStmt macros.html#nnkExportExceptStmt NimNodeKind.nnkExportExceptStmt 32 +nim nnkFromStmt macros.html#nnkFromStmt NimNodeKind.nnkFromStmt 32 +nim nnkIncludeStmt macros.html#nnkIncludeStmt NimNodeKind.nnkIncludeStmt 32 +nim nnkBindStmt macros.html#nnkBindStmt NimNodeKind.nnkBindStmt 32 +nim nnkMixinStmt macros.html#nnkMixinStmt NimNodeKind.nnkMixinStmt 32 +nim nnkUsingStmt macros.html#nnkUsingStmt NimNodeKind.nnkUsingStmt 32 +nim nnkCommentStmt macros.html#nnkCommentStmt NimNodeKind.nnkCommentStmt 32 +nim nnkStmtListExpr macros.html#nnkStmtListExpr NimNodeKind.nnkStmtListExpr 32 +nim nnkBlockExpr macros.html#nnkBlockExpr NimNodeKind.nnkBlockExpr 32 +nim nnkStmtListType macros.html#nnkStmtListType NimNodeKind.nnkStmtListType 32 +nim nnkBlockType macros.html#nnkBlockType NimNodeKind.nnkBlockType 32 +nim nnkWith macros.html#nnkWith NimNodeKind.nnkWith 32 +nim nnkWithout macros.html#nnkWithout NimNodeKind.nnkWithout 32 +nim nnkTypeOfExpr macros.html#nnkTypeOfExpr NimNodeKind.nnkTypeOfExpr 32 +nim nnkObjectTy macros.html#nnkObjectTy NimNodeKind.nnkObjectTy 32 +nim nnkTupleTy macros.html#nnkTupleTy NimNodeKind.nnkTupleTy 32 +nim nnkTupleClassTy macros.html#nnkTupleClassTy NimNodeKind.nnkTupleClassTy 32 +nim nnkTypeClassTy macros.html#nnkTypeClassTy NimNodeKind.nnkTypeClassTy 32 +nim nnkStaticTy macros.html#nnkStaticTy NimNodeKind.nnkStaticTy 32 +nim nnkRecList macros.html#nnkRecList NimNodeKind.nnkRecList 32 +nim nnkRecCase macros.html#nnkRecCase NimNodeKind.nnkRecCase 32 +nim nnkRecWhen macros.html#nnkRecWhen NimNodeKind.nnkRecWhen 32 +nim nnkRefTy macros.html#nnkRefTy NimNodeKind.nnkRefTy 32 +nim nnkPtrTy macros.html#nnkPtrTy NimNodeKind.nnkPtrTy 32 +nim nnkVarTy macros.html#nnkVarTy NimNodeKind.nnkVarTy 32 +nim nnkConstTy macros.html#nnkConstTy NimNodeKind.nnkConstTy 32 +nim nnkOutTy macros.html#nnkOutTy NimNodeKind.nnkOutTy 32 +nim nnkDistinctTy macros.html#nnkDistinctTy NimNodeKind.nnkDistinctTy 32 +nim nnkProcTy macros.html#nnkProcTy NimNodeKind.nnkProcTy 32 +nim nnkIteratorTy macros.html#nnkIteratorTy NimNodeKind.nnkIteratorTy 32 +nim nnkSinkAsgn macros.html#nnkSinkAsgn NimNodeKind.nnkSinkAsgn 32 +nim nnkEnumTy macros.html#nnkEnumTy NimNodeKind.nnkEnumTy 32 +nim nnkEnumFieldDef macros.html#nnkEnumFieldDef NimNodeKind.nnkEnumFieldDef 32 +nim nnkArgList macros.html#nnkArgList NimNodeKind.nnkArgList 32 +nim nnkPattern macros.html#nnkPattern NimNodeKind.nnkPattern 32 +nim nnkHiddenTryStmt macros.html#nnkHiddenTryStmt NimNodeKind.nnkHiddenTryStmt 32 +nim nnkClosure macros.html#nnkClosure NimNodeKind.nnkClosure 32 +nim nnkGotoState macros.html#nnkGotoState NimNodeKind.nnkGotoState 32 +nim nnkState macros.html#nnkState NimNodeKind.nnkState 32 +nim nnkBreakState macros.html#nnkBreakState NimNodeKind.nnkBreakState 32 +nim nnkFuncDef macros.html#nnkFuncDef NimNodeKind.nnkFuncDef 32 +nim nnkTupleConstr macros.html#nnkTupleConstr NimNodeKind.nnkTupleConstr 32 +nim nnkError macros.html#nnkError NimNodeKind.nnkError 32 +nim nnkModuleRef macros.html#nnkModuleRef NimNodeKind.nnkModuleRef 32 +nim nnkReplayAction macros.html#nnkReplayAction NimNodeKind.nnkReplayAction 32 +nim nnkNilRodNode macros.html#nnkNilRodNode NimNodeKind.nnkNilRodNode 32 +nim nnkOpenSym macros.html#nnkOpenSym NimNodeKind.nnkOpenSym 32 +nim NimNodeKind macros.html#NimNodeKind enum NimNodeKind 32 +nim NimNodeKinds macros.html#NimNodeKinds type NimNodeKinds 99 +nim ntyNone macros.html#ntyNone NimTypeKind.ntyNone 100 +nim ntyBool macros.html#ntyBool NimTypeKind.ntyBool 100 +nim ntyChar macros.html#ntyChar NimTypeKind.ntyChar 100 +nim ntyEmpty macros.html#ntyEmpty NimTypeKind.ntyEmpty 100 +nim ntyAlias macros.html#ntyAlias NimTypeKind.ntyAlias 100 +nim ntyNil macros.html#ntyNil NimTypeKind.ntyNil 100 +nim ntyExpr macros.html#ntyExpr NimTypeKind.ntyExpr 100 +nim ntyStmt macros.html#ntyStmt NimTypeKind.ntyStmt 100 +nim ntyTypeDesc macros.html#ntyTypeDesc NimTypeKind.ntyTypeDesc 100 +nim ntyGenericInvocation macros.html#ntyGenericInvocation NimTypeKind.ntyGenericInvocation 100 +nim ntyGenericBody macros.html#ntyGenericBody NimTypeKind.ntyGenericBody 100 +nim ntyGenericInst macros.html#ntyGenericInst NimTypeKind.ntyGenericInst 100 +nim ntyGenericParam macros.html#ntyGenericParam NimTypeKind.ntyGenericParam 100 +nim ntyDistinct macros.html#ntyDistinct NimTypeKind.ntyDistinct 100 +nim ntyEnum macros.html#ntyEnum NimTypeKind.ntyEnum 100 +nim ntyOrdinal macros.html#ntyOrdinal NimTypeKind.ntyOrdinal 100 +nim ntyArray macros.html#ntyArray NimTypeKind.ntyArray 100 +nim ntyObject macros.html#ntyObject NimTypeKind.ntyObject 100 +nim ntyTuple macros.html#ntyTuple NimTypeKind.ntyTuple 100 +nim ntySet macros.html#ntySet NimTypeKind.ntySet 100 +nim ntyRange macros.html#ntyRange NimTypeKind.ntyRange 100 +nim ntyPtr macros.html#ntyPtr NimTypeKind.ntyPtr 100 +nim ntyRef macros.html#ntyRef NimTypeKind.ntyRef 100 +nim ntyVar macros.html#ntyVar NimTypeKind.ntyVar 100 +nim ntySequence macros.html#ntySequence NimTypeKind.ntySequence 100 +nim ntyProc macros.html#ntyProc NimTypeKind.ntyProc 100 +nim ntyPointer macros.html#ntyPointer NimTypeKind.ntyPointer 100 +nim ntyOpenArray macros.html#ntyOpenArray NimTypeKind.ntyOpenArray 100 +nim ntyString macros.html#ntyString NimTypeKind.ntyString 100 +nim ntyCString macros.html#ntyCString NimTypeKind.ntyCString 100 +nim ntyForward macros.html#ntyForward NimTypeKind.ntyForward 100 +nim ntyInt macros.html#ntyInt NimTypeKind.ntyInt 100 +nim ntyInt8 macros.html#ntyInt8 NimTypeKind.ntyInt8 100 +nim ntyInt16 macros.html#ntyInt16 NimTypeKind.ntyInt16 100 +nim ntyInt32 macros.html#ntyInt32 NimTypeKind.ntyInt32 100 +nim ntyInt64 macros.html#ntyInt64 NimTypeKind.ntyInt64 100 +nim ntyFloat macros.html#ntyFloat NimTypeKind.ntyFloat 100 +nim ntyFloat32 macros.html#ntyFloat32 NimTypeKind.ntyFloat32 100 +nim ntyFloat64 macros.html#ntyFloat64 NimTypeKind.ntyFloat64 100 +nim ntyFloat128 macros.html#ntyFloat128 NimTypeKind.ntyFloat128 100 +nim ntyUInt macros.html#ntyUInt NimTypeKind.ntyUInt 100 +nim ntyUInt8 macros.html#ntyUInt8 NimTypeKind.ntyUInt8 100 +nim ntyUInt16 macros.html#ntyUInt16 NimTypeKind.ntyUInt16 100 +nim ntyUInt32 macros.html#ntyUInt32 NimTypeKind.ntyUInt32 100 +nim ntyUInt64 macros.html#ntyUInt64 NimTypeKind.ntyUInt64 100 +nim ntyUnused0 macros.html#ntyUnused0 NimTypeKind.ntyUnused0 100 +nim ntyUnused1 macros.html#ntyUnused1 NimTypeKind.ntyUnused1 100 +nim ntyUnused2 macros.html#ntyUnused2 NimTypeKind.ntyUnused2 100 +nim ntyVarargs macros.html#ntyVarargs NimTypeKind.ntyVarargs 100 +nim ntyUncheckedArray macros.html#ntyUncheckedArray NimTypeKind.ntyUncheckedArray 100 +nim ntyError macros.html#ntyError NimTypeKind.ntyError 100 +nim ntyBuiltinTypeClass macros.html#ntyBuiltinTypeClass NimTypeKind.ntyBuiltinTypeClass 100 +nim ntyUserTypeClass macros.html#ntyUserTypeClass NimTypeKind.ntyUserTypeClass 100 +nim ntyUserTypeClassInst macros.html#ntyUserTypeClassInst NimTypeKind.ntyUserTypeClassInst 100 +nim ntyCompositeTypeClass macros.html#ntyCompositeTypeClass NimTypeKind.ntyCompositeTypeClass 100 +nim ntyInferred macros.html#ntyInferred NimTypeKind.ntyInferred 100 +nim ntyAnd macros.html#ntyAnd NimTypeKind.ntyAnd 100 +nim ntyOr macros.html#ntyOr NimTypeKind.ntyOr 100 +nim ntyNot macros.html#ntyNot NimTypeKind.ntyNot 100 +nim ntyAnything macros.html#ntyAnything NimTypeKind.ntyAnything 100 +nim ntyStatic macros.html#ntyStatic NimTypeKind.ntyStatic 100 +nim ntyFromExpr macros.html#ntyFromExpr NimTypeKind.ntyFromExpr 100 +nim ntyOptDeprecated macros.html#ntyOptDeprecated NimTypeKind.ntyOptDeprecated 100 +nim ntyVoid macros.html#ntyVoid NimTypeKind.ntyVoid 100 +nim NimTypeKind macros.html#NimTypeKind enum NimTypeKind 100 +nim TNimTypeKinds macros.html#TNimTypeKinds type TNimTypeKinds 120 +nim nskUnknown macros.html#nskUnknown NimSymKind.nskUnknown 121 +nim nskConditional macros.html#nskConditional NimSymKind.nskConditional 121 +nim nskDynLib macros.html#nskDynLib NimSymKind.nskDynLib 121 +nim nskParam macros.html#nskParam NimSymKind.nskParam 121 +nim nskGenericParam macros.html#nskGenericParam NimSymKind.nskGenericParam 121 +nim nskTemp macros.html#nskTemp NimSymKind.nskTemp 121 +nim nskModule macros.html#nskModule NimSymKind.nskModule 121 +nim nskType macros.html#nskType NimSymKind.nskType 121 +nim nskVar macros.html#nskVar NimSymKind.nskVar 121 +nim nskLet macros.html#nskLet NimSymKind.nskLet 121 +nim nskConst macros.html#nskConst NimSymKind.nskConst 121 +nim nskResult macros.html#nskResult NimSymKind.nskResult 121 +nim nskProc macros.html#nskProc NimSymKind.nskProc 121 +nim nskFunc macros.html#nskFunc NimSymKind.nskFunc 121 +nim nskMethod macros.html#nskMethod NimSymKind.nskMethod 121 +nim nskIterator macros.html#nskIterator NimSymKind.nskIterator 121 +nim nskConverter macros.html#nskConverter NimSymKind.nskConverter 121 +nim nskMacro macros.html#nskMacro NimSymKind.nskMacro 121 +nim nskTemplate macros.html#nskTemplate NimSymKind.nskTemplate 121 +nim nskField macros.html#nskField NimSymKind.nskField 121 +nim nskEnumField macros.html#nskEnumField NimSymKind.nskEnumField 121 +nim nskForVar macros.html#nskForVar NimSymKind.nskForVar 121 +nim nskLabel macros.html#nskLabel NimSymKind.nskLabel 121 +nim nskStub macros.html#nskStub NimSymKind.nskStub 121 +nim NimSymKind macros.html#NimSymKind enum NimSymKind 121 +nim TNimSymKinds macros.html#TNimSymKinds type TNimSymKinds 130 +nim nnkMutableTy macros.html#nnkMutableTy const nnkMutableTy 133 +nim nnkSharedTy macros.html#nnkSharedTy const nnkSharedTy 134 +nim NimIdent macros.html#NimIdent object NimIdent 137 +nim NimSym macros.html#NimSym type NimSym 143 +nim nnkLiterals macros.html#nnkLiterals const nnkLiterals 149 +nim nnkCallKinds macros.html#nnkCallKinds const nnkCallKinds 151 +nim toNimIdent macros.html#toNimIdent,string proc toNimIdent(s: string): NimIdent 157 +nim `==` macros.html#==,NimIdent,NimIdent proc `==`(a, b: NimIdent): bool 161 +nim `==` macros.html#==,NimNode,NimNode proc `==`(a, b: NimNode): bool 165 +nim `==` macros.html#==,NimSym,NimSym proc `==`(a, b: NimSym): bool 169 +nim sameType macros.html#sameType,NimNode,NimNode proc sameType(a, b: NimNode): bool 175 +nim len macros.html#len,NimNode proc len(n: NimNode): int 180 +nim `[]` macros.html#[],NimNode,int proc `[]`(n: NimNode; i: int): NimNode 183 +nim `[]` macros.html#[],NimNode,BackwardsIndex proc `[]`(n: NimNode; i: BackwardsIndex): NimNode 186 +nim `[]` macros.html#[],NimNode,HSlice[T: Ordinal,U: Ordinal] proc `[]`[T, U: Ordinal](n: NimNode; x: HSlice[T, U]): seq[NimNode] 192 +nim `[]=` macros.html#[]=,NimNode,int,NimNode proc `[]=`(n: NimNode; i: int; child: NimNode) 201 +nim `[]=` macros.html#[]=,NimNode,BackwardsIndex,NimNode proc `[]=`(n: NimNode; i: BackwardsIndex; child: NimNode) 205 +nim `or` macros.html#or.t,NimNode,NimNode template `or`(x, y: NimNode): NimNode 209 +nim add macros.html#add,NimNode,NimNode proc add(father, child: NimNode): NimNode 223 +nim add macros.html#add,NimNode,varargs[NimNode] proc add(father: NimNode; children: varargs[NimNode]): NimNode 228 +nim del macros.html#del,NimNode,int,int proc del(father: NimNode; idx = 0; n = 1) 233 +nim kind macros.html#kind,NimNode proc kind(n: NimNode): NimNodeKind 236 +nim intVal macros.html#intVal,NimNode proc intVal(n: NimNode): BiggestInt 239 +nim floatVal macros.html#floatVal,NimNode proc floatVal(n: NimNode): BiggestFloat 242 +nim symKind macros.html#symKind,NimNode proc symKind(symbol: NimNode): NimSymKind 246 +nim getImpl macros.html#getImpl,NimNode proc getImpl(symbol: NimNode): NimNode 247 +nim strVal macros.html#strVal,NimNode proc strVal(n: NimNode): string 249 +nim ident macros.html#ident,NimNode proc ident(n: NimNode): NimIdent 257 +nim symbol macros.html#symbol,NimNode proc symbol(n: NimNode): NimSym 260 +nim getImpl macros.html#getImpl,NimSym proc getImpl(s: NimSym): NimNode 263 +nim `$` macros.html#$,NimIdent proc `$`(i: NimIdent): string 265 +nim `$` macros.html#$,NimSym proc `$`(s: NimSym): string 269 +nim getImplTransformed macros.html#getImplTransformed,NimNode proc getImplTransformed(symbol: NimNode): NimNode 276 +nim owner macros.html#owner,NimNode proc owner(sym: NimNode): NimNode 282 +nim isInstantiationOf macros.html#isInstantiationOf,NimNode,NimNode proc isInstantiationOf(instanceProcSym, genProcSym: NimNode): bool 293 +nim getType macros.html#getType,NimNode proc getType(n: NimNode): NimNode 298 +nim getType macros.html#getType,typedesc proc getType(n: typedesc): NimNode 306 +nim typeKind macros.html#typeKind,NimNode proc typeKind(n: NimNode): NimTypeKind 309 +nim getTypeInst macros.html#getTypeInst,NimNode proc getTypeInst(n: NimNode): NimNode 313 +nim getTypeInst macros.html#getTypeInst,typedesc proc getTypeInst(n: typedesc): NimNode 331 +nim getTypeImpl macros.html#getTypeImpl,NimNode proc getTypeImpl(n: NimNode): NimNode 334 +nim signatureHash macros.html#signatureHash,NimNode proc signatureHash(n: NimNode): string 357 +nim symBodyHash macros.html#symBodyHash,NimNode proc symBodyHash(s: NimNode): string 363 +nim getTypeImpl macros.html#getTypeImpl,typedesc proc getTypeImpl(n: typedesc): NimNode 370 +nim intVal= macros.html#intVal=,NimNode,BiggestInt proc intVal=(n: NimNode; val: BiggestInt) 373 +nim floatVal= macros.html#floatVal=,NimNode,BiggestFloat proc floatVal=(n: NimNode; val: BiggestFloat) 374 +nim symbol= macros.html#symbol=,NimNode,NimSym proc symbol=(n: NimNode; val: NimSym) 378 +nim ident= macros.html#ident=,NimNode,NimIdent proc ident=(n: NimNode; val: NimIdent) 381 +nim strVal= macros.html#strVal=,NimNode,string proc strVal=(n: NimNode; val: string) 386 +nim newNimNode macros.html#newNimNode,NimNodeKind,NimNode proc newNimNode(kind: NimNodeKind; lineInfoFrom: NimNode = nil): NimNode 396 +nim copyNimNode macros.html#copyNimNode,NimNode proc copyNimNode(n: NimNode): NimNode 405 +nim copyNimTree macros.html#copyNimTree,NimNode proc copyNimTree(n: NimNode): NimNode 418 +nim error macros.html#error,string,NimNode proc error(msg: string; n: NimNode = nil) 436 +nim warning macros.html#warning,string,NimNode proc warning(msg: string; n: NimNode = nil) 441 +nim hint macros.html#hint,string,NimNode proc hint(msg: string; n: NimNode = nil) 444 +nim newStrLitNode macros.html#newStrLitNode,string proc newStrLitNode(s: string): NimNode 447 +nim newCommentStmtNode macros.html#newCommentStmtNode,string proc newCommentStmtNode(s: string): NimNode 452 +nim newIntLitNode macros.html#newIntLitNode,BiggestInt proc newIntLitNode(i: BiggestInt): NimNode 457 +nim newFloatLitNode macros.html#newFloatLitNode,BiggestFloat proc newFloatLitNode(f: BiggestFloat): NimNode 462 +nim newIdentNode macros.html#newIdentNode,NimIdent proc newIdentNode(i: NimIdent): NimNode 469 +nim newIdentNode macros.html#newIdentNode,string proc newIdentNode(i: string): NimNode 476 +nim ident macros.html#ident,string proc ident(name: string): NimNode 480 +nim brClosed macros.html#brClosed BindSymRule.brClosed 484 +nim brOpen macros.html#brOpen BindSymRule.brOpen 484 +nim brForceOpen macros.html#brForceOpen BindSymRule.brForceOpen 484 +nim BindSymRule macros.html#BindSymRule enum BindSymRule 484 +nim bindSym macros.html#bindSym,,BindSymRule proc bindSym(ident: string | NimNode; rule: BindSymRule = brClosed): NimNode 495 +nim genSym macros.html#genSym,NimSymKind,string proc genSym(kind: NimSymKind = nskLet; ident = ""): NimNode 509 +nim callsite macros.html#callsite proc callsite(): NimNode 514 +nim toStrLit macros.html#toStrLit,NimNode proc toStrLit(n: NimNode): NimNode 519 +nim LineInfo macros.html#LineInfo object LineInfo 525 +nim `$` macros.html#$,LineInfo proc `$`(arg: LineInfo): string 529 +nim copyLineInfo macros.html#copyLineInfo,NimNode,NimNode proc copyLineInfo(arg: NimNode; info: NimNode) 542 +nim setLineInfo macros.html#setLineInfo,NimNode,string,int,int proc setLineInfo(arg: NimNode; file: string; line: int; column: int) 549 +nim setLineInfo macros.html#setLineInfo,NimNode,LineInfo proc setLineInfo(arg: NimNode; lineInfo: LineInfo) 557 +nim lineInfoObj macros.html#lineInfoObj,NimNode proc lineInfoObj(n: NimNode): LineInfo 561 +nim lineInfo macros.html#lineInfo,NimNode proc lineInfo(arg: NimNode): string 565 +nim internalErrorFlag macros.html#internalErrorFlag proc internalErrorFlag(): string 575 +nim parseExpr macros.html#parseExpr,string,string proc parseExpr(s: string; filename: string = ""): NimNode 579 +nim parseStmt macros.html#parseStmt,string,string proc parseStmt(s: string; filename: string = ""): NimNode 587 +nim getAst macros.html#getAst,untyped proc getAst(macroOrTemplate: untyped): NimNode 595 +nim quote macros.html#quote,typed,string proc quote(bl: typed; op = "``"): NimNode 604 +nim expectKind macros.html#expectKind,NimNode,NimNodeKind proc expectKind(n: NimNode; k: NimNodeKind) 687 +nim expectMinLen macros.html#expectMinLen,NimNode,int proc expectMinLen(n: NimNode; min: int) 693 +nim expectLen macros.html#expectLen,NimNode,int proc expectLen(n: NimNode; len: int) 699 +nim expectLen macros.html#expectLen,NimNode,int,int proc expectLen(n: NimNode; min, max: int) 705 +nim newTree macros.html#newTree,NimNodeKind,varargs[NimNode] proc newTree(kind: NimNodeKind; children: varargs[NimNode]): NimNode 712 +nim newCall macros.html#newCall,NimNode,varargs[NimNode] proc newCall(theProc: NimNode; args: varargs[NimNode]): NimNode 718 +nim newCall macros.html#newCall,NimIdent,varargs[NimNode] proc newCall(theProc: NimIdent; args: varargs[NimNode]): NimNode 727 +nim newCall macros.html#newCall,string,varargs[NimNode] proc newCall(theProc: string; args: varargs[NimNode]): NimNode 737 +nim newLit macros.html#newLit,char proc newLit(c: char): NimNode 745 +nim newLit macros.html#newLit,int proc newLit(i: int): NimNode 750 +nim newLit macros.html#newLit,int8 proc newLit(i: int8): NimNode 755 +nim newLit macros.html#newLit,int16 proc newLit(i: int16): NimNode 760 +nim newLit macros.html#newLit,int32 proc newLit(i: int32): NimNode 765 +nim newLit macros.html#newLit,int64 proc newLit(i: int64): NimNode 770 +nim newLit macros.html#newLit,uint proc newLit(i: uint): NimNode 775 +nim newLit macros.html#newLit,uint8 proc newLit(i: uint8): NimNode 780 +nim newLit macros.html#newLit,uint16 proc newLit(i: uint16): NimNode 785 +nim newLit macros.html#newLit,uint32 proc newLit(i: uint32): NimNode 790 +nim newLit macros.html#newLit,uint64 proc newLit(i: uint64): NimNode 795 +nim newLit macros.html#newLit,bool proc newLit(b: bool): NimNode 800 +nim newLit macros.html#newLit,string proc newLit(s: string): NimNode 804 +nim newLit macros.html#newLit,float32 proc newLit(f: float32): NimNode 816 +nim newLit macros.html#newLit,float64 proc newLit(f: float64): NimNode 821 +nim newLit macros.html#newLit proc newLit(arg: enum): NimNode 832 +nim newLit macros.html#newLit,array[N,T] proc newLit[N, T](arg: array[N, T]): NimNode 838 +nim newLit macros.html#newLit,seq[T] proc newLit[T](arg: seq[T]): NimNode 839 +nim newLit macros.html#newLit,set[T] proc newLit[T](s: set[T]): NimNode 840 +nim newLit macros.html#newLit,T proc newLit[T: tuple](arg: T): NimNode 841 +nim newLit macros.html#newLit_2 proc newLit(arg: object): NimNode 843 +nim newLit macros.html#newLit,ref. proc newLit(arg: ref object): NimNode 848 +nim nestList macros.html#nestList,NimNode,NimNode proc nestList(op: NimNode; pack: NimNode): NimNode 895 +nim nestList macros.html#nestList,NimNode,NimNode,NimNode proc nestList(op: NimNode; pack: NimNode; init: NimNode): NimNode 905 +nim eqIdent macros.html#eqIdent,string,string proc eqIdent(a: string; b: string): bool 913 +nim eqIdent macros.html#eqIdent,NimNode,string proc eqIdent(a: NimNode; b: string): bool 916 +nim eqIdent macros.html#eqIdent,string,NimNode proc eqIdent(a: string; b: NimNode): bool 922 +nim eqIdent macros.html#eqIdent,NimNode,NimNode proc eqIdent(a: NimNode; b: NimNode): bool 928 +nim treeRepr macros.html#treeRepr,NimNode proc treeRepr(n: NimNode): string 985 +nim lispRepr macros.html#lispRepr,NimNode proc lispRepr(n: NimNode; indented = false): string 992 +nim astGenRepr macros.html#astGenRepr,NimNode proc astGenRepr(n: NimNode): string 999 +nim dumpTree macros.html#dumpTree.m,untyped macro dumpTree(s: untyped): untyped 1049 +nim dumpLisp macros.html#dumpLisp.m,untyped macro dumpLisp(s: untyped): untyped 1073 +nim dumpAstGen macros.html#dumpAstGen.m,untyped macro dumpAstGen(s: untyped): untyped 1097 +nim newEmptyNode macros.html#newEmptyNode proc newEmptyNode(): NimNode 1122 +nim newStmtList macros.html#newStmtList,varargs[NimNode] proc newStmtList(stmts: varargs[NimNode]): NimNode 1126 +nim newPar macros.html#newPar,NimNode proc newPar(exprs: NimNode): NimNode 1130 +nim newPar macros.html#newPar,varargs[NimNode] proc newPar(exprs: varargs[NimNode]): NimNode 1134 +nim newBlockStmt macros.html#newBlockStmt,NimNode,NimNode proc newBlockStmt(label, body: NimNode): NimNode 1139 +nim newBlockStmt macros.html#newBlockStmt,NimNode proc newBlockStmt(body: NimNode): NimNode 1143 +nim newVarStmt macros.html#newVarStmt,NimNode,NimNode proc newVarStmt(name, value: NimNode): NimNode 1147 +nim newLetStmt macros.html#newLetStmt,NimNode,NimNode proc newLetStmt(name, value: NimNode): NimNode 1152 +nim newConstStmt macros.html#newConstStmt,NimNode,NimNode proc newConstStmt(name, value: NimNode): NimNode 1157 +nim newAssignment macros.html#newAssignment,NimNode,NimNode proc newAssignment(lhs, rhs: NimNode): NimNode 1162 +nim newDotExpr macros.html#newDotExpr,NimNode,NimNode proc newDotExpr(a, b: NimNode): NimNode 1165 +nim newColonExpr macros.html#newColonExpr,NimNode,NimNode proc newColonExpr(a, b: NimNode): NimNode 1170 +nim newIdentDefs macros.html#newIdentDefs,NimNode,NimNode proc newIdentDefs(name, kind: NimNode; default = newEmptyNode()): NimNode 1175 +nim newNilLit macros.html#newNilLit proc newNilLit(): NimNode 1206 +nim last macros.html#last,NimNode proc last(node: NimNode): NimNode 1210 +nim RoutineNodes macros.html#RoutineNodes const RoutineNodes 1215 +nim AtomicNodes macros.html#AtomicNodes const AtomicNodes 1217 +nim CallNodes macros.html#CallNodes const CallNodes 1219 +nim expectKind macros.html#expectKind,NimNode,set[NimNodeKind] proc expectKind(n: NimNode; k: set[NimNodeKind]) 1221 +nim newProc macros.html#newProc,openArray[NimNode],NimNode,NimNode proc newProc(name = newEmptyNode(); params: openArray[NimNode] = [newEmptyNode()];\n body: NimNode = newStmtList(); procType = nnkProcDef;\n pragmas: NimNode = newEmptyNode()): NimNode 1227 +nim newIfStmt macros.html#newIfStmt,varargs[tuple[NimNode,NimNode]] proc newIfStmt(branches: varargs[tuple[cond, body: NimNode]]): NimNode 1248 +nim newEnum macros.html#newEnum,NimNode,openArray[NimNode],bool,bool proc newEnum(name: NimNode; fields: openArray[NimNode]; public, pure: bool): NimNode 1262 +nim copyChildrenTo macros.html#copyChildrenTo,NimNode,NimNode proc copyChildrenTo(src, dest: NimNode) 1304 +nim name macros.html#name,NimNode proc name(someProc: NimNode): NimNode 1312 +nim name= macros.html#name=,NimNode,NimNode proc name=(someProc: NimNode; val: NimNode) 1323 +nim params macros.html#params,NimNode proc params(someProc: NimNode): NimNode 1329 +nim params= macros.html#params=,NimNode,NimNode proc params=(someProc: NimNode; params: NimNode) 1336 +nim pragma macros.html#pragma,NimNode proc pragma(someProc: NimNode): NimNode 1344 +nim pragma= macros.html#pragma=,NimNode,NimNode proc pragma=(someProc: NimNode; val: NimNode) 1352 +nim addPragma macros.html#addPragma,NimNode,NimNode proc addPragma(someProc, pragma: NimNode) 1361 +nim body macros.html#body,NimNode proc body(someProc: NimNode): NimNode 1373 +nim body= macros.html#body=,NimNode,NimNode proc body=(someProc: NimNode; val: NimNode) 1384 +nim basename macros.html#basename,NimNode proc basename(a: NimNode): NimNode 1395 +nim `$` macros.html#$,NimNode proc `$`(node: NimNode): string 1405 +nim items macros.html#items.i,NimNode iterator items(n: NimNode): NimNode 1421 +nim pairs macros.html#pairs.i,NimNode iterator pairs(n: NimNode): (int, NimNode) 1426 +nim children macros.html#children.i,NimNode iterator children(n: NimNode): NimNode 1431 +nim findChild macros.html#findChild.t,NimNode,untyped template findChild(n: NimNode; cond: untyped): NimNode 1436 +nim insert macros.html#insert,NimNode,int,NimNode proc insert(a: NimNode; pos: int; b: NimNode) 1450 +nim basename= macros.html#basename=,NimNode,string proc basename=(a: NimNode; val: string) 1465 +nim postfix macros.html#postfix,NimNode,string proc postfix(node: NimNode; op: string): NimNode 1476 +nim prefix macros.html#prefix,NimNode,string proc prefix(node: NimNode; op: string): NimNode 1479 +nim infix macros.html#infix,NimNode,string,NimNode proc infix(a: NimNode; op: string; b: NimNode): NimNode 1482 +nim unpackPostfix macros.html#unpackPostfix,NimNode proc unpackPostfix(node: NimNode): tuple[node: NimNode, op: string] 1486 +nim unpackPrefix macros.html#unpackPrefix,NimNode proc unpackPrefix(node: NimNode): tuple[node: NimNode, op: string] 1490 +nim unpackInfix macros.html#unpackInfix,NimNode proc unpackInfix(node: NimNode): tuple[left: NimNode, op: string, right: NimNode] 1494 +nim copy macros.html#copy,NimNode proc copy(node: NimNode): NimNode 1498 +nim expectIdent macros.html#expectIdent,NimNode,string proc expectIdent(n: NimNode; name: string) 1502 +nim hasArgOfName macros.html#hasArgOfName,NimNode,string proc hasArgOfName(params: NimNode; name: string): bool 1509 +nim addIdentIfAbsent macros.html#addIdentIfAbsent,NimNode,string proc addIdentIfAbsent(dest: NimNode; ident: string) 1517 +nim boolVal macros.html#boolVal,NimNode proc boolVal(n: NimNode): bool 1529 +nim nodeID macros.html#nodeID,NimNode proc nodeID(n: NimNode): int 1533 +nim expandMacros macros.html#expandMacros.m,typed macro expandMacros(body: typed): untyped 1538 +nim hasCustomPragma macros.html#hasCustomPragma.m,typed, macro hasCustomPragma(n: typed; cp: typed{nkSym}): untyped 1655 +nim getCustomPragmaVal macros.html#getCustomPragmaVal.m,typed, macro getCustomPragmaVal(n: typed; cp: typed{nkSym}): untyped 1680 +nim unpackVarargs macros.html#unpackVarargs.m,untyped,varargs[untyped] macro unpackVarargs(callee: untyped; args: varargs[untyped]): untyped 1713 +nim getProjectPath macros.html#getProjectPath proc getProjectPath(): string 1733 +nim getSize macros.html#getSize,NimNode proc getSize(arg: NimNode): int 1758 +nim getAlign macros.html#getAlign,NimNode proc getAlign(arg: NimNode): int 1762 +nim getOffset macros.html#getOffset,NimNode proc getOffset(arg: NimNode): int 1767 +nim isExported macros.html#isExported,NimNode proc isExported(n: NimNode): bool 1774 +nim extractDocCommentsAndRunnables macros.html#extractDocCommentsAndRunnables,NimNode proc extractDocCommentsAndRunnables(n: NimNode): NimNode 1777 +idx AST macros.html#ast_1 Module macros 0 +heading The AST in Nim macros.html#the-ast-in-nim The AST in Nim 0 +heading Leaf nodes/Atoms macros.html#leaf-nodesslashatoms Leaf nodes/Atoms 0 +heading Calls/expressions macros.html#callsslashexpressions Calls/expressions 0 +heading Command call macros.html#callsslashexpressions-command-call Command call 0 +heading Call with () macros.html#callsslashexpressions-call-with Call with () 0 +heading Infix operator call macros.html#callsslashexpressions-infix-operator-call Infix operator call 0 +heading Prefix operator call macros.html#callsslashexpressions-prefix-operator-call Prefix operator call 0 +heading Postfix operator call macros.html#callsslashexpressions-postfix-operator-call Postfix operator call 0 +heading Call with named arguments macros.html#callsslashexpressions-call-with-named-arguments Call with named arguments 0 +heading Call with raw string literal macros.html#callsslashexpressions-call-with-raw-string-literal Call with raw string literal 0 +heading Dereference operator [] macros.html#callsslashexpressions-dereference-operator Dereference operator [] 0 +heading Addr operator macros.html#callsslashexpressions-addr-operator Addr operator 0 +heading Cast operator macros.html#callsslashexpressions-cast-operator Cast operator 0 +heading Object access operator . macros.html#callsslashexpressions-object-access-operator-dot Object access operator . 0 +heading Array access operator [] macros.html#callsslashexpressions-array-access-operator Array access operator [] 0 +heading Parentheses macros.html#callsslashexpressions-parentheses Parentheses 0 +heading Tuple Constructors macros.html#callsslashexpressions-tuple-constructors Tuple Constructors 0 +heading Curly braces macros.html#callsslashexpressions-curly-braces Curly braces 0 +heading Brackets macros.html#callsslashexpressions-brackets Brackets 0 +heading Ranges macros.html#callsslashexpressions-ranges Ranges 0 +heading If expression macros.html#callsslashexpressions-if-expression If expression 0 +heading Documentation Comments macros.html#callsslashexpressions-documentation-comments Documentation Comments 0 +heading Pragmas macros.html#callsslashexpressions-pragmas Pragmas 0 +heading Statements macros.html#statements Statements 0 +heading If statement macros.html#statements-if-statement If statement 0 +heading When statement macros.html#statements-when-statement When statement 0 +heading Assignment macros.html#statements-assignment Assignment 0 +heading Statement list macros.html#statements-statement-list Statement list 0 +heading Case statement macros.html#statements-case-statement Case statement 0 +heading While statement macros.html#statements-while-statement While statement 0 +heading For statement macros.html#statements-for-statement For statement 0 +heading Try statement macros.html#statements-try-statement Try statement 0 +heading Return statement macros.html#statements-return-statement Return statement 0 +heading Yield statement macros.html#statements-yield-statement Yield statement 0 +heading Discard statement macros.html#statements-discard-statement Discard statement 0 +heading Continue statement macros.html#statements-continue-statement Continue statement 0 +heading Break statement macros.html#statements-break-statement Break statement 0 +heading Block statement macros.html#statements-block-statement Block statement 0 +heading Asm statement macros.html#statements-asm-statement Asm statement 0 +heading Import section macros.html#statements-import-section Import section 0 +heading From statement macros.html#statements-from-statement From statement 0 +heading Export statement macros.html#statements-export-statement Export statement 0 +heading Include statement macros.html#statements-include-statement Include statement 0 +heading Var section macros.html#statements-var-section Var section 0 +heading Let section macros.html#statements-let-section Let section 0 +heading Const section macros.html#statements-const-section Const section 0 +heading Type section macros.html#statements-type-section Type section 0 +heading Mixin statement macros.html#statements-mixin-statement Mixin statement 0 +heading Bind statement macros.html#statements-bind-statement Bind statement 0 +heading Procedure declaration macros.html#statements-procedure-declaration Procedure declaration 0 +heading Iterator declaration macros.html#statements-iterator-declaration Iterator declaration 0 +heading Converter declaration macros.html#statements-converter-declaration Converter declaration 0 +heading Template declaration macros.html#statements-template-declaration Template declaration 0 +heading Macro declaration macros.html#statements-macro-declaration Macro declaration 0 +heading Hidden Standard Conversion macros.html#statements-hidden-standard-conversion Hidden Standard Conversion 0 +heading Special node kinds macros.html#special-node-kinds Special node kinds 0 +idx type macros.html#type_1 Special node kinds 0 +idx type macros.html#type_2 Special node kinds 0 +idx type macros.html#type_3 Special node kinds 0 +nimgrp gettype macros.html#getType-procs-all proc 298 +nimgrp nestlist macros.html#nestList-procs-all proc 895 +nimgrp setlineinfo macros.html#setLineInfo-procs-all proc 549 +nimgrp [] macros.html#[]-procs-all proc 183 +nimgrp newlit macros.html#newLit-procs-all proc 745 +nimgrp gettypeimpl macros.html#getTypeImpl-procs-all proc 334 +nimgrp newpar macros.html#newPar-procs-all proc 1130 +nimgrp == macros.html#==-procs-all proc 161 +nimgrp gettypeinst macros.html#getTypeInst-procs-all proc 313 +nimgrp expectlen macros.html#expectLen-procs-all proc 699 +nimgrp getimpl macros.html#getImpl-procs-all proc 247 +nimgrp eqident macros.html#eqIdent-procs-all proc 913 +nimgrp []= macros.html#[]=-procs-all proc 201 +nimgrp ident macros.html#ident-procs-all proc 257 +nimgrp newidentnode macros.html#newIdentNode-procs-all proc 469 +nimgrp newblockstmt macros.html#newBlockStmt-procs-all proc 1139 +nimgrp add macros.html#add-procs-all proc 223 +nimgrp newcall macros.html#newCall-procs-all proc 718 +nimgrp expectkind macros.html#expectKind-procs-all proc 687 +nimgrp $ macros.html#$-procs-all proc 265 diff --git a/manual.html b/manual.html new file mode 100644 index 0000000000000..0ff976d5658fa --- /dev/null +++ b/manual.html @@ -0,0 +1,5099 @@ + + + + + + + +Nim Manual + + + + + + + + + + + + + + + + +
+
+

Nim Manual

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + + +
+
+ Source   +Edit   + +
+ +

+ +
Authors:Andreas Rumpf, Zahary Karadjov
Version:2.2.1

"Complexity" seems to be a lot like "energy": you can transfer it from the end-user to one/some of the other players, but the total amount seems to remain pretty much constant for a given task. -- Ran

+ +

About this document

Note: This document is a draft! Several of Nim's features may need more precise wording. This manual is constantly evolving into a proper specification.

+

Note: The experimental features of Nim are covered here.

+

Note: Assignments, moves, and destruction are specified in the destructors document.

+

This document describes the lexis, the syntax, and the semantics of the Nim language.

+

To learn how to compile Nim programs and generate documentation see the Compiler User Guide and the DocGen Tools Guide.

+

The language constructs are explained using an extended BNF, in which (a)* means 0 or more a's, a+ means 1 or more a's, and (a)? means an optional a. Parentheses may be used to group elements.

+

& is the lookahead operator; &a means that an a is expected but not consumed. It will be consumed in the following rule.

+

The |, / symbols are used to mark alternatives and have the lowest precedence. / is the ordered choice that requires the parser to try the alternatives in the given order. / is often used to ensure the grammar is not ambiguous.

+

Non-terminals start with a lowercase letter, abstract terminal symbols are in UPPERCASE. Verbatim terminal symbols (including keywords) are quoted with '. An example:

+
ifStmt = 'if' expr ':' stmts ('elif' expr ':' stmts)* ('else' stmts)?
+

The binary ^* operator is used as a shorthand for 0 or more occurrences separated by its second argument; likewise ^+ means 1 or more occurrences: a ^+ b is short for a (b a)* and a ^* b is short for (a (b a)*)?. Example:

+
arrayConstructor = '[' expr ^* ',' ']'
+

Other parts of Nim, like scoping rules or runtime semantics, are described informally.

+ +

Definitions

Nim code specifies a computation that acts on a memory consisting of components called locations. A variable is basically a name for a location. Each variable and location is of a certain type. The variable's type is called static type, the location's type is called dynamic type. If the static type is not the same as the dynamic type, it is a super-type or subtype of the dynamic type.

+

An identifier is a symbol declared as a name for a variable, type, procedure, etc. The region of the program over which a declaration applies is called the scope of the declaration. Scopes can be nested. The meaning of an identifier is determined by the smallest enclosing scope in which the identifier is declared unless overloading resolution rules suggest otherwise.

+

An expression specifies a computation that produces a value or location. Expressions that produce locations are called l-values. An l-value can denote either a location or the value the location contains, depending on the context.

+

A Nim program consists of one or more text source files containing Nim code. It is processed by a Nim compiler into an executable. The nature of this executable depends on the compiler implementation; it may, for example, be a native binary or JavaScript source code.

+

In a typical Nim program, most of the code is compiled into the executable. However, some code may be executed at compile-time. This can include constant expressions, macro definitions, and Nim procedures used by macro definitions. Most of the Nim language is supported at compile-time, but there are some restrictions -- see Restrictions on Compile-Time Execution for details. We use the term runtime to cover both compile-time execution and code execution in the executable.

+

The compiler parses Nim source code into an internal data structure called the abstract syntax tree (AST). Then, before executing the code or compiling it into the executable, it transforms the AST through semantic analysis. This adds semantic information such as expression types, identifier meanings, and in some cases expression values. An error detected during semantic analysis is called a static error. Errors described in this manual are static errors when not otherwise specified.

+

A panic is an error that the implementation detects and reports at runtime. The method for reporting such errors is via raising exceptions or dying with a fatal error. However, the implementation provides a means to disable these runtime checks. See the section Pragmas for details.

+

Whether a panic results in an exception or in a fatal error is implementation specific. Thus, the following program is invalid; even though the code purports to catch the IndexDefect from an out-of-bounds array access, the compiler may instead choose to allow the program to die with a fatal error.

+

var a: array[0..1, char]
+let i = 5
+try:
+  a[i] = 'N'
+except IndexDefect:
+  echo "invalid index"

+

The current implementation allows switching between these different behaviors via --panics:on|off. When panics are turned on, the program dies with a panic, if they are turned off the runtime errors are turned into exceptions. The benefit of --panics:on is that it produces smaller binary code and the compiler has more freedom to optimize the code.

+

An unchecked runtime error is an error that is not guaranteed to be detected and can cause the subsequent behavior of the computation to be arbitrary. Unchecked runtime errors cannot occur if only safe language features are used and if no runtime checks are disabled.

+

A constant expression is an expression whose value can be computed during a semantic analysis of the code in which it appears. It is never an l-value and never has side effects. Constant expressions are not limited to the capabilities of semantic analysis, such as constant folding; they can use all Nim language features that are supported for compile-time execution. Since constant expressions can be used as an input to semantic analysis (such as for defining array bounds), this flexibility requires the compiler to interleave semantic analysis and compile-time code execution.

+

It is mostly accurate to picture semantic analysis proceeding top to bottom and left to right in the source code, with compile-time code execution interleaved when necessary to compute values that are required for subsequent semantic analysis. We will see much later in this document that macro invocation not only requires this interleaving, but also creates a situation where semantic analysis does not entirely proceed top to bottom and left to right.

+ +

Lexical Analysis

+

Encoding

All Nim source files are in the UTF-8 encoding (or its ASCII subset). Other encodings are not supported. Any of the standard platform line termination sequences can be used - the Unix form using ASCII LF (linefeed), the Windows form using the ASCII sequence CR LF (return followed by linefeed), or the old Macintosh form using the ASCII CR (return) character. All of these forms can be used equally, regardless of the platform.

+ +

Indentation

Nim's standard grammar describes an indentation sensitive language. This means that all the control structures are recognized by indentation. Indentation consists only of spaces; tabulators are not allowed.

+

The indentation handling is implemented as follows: The lexer annotates the following token with the preceding number of spaces; indentation is not a separate token. This trick allows parsing of Nim with only 1 token of lookahead.

+

The parser uses a stack of indentation levels: the stack consists of integers counting the spaces. The indentation information is queried at strategic places in the parser but ignored otherwise: The pseudo-terminal IND{>} denotes an indentation that consists of more spaces than the entry at the top of the stack; IND{=} an indentation that has the same number of spaces. DED is another pseudo terminal that describes the action of popping a value from the stack, IND{>} then implies to push onto the stack.

+

With this notation we can now easily define the core of the grammar: A block of statements (simplified example):

+
ifStmt = 'if' expr ':' stmt
+         (IND{=} 'elif' expr ':' stmt)*
+         (IND{=} 'else' ':' stmt)?
+
+simpleStmt = ifStmt / ...
+
+stmt = IND{>} stmt ^+ IND{=} DED  # list of statements
+     / simpleStmt                 # or a simple statement
+ +

Comments

Comments start anywhere outside a string or character literal with the hash character #. Comments consist of a concatenation of comment pieces. A comment piece starts with # and runs until the end of the line. The end of line characters belong to the piece. If the next line only consists of a comment piece with no other tokens between it and the preceding one, it does not start a new comment:

+

i = 0     # This is a single comment over multiple lines.
+  # The lexer merges these two pieces.
+  # The comment continues here.

+

Documentation comments are comments that start with two ##. Documentation comments are tokens; they are only allowed at certain places in the input file as they belong to the syntax tree.

+ +

Multiline comments

Starting with version 0.13.0 of the language Nim supports multiline comments. They look like:

+

#[Comment here.
+Multiple lines
+are not a problem.]#

+

Multiline comments support nesting:

+

#[  #[ Multiline comment in already
+   commented out code. ]#
+proc p[T](x: T) = discard
+]#

+

Multiline documentation comments also exist and support nesting too:

+

proc foo =
+  ##[Long documentation comment
+     here.
+  ]##

+

You can also use the discard statement together with triple quoted string literals to create multiline comments:

+

discard """ You can have any Nim code text commented
+out inside this with no indentation restrictions.
+      yes("May I ask a pointless question?") """

+

This was how multiline comments were done before version 0.13.0, and it is used to provide specifications to testament test framework.

+ +

Identifiers & Keywords

Identifiers in Nim can be any string of letters, digits and underscores, with the following restrictions:

+
  • begins with a letter
  • +
  • does not end with an underscore _
  • +
  • two immediate following underscores __ are not allowed:

    +

    letter ::= 'A'..'Z' | 'a'..'z' | '\x80'..'\xff'
    +digit ::= '0'..'9'
    +IDENTIFIER ::= letter ( ['_'] (letter | digit) )*

    +
  • +
+

Currently, any Unicode character with an ordinal value > 127 (non-ASCII) is classified as a letter and may thus be part of an identifier but later versions of the language may assign some Unicode characters to belong to the operator characters instead.

+

The following keywords are reserved and cannot be used as identifiers:

+

addr and as asm
+bind block break
+case cast concept const continue converter
+defer discard distinct div do
+elif else end enum except export
+finally for from func
+if import in include interface is isnot iterator
+let
+macro method mixin mod
+nil not notin
+object of or out
+proc ptr
+raise ref return
+shl shr static
+template try tuple type
+using
+var
+when while
+xor
+yield
+

+

Some keywords are unused; they are reserved for future developments of the language.

+ +

Identifier equality

Two identifiers are considered equal if the following algorithm returns true:

+

proc sameIdentifier(a, b: string): bool =
+  a[0] == b[0] and
+    a.replace("_", "").toLowerAscii == b.replace("_", "").toLowerAscii

+

That means only the first letters are compared in a case-sensitive manner. Other letters are compared case-insensitively within the ASCII range and underscores are ignored.

+

This rather unorthodox way to do identifier comparisons is called partial case-insensitivity and has some advantages over the conventional case sensitivity:

+

It allows programmers to mostly use their own preferred spelling style, be it humpStyle or snake_style, and libraries written by different programmers cannot use incompatible conventions. A Nim-aware editor or IDE can show the identifiers as preferred. Another advantage is that it frees the programmer from remembering the exact spelling of an identifier. The exception with respect to the first letter allows common code like var foo: Foo to be parsed unambiguously.

+

Note that this rule also applies to keywords, meaning that notin is the same as notIn and not_in (all-lowercase version (notin, isnot) is the preferred way of writing keywords).

+

Historically, Nim was a fully style-insensitive language. This meant that it was not case-sensitive and underscores were ignored and there was not even a distinction between foo and Foo.

+ +

Keywords as identifiers

If a keyword is enclosed in backticks it loses its keyword property and becomes an ordinary identifier.

+

Examples

+

var `var` = "Hello Stropping"

+

type Obj = object
+  `type`: int
+
+let `object` = Obj(`type`: 9)
+assert `object` is Obj
+assert `object`.`type` == 9
+
+var `var` = 42
+let `let` = 8
+assert `var` + `let` == 50
+
+const `assert` = true
+assert `assert`

+ +

String literals

Terminal symbol in the grammar: STR_LIT.

+

String literals can be delimited by matching double quotes, and can contain the following escape sequences:

+ + + + + + + + + + + + + + + + + +
Escape sequenceMeaning
\pplatform specific newline: CRLF on Windows, LF on Unix
\r, \ccarriage return
\n, \lline feed (often called newline)
\fform feed
\ttabulator
\vvertical tabulator
\\backslash
\"quotation mark
\'apostrophe
\ '0'..'9'+character with decimal value d; all decimal digits directly following are used for the character
\aalert
\bbackspace
\eescape [ESC]
\x HHcharacter with hex value HH; exactly two hex digits are allowed
\u HHHHunicode codepoint with hex value HHHH; exactly four hex digits are allowed
\u {H+}unicode codepoint; all hex digits enclosed in {} are used for the codepoint

Strings in Nim may contain any 8-bit value, even embedded zeros. However, some operations may interpret the first binary zero as a terminator.

+ +

Triple quoted string literals

Terminal symbol in the grammar: TRIPLESTR_LIT.

+

String literals can also be delimited by three double quotes """ ... """. Literals in this form may run for several lines, may contain " and do not interpret any escape sequences. For convenience, when the opening """ is followed by a newline (there may be whitespace between the opening """ and the newline), the newline (and the preceding whitespace) is not included in the string. The ending of the string literal is defined by the pattern """[^"], so this:

+

""""long string within quotes""""

+

Produces:

+
"long string within quotes"
+ +

Raw string literals

Terminal symbol in the grammar: RSTR_LIT.

+

There are also raw string literals that are preceded with the letter r (or R) and are delimited by matching double quotes (just like ordinary string literals) and do not interpret the escape sequences. This is especially convenient for regular expressions or Windows paths:

+

var f = openFile(r"C:\texts\text.txt") # a raw string, so ``\t`` is no tab

+

To produce a single " within a raw string literal, it has to be doubled:

+

r"a""b"

+

Produces:

+
a"b
+

r"""" is not possible with this notation, because the three leading quotes introduce a triple quoted string literal. r""" is the same as """ since triple quoted string literals do not interpret escape sequences either.

+ +

Generalized raw string literals

Terminal symbols in the grammar: GENERALIZED_STR_LIT, GENERALIZED_TRIPLESTR_LIT.

+

The construct identifier"string literal" (without whitespace between the identifier and the opening quotation mark) is a generalized raw string literal. It is a shortcut for the construct identifier(r"string literal"), so it denotes a routine call with a raw string literal as its only argument. Generalized raw string literals are especially convenient for embedding mini languages directly into Nim (for example regular expressions).

+

The construct identifier"""string literal""" exists too. It is a shortcut for identifier("""string literal""").

+ +

Character literals

Character literals are enclosed in single quotes '' and can contain the same escape sequences as strings - with one exception: the platform dependent newline (\p) is not allowed as it may be wider than one character (it can be the pair CR/LF). Here are the valid escape sequences for character literals:

+ + + + + + + + + + + + + + +
Escape sequenceMeaning
\r, \ccarriage return
\n, \lline feed
\fform feed
\ttabulator
\vvertical tabulator
\\backslash
\"quotation mark
\'apostrophe
\ '0'..'9'+character with decimal value d; all decimal digits directly following are used for the character
\aalert
\bbackspace
\eescape [ESC]
\x HHcharacter with hex value HH; exactly two hex digits are allowed

A character is not a Unicode character but a single byte.

+

Rationale: It enables the efficient support of array[char, int] or set[char].

+

The Rune type can represent any Unicode character. Rune is declared in the unicode module.

+

A character literal that does not end in ' is interpreted as ' if there is a preceding backtick token. There must be no whitespace between the preceding backtick token and the character literal. This special case ensures that a declaration like proc `'customLiteral`(s: string) is valid. proc `'customLiteral`(s: string) is the same as proc `'\''customLiteral`(s: string).

+

See also custom numeric literals.

+ +

Numeric literals

Numeric literals have the form:

+
hexdigit = digit | 'A'..'F' | 'a'..'f'
+octdigit = '0'..'7'
+bindigit = '0'..'1'
+unary_minus = '-' # See the section about unary minus
+HEX_LIT = unary_minus? '0' ('x' | 'X' ) hexdigit ( ['_'] hexdigit )*
+DEC_LIT = unary_minus? digit ( ['_'] digit )*
+OCT_LIT = unary_minus? '0' 'o' octdigit ( ['_'] octdigit )*
+BIN_LIT = unary_minus? '0' ('b' | 'B' ) bindigit ( ['_'] bindigit )*
+
+INT_LIT = HEX_LIT
+        | DEC_LIT
+        | OCT_LIT
+        | BIN_LIT
+
+INT8_LIT = INT_LIT ['\''] ('i' | 'I') '8'
+INT16_LIT = INT_LIT ['\''] ('i' | 'I') '16'
+INT32_LIT = INT_LIT ['\''] ('i' | 'I') '32'
+INT64_LIT = INT_LIT ['\''] ('i' | 'I') '64'
+
+UINT_LIT = INT_LIT ['\''] ('u' | 'U')
+UINT8_LIT = INT_LIT ['\''] ('u' | 'U') '8'
+UINT16_LIT = INT_LIT ['\''] ('u' | 'U') '16'
+UINT32_LIT = INT_LIT ['\''] ('u' | 'U') '32'
+UINT64_LIT = INT_LIT ['\''] ('u' | 'U') '64'
+
+exponent = ('e' | 'E' ) ['+' | '-'] digit ( ['_'] digit )*
+FLOAT_LIT = unary_minus? digit (['_'] digit)* (('.' digit (['_'] digit)* [exponent]) |exponent)
+FLOAT32_SUFFIX = ('f' | 'F') ['32']
+FLOAT32_LIT = HEX_LIT '\'' FLOAT32_SUFFIX
+            | (FLOAT_LIT | DEC_LIT | OCT_LIT | BIN_LIT) ['\''] FLOAT32_SUFFIX
+FLOAT64_SUFFIX = ( ('f' | 'F') '64' ) | 'd' | 'D'
+FLOAT64_LIT = HEX_LIT '\'' FLOAT64_SUFFIX
+            | (FLOAT_LIT | DEC_LIT | OCT_LIT | BIN_LIT) ['\''] FLOAT64_SUFFIX
+
+CUSTOM_NUMERIC_LIT = (FLOAT_LIT | INT_LIT) '\'' CUSTOM_NUMERIC_SUFFIX
+
+# CUSTOM_NUMERIC_SUFFIX is any Nim identifier that is not
+# a pre-defined type suffix.
+

As can be seen in the productions, numeric literals can contain underscores for readability. Integer and floating-point literals may be given in decimal (no prefix), binary (prefix 0b), octal (prefix 0o), and hexadecimal (prefix 0x) notation.

+

The fact that the unary minus - in a number literal like -1 is considered to be part of the literal is a late addition to the language. The rationale is that an expression -128'i8 should be valid and without this special case, this would be impossible -- 128 is not a valid int8 value, only -128 is.

+

For the unary_minus rule there are further restrictions that are not covered in the formal grammar. For - to be part of the number literal the immediately preceding character has to be in the set {' ', '\t', '\n', '\r', ',', ';', '(', '[', '{'}. This set was designed to cover most cases in a natural manner.

+

In the following examples, -1 is a single token:

+

echo -1
+echo(-1)
+echo [-1]
+echo 3,-1
+
+"abc";-1

+

In the following examples, -1 is parsed as two separate tokens (as - 1):

+

echo x-1
+echo (int)-1
+echo [a]-1
+"abc"-1

+

The suffix starting with an apostrophe (''') is called a type suffix. Literals without a type suffix are of an integer type unless the literal contains a dot or E|e in which case it is of type float. This integer type is int if the literal is in the range low(int32)..high(int32), otherwise it is int64. For notational convenience, the apostrophe of a type suffix is optional if it is not ambiguous (only hexadecimal floating-point literals with a type suffix can be ambiguous).

+

The pre-defined type suffixes are:

+ + + + + + + + + + + + + + +
Type SuffixResulting type of literal
'i8int8
'i16int16
'i32int32
'i64int64
'uuint
'u8uint8
'u16uint16
'u32uint32
'u64uint64
'ffloat32
'dfloat64
'f32float32
'f64float64

Floating-point literals may also be in binary, octal or hexadecimal notation: 0B0_10001110100_0000101001000111101011101111111011000101001101001001'f64 is approximately 1.72826e35 according to the IEEE floating-point standard.

+

Literals must match the datatype, for example, 333'i8 is an invalid literal. Non-base-10 literals are used mainly for flags and bit pattern representations, therefore the checking is done on bit width and not on value range. Hence: 0b10000000'u8 == 0x80'u8 == 128, but, 0b10000000'i8 == 0x80'i8 == -1 instead of causing an overflow error.

+ +

Custom numeric literals

If the suffix is not predefined, then the suffix is assumed to be a call to a proc, template, macro or other callable identifier that is passed the string containing the literal. The callable identifier needs to be declared with a special ' prefix:

+

import std/strutils
+type u4 = distinct uint8 # a 4-bit unsigned integer aka "nibble"
+proc `'u4`(n: string): u4 =
+  # The leading ' is required.
+  result = (parseInt(n) and 0x0F).u4
+
+var x = 5'u4

+

More formally, a custom numeric literal 123'custom is transformed to r"123".'custom in the parsing step. There is no AST node kind that corresponds to this transformation. The transformation naturally handles the case that additional parameters are passed to the callee:

+

import std/strutils
+type u4 = distinct uint8 # a 4-bit unsigned integer aka "nibble"
+proc `'u4`(n: string; moreData: int): u4 =
+  result = (parseInt(n) and 0x0F).u4
+
+var x = 5'u4(123)

+

Custom numeric literals are covered by the grammar rule named CUSTOM_NUMERIC_LIT. A custom numeric literal is a single token.

+ +

Operators

Nim allows user defined operators. An operator is any combination of the following characters:

+
=     +     -     *     /     <     >
+@     $     ~     &     %     |
+!     ?     ^     .     :     \
+

(The grammar uses the terminal OPR to refer to operator symbols as defined here.)

+

These keywords are also operators: and or not xor shl shr div mod in notin is isnot of as from.

+

., =, :, :: are not available as general operators; they are used for other notational purposes.

+

*: is as a special case treated as the two tokens * and : (to support var v*: T).

+

The not keyword is always a unary operator, a not b is parsed as a(not b), not as (a) not (b).

+ +

Unicode Operators

These Unicode operators are also parsed as operators:

+
∙ ∘ × ★ ⊗ ⊘ ⊙ ⊛ ⊠ ⊡ ∩ ∧ ⊓   # same priority as * (multiplication)
+± ⊕ ⊖ ⊞ ⊟ ∪ ∨ ⊔             # same priority as + (addition)
+

Unicode operators can be combined with non-Unicode operator symbols. The usual precedence extensions then apply, for example, = is an assignment like operator just like *= is.

+

No Unicode normalization step is performed.

+ +

Other tokens

The following strings denote other tokens:

+
`   (    )     {    }     [    ]    ,  ;   [.    .]  {.   .}  (.  .)  [:
+

The slice operator .. takes precedence over other tokens that contain a dot: {..} are the three tokens {, .., } and not the two tokens {., .}.

+ +

Syntax

This section lists Nim's standard syntax. How the parser handles the indentation is already described in the Lexical Analysis section.

+

Nim allows user-definable operators. Binary operators have 11 different levels of precedence.

+ +

Associativity

Binary operators whose first character is ^ are right-associative, all other binary operators are left-associative.

+

proc `^/`(x, y: float): float =
+  # a right-associative division operator
+  result = x / y
+echo 12 ^/ 4 ^/ 8 # 24.0 (4 / 8 = 0.5, then 12 / 0.5 = 24.0)
+echo 12  / 4  / 8 # 0.375 (12 / 4 = 3.0, then 3 / 8 = 0.375)

+ +

Precedence

Unary operators always bind stronger than any binary operator: $a + b is ($a) + b and not $(a + b).

+

If a unary operator's first character is @ it is a sigil-like operator which binds stronger than a primarySuffix: @x.abc is parsed as (@x).abc whereas $x.abc is parsed as $(x.abc).

+

For binary operators that are not keywords, the precedence is determined by the following rules:

+

Operators ending in either ->, ~> or => are called arrow like, and have the lowest precedence of all operators.

+

If the operator ends with = and its first character is none of <, >, !, =, ~, ?, it is an assignment operator which has the second-lowest precedence.

+

Otherwise, precedence is determined by the first character.

+ + + + + + + + + + + + +
Precedence levelOperatorsFirst characterTerminal symbol
10 (highest)$ ^OP10
9* / div mod shl shr %* % \ /OP9
8+ -+ - ~ |OP8
7&&OP7
6...OP6
5== <= < >= > != in notin is isnot not of as from= < > !OP5
4andOP4
3or xorOP3
2@ : ?OP2
1assignment operator (like +=, *=)OP1
0 (lowest)arrow like operator (like ->, =>)OP0

Whether an operator is used as a prefix operator is also affected by preceding whitespace (this parsing change was introduced with version 0.13.0):

+

echo $foo
+# is parsed as
+echo($foo)

+

Spacing also determines whether (a, b) is parsed as an argument list of a call or whether it is parsed as a tuple constructor:

+

echo(1, 2) # pass 1 and 2 to echo

+

echo (1, 2) # pass the tuple (1, 2) to echo

+ +

Dot-like operators

Terminal symbol in the grammar: DOTLIKEOP.

+

Dot-like operators are operators starting with ., but not with .., for e.g. .?; they have the same precedence as ., so that a.?b.c is parsed as (a.?b).c instead of a.?(b.c).

+ +

Grammar

The grammar's start symbol is module.

+
# This file is generated by compiler/parser.nim.
+module = complexOrSimpleStmt ^* (';' / IND{=})
+comma = ',' COMMENT?
+semicolon = ';' COMMENT?
+colon = ':' COMMENT?
+colcom = ':' COMMENT?
+operator =  OP0 | OP1 | OP2 | OP3 | OP4 | OP5 | OP6 | OP7 | OP8 | OP9
+         | 'or' | 'xor' | 'and'
+         | 'is' | 'isnot' | 'in' | 'notin' | 'of' | 'as' | 'from'
+         | 'div' | 'mod' | 'shl' | 'shr' | 'not' | '..'
+prefixOperator = operator
+optInd = COMMENT? IND?
+optPar = (IND{>} | IND{=})?
+simpleExpr = arrowExpr (OP0 optInd arrowExpr)* pragma?
+arrowExpr = assignExpr (OP1 optInd assignExpr)*
+assignExpr = orExpr (OP2 optInd orExpr)*
+orExpr = andExpr (OP3 optInd andExpr)*
+andExpr = cmpExpr (OP4 optInd cmpExpr)*
+cmpExpr = sliceExpr (OP5 optInd sliceExpr)*
+sliceExpr = ampExpr (OP6 optInd ampExpr)*
+ampExpr = plusExpr (OP7 optInd plusExpr)*
+plusExpr = mulExpr (OP8 optInd mulExpr)*
+mulExpr = dollarExpr (OP9 optInd dollarExpr)*
+dollarExpr = primary (OP10 optInd primary)*
+operatorB = OP0 | OP1 | OP2 | OP3 | OP4 | OP5 | OP6 | OP7 | OP8 | OP9 |
+            'div' | 'mod' | 'shl' | 'shr' | 'in' | 'notin' |
+            'is' | 'isnot' | 'not' | 'of' | 'as' | 'from' | '..' | 'and' | 'or' | 'xor'
+symbol = '`' (KEYW|IDENT|literal|(operator|'('|')'|'['|']'|'{'|'}'|'=')+)+ '`'
+       | IDENT | 'addr' | 'type' | 'static'
+symbolOrKeyword = symbol | KEYW
+exprColonEqExpr = expr ((':'|'=') expr
+                       / doBlock extraPostExprBlock*)?
+exprEqExpr = expr ('=' expr
+                  / doBlock extraPostExprBlock*)?
+exprList = expr ^+ comma
+optionalExprList = expr ^* comma
+exprColonEqExprList = exprColonEqExpr (comma exprColonEqExpr)* (comma)?
+qualifiedIdent = symbol ('.' optInd symbolOrKeyword)?
+setOrTableConstr = '{' ((exprColonEqExpr comma)* | ':' ) '}'
+castExpr = 'cast' ('[' optInd typeDesc optPar ']' '(' optInd expr optPar ')') /
+parKeyw = 'discard' | 'include' | 'if' | 'while' | 'case' | 'try'
+        | 'finally' | 'except' | 'for' | 'block' | 'const' | 'let'
+        | 'when' | 'var' | 'mixin'
+par = '(' optInd
+          ( &parKeyw (ifExpr / complexOrSimpleStmt) ^+ ';'
+          | ';' (ifExpr / complexOrSimpleStmt) ^+ ';'
+          | pragmaStmt
+          | simpleExpr ( (doBlock extraPostExprBlock*)
+                       | ('=' expr (';' (ifExpr / complexOrSimpleStmt) ^+ ';' )? )
+                       | (':' expr (',' exprColonEqExpr     ^+ ',' )? ) ) )
+          optPar ')'
+literal = | INT_LIT | INT8_LIT | INT16_LIT | INT32_LIT | INT64_LIT
+          | UINT_LIT | UINT8_LIT | UINT16_LIT | UINT32_LIT | UINT64_LIT
+          | FLOAT_LIT | FLOAT32_LIT | FLOAT64_LIT
+          | STR_LIT | RSTR_LIT | TRIPLESTR_LIT
+          | CHAR_LIT | CUSTOM_NUMERIC_LIT
+          | NIL
+generalizedLit = GENERALIZED_STR_LIT | GENERALIZED_TRIPLESTR_LIT
+identOrLiteral = generalizedLit | symbol | literal
+               | par | arrayConstr | setOrTableConstr | tupleConstr
+               | castExpr
+tupleConstr = '(' optInd (exprColonEqExpr comma?)* optPar ')'
+arrayConstr = '[' optInd (exprColonEqExpr comma?)* optPar ']'
+primarySuffix = '(' (exprColonEqExpr comma?)* ')'
+      | '.' optInd symbolOrKeyword ('[:' exprList ']' ( '(' exprColonEqExpr ')' )?)? generalizedLit?
+      | DOTLIKEOP optInd symbolOrKeyword generalizedLit?
+      | '[' optInd exprColonEqExprList optPar ']'
+      | '{' optInd exprColonEqExprList optPar '}'
+pragma = '{.' optInd (exprColonEqExpr comma?)* optPar ('.}' | '}')
+identVis = symbol OPR?  # postfix position
+identVisDot = symbol '.' optInd symbolOrKeyword OPR?
+identWithPragma = identVis pragma?
+identWithPragmaDot = identVisDot pragma?
+declColonEquals = identWithPragma (comma identWithPragma)* comma?
+                  (':' optInd typeDescExpr)? ('=' optInd expr)?
+identColonEquals = IDENT (comma IDENT)* comma?
+     (':' optInd typeDescExpr)? ('=' optInd expr)?)
+tupleTypeBracket = '[' optInd (identColonEquals (comma/semicolon)?)* optPar ']'
+tupleType = 'tuple' tupleTypeBracket
+tupleDecl = 'tuple' (tupleTypeBracket /
+    COMMENT? (IND{>} identColonEquals (IND{=} identColonEquals)*)?)
+paramList = '(' declColonEquals ^* (comma/semicolon) ')'
+paramListArrow = paramList? ('->' optInd typeDesc)?
+paramListColon = paramList? (':' optInd typeDesc)?
+doBlock = 'do' paramListArrow pragma? colcom stmt
+routineExpr = ('proc' | 'func' | 'iterator') paramListColon pragma? ('=' COMMENT? stmt)?
+routineType = ('proc' | 'iterator') paramListColon pragma?
+forStmt = 'for' ((varTuple / identWithPragma) ^+ comma) 'in' expr colcom stmt
+forExpr = forStmt
+expr = (blockExpr
+      | ifExpr
+      | whenExpr
+      | caseStmt
+      | forExpr
+      | tryExpr)
+      / simpleExpr
+simplePrimary = SIGILLIKEOP? identOrLiteral primarySuffix*
+commandStart = &('`'|IDENT|literal|'cast'|'addr'|'type'|'var'|'out'|
+                 'static'|'enum'|'tuple'|'object'|'proc')
+primary = simplePrimary (commandStart expr (doBlock extraPostExprBlock*)?)?
+        / operatorB primary
+        / routineExpr
+        / rawTypeDesc
+        / prefixOperator primary
+rawTypeDesc = (tupleType | routineType | 'enum' | 'object' |
+                ('var' | 'out' | 'ref' | 'ptr' | 'distinct') typeDesc?)
+                ('not' primary)?
+typeDescExpr = (routineType / simpleExpr) ('not' primary)?
+typeDesc = rawTypeDesc / typeDescExpr
+typeDefValue = ((tupleDecl | enumDecl | objectDecl | conceptDecl |
+                 ('ref' | 'ptr' | 'distinct') (tupleDecl | objectDecl))
+               / (simpleExpr (exprEqExpr ^+ comma postExprBlocks?)?))
+               ('not' primary)?
+extraPostExprBlock = ( IND{=} doBlock
+                     | IND{=} 'of' exprList ':' stmt
+                     | IND{=} 'elif' expr ':' stmt
+                     | IND{=} 'except' optionalExprList ':' stmt
+                     | IND{=} 'finally' ':' stmt
+                     | IND{=} 'else' ':' stmt )
+postExprBlocks = (doBlock / ':' (extraPostExprBlock / stmt)) extraPostExprBlock*
+exprStmt = simpleExpr postExprBlocks?
+         / simplePrimary (exprEqExpr ^+ comma) postExprBlocks?
+         / simpleExpr '=' optInd (expr postExprBlocks?)
+importStmt = 'import' optInd expr
+              ((comma expr)*
+              / 'except' optInd (expr ^+ comma))
+exportStmt = 'export' optInd expr
+              ((comma expr)*
+              / 'except' optInd (expr ^+ comma))
+includeStmt = 'include' optInd expr ^+ comma
+fromStmt = 'from' expr 'import' optInd expr (comma expr)*
+returnStmt = 'return' optInd expr?
+raiseStmt = 'raise' optInd expr?
+yieldStmt = 'yield' optInd expr?
+discardStmt = 'discard' optInd expr?
+breakStmt = 'break' optInd expr?
+continueStmt = 'continue' optInd expr?
+condStmt = expr colcom stmt COMMENT?
+           (IND{=} 'elif' expr colcom stmt)*
+           (IND{=} 'else' colcom stmt)?
+ifStmt = 'if' condStmt
+whenStmt = 'when' condStmt
+condExpr = expr colcom stmt optInd
+        ('elif' expr colcom stmt optInd)*
+         'else' colcom stmt
+ifExpr = 'if' condExpr
+whenExpr = 'when' condExpr
+whileStmt = 'while' expr colcom stmt
+ofBranch = 'of' exprList colcom stmt
+ofBranches = ofBranch (IND{=} ofBranch)*
+                      (IND{=} 'elif' expr colcom stmt)*
+                      (IND{=} 'else' colcom stmt)?
+caseStmt = 'case' expr ':'? COMMENT?
+            (IND{>} ofBranches DED
+            | IND{=} ofBranches)
+tryStmt = 'try' colcom stmt &(IND{=}? 'except'|'finally')
+           (IND{=}? 'except' optionalExprList colcom stmt)*
+           (IND{=}? 'finally' colcom stmt)?
+tryExpr = 'try' colcom stmt &(optInd 'except'|'finally')
+           (optInd 'except' optionalExprList colcom stmt)*
+           (optInd 'finally' colcom stmt)?
+blockStmt = 'block' symbol? colcom stmt
+blockExpr = 'block' symbol? colcom stmt
+staticStmt = 'static' colcom stmt
+deferStmt = 'defer' colcom stmt
+asmStmt = 'asm' pragma? (STR_LIT | RSTR_LIT | TRIPLESTR_LIT)
+genericParam = symbol (comma symbol)* (colon expr)? ('=' optInd expr)?
+genericParamList = '[' optInd
+  genericParam ^* (comma/semicolon) optPar ']'
+pattern = '{' stmt '}'
+indAndComment = (IND{>} COMMENT)? | COMMENT?
+routine = optInd identVis pattern? genericParamList?
+  paramListColon pragma? ('=' COMMENT? stmt)? indAndComment
+commentStmt = COMMENT
+section(RULE) = COMMENT? RULE / (IND{>} (RULE / COMMENT)^+IND{=} DED)
+enumDecl = 'enum' optInd (symbol pragma? optInd ('=' optInd expr COMMENT?)? comma?)+
+objectWhen = 'when' expr colcom objectPart COMMENT?
+            ('elif' expr colcom objectPart COMMENT?)*
+            ('else' colcom objectPart COMMENT?)?
+objectBranch = 'of' exprList colcom objectPart
+objectBranches = objectBranch (IND{=} objectBranch)*
+                      (IND{=} 'elif' expr colcom objectPart)*
+                      (IND{=} 'else' colcom objectPart)?
+objectCase = 'case' declColonEquals ':'? COMMENT?
+            (IND{>} objectBranches DED
+            | IND{=} objectBranches)
+objectPart = IND{>} objectPart^+IND{=} DED
+           / objectWhen / objectCase / 'nil' / 'discard' / declColonEquals
+objectDecl = 'object' ('of' typeDesc)? COMMENT? objectPart
+conceptParam = ('var' | 'out' | 'ptr' | 'ref' | 'static' | 'type')? symbol
+conceptDecl = 'concept' conceptParam ^* ',' (pragma)? ('of' typeDesc ^* ',')?
+              &IND{>} stmt
+typeDef = identVisDot genericParamList? pragma '=' optInd typeDefValue
+            indAndComment?
+varTupleLhs = '(' optInd (identWithPragma / varTupleLhs) ^+ comma optPar ')' (':' optInd typeDescExpr)?
+varTuple = varTupleLhs '=' optInd expr
+colonBody = colcom stmt postExprBlocks?
+variable = (varTuple / identColonEquals) colonBody? indAndComment
+constant = (varTuple / identWithPragma) (colon typeDesc)? '=' optInd expr indAndComment
+bindStmt = 'bind' optInd qualifiedIdent ^+ comma
+mixinStmt = 'mixin' optInd qualifiedIdent ^+ comma
+pragmaStmt = pragma (':' COMMENT? stmt)?
+simpleStmt = ((returnStmt | raiseStmt | yieldStmt | discardStmt | breakStmt
+           | continueStmt | pragmaStmt | importStmt | exportStmt | fromStmt
+           | includeStmt | commentStmt) / exprStmt) COMMENT?
+complexOrSimpleStmt = (ifStmt | whenStmt | whileStmt
+                    | tryStmt | forStmt
+                    | blockStmt | staticStmt | deferStmt | asmStmt
+                    | 'proc' routine
+                    | 'method' routine
+                    | 'func' routine
+                    | 'iterator' routine
+                    | 'macro' routine
+                    | 'template' routine
+                    | 'converter' routine
+                    | 'type' section(typeDef)
+                    | 'const' section(constant)
+                    | ('let' | 'var' | 'using') section(variable)
+                    | bindStmt | mixinStmt)
+                    / simpleStmt
+stmt = (IND{>} complexOrSimpleStmt^+(IND{=} / ';') DED)
+     / simpleStmt ^+ ';'
+
+ +

Order of evaluation

Order of evaluation is strictly left-to-right, inside-out as it is typical for most others imperative programming languages:

+

var s = ""
+
+proc p(arg: int): int =
+  s.add $arg
+  result = arg
+
+discard p(p(1) + p(2))
+
+doAssert s == "123"

+

Assignments are not special, the left-hand-side expression is evaluated before the right-hand side:

+

var v = 0
+proc getI(): int =
+  result = v
+  inc v
+
+var a, b: array[0..2, int]
+
+proc someCopy(a: var int; b: int) = a = b
+
+a[getI()] = getI()
+
+doAssert a == [1, 0, 0]
+
+v = 0
+someCopy(b[getI()], getI())
+
+doAssert b == [1, 0, 0]

+

Rationale: Consistency with overloaded assignment or assignment-like operations, a = b can be read as performSomeCopy(a, b).

+

However, the concept of "order of evaluation" is only applicable after the code was normalized: The normalization involves template expansions and argument reorderings that have been passed to named parameters:

+

var s = ""
+
+proc p(): int =
+  s.add "p"
+  result = 5
+
+proc q(): int =
+  s.add "q"
+  result = 3
+
+# Evaluation order is 'b' before 'a' due to template
+# expansion's semantics.
+template swapArgs(a, b): untyped =
+  b + a
+
+doAssert swapArgs(p() + q(), q() - p()) == 6
+doAssert s == "qppq"
+
+# Evaluation order is not influenced by named parameters:
+proc construct(first, second: int) =
+  discard
+
+# 'p' is evaluated before 'q'!
+construct(second = q(), first = p())
+
+doAssert s == "qppqpq"

+

Rationale: This is far easier to implement than hypothetical alternatives.

+ +

Constants and Constant Expressions

A constant is a symbol that is bound to the value of a constant expression. Constant expressions are restricted to depend only on the following categories of values and operations, because these are either built into the language or declared and evaluated before semantic analysis of the constant expression:

+
  • literals
  • +
  • built-in operators
  • +
  • previously declared constants and compile-time variables
  • +
  • previously declared macros and templates
  • +
  • previously declared procedures that have no side effects beyond possibly modifying compile-time variables
  • +
+

A constant expression can contain code blocks that may internally use all Nim features supported at compile time (as detailed in the next section below). Within such a code block, it is possible to declare variables and then later read and update them, or declare variables and pass them to procedures that modify them. However, the code in such a block must still adhere to the restrictions listed above for referencing values and operations outside the block.

+

The ability to access and modify compile-time variables adds flexibility to constant expressions that may be surprising to those coming from other statically typed languages. For example, the following code echoes the beginning of the Fibonacci series at compile-time. (This is a demonstration of flexibility in defining constants, not a recommended style for solving this problem.)

+

import std/strformat
+
+var fibN {.compileTime.}: int
+var fibPrev {.compileTime.}: int
+var fibPrevPrev {.compileTime.}: int
+
+proc nextFib(): int =
+  result = if fibN < 2:
+    fibN
+  else:
+    fibPrevPrev + fibPrev
+  inc(fibN)
+  fibPrevPrev = fibPrev
+  fibPrev = result
+
+const f0 = nextFib()
+const f1 = nextFib()
+
+const displayFib = block:
+  const f2 = nextFib()
+  var result = fmt"Fibonacci sequence: {f0}, {f1}, {f2}"
+  for i in 3..12:
+    add(result, fmt", {nextFib()}")
+  result
+
+static:
+  echo displayFib

+ +

Restrictions on Compile-Time Execution

Nim code that will be executed at compile time cannot use the following language features:

+
  • methods
  • +
  • closure iterators
  • +
  • the cast operator
  • +
  • reference (pointer) types
  • +
  • FFI
  • +
+

The use of wrappers that use FFI and/or cast is also disallowed. Note that these wrappers include the ones in the standard libraries.

+

Some or all of these restrictions are likely to be lifted over time.

+ +

Types

All expressions have a type that is known during semantic analysis. Nim is statically typed. One can declare new types, which is in essence defining an identifier that can be used to denote this custom type.

+

These are the major type classes:

+
  • ordinal types (consist of integer, bool, character, enumeration (and subranges thereof) types)
  • +
  • floating-point types
  • +
  • string type
  • +
  • structured types
  • +
  • reference (pointer) type
  • +
  • procedural type
  • +
  • generic type
  • +
+ +

Ordinal types

Ordinal types have the following characteristics:

+
  • Ordinal types are countable and ordered. This property allows the operation of functions such as inc, ord, and dec on ordinal types to be defined.
  • +
  • Ordinal types have a smallest possible value, accessible with low(type). Trying to count further down than the smallest value produces a panic or a static error.
  • +
  • Ordinal types have a largest possible value, accessible with high(type). Trying to count further up than the largest value produces a panic or a static error.
  • +
+

Integers, bool, characters, and enumeration types (and subranges of these types) belong to ordinal types.

+

A distinct type is an ordinal type if its base type is an ordinal type.

+ +

Pre-defined integer types

These integer types are pre-defined:

+
int
+
the generic signed integer type; its size is platform-dependent and has the same size as a pointer. This type should be used in general. An integer literal that has no type suffix is of this type if it is in the range low(int32)..high(int32) otherwise the literal's type is int64.
+
intXX
+
additional signed integer types of XX bits use this naming scheme (example: int16 is a 16-bit wide integer). The current implementation supports int8, int16, int32, int64. Literals of these types have the suffix 'iXX.
+
uint
+
the generic unsigned integer type; its size is platform-dependent and has the same size as a pointer. An integer literal with the type suffix 'u is of this type.
+
uintXX
+
additional unsigned integer types of XX bits use this naming scheme (example: uint16 is a 16-bit wide unsigned integer). The current implementation supports uint8, uint16, uint32, uint64. Literals of these types have the suffix 'uXX. Unsigned operations all wrap around; they cannot lead to over- or underflow errors.
+
+

In addition to the usual arithmetic operators for signed and unsigned integers (+ - * etc.) there are also operators that formally work on signed integers but treat their arguments as unsigned: They are mostly provided for backwards compatibility with older versions of the language that lacked unsigned integer types. These unsigned operations for signed integers use the % suffix as convention:

+ + + + + + + + +
operationmeaning
a +% bunsigned integer addition
a -% bunsigned integer subtraction
a *% bunsigned integer multiplication
a /% bunsigned integer division
a %% bunsigned integer modulo operation
a <% btreat a and b as unsigned and compare
a <=% btreat a and b as unsigned and compare

Automatic type conversion is performed in expressions where different kinds of integer types are used: the smaller type is converted to the larger.

+

A narrowing type conversion converts a larger to a smaller type (for example int32 -> int16). A widening type conversion converts a smaller type to a larger type (for example int16 -> int32). In Nim only widening type conversions are implicit:

+

var myInt16 = 5i16
+var myInt: int
+myInt16 + 34     # of type `int16`
+myInt16 + myInt  # of type `int`
+myInt16 + 2i32   # of type `int32`

+

However, int literals are implicitly convertible to a smaller integer type if the literal's value fits this smaller type and such a conversion is less expensive than other implicit conversions, so myInt16 + 34 produces an int16 result.

+

For further details, see Convertible relation.

+ +

Subrange types

A subrange type is a range of values from an ordinal or floating-point type (the base type). To define a subrange type, one must specify its limiting values -- the lowest and highest value of the type. For example:

+

type
+  Subrange = range[0..5]
+  PositiveFloat = range[0.0..Inf]
+  Positive* = range[1..high(int)] # as defined in `system`

+

Subrange is a subrange of an integer which can only hold the values 0 to 5. PositiveFloat defines a subrange of all positive floating-point values. NaN does not belong to any subrange of floating-point types. Assigning any other value to a variable of type Subrange is a panic (or a static error if it can be determined during semantic analysis). Assignments from the base type to one of its subrange types (and vice versa) are allowed.

+

A subrange type has the same size as its base type (int in the Subrange example).

+ +

Pre-defined floating-point types

The following floating-point types are pre-defined:

+
float
+
the generic floating-point type; its size used to be platform-dependent, but now it is always mapped to float64. This type should be used in general.
+
floatXX
+
an implementation may define additional floating-point types of XX bits using this naming scheme (example: float64 is a 64-bit wide float). The current implementation supports float32 and float64. Literals of these types have the suffix 'fXX.
+
+

Automatic type conversion in expressions with different kinds of floating-point types is performed: See Convertible relation for further details. Arithmetic performed on floating-point types follows the IEEE standard. Integer types are not converted to floating-point types automatically and vice versa.

+

The IEEE standard defines five types of floating-point exceptions:

+
  • Invalid: operations with mathematically invalid operands, for example 0.0/0.0, sqrt(-1.0), and log(-37.8).
  • +
  • Division by zero: divisor is zero and dividend is a finite nonzero number, for example 1.0/0.0.
  • +
  • Overflow: operation produces a result that exceeds the range of the exponent, for example MAXDOUBLE+0.0000000000001e308.
  • +
  • Underflow: operation produces a result that is too small to be represented as a normal number, for example, MINDOUBLE * MINDOUBLE.
  • +
  • Inexact: operation produces a result that cannot be represented with infinite precision, for example, 2.0 / 3.0, log(1.1) and 0.1 in input.
  • +
+

The IEEE exceptions are either ignored during execution or mapped to the Nim exceptions: FloatInvalidOpDefect, FloatDivByZeroDefect, FloatOverflowDefect, FloatUnderflowDefect, and FloatInexactDefect. These exceptions inherit from the FloatingPointDefect base class.

+

Nim provides the pragmas nanChecks and infChecks to control whether the IEEE exceptions are ignored or trap a Nim exception:

+

{.nanChecks: on, infChecks: on.}
+var a = 1.0
+var b = 0.0
+echo b / b # raises FloatInvalidOpDefect
+echo a / b # raises FloatOverflowDefect

+

In the current implementation FloatDivByZeroDefect and FloatInexactDefect are never raised. FloatOverflowDefect is raised instead of FloatDivByZeroDefect. There is also a floatChecks pragma that is a short-cut for the combination of nanChecks and infChecks pragmas. floatChecks are turned off as default.

+

The only operations that are affected by the floatChecks pragma are the +, -, *, / operators for floating-point types.

+

An implementation should always use the maximum precision available to evaluate floating-point values during semantic analysis; this means expressions like 0.09'f32 + 0.01'f32 == 0.09'f64 + 0.01'f64 that are evaluating during constant folding are true.

+ +

Boolean type

The boolean type is named bool in Nim and can be one of the two pre-defined values true and false. Conditions in while, if, elif, when-statements need to be of type bool.

+

This condition holds:

+

ord(false) == 0 and ord(true) == 1

+

The operators not, and, or, xor, <, <=, >, >=, !=, == are defined for the bool type. The and and or operators perform short-cut evaluation. Example:

+

while p != nil and p.name != "xyz":
+  # p.name is not evaluated if p == nil
+  p = p.next

+

The size of the bool type is one byte.

+ +

Character type

The character type is named char in Nim. Its size is one byte. Thus, it cannot represent a UTF-8 character, but a part of it.

+

The Rune type is used for Unicode characters, it can represent any Unicode character. Rune is declared in the unicode module.

+ +

Enumeration types

Enumeration types define a new type whose values consist of the ones specified. The values are ordered. Example:

+

type
+  Direction = enum
+    north, east, south, west

+

Now the following holds:

+

ord(north) == 0
+ord(east) == 1
+ord(south) == 2
+ord(west) == 3
+
+# Also allowed:
+ord(Direction.west) == 3

+

The implied order is: north < east < south < west. The comparison operators can be used with enumeration types. Instead of north etc., the enum value can also be qualified with the enum type that it resides in, Direction.north.

+

For better interfacing to other programming languages, the fields of enum types can be assigned an explicit ordinal value. However, the ordinal values have to be in ascending order. A field whose ordinal value is not explicitly given is assigned the value of the previous field + 1.

+

An explicit ordered enum can have holes:

+

type
+  TokenType = enum
+    a = 2, b = 4, c = 89 # holes are valid

+

However, it is then not ordinal anymore, so it is impossible to use these enums as an index type for arrays. The procedures inc, dec, succ and pred are not available for them either.

+

The compiler supports the built-in stringify operator $ for enumerations. The stringify's result can be controlled by explicitly giving the string values to use:

+

type
+  MyEnum = enum
+    valueA = (0, "my value A"),
+    valueB = "value B",
+    valueC = 2,
+    valueD = (3, "abc")

+

As can be seen from the example, it is possible to both specify a field's ordinal value and its string value by using a tuple. It is also possible to only specify one of them.

+

An enum can be marked with the pure pragma so that its fields are added to a special module-specific hidden scope that is only queried as the last attempt. Only non-ambiguous symbols are added to this scope. But one can always access these via type qualification written as MyEnum.value:

+

type
+  MyEnum {.pure.} = enum
+    valueA, valueB, valueC, valueD, amb
+  
+  OtherEnum {.pure.} = enum
+    valueX, valueY, valueZ, amb
+
+
+echo valueA # MyEnum.valueA
+echo amb    # Error: Unclear whether it's MyEnum.amb or OtherEnum.amb
+echo MyEnum.amb # OK.

+

Enum value names are overloadable, much like routines. If both of the enums T and U have a member named foo, then the identifier foo corresponds to a choice between T.foo and U.foo. During overload resolution, the correct type of foo is decided from the context. If the type of foo is ambiguous, a static error will be produced.

+

+type
+  E1 = enum
+    value1,
+    value2
+  E2 = enum
+    value1,
+    value2 = 4
+
+const
+  Lookuptable = [
+    E1.value1: "1",
+    # no need to qualify value2, known to be E1.value2
+    value2: "2"
+  ]
+
+proc p(e: E1) =
+  # disambiguation in 'case' statements:
+  case e
+  of value1: echo "A"
+  of value2: echo "B"
+
+p value2

+

In some cases, ambiguity of enums is resolved depending on the relation between the current scope and the scope the enums were defined in.

+

# a.nim
+type Foo* = enum abc
+
+# b.nim
+import a
+type Bar = enum abc
+echo abc is Bar # true
+
+block:
+  type Baz = enum abc
+  echo abc is Baz # true

+

To implement bit fields with enums see Bit fields.

+ +

String type

All string literals are of the type string. A string in Nim is very similar to a sequence of characters. However, strings in Nim are both zero-terminated and have a length field. One can retrieve the length with the builtin len procedure; the length never counts the terminating zero.

+

The terminating zero cannot be accessed unless the string is converted to the cstring type first. The terminating zero assures that this conversion can be done in O(1) and without any allocations.

+

The assignment operator for strings always copies the string. The & operator concatenates strings.

+

Most native Nim types support conversion to strings with the special $ proc. When calling the echo proc, for example, the built-in stringify operation for the parameter is called:

+

echo 3 # calls `$` for `int`

+

Whenever a user creates a specialized object, implementation of this procedure provides for string representation.

+

type
+  Person = object
+    name: string
+    age: int
+
+proc `$`(p: Person): string = # `$` always returns a string
+  result = p.name & " is " &
+          $p.age & # we *need* the `$` in front of p.age which
+                   # is natively an integer to convert it to
+                   # a string
+          " years old."

+

While $p.name can also be used, the $ operation on a string does nothing. Note that we cannot rely on automatic conversion from an int to a string like we can for the echo proc.

+

Strings are compared by their lexicographical order. All comparison operators are available. Strings can be indexed like arrays (lower bound is 0). Unlike arrays, they can be used in case statements:

+

case paramStr(i)
+of "-v": incl(options, optVerbose)
+of "-h", "-?": incl(options, optHelp)
+else: write(stdout, "invalid command line option!\n")

+

Per convention, all strings are UTF-8 strings, but this is not enforced. For example, when reading strings from binary files, they are merely a sequence of bytes. The index operation s[i] means the i-th char of s, not the i-th unichar. The iterator runes from the unicode module can be used for iteration over all Unicode characters.

+ +

cstring type

The cstring type meaning compatible string is the native representation of a string for the compilation backend. For the C backend the cstring type represents a pointer to a zero-terminated char array compatible with the type char* in ANSI C. Its primary purpose lies in easy interfacing with C. The index operation s[i] means the i-th char of s; however no bounds checking for cstring is performed making the index operation unsafe.

+

A Nim string is implicitly convertible to cstring for convenience. If a Nim string is passed to a C-style variadic proc, it is implicitly converted to cstring too:

+

proc printf(formatstr: cstring) {.importc: "printf", varargs,
+                                  header: "<stdio.h>".}
+
+printf("This works %s", "as expected")

+

Even though the conversion is implicit, it is not safe: The garbage collector does not consider a cstring to be a root and may collect the underlying memory. For this reason, the implicit conversion will be removed in future releases of the Nim compiler. Certain idioms like conversion of a const string to cstring are safe and will remain to be allowed.

+

A $ proc is defined for cstrings that returns a string. Thus, to get a nim string from a cstring:

+

var str: string = "Hello!"
+var cstr: cstring = str
+var newstr: string = $cstr

+

cstring literals shouldn't be modified.

+

var x = cstring"literals"
+x[1] = 'A' # This is wrong!!!

+

If the cstring originates from a regular memory (not read-only memory), it can be modified:

+

var x = "123456"
+prepareMutation(x) # call `prepareMutation` before modifying the strings
+var s: cstring = cstring(x)
+s[0] = 'u' # This is ok

+

cstring values may also be used in case statements like strings.

+ +

Structured types

A variable of a structured type can hold multiple values at the same time. Structured types can be nested to unlimited levels. Arrays, sequences, tuples, objects, and sets belong to the structured types.

+ +

Array and sequence types

Arrays are a homogeneous type, meaning that each element in the array has the same type. Arrays always have a fixed length specified as a constant expression (except for open arrays). They can be indexed by any ordinal type. A parameter A may be an open array, in which case it is indexed by integers from 0 to len(A)-1. An array expression may be constructed by the array constructor []. The element type of this array expression is inferred from the type of the first element. All other elements need to be implicitly convertible to this type.

+

An array type can be defined using the array[size, T] syntax, or using array[lo..hi, T] for arrays that start at an index other than zero.

+

Sequences are similar to arrays but of dynamic length which may change during runtime (like strings). Sequences are implemented as growable arrays, allocating pieces of memory as items are added. A sequence S is always indexed by integers from 0 to len(S)-1 and its bounds are checked. Sequences can be constructed by the array constructor [] in conjunction with the array to sequence operator @. Another way to allocate space for a sequence is to call the built-in newSeq procedure.

+

A sequence may be passed to a parameter that is of type open array.

+

Example:

+

type
+  IntArray = array[0..5, int] # an array that is indexed with 0..5
+  IntSeq = seq[int] # a sequence of integers
+var
+  x: IntArray
+  y: IntSeq
+x = [1, 2, 3, 4, 5, 6]  # [] is the array constructor
+y = @[1, 2, 3, 4, 5, 6] # the @ turns the array into a sequence
+
+let z = [1.0, 2, 3, 4] # the type of z is array[0..3, float]

+

The lower bound of an array or sequence may be received by the built-in proc low(), the higher bound by high(). The length may be received by len(). low() for a sequence or an open array always returns 0, as this is the first valid index. One can append elements to a sequence with the add() proc or the & operator, and remove (and get) the last element of a sequence with the pop() proc.

+

The notation x[i] can be used to access the i-th element of x.

+

Arrays are always bounds checked (statically or at runtime). These checks can be disabled via pragmas or invoking the compiler with the --boundChecks:off command-line switch.

+

An array constructor can have explicit indexes for readability:

+

type
+  Values = enum
+    valA, valB, valC
+
+const
+  lookupTable = [
+    valA: "A",
+    valB: "B",
+    valC: "C"
+  ]

+

If an index is left out, succ(lastIndex) is used as the index value:

+

type
+  Values = enum
+    valA, valB, valC, valD, valE
+
+const
+  lookupTable = [
+    valA: "A",
+    "B",
+    valC: "C",
+    "D", "e"
+  ]

+ +

Open arrays

Often fixed size arrays turn out to be too inflexible; procedures should be able to deal with arrays of different sizes. The openarray type allows this; it can only be used for parameters. Open arrays are always indexed with an int starting at position 0. The len, low and high operations are available for open arrays too. Any array with a compatible base type can be passed to an open array parameter, the index type does not matter. In addition to arrays, sequences can also be passed to an open array parameter.

+

The openarray type cannot be nested: multidimensional open arrays are not supported because this is seldom needed and cannot be done efficiently.

+

proc testOpenArray(x: openArray[int]) = echo repr(x)
+
+testOpenArray([1,2,3])  # array[]
+testOpenArray(@[1,2,3]) # seq[]

+ +

Varargs

A varargs parameter is an open array parameter that additionally allows a variable number of arguments to be passed to a procedure. The compiler converts the list of arguments to an array implicitly:

+

proc myWriteln(f: File, a: varargs[string]) =
+  for s in items(a):
+    write(f, s)
+  write(f, "\n")
+
+myWriteln(stdout, "abc", "def", "xyz")
+# is transformed to:
+myWriteln(stdout, ["abc", "def", "xyz"])

+

This transformation is only done if the varargs parameter is the last parameter in the procedure header. It is also possible to perform type conversions in this context:

+

proc myWriteln(f: File, a: varargs[string, `$`]) =
+  for s in items(a):
+    write(f, s)
+  write(f, "\n")
+
+myWriteln(stdout, 123, "abc", 4.0)
+# is transformed to:
+myWriteln(stdout, [$123, $"abc", $4.0])

+

In this example $ is applied to any argument that is passed to the parameter a. (Note that $ applied to strings is a nop.)

+

Note that an explicit array constructor passed to a varargs parameter is not wrapped in another implicit array construction:

+

proc takeV[T](a: varargs[T]) = discard
+
+takeV([123, 2, 1]) # takeV's T is "int", not "array of int"

+

varargs[typed] is treated specially: It matches a variable list of arguments of arbitrary type but always constructs an implicit array. This is required so that the builtin echo proc does what is expected:

+

proc echo*(x: varargs[typed, `$`]) {...}
+
+echo @[1, 2, 3]
+# prints "@[1, 2, 3]" and not "123"

+ +

Unchecked arrays

The UncheckedArray[T] type is a special kind of array where its bounds are not checked. This is often useful to implement customized flexibly sized arrays. Additionally, an unchecked array is translated into a C array of undetermined size:

+

type
+  MySeq = object
+    len, cap: int
+    data: UncheckedArray[int]

+

Produces roughly this C code:

+

typedef struct {
+  NI len;
+  NI cap;
+  NI data[];
+} MySeq;

+

The base type of the unchecked array may not contain any GC'ed memory but this is currently not checked.

+

Future directions: GC'ed memory should be allowed in unchecked arrays and there should be an explicit annotation of how the GC is to determine the runtime size of the array.

+ +

Tuples and object types

A variable of a tuple or object type is a heterogeneous storage container. A tuple or object defines various named fields of a type. A tuple also defines a lexicographic order of the fields. Tuples are meant to be heterogeneous storage types with few abstractions. The () syntax can be used to construct tuples. The order of the fields in the constructor must match the order of the tuple's definition. Different tuple-types are equivalent if they specify the same fields of the same type in the same order. The names of the fields also have to be the same.

+

type
+  Person = tuple[name: string, age: int] # type representing a person:
+                                         # it consists of a name and an age.
+var person: Person
+person = (name: "Peter", age: 30)
+assert person.name == "Peter"
+# the same, but less readable:
+person = ("Peter", 30)
+assert person[0] == "Peter"
+assert Person is (string, int)
+assert (string, int) is Person
+assert Person isnot tuple[other: string, age: int] # `other` is a different identifier

+

A tuple with one unnamed field can be constructed with the parentheses and a trailing comma:

+

proc echoUnaryTuple(a: (int,)) =
+  echo a[0]
+
+echoUnaryTuple (1,)

+

In fact, a trailing comma is allowed for every tuple construction.

+

The implementation aligns the fields for the best access performance. The alignment is compatible with the way the C compiler does it.

+

For consistency with object declarations, tuples in a type section can also be defined with indentation instead of []:

+

type
+  Person = tuple   # type representing a person
+    name: string   # a person consists of a name
+    age: Natural   # and an age

+

Objects provide many features that tuples do not. Objects provide inheritance and the ability to hide fields from other modules. Objects with inheritance enabled have information about their type at runtime so that the of operator can be used to determine the object's type. The of operator is similar to the instanceof operator in Java.

+

type
+  Person = object of RootObj
+    name*: string   # the * means that `name` is accessible from other modules
+    age: int        # no * means that the field is hidden
+  
+  Student = ref object of Person # a student is a person
+    id: int                      # with an id field
+
+var
+  student: Student
+  person: Person
+assert(student of Student) # is true
+assert(student of Person) # also true

+

Object fields that should be visible from outside the defining module have to be marked by *. In contrast to tuples, different object types are never equivalent, they are nominal types whereas tuples are structural. Objects that have no ancestor are implicitly final and thus have no hidden type information. One can use the inheritable pragma to introduce new object roots apart from system.RootObj.

+

type
+  Person = object # example of a final object
+    name*: string
+    age: int
+  
+  Student = ref object of Person # Error: inheritance only works with non-final objects
+    id: int

+

The assignment operator for tuples and objects copies each component. The methods to override this copying behavior are described here.

+ +

Object construction

Objects can also be created with an object construction expression that has the syntax T(fieldA: valueA, fieldB: valueB, ...) where T is an object type or a ref object type:

+

type
+  Student = object
+    name: string
+    age: int
+  PStudent = ref Student
+var a1 = Student(name: "Anton", age: 5)
+var a2 = PStudent(name: "Anton", age: 5)
+# this also works directly:
+var a3 = (ref Student)(name: "Anton", age: 5)
+# not all fields need to be mentioned, and they can be mentioned out of order:
+var a4 = Student(age: 5)

+

Note that, unlike tuples, objects require the field names along with their values. For a ref object type system.new is invoked implicitly.

+ +

Object variants

Often an object hierarchy is an overkill in certain situations where simple variant types are needed. Object variants are tagged unions discriminated via an enumerated type used for runtime type flexibility, mirroring the concepts of sum types and algebraic data types (ADTs) as found in other languages.

+

An example:

+

# This is an example of how an abstract syntax tree could be modelled in Nim
+type
+  NodeKind = enum  # the different node types
+    nkInt,          # a leaf with an integer value
+    nkFloat,        # a leaf with a float value
+    nkString,       # a leaf with a string value
+    nkAdd,          # an addition
+    nkSub,          # a subtraction
+    nkIf            # an if statement
+  Node = ref NodeObj
+  NodeObj = object
+    case kind: NodeKind  # the `kind` field is the discriminator
+    of nkInt: intVal: int
+    of nkFloat: floatVal: float
+    of nkString: strVal: string
+    of nkAdd, nkSub:
+      leftOp, rightOp: Node
+    of nkIf:
+      condition, thenPart, elsePart: Node
+
+# create a new case object:
+var n = Node(kind: nkIf, condition: nil)
+# accessing n.thenPart is valid because the `nkIf` branch is active:
+n.thenPart = Node(kind: nkFloat, floatVal: 2.0)
+
+# the following statement raises an `FieldDefect` exception, because
+# n.kind's value does not fit and the `nkString` branch is not active:
+n.strVal = ""
+
+# invalid: would change the active object branch:
+n.kind = nkInt
+
+var x = Node(kind: nkAdd, leftOp: Node(kind: nkInt, intVal: 4),
+                          rightOp: Node(kind: nkInt, intVal: 2))
+# valid: does not change the active object branch:
+x.kind = nkSub

+

As can be seen from the example, an advantage to an object hierarchy is that no casting between different object types is needed. Yet, access to invalid object fields raises an exception.

+

The syntax of case in an object declaration follows closely the syntax of the case statement: The branches in a case section may be indented too.

+

In the example, the kind field is called the discriminator: For safety, its address cannot be taken and assignments to it are restricted: The new value must not lead to a change of the active object branch. Also, when the fields of a particular branch are specified during object construction, the corresponding discriminator value must be specified as a constant expression.

+

Instead of changing the active object branch, replace the old object in memory with a new one completely:

+

var x = Node(kind: nkAdd, leftOp: Node(kind: nkInt, intVal: 4),
+                          rightOp: Node(kind: nkInt, intVal: 2))
+# change the node's contents:
+x[] = NodeObj(kind: nkString, strVal: "abc")

+

Starting with version 0.20 system.reset cannot be used anymore to support object branch changes as this never was completely memory safe.

+

As a special rule, the discriminator kind can also be bounded using a case statement. If possible values of the discriminator variable in a case statement branch are a subset of discriminator values for the selected object branch, the initialization is considered valid. This analysis only works for immutable discriminators of an ordinal type and disregards elif branches. For discriminator values with a range type, the compiler checks if the entire range of possible values for the discriminator value is valid for the chosen object branch.

+

A small example:

+

let unknownKind = nkSub
+
+# invalid: unsafe initialization because the kind field is not statically known:
+var y = Node(kind: unknownKind, strVal: "y")
+
+var z = Node()
+case unknownKind
+of nkAdd, nkSub:
+  # valid: possible values of this branch are a subset of nkAdd/nkSub object branch:
+  z = Node(kind: unknownKind, leftOp: Node(), rightOp: Node())
+else:
+  echo "ignoring: ", unknownKind
+
+# also valid, since unknownKindBounded can only contain the values nkAdd or nkSub
+let unknownKindBounded = range[nkAdd..nkSub](unknownKind)
+z = Node(kind: unknownKindBounded, leftOp: Node(), rightOp: Node())

+ +

cast uncheckedAssign

Some restrictions for case objects can be disabled via a {.cast(uncheckedAssign).} section:

+

type
+  TokenKind* = enum
+    strLit, intLit
+  Token = object
+    case kind*: TokenKind
+    of strLit:
+      s*: string
+    of intLit:
+      i*: int64
+
+proc passToVar(x: var TokenKind) = discard
+
+var t = Token(kind: strLit, s: "abc")
+
+{.cast(uncheckedAssign).}:
+  # inside the 'cast' section it is allowed to pass 't.kind' to a 'var T' parameter:
+  passToVar(t.kind)
+  
+  # inside the 'cast' section it is allowed to set field 's' even though the
+  # constructed 'kind' field has an unknown value:
+  t = Token(kind: t.kind, s: "abc")
+  
+  # inside the 'cast' section it is allowed to assign to the 't.kind' field directly:
+  t.kind = intLit

+ +

Default values for object fields

Object fields are allowed to have a constant default value. The type of field can be omitted if a default value is given.

+

type
+  Foo = object
+    a: int = 2
+    b: float = 3.14
+    c = "I can have a default value"
+  
+  Bar = ref object
+    a: int = 2
+    b: float = 3.14
+    c = "I can have a default value"

+

The explicit initialization uses these defaults which includes an object created with an object construction expression or the procedure default; a ref object created with an object construction expression or the procedure new; an array or a tuple with a subtype which has a default created with the procedure default.

+

type
+  Foo = object
+    a: int = 2
+    b = 3.0
+  Bar = ref object
+    a: int = 2
+    b = 3.0
+
+block: # created with an object construction expression
+  let x = Foo()
+  assert x.a == 2 and x.b == 3.0
+  
+  let y = Bar()
+  assert y.a == 2 and y.b == 3.0
+
+block: # created with an object construction expression
+  let x = default(Foo)
+  assert x.a == 2 and x.b == 3.0
+  
+  let y = default(array[1, Foo])
+  assert y[0].a == 2 and y[0].b == 3.0
+  
+  let z = default(tuple[x: Foo])
+  assert z.x.a == 2 and z.x.b == 3.0
+
+block: # created with the procedure `new`
+  let y = new Bar
+  assert y.a == 2 and y.b == 3.0

+ +

Set type

The set type models the mathematical notion of a set. The set's basetype can only be an ordinal type of a certain size, namely:
  • int8-int16
  • +
  • uint8/byte-uint16
  • +
  • char
  • +
  • enum
  • +
  • Ordinal subrange types, i.e. range[-10..10]
  • +
+

or equivalent. When constructing a set with signed integer literals, the set's base type is defined to be in the range 0 .. DefaultSetElements-1 where DefaultSetElements is currently always 2^8. The maximum range length for the base type of a set is MaxSetElements which is currently always 2^16. Types with a bigger range length are coerced into the range 0 .. MaxSetElements-1.

+

The reason is that sets are implemented as high performance bit vectors. Attempting to declare a set with a larger type will result in an error:

+

  var s: set[int64] # Error: set is too large; use `std/sets` for ordinal types
+                    # with more than 2^16 elements

+

Note: Nim also offers hash sets (which you need to import with import std/sets), which have no such restrictions.

+

Sets can be constructed via the set constructor: {} is the empty set. The empty set is type compatible with any concrete set type. The constructor can also be used to include elements (and ranges of elements):

+

type
+  CharSet = set[char]
+var
+  x: CharSet
+x = {'a'..'z', '0'..'9'} # This constructs a set that contains the
+                         # letters from 'a' to 'z' and the digits
+                         # from '0' to '9'

+

The module `std/setutils` provides a way to initialize a set from an iterable:

+

import std/setutils
+
+let uniqueChars = myString.toSet

+

These operations are supported by sets:

+ + + + + + + + + + + + + +
operationmeaning
A + Bunion of two sets
A * Bintersection of two sets
A - Bdifference of two sets (A without B's elements)
A == Bset equality
A <= Bsubset relation (A is subset of B or equal to B)
A < Bstrict subset relation (A is a proper subset of B)
e in Aset membership (A contains element e)
e notin AA does not contain element e
contains(A, e)A contains element e
card(A)the cardinality of A (number of elements in A)
incl(A, elem)same as A = A + {elem}
excl(A, elem)same as A = A - {elem}
+

Bit fields

Sets are often used to define a type for the flags of a procedure. This is a cleaner (and type safe) solution than defining integer constants that have to be or'ed together.

+

Enum, sets and casting can be used together as in:

+

type
+  MyFlag* {.size: sizeof(cint).} = enum
+    A
+    B
+    C
+    D
+  MyFlags = set[MyFlag]
+
+proc toNum(f: MyFlags): int = cast[cint](f)
+proc toFlags(v: int): MyFlags = cast[MyFlags](v)
+
+assert toNum({}) == 0
+assert toNum({A}) == 1
+assert toNum({D}) == 8
+assert toNum({A, C}) == 5
+assert toFlags(0) == {}
+assert toFlags(7) == {A, B, C}

+

Note how the set turns enum values into powers of 2.

+

If using enums and sets with C, use distinct cint.

+

For interoperability with C see also the bitsize pragma.

+ +

Reference and pointer types

References (similar to pointers in other programming languages) are a way to introduce many-to-one relationships. This means different references can point to and modify the same location in memory (also called aliasing).

+

Nim distinguishes between traced and untraced references. Untraced references are also called pointers. Traced references point to objects of a garbage-collected heap, untraced references point to manually allocated objects or objects somewhere else in memory. Thus, untraced references are unsafe. However, for certain low-level operations (accessing the hardware) untraced references are unavoidable.

+

Traced references are declared with the ref keyword, untraced references are declared with the ptr keyword. In general, a ptr T is implicitly convertible to the pointer type.

+

An empty subscript [] notation can be used to de-refer a reference, the addr procedure returns the address of an item. An address is always an untraced reference. Thus, the usage of addr is an unsafe feature.

+

The . (access a tuple/object field operator) and [] (array/string/sequence index operator) operators perform implicit dereferencing operations for reference types:

+

type
+  Node = ref NodeObj
+  NodeObj = object
+    le, ri: Node
+    data: int
+
+var
+  n: Node
+new(n)
+n.data = 9
+# no need to write n[].data; in fact n[].data is highly discouraged!

+

In order to simplify structural type checking, recursive tuples are not valid:

+

# invalid recursion
+type MyTuple = tuple[a: ref MyTuple]

+

Likewise T = ref T is an invalid type.

+

As a syntactical extension, object types can be anonymous if declared in a type section via the ref object or ptr object notations. This feature is useful if an object should only gain reference semantics:

+

type
+  Node = ref object
+    le, ri: Node
+    data: int

+

To allocate a new traced object, the built-in procedure new has to be used. To deal with untraced memory, the procedures alloc, dealloc and realloc can be used. The documentation of the system module contains further information.

+ +

Nil

If a reference points to nothing, it has the value nil. nil is the default value for all ref and ptr types. The nil value can also be used like any other literal value. For example, it can be used in an assignment like myRef = nil.

+

Dereferencing nil is an unrecoverable fatal runtime error (and not a panic).

+

A successful dereferencing operation p[] implies that p is not nil. This can be exploited by the implementation to optimize code like:

+

p[].field = 3
+if p != nil:
+  # if p were nil, `p[]` would have caused a crash already,
+  # so we know `p` is always not nil here.
+  action()

+

Into:

+

p[].field = 3
+action()

+

Note: This is not comparable to C's "undefined behavior" for dereferencing NULL pointers.

+ +

Mixing GC'ed memory with ptr

Special care has to be taken if an untraced object contains traced objects like traced references, strings, or sequences: in order to free everything properly, the built-in procedure reset has to be called before freeing the untraced memory manually:

+

type
+  Data = tuple[x, y: int, s: string]
+
+# allocate memory for Data on the heap:
+var d = cast[ptr Data](alloc0(sizeof(Data)))
+
+# create a new string on the garbage collected heap:
+d.s = "abc"
+
+# tell the GC that the string is not needed anymore:
+reset(d.s)
+
+# free the memory:
+dealloc(d)

+

Without the reset call the memory allocated for the d.s string would never be freed. The example also demonstrates two important features for low-level programming: the sizeof proc returns the size of a type or value in bytes. The cast operator can circumvent the type system: the compiler is forced to treat the result of the alloc0 call (which returns an untyped pointer) as if it would have the type ptr Data. Casting should only be done if it is unavoidable: it breaks type safety and bugs can lead to mysterious crashes.

+

Note: The example only works because the memory is initialized to zero (alloc0 instead of alloc does this): d.s is thus initialized to binary zero which the string assignment can handle. One needs to know low-level details like this when mixing garbage-collected data with unmanaged memory.

+ +

Procedural type

A procedural type is internally a pointer to a procedure. nil is an allowed value for a variable of a procedural type.

+

Examples:

+

proc printItem(x: int) = ...
+
+proc forEach(c: proc (x: int) {.cdecl.}) =
+  ...
+
+forEach(printItem)  # this will NOT compile because calling conventions differ

+

type
+  OnMouseMove = proc (x, y: int) {.closure.}
+
+proc onMouseMove(mouseX, mouseY: int) =
+  # has default calling convention
+  echo "x: ", mouseX, " y: ", mouseY
+
+proc setOnMouseMove(mouseMoveEvent: OnMouseMove) = discard
+
+# ok, 'onMouseMove' has the default calling convention, which is compatible
+# to 'closure':
+setOnMouseMove(onMouseMove)

+

A subtle issue with procedural types is that the calling convention of the procedure influences the type compatibility: procedural types are only compatible if they have the same calling convention. As a special extension, a procedure of the calling convention nimcall can be passed to a parameter that expects a proc of the calling convention closure.

+

Nim supports these calling conventions:

+
nimcall
+
is the default convention used for a Nim proc. It is the same as fastcall, but only for C compilers that support fastcall.
+
closure
+
is the default calling convention for a procedural type that lacks any pragma annotations. It indicates that the procedure has a hidden implicit parameter (an environment). Proc vars that have the calling convention closure take up two machine words: One for the proc pointer and another one for the pointer to implicitly passed environment.
+
stdcall
+
This is the stdcall convention as specified by Microsoft. The generated C procedure is declared with the __stdcall keyword.
+
cdecl
+
The cdecl convention means that a procedure shall use the same convention as the C compiler. Under Windows the generated C procedure is declared with the __cdecl keyword.
+
safecall
+
This is the safecall convention as specified by Microsoft. The generated C procedure is declared with the __safecall keyword. The word safe refers to the fact that all hardware registers shall be pushed to the hardware stack.
+
inline
+
The inline convention means the caller should not call the procedure, but inline its code directly. Note that Nim does not inline, but leaves this to the C compiler; it generates __inline procedures. This is only a hint for the compiler: it may completely ignore it, and it may inline procedures that are not marked as inline.
+
noinline
+
The backend compiler may inline procedures that are not marked as inline. The noinline convention prevents it.
+
fastcall
+
Fastcall means different things to different C compilers. One gets whatever the C __fastcall means.
+
thiscall
+
This is the thiscall calling convention as specified by Microsoft, used on C++ class member functions on the x86 architecture.
+
syscall
+
The syscall convention is the same as __syscall in C. It is used for interrupts.
+
noconv
+
The generated C code will not have any explicit calling convention and thus use the C compiler's default calling convention. This is needed because Nim's default calling convention for procedures is fastcall to improve speed.
+
+

Most calling conventions exist only for the Windows 32-bit platform.

+

The default calling convention is nimcall, unless it is an inner proc (a proc inside of a proc). For an inner proc an analysis is performed whether it accesses its environment. If it does so, it has the calling convention closure, otherwise it has the calling convention nimcall.

+ +

Distinct type

A distinct type is a new type derived from a base type that is incompatible with its base type. In particular, it is an essential property of a distinct type that it does not imply a subtype relation between it and its base type. Explicit type conversions from a distinct type to its base type and vice versa are allowed. See also distinctBase to get the reverse operation.

+

A distinct type is an ordinal type if its base type is an ordinal type.

+ +

Modeling currencies

A distinct type can be used to model different physical units with a numerical base type, for example. The following example models currencies.

+

Different currencies should not be mixed in monetary calculations. Distinct types are a perfect tool to model different currencies:

+

type
+  Dollar = distinct int
+  Euro = distinct int
+
+var
+  d: Dollar
+  e: Euro
+
+echo d + 12
+# Error: cannot add a number with no unit and a `Dollar`

+

Unfortunately, d + 12.Dollar is not allowed either, because + is defined for int (among others), not for Dollar. So a + for dollars needs to be defined:

+

proc `+` (x, y: Dollar): Dollar =
+  result = Dollar(int(x) + int(y))

+

It does not make sense to multiply a dollar with a dollar, but with a number without unit; and the same holds for division:

+

proc `*` (x: Dollar, y: int): Dollar =
+  result = Dollar(int(x) * y)
+
+proc `*` (x: int, y: Dollar): Dollar =
+  result = Dollar(x * int(y))
+
+proc `div` ...

+

This quickly gets tedious. The implementations are trivial and the compiler should not generate all this code only to optimize it away later - after all + for dollars should produce the same binary code as + for ints. The pragma borrow has been designed to solve this problem; in principle, it generates the above trivial implementations:

+

proc `*` (x: Dollar, y: int): Dollar {.borrow.}
+proc `*` (x: int, y: Dollar): Dollar {.borrow.}
+proc `div` (x: Dollar, y: int): Dollar {.borrow.}

+

The borrow pragma makes the compiler use the same implementation as the proc that deals with the distinct type's base type, so no code is generated.

+

But it seems all this boilerplate code needs to be repeated for the Euro currency. This can be solved with templates.

+

template additive(typ: typedesc) =
+  proc `+` *(x, y: typ): typ {.borrow.}
+  proc `-` *(x, y: typ): typ {.borrow.}
+  
+  # unary operators:
+  proc `+` *(x: typ): typ {.borrow.}
+  proc `-` *(x: typ): typ {.borrow.}
+
+template multiplicative(typ, base: typedesc) =
+  proc `*` *(x: typ, y: base): typ {.borrow.}
+  proc `*` *(x: base, y: typ): typ {.borrow.}
+  proc `div` *(x: typ, y: base): typ {.borrow.}
+  proc `mod` *(x: typ, y: base): typ {.borrow.}
+
+template comparable(typ: typedesc) =
+  proc `<` * (x, y: typ): bool {.borrow.}
+  proc `<=` * (x, y: typ): bool {.borrow.}
+  proc `==` * (x, y: typ): bool {.borrow.}
+
+template defineCurrency(typ, base: untyped) =
+  type
+    typ* = distinct base
+  additive(typ)
+  multiplicative(typ, base)
+  comparable(typ)
+
+defineCurrency(Dollar, int)
+defineCurrency(Euro, int)

+

The borrow pragma can also be used to annotate the distinct type to allow certain builtin operations to be lifted:

+

type
+  Foo = object
+    a, b: int
+    s: string
+  
+  Bar {.borrow: `.`.} = distinct Foo
+
+var bb: ref Bar
+new bb
+# field access now valid
+bb.a = 90
+bb.s = "abc"

+

Currently, only the dot accessor can be borrowed in this way.

+ +

Avoiding SQL injection attacks

An SQL statement that is passed from Nim to an SQL database might be modeled as a string. However, using string templates and filling in the values is vulnerable to the famous SQL injection attack:

+

import std/strutils
+
+proc query(db: DbHandle, statement: string) = ...
+
+var
+  username: string
+
+db.query("SELECT FROM users WHERE name = '$1'" % username)
+# Horrible security hole, but the compiler does not mind!

+

This can be avoided by distinguishing strings that contain SQL from strings that don't. Distinct types provide a means to introduce a new string type SQL that is incompatible with string:

+

type
+  SQL = distinct string
+
+proc query(db: DbHandle, statement: SQL) = ...
+
+var
+  username: string
+
+db.query("SELECT FROM users WHERE name = '$1'" % username)
+# Static error: `query` expects an SQL string!

+

It is an essential property of abstract types that they do not imply a subtype relation between the abstract type and its base type. Explicit type conversions from string to SQL are allowed:

+

import std/[strutils, sequtils]
+
+proc properQuote(s: string): SQL =
+  # quotes a string properly for an SQL statement
+  return SQL(s)
+
+proc `%` (frmt: SQL, values: openarray[string]): SQL =
+  # quote each argument:
+  let v = values.mapIt(properQuote(it))
+  # we need a temporary type for the type conversion :-(
+  type StrSeq = seq[string]
+  # call strutils.`%`:
+  result = SQL(string(frmt) % StrSeq(v))
+
+db.query("SELECT FROM users WHERE name = '$1'".SQL % [username])

+

Now we have compile-time checking against SQL injection attacks. Since "".SQL is transformed to SQL("") no new syntax is needed for nice looking SQL string literals. The hypothetical SQL type actually exists in the library as the SqlQuery type of modules like db_sqlite.

+ +

Auto type

The auto type can only be used for return types and parameters. For return types it causes the compiler to infer the type from the routine body:

+

proc returnsInt(): auto = 1984

+

For parameters it currently creates implicitly generic routines:

+

proc foo(a, b: auto) = discard

+

Is the same as:

+

proc foo[T1, T2](a: T1, b: T2) = discard

+

However, later versions of the language might change this to mean "infer the parameters' types from the body". Then the above foo would be rejected as the parameters' types can not be inferred from an empty discard statement.

+ +

Type relations

The following section defines several relations on types that are needed to describe the type checking done by the compiler.

+ +

Type equality

Nim uses structural type equivalence for most types. Only for objects, enumerations and distinct types and for generic types name equivalence is used.

+ +

Subtype relation

If object a inherits from b, a is a subtype of b.

+

This subtype relation is extended to the types var, ref, ptr. If A is a subtype of B and A and B are object types then:

+
  • var A is a subtype of var B
  • +
  • ref A is a subtype of ref B
  • +
  • ptr A is a subtype of ptr B.
  • +
+

Note: One of the above pointer-indirections is required for assignment from a subtype to its parent type to prevent "object slicing".

+ +

Convertible relation

A type a is implicitly convertible to type b iff the following algorithm returns true:

+

proc isImplicitlyConvertible(a, b: PType): bool =
+  if isSubtype(a, b):
+    return true
+  if isIntLiteral(a):
+    return b in {int8, int16, int32, int64, int, uint, uint8, uint16,
+                 uint32, uint64, float32, float64}
+  case a.kind
+  of int:     result = b in {int32, int64}
+  of int8:    result = b in {int16, int32, int64, int}
+  of int16:   result = b in {int32, int64, int}
+  of int32:   result = b in {int64, int}
+  of uint:    result = b in {uint32, uint64}
+  of uint8:   result = b in {uint16, uint32, uint64}
+  of uint16:  result = b in {uint32, uint64}
+  of uint32:  result = b in {uint64}
+  of float32: result = b in {float64}
+  of float64: result = b in {float32}
+  of seq:
+    result = b == openArray and typeEquals(a.baseType, b.baseType)
+  of array:
+    result = b == openArray and typeEquals(a.baseType, b.baseType)
+    if a.baseType == char and a.indexType.rangeA == 0:
+      result = b == cstring
+  of cstring, ptr:
+    result = b == pointer
+  of string:
+    result = b == cstring
+  of proc:
+    result = typeEquals(a, b) or compatibleParametersAndEffects(a, b)

+

We used the predicate typeEquals(a, b) for the "type equality" property and the predicate isSubtype(a, b) for the "subtype relation". compatibleParametersAndEffects(a, b) is currently not specified.

+

Implicit conversions are also performed for Nim's range type constructor.

+

Let a0, b0 of type T.

+

Let A = range[a0..b0] be the argument's type, F the formal parameter's type. Then an implicit conversion from A to F exists if a0 >= low(F) and b0 <= high(F) and both T and F are signed integers or if both are unsigned integers.

+

A type a is explicitly convertible to type b iff the following algorithm returns true:

+

proc isIntegralType(t: PType): bool =
+  result = isOrdinal(t) or t.kind in {float, float32, float64}
+
+proc isExplicitlyConvertible(a, b: PType): bool =
+  result = false
+  if isImplicitlyConvertible(a, b): return true
+  if typeEquals(a, b): return true
+  if a == distinct and typeEquals(a.baseType, b): return true
+  if b == distinct and typeEquals(b.baseType, a): return true
+  if isIntegralType(a) and isIntegralType(b): return true
+  if isSubtype(a, b) or isSubtype(b, a): return true

+

The convertible relation can be relaxed by a user-defined type converter.

+

converter toInt(x: char): int = result = ord(x)
+
+var
+  x: int
+  chr: char = 'a'
+
+# implicit conversion magic happens here
+x = chr
+echo x # => 97
+# one can use the explicit form too
+x = chr.toInt
+echo x # => 97

+

The type conversion T(a) is an L-value if a is an L-value and typeEqualsOrDistinct(T, typeof(a)) holds.

+ +

Assignment compatibility

An expression b can be assigned to an expression a iff a is an l-value and isImplicitlyConvertible(b.typ, a.typ) holds.

+ +

Overload resolution

In a call p(args) where p may refer to more than one candidate, it is said to be a symbol choice. Overload resolution will attempt to find the best candidate, thus transforming the symbol choice into a resolved symbol. The routine p that matches best is selected following a series of trials explained below. In order: Category matching, Hierarchical Order Comparison, and finally, Complexity Analysis.

+

If multiple candidates match equally well after all trials have been tested, the ambiguity is reported during semantic analysis.

+ +

First Trial: Category matching

Every arg in args needs to match and there are multiple different categories of matches. Let f be the formal parameter's type and a the type of the argument.

+
  1. Exact match: a and f are of the same type.
  2. +
  3. Literal match: a is an integer literal of value v and f is a signed or unsigned integer type and v is in f's range. Or: a is a floating-point literal of value v and f is a floating-point type and v is in f's range.
  4. +
  5. Generic match: f is a generic type and a matches, for instance a is int and f is a generic (constrained) parameter type (like in [T] or [T: int|char]).
  6. +
  7. Subrange or subtype match: a is a range[T] and T matches f exactly. Or: a is a subtype of f.
  8. +
  9. Integral conversion match: a is convertible to f and f and a is some integer or floating-point type.
  10. +
  11. Conversion match: a is convertible to f, possibly via a user defined converter.
  12. +
+

Each operand may fall into one of the categories above; the operand's highest priority category. The list above is in order or priority. If a candidate has more priority matches than all other candidates, it is selected as the resolved symbol.

+

For example, if a candidate with one exact match is compared to a candidate with multiple generic matches and zero exact matches, the candidate with an exact match will win.

+

Below is a pseudocode interpretation of category matching, count(p, m) counts the number of matches of the matching category m for the routine p.

+

A routine p matches better than a routine q if the following algorithm returns true:

+

for each matching category m in ["exact match", "literal match",
+                                "generic match", "subtype match",
+                                "integral match", "conversion match"]:
+  if count(p, m) > count(q, m): return true
+  elif count(p, m) == count(q, m):
+    discard "continue with next category m"
+  else:
+    return false
+return "ambiguous"

+ +

Second Trial: Hierarchical Order Comparison

The hierarchical order of a type is analogous to its relative specificity. Consider the type defined:

+

type A[T] = object

+

Matching formals for this type include T, object, A, A[...] and A[C] where C is a concrete type, A[...] is a generic typeclass composition and T is an unconstrained generic type variable. This list is in order of specificity with respect to A as each subsequent category narrows the set of types that are members of their match set.

+

In this trial, the formal parameters of candidates are compared in order (1st parameter, 2nd parameter, etc.) to search for a candidate that has an unrivaled specificity. If such a formal parameter is found, the candidate it belongs to is chosen as the resolved symbol.

+ +

Third Trial: Complexity Analysis

A slight clarification: While category matching digests all the formal parameters of a candidate at once (order doesn't matter), specificity comparison and complexity analysis operate on each formal parameter at a time. The following is the final trial to disambiguate a symbol choice when a pair of formal parameters have the same hierarchical order.

+

The complexity of a type is essentially its number of modifiers and depth of shape. The definition with the highest complexity wins. Consider the following types:

+

type
+  A[T] = object
+  B[T, H] = object

+

Note: The below examples are not exhaustive.

+

We shall say that:

+
  1. A[T] has a higher complexity than A
  2. +
  3. var A[T] has a higher complexity than A[T]
  4. +
  5. A[A[T]] has a higher complexity than A[T]
  6. +
  7. B[T, H] has a higher complexity than A[T] (A and B are not compatible here, but convoluted versions of this exist)
  8. +
  9. B[ptr T, H] has a higher complexity than B[T, H]
  10. +
+ +

Some Examples

proc takesInt(x: int) = echo "int"
+proc takesInt[T](x: T) = echo "T"
+proc takesInt(x: int16) = echo "int16"
+
+takesInt(4) # "int"
+var x: int32
+takesInt(x) # "T"
+var y: int16
+takesInt(y) # "int16"
+var z: range[0..4] = 0
+takesInt(z) # "T"

+

If the argument a matches both the parameter type f of p and g of q via a subtyping relation, the inheritance depth is taken into account:

+

type
+  A = object of RootObj
+  B = object of A
+  C = object of B
+
+proc p(obj: A) =
+  echo "A"
+
+proc p(obj: B) =
+  echo "B"
+
+var c = C()
+# not ambiguous, calls 'B', not 'A' since B is a subtype of A
+# but not vice versa:
+p(c)
+
+proc pp(obj: A, obj2: B) = echo "A B"
+proc pp(obj: B, obj2: A) = echo "B A"
+
+# but this is ambiguous:
+pp(c, c)

+

Likewise, for generic matches, the most specialized generic type (that still matches) is preferred:

+

proc gen[T](x: ref ref T) = echo "ref ref T"
+proc gen[T](x: ref T) = echo "ref T"
+proc gen[T](x: T) = echo "T"
+
+var ri: ref int
+gen(ri) # "ref T"

+ +

Type variables match

When overload resolution is considering candidates, the type variable's definition is not overlooked as it is used to define the formal parameter's type via variable substitution.

+

For example:

+

type A
+proc p[T: A](param: T)
+proc p[T: object](param: T)

+

These signatures are not ambiguous for a concrete type of A even though the formal parameters match ("T" == "T"). Instead T is treated as a variable in that (T ?= T) depending on the bound type of T at the time of overload resolution.

+ +

Overloading based on 'var T'

If the formal parameter f is of type var T in addition to the ordinary type checking, the argument is checked to be an l-value. var T matches better than just T then.

+

proc sayHi(x: int): string =
+  # matches a non-var int
+  result = $x
+proc sayHi(x: var int): string =
+  # matches a var int
+  result = $(x + 10)
+
+proc sayHello(x: int) =
+  var m = x # a mutable version of x
+  echo sayHi(x) # matches the non-var version of sayHi
+  echo sayHi(m) # matches the var version of sayHi
+
+sayHello(3) # 3
+            # 13

+ +

Lazy type resolution for untyped

Note: An unresolved expression is an expression for which no symbol lookups and no type checking have been performed.

+

Since templates and macros that are not declared as immediate participate in overloading resolution, it's essential to have a way to pass unresolved expressions to a template or macro. This is what the meta-type untyped accomplishes:

+

template rem(x: untyped) = discard
+
+rem unresolvedExpression(undeclaredIdentifier)

+

A parameter of type untyped always matches any argument (as long as there is any argument passed to it).

+

But one has to watch out because other overloads might trigger the argument's resolution:

+

template rem(x: untyped) = discard
+proc rem[T](x: T) = discard
+
+# undeclared identifier: 'unresolvedExpression'
+rem unresolvedExpression(undeclaredIdentifier)

+

untyped and varargs[untyped] are the only metatype that are lazy in this sense, the other metatypes typed and typedesc are not lazy.

+ +

Varargs matching

See Varargs.

+ +

iterable

A called iterator yielding type T can be passed to a template or macro via a parameter typed as untyped (for unresolved expressions) or the type class iterable or iterable[T] (after type checking and overload resolution).

+

iterator iota(n: int): int =
+  for i in 0..<n: yield i
+
+template toSeq2[T](a: iterable[T]): seq[T] =
+  var ret: seq[T]
+  assert a.typeof is T
+  for ai in a: ret.add ai
+  ret
+
+assert iota(3).toSeq2 == @[0, 1, 2]
+assert toSeq2(5..7) == @[5, 6, 7]
+assert not compiles(toSeq2(@[1,2])) # seq[int] is not an iterable
+assert toSeq2(items(@[1,2])) == @[1, 2] # but items(@[1,2]) is

+ +

Overload disambiguation

For routine calls "overload resolution" is performed. There is a weaker form of overload resolution called overload disambiguation that is performed when an overloaded symbol is used in a context where there is additional type information available. Let p be an overloaded symbol. These contexts are:

+
  • In a function call q(..., p, ...) when the corresponding formal parameter of q is a proc type. If q itself is overloaded then the cartesian product of every interpretation of q and p must be considered.
  • +
  • In an object constructor Obj(..., field: p, ...) when field is a proc type. Analogous rules exist for array/set/tuple constructors.
  • +
  • In a declaration like x: T = p when T is a proc type.
  • +
+

As usual, ambiguous matches produce a compile-time error.

+ +

Named argument overloading

Routines with the same type signature can be called individually if a parameter has different names between them.

+

proc foo(x: int) =
+  echo "Using x: ", x
+proc foo(y: int) =
+  echo "Using y: ", y
+
+foo(x = 2) # Using x: 2
+foo(y = 2) # Using y: 2

+

Not supplying the parameter name in such cases results in an ambiguity error.

+ +

Statements and expressions

Nim uses the common statement/expression paradigm: Statements do not produce a value in contrast to expressions. However, some expressions are statements.

+

Statements are separated into simple statements and complex statements. Simple statements are statements that cannot contain other statements like assignments, calls, or the return statement; complex statements can contain other statements. To avoid the dangling else problem, complex statements always have to be indented. The details can be found in the grammar.

+ +

Statement list expression

Statements can also occur in an expression context that looks like (stmt1; stmt2; ...; ex). This is called a statement list expression or (;). The type of (stmt1; stmt2; ...; ex) is the type of ex. All the other statements must be of type void. (One can use discard to produce a void type.) (;) does not introduce a new scope.

+ +

Discard statement

Example:

+

proc p(x, y: int): int =
+  result = x + y
+
+discard p(3, 4) # discard the return value of `p`

+

The discard statement evaluates its expression for side-effects and throws the expression's resulting value away, and should only be used when ignoring this value is known not to cause problems.

+

Ignoring the return value of a procedure without using a discard statement is a static error.

+

The return value can be ignored implicitly if the called proc/iterator has been declared with the discardable pragma:

+

proc p(x, y: int): int {.discardable.} =
+  result = x + y
+
+p(3, 4) # now valid

+

however the discardable pragma does not work on templates as templates substitute the AST in place. For example:

+

{.push discardable .}
+template example(): string = "https://nim-lang.org"
+{.pop.}
+
+example()

+

This template will resolve into "https://nim-lang.org" which is a string literal and since {.discardable.} doesn't apply to literals, the compiler will error.

+

An empty discard statement is often used as a null statement:

+

proc classify(s: string) =
+  case s[0]
+  of SymChars, '_': echo "an identifier"
+  of '0'..'9': echo "a number"
+  else: discard

+ +

Void context

In a list of statements, every expression except the last one needs to have the type void. In addition to this rule an assignment to the builtin result symbol also triggers a mandatory void context for the subsequent expressions:

+

proc invalid*(): string =
+  result = "foo"
+  "invalid"  # Error: value of type 'string' has to be discarded

+

proc valid*(): string =
+  let x = 317
+  "valid"

+ +

Var statement

Var statements declare new local and global variables and initialize them. A comma-separated list of variables can be used to specify variables of the same type:

+

var
+  a: int = 0
+  x, y, z: int

+

If an initializer is given, the type can be omitted: the variable is then of the same type as the initializing expression. Variables are always initialized with a default value if there is no initializing expression. The default value depends on the type and is always a zero in binary.

+ + + + + + + + + + + + + +
Typedefault value
any integer type0
any float0.0
char'\0'
boolfalse
ref or pointer typenil
procedural typenil
sequence@[]
string""
tuple[x: A, y: B, ...](zeroDefault(A), zeroDefault(B), ...) (analogous for objects)
array[0..., T][zeroDefault(T), ...]
range[T]default(T); this may be out of the valid range
T = enumcast[T](0); this may be an invalid value

The implicit initialization can be avoided for optimization reasons with the noinit pragma:

+

var
+  a {.noinit.}: array[0..1023, char]

+

If a proc is annotated with the noinit pragma, this refers to its implicit result variable:

+

proc returnUndefinedValue: int {.noinit.} = discard

+

The implicit initialization can also be prevented by the requiresInit type pragma. The compiler requires an explicit initialization for the object and all of its fields. However, it does a control flow analysis to prove the variable has been initialized and does not rely on syntactic properties:

+

type
+  MyObject {.requiresInit.} = object
+
+proc p() =
+  # the following is valid:
+  var x: MyObject
+  if someCondition():
+    x = a()
+  else:
+    x = a()
+  # use x

+

requiresInit pragma can also be applied to distinct types.

+

Given the following distinct type definitions:

+

type
+  Foo = object
+    x: string
+  
+  DistinctFoo {.requiresInit, borrow: `.`.} = distinct Foo
+  DistinctString {.requiresInit.} = distinct string

+

The following code blocks will fail to compile:

+

var foo: DistinctFoo
+foo.x = "test"
+doAssert foo.x == "test"

+

var s: DistinctString
+s = "test"
+doAssert string(s) == "test"

+

But these will compile successfully:

+

let foo = DistinctFoo(Foo(x: "test"))
+doAssert foo.x == "test"

+

let s = DistinctString("test")
+doAssert string(s) == "test"

+ +

Let statement

A let statement declares new local and global single assignment variables and binds a value to them. The syntax is the same as that of the var statement, except that the keyword var is replaced by the keyword let. Let variables are not l-values and can thus not be passed to var parameters nor can their address be taken. They cannot be assigned new values.

+

For let variables, the same pragmas are available as for ordinary variables.

+

As let statements are immutable after creation they need to define a value when they are declared. The only exception to this is if the {.importc.} pragma (or any of the other importX pragmas) is applied, in this case the value is expected to come from native code, typically a C/C++ const.

+ +

Special identifier _ (underscore)

The identifier _ has a special meaning in declarations. Any definition with the name _ will not be added to scope, meaning the definition is evaluated, but cannot be used. As a result the name _ can be indefinitely redefined.

+

let _ = 123
+echo _ # error
+let _ = 456 # compiles

+ +

Tuple unpacking

In a var, let or const statement tuple unpacking can be performed. The special identifier _ can be used to ignore some parts of the tuple:

+

proc returnsTuple(): (int, int, int) = (4, 2, 3)
+
+let (x, _, z) = returnsTuple()

+

This is treated as syntax sugar for roughly the following:

+

let
+  tmpTuple = returnsTuple()
+  x = tmpTuple[0]
+  z = tmpTuple[2]

+

For var or let statements, if the value expression is a tuple literal, each expression is directly expanded into an assignment without the use of a temporary variable.

+

let (x, y, z) = (1, 2, 3)
+# becomes
+let
+  x = 1
+  y = 2
+  z = 3

+

Tuple unpacking can also be nested:

+

proc returnsNestedTuple(): (int, (int, int), int, int) = (4, (5, 7), 2, 3)
+
+let (x, (_, y), _, z) = returnsNestedTuple()

+ +

Const section

A const section declares constants whose values are constant expressions:

+

import std/[strutils]
+const
+  roundPi = 3.1415
+  constEval = contains("abc", 'b') # computed at compile time!

+

Once declared, a constant's symbol can be used as a constant expression.

+

The value part of a constant declaration opens a new scope for each constant, so no symbols declared in the constant value are accessible outside of it.

+

const foo = (var a = 1; a)
+const bar = a # error
+let baz = a # error

+

See Constants and Constant Expressions for details.

+ +

Static statement/expression

A static statement/expression explicitly requires compile-time execution. Even some code that has side effects is permitted in a static block:

+

static:
+  echo "echo at compile time"

+

static can also be used like a routine.

+

proc getNum(a: int): int = a
+
+# Below calls "echo getNum(123)" at compile time.
+static:
+  echo getNum(123)
+
+# Below call evaluates the "getNum(123)" at compile time, but its
+# result gets used at run time.
+echo static(getNum(123))

+

There are limitations on what Nim code can be executed at compile time; see Restrictions on Compile-Time Execution for details. It's a static error if the compiler cannot execute the block at compile time.

+ +

If statement

Example:

+

var name = readLine(stdin)
+
+if name == "Andreas":
+  echo "What a nice name!"
+elif name == "":
+  echo "Don't you have a name?"
+else:
+  echo "Boring name..."

+

The if statement is a simple way to make a branch in the control flow: The expression after the keyword if is evaluated, if it is true the corresponding statements after the : are executed. Otherwise, the expression after the elif is evaluated (if there is an elif branch), if it is true the corresponding statements after the : are executed. This goes on until the last elif. If all conditions fail, the else part is executed. If there is no else part, execution continues with the next statement.

+

In if statements, new scopes begin immediately after the if/elif/else keywords and ends after the corresponding then block. For visualization purposes the scopes have been enclosed in {| |} in the following example:

+

if {| (let m = input =~ re"(\w+)=\w+"; m.isMatch):
+  echo "key ", m[0], " value ", m[1]  |}
+elif {| (let m = input =~ re""; m.isMatch):
+  echo "new m in this scope"  |}
+else: {|
+  echo "m not declared here"  |}

+ +

Case statement

Example:

+

let line = readline(stdin)
+case line
+of "delete-everything", "restart-computer":
+  echo "permission denied"
+of "go-for-a-walk":     echo "please yourself"
+elif line.len == 0:     echo "empty" # optional, must come after `of` branches
+else:                   echo "unknown command" # ditto
+
+# indentation of the branches is also allowed; and so is an optional colon
+# after the selecting expression:
+case readline(stdin):
+  of "delete-everything", "restart-computer":
+    echo "permission denied"
+  of "go-for-a-walk":     echo "please yourself"
+  else:                   echo "unknown command"

+

The case statement is similar to the if statement, but it represents a multi-branch selection. The expression after the keyword case is evaluated and if its value is in a slicelist the corresponding statements (after the of keyword) are executed. If the value is not in any given slicelist, trailing elif and else parts are executed using same semantics as for if statement, and elif is handled just like else: if. If there are no else or elif parts and not all possible values that expr can hold occur in a slicelist, a static error occurs. This holds only for expressions of ordinal types. "All possible values" of expr are determined by expr's type. To suppress the static error an else: discard should be used.

+

Only ordinal types, floats, strings and cstrings are allowed as values in case statements.

+

For non-ordinal types, it is not possible to list every possible value and so these always require an else part. An exception to this rule is for the string type, which currently doesn't require a trailing else or elif branch; it's unspecified whether this will keep working in future versions.

+

Because case statements are checked for exhaustiveness during semantic analysis, the value in every of branch must be a constant expression. This restriction also allows the compiler to generate more performant code.

+

As a special semantic extension, an expression in an of branch of a case statement may evaluate to a set or array constructor; the set or array is then expanded into a list of its elements:

+

const
+  SymChars: set[char] = {'a'..'z', 'A'..'Z', '\x80'..'\xFF'}
+
+proc classify(s: string) =
+  case s[0]
+  of SymChars, '_': echo "an identifier"
+  of '0'..'9': echo "a number"
+  else: echo "other"
+
+# is equivalent to:
+proc classify(s: string) =
+  case s[0]
+  of 'a'..'z', 'A'..'Z', '\x80'..'\xFF', '_': echo "an identifier"
+  of '0'..'9': echo "a number"
+  else: echo "other"

+

The case statement doesn't produce an l-value, so the following example won't work:

+

type
+  Foo = ref object
+    x: seq[string]
+
+proc get_x(x: Foo): var seq[string] =
+  # doesn't work
+  case true
+  of true:
+    x.x
+  else:
+    x.x
+
+var foo = Foo(x: @[])
+foo.get_x().add("asd")

+

This can be fixed by explicitly using result or return:

+

proc get_x(x: Foo): var seq[string] =
+  case true
+  of true:
+    result = x.x
+  else:
+    result = x.x

+ +

When statement

Example:

+

when sizeof(int) == 2:
+  echo "running on a 16 bit system!"
+elif sizeof(int) == 4:
+  echo "running on a 32 bit system!"
+elif sizeof(int) == 8:
+  echo "running on a 64 bit system!"
+else:
+  echo "cannot happen!"

+

The when statement is almost identical to the if statement with some exceptions:

+
  • Each condition (expr) has to be a constant expression (of type bool).
  • +
  • The statements do not open a new scope.
  • +
  • The statements that belong to the expression that evaluated to true are translated by the compiler, the other statements are not checked for semantics! However, each condition is checked for semantics.
  • +
+

The when statement enables conditional compilation techniques. As a special syntactic extension, the when construct is also available within object definitions.

+ +

When nimvm statement

nimvm is a special symbol that may be used as the expression of a when nimvm statement to differentiate the execution path between compile-time and the executable.

+

Example:

+

proc someProcThatMayRunInCompileTime(): bool =
+  when nimvm:
+    # This branch is taken at compile time.
+    result = true
+  else:
+    # This branch is taken in the executable.
+    result = false
+const ctValue = someProcThatMayRunInCompileTime()
+let rtValue = someProcThatMayRunInCompileTime()
+assert(ctValue == true)
+assert(rtValue == false)

+

A when nimvm statement must meet the following requirements:

+
  • Its expression must always be nimvm. More complex expressions are not allowed.
  • +
  • It must not contain elif branches.
  • +
  • It must contain an else branch.
  • +
  • Code in branches must not affect semantics of the code that follows the when nimvm statement. E.g. it must not define symbols that are used in the following code.
  • +
+ +

Return statement

Example:

+

return 40 + 2

+

The return statement ends the execution of the current procedure. It is only allowed in procedures. If there is an expr, this is syntactic sugar for:

+

result = expr
+return result

+

return without an expression is a short notation for return result if the proc has a return type. The result variable is always the return value of the procedure. It is automatically declared by the compiler. As all variables, result is initialized to (binary) zero:

+

proc returnZero(): int =
+  # implicitly returns 0

+ +

Yield statement

Example:

+

yield (1, 2, 3)

+

The yield statement is used instead of the return statement in iterators. It is only valid in iterators. Execution is returned to the body of the for loop that called the iterator. Yield does not end the iteration process, but the execution is passed back to the iterator if the next iteration starts. See the section about iterators (Iterators and the for statement) for further information.

+ +

Block statement

Example:

+

var found = false
+block myblock:
+  for i in 0..3:
+    for j in 0..3:
+      if a[j][i] == 7:
+        found = true
+        break myblock # leave the block, in this case both for-loops
+echo found

+

The block statement is a means to group statements to a (named) block. Inside the block, the break statement is allowed to leave the block immediately. A break statement can contain a name of a surrounding block to specify which block is to be left.

+ +

Break statement

Example:

+

break

+

The break statement is used to leave a block immediately. If symbol is given, it is the name of the enclosing block that is to be left. If it is absent, the innermost block is left.

+ +

While statement

Example:

+

echo "Please tell me your password:"
+var pw = readLine(stdin)
+while pw != "12345":
+  echo "Wrong password! Next try:"
+  pw = readLine(stdin)

+

The while statement is executed until the expr evaluates to false. Endless loops are no error. while statements open an implicit block so that they can be left with a break statement.

+ +

Continue statement

A continue statement leads to the immediate next iteration of the surrounding loop construct. It is only allowed within a loop. A continue statement is syntactic sugar for a nested block:

+

while expr1:
+  stmt1
+  continue
+  stmt2

+

Is equivalent to:

+

while expr1:
+  block myBlockName:
+    stmt1
+    break myBlockName
+    stmt2

+ +

Assembler statement

The direct embedding of assembler code into Nim code is supported by the unsafe asm statement. Identifiers in the assembler code that refer to Nim identifiers shall be enclosed in a special character which can be specified in the statement's pragmas. The default special character is '`':

+

{.push stackTrace:off.}
+proc addInt(a, b: int): int =
+  # a in eax, and b in edx
+  asm """
+      mov eax, `a`
+      add eax, `b`
+      jno theEnd
+      call `raiseOverflow`
+    theEnd:
+  """
+{.pop.}

+

If the GNU assembler is used, quotes and newlines are inserted automatically:

+

proc addInt(a, b: int): int =
+  asm """
+    addl %%ecx, %%eax
+    jno 1
+    call `raiseOverflow`
+    1:
+    :"=a"(`result`)
+    :"a"(`a`), "c"(`b`)
+  """

+

Instead of:

+

proc addInt(a, b: int): int =
+  asm """
+    "addl %%ecx, %%eax\n"
+    "jno 1\n"
+    "call `raiseOverflow`\n"
+    "1: \n"
+    :"=a"(`result`)
+    :"a"(`a`), "c"(`b`)
+  """

+ +

Using statement

The using statement provides syntactic convenience in modules where the same parameter names and types are used over and over. Instead of:

+

proc foo(c: Context; n: Node) = ...
+proc bar(c: Context; n: Node, counter: int) = ...
+proc baz(c: Context; n: Node) = ...

+

One can tell the compiler about the convention that a parameter of name c should default to type Context, n should default to Node etc.:

+

using
+  c: Context
+  n: Node
+  counter: int
+
+proc foo(c, n) = ...
+proc bar(c, n, counter) = ...
+proc baz(c, n) = ...
+
+proc mixedMode(c, n; x, y: int) =
+  # 'c' is inferred to be of the type 'Context'
+  # 'n' is inferred to be of the type 'Node'
+  # But 'x' and 'y' are of type 'int'.

+

The using section uses the same indentation based grouping syntax as a var or let section.

+

Note that using is not applied for template since the untyped template parameters default to the type system.untyped.

+

Mixing parameters that should use the using declaration with parameters that are explicitly typed is possible and requires a semicolon between them.

+ +

If expression

An if expression is almost like an if statement, but it is an expression. This feature is similar to ternary operators in other languages. Example:

+

var y = if x > 8: 9 else: 10

+

An if expression always results in a value, so the else part is required. elif parts are also allowed.

+ +

When expression

Just like an if expression, but corresponding to the when statement.

+ +

Case expression

The case expression is again very similar to the case statement:

+

var favoriteFood = case animal
+  of "dog": "bones"
+  of "cat": "mice"
+  elif animal.endsWith"whale": "plankton"
+  else:
+    echo "I'm not sure what to serve, but everybody loves ice cream"
+    "ice cream"

+

As seen in the above example, the case expression can also introduce side effects. When multiple statements are given for a branch, Nim will use the last expression as the result value.

+ +

Block expression

A block expression is almost like a block statement, but it is an expression that uses the last expression under the block as the value. It is similar to the statement list expression, but the statement list expression does not open a new block scope.

+

let a = block:
+  var fib = @[0, 1]
+  for i in 0..10:
+    fib.add fib[^1] + fib[^2]
+  fib

+ +

Table constructor

A table constructor is syntactic sugar for an array constructor:

+

{"key1": "value1", "key2", "key3": "value2"}
+
+# is the same as:
+[("key1", "value1"), ("key2", "value2"), ("key3", "value2")]

+

The empty table can be written {:} (in contrast to the empty set which is {}) which is thus another way to write the empty array constructor []. This slightly unusual way of supporting tables has lots of advantages:

+
  • The order of the (key,value)-pairs is preserved, thus it is easy to support ordered dicts with for example {key: val}.newOrderedTable.
  • +
  • A table literal can be put into a const section and the compiler can easily put it into the executable's data section just like it can for arrays and the generated data section requires a minimal amount of memory.
  • +
  • Every table implementation is treated equally syntactically.
  • +
  • Apart from the minimal syntactic sugar, the language core does not need to know about tables.
  • +
+ +

Type conversions

Syntactically a type conversion is like a procedure call, but a type name replaces the procedure name. A type conversion is always safe in the sense that a failure to convert a type to another results in an exception (if it cannot be determined statically).

+

Ordinary procs are often preferred over type conversions in Nim: For instance, $ is the toString operator by convention and toFloat and toInt can be used to convert from floating-point to integer or vice versa.

+

Type conversion can also be used to disambiguate overloaded routines:

+

proc p(x: int) = echo "int"
+proc p(x: string) = echo "string"
+
+let procVar = (proc(x: string))(p)
+procVar("a")

+

Since operations on unsigned numbers wrap around and are unchecked so are type conversions to unsigned integers and between unsigned integers. The rationale for this is mostly better interoperability with the C Programming language when algorithms are ported from C to Nim.

+

Note: Historically the operations were unchecked and the conversions were sometimes checked but starting with the revision 1.0.4 of this document and the language implementation the conversions too are now always unchecked.

+ +

Type casts

Type casts are a crude mechanism to interpret the bit pattern of an expression as if it would be of another type. Type casts are only needed for low-level programming and are inherently unsafe.

+

cast[int](x)

+

The target type of a cast must be a concrete type, for instance, a target type that is a type class (which is non-concrete) would be invalid:

+

type Foo = int or float
+var x = cast[Foo](1) # Error: cannot cast to a non concrete type: 'Foo'

+

Type casts should not be confused with type conversions, as mentioned in the prior section. Unlike type conversions, a type cast cannot change the underlying bit pattern of the data being cast (aside from that the size of the target type may differ from the source type). Casting resembles type punning in other languages or C++'s reinterpret_cast and bit_cast features.

+

If the size of the target type is larger than the size of the source type, the remaining memory is zeroed.

+ +

The addr operator

The addr operator returns the address of an l-value. If the type of the location is T, the addr operator result is of the type ptr T. An address is always an untraced reference. Taking the address of an object that resides on the stack is unsafe, as the pointer may live longer than the object on the stack and can thus reference a non-existing object. One can get the address of variables. For easier interoperability with other compiled languages such as C, retrieving the address of a let variable, a parameter, or a for loop variable can be accomplished too:

+

let t1 = "Hello"
+var
+  t2 = t1
+  t3 : pointer = addr(t2)
+echo repr(addr(t2))
+# --> ref 0x7fff6b71b670 --> 0x10bb81050"Hello"
+echo cast[ptr string](t3)[]
+# --> Hello
+# The following line also works
+echo repr(addr(t1))

+ +

The unsafeAddr operator

The unsafeAddr operator is a deprecated alias for the addr operator:

+

let myArray = [1, 2, 3]
+foreignProcThatTakesAnAddr(unsafeAddr myArray)

+ +

Procedures

What most programming languages call methods or functions are called procedures in Nim. A procedure declaration consists of an identifier, zero or more formal parameters, a return value type and a block of code. Formal parameters are declared as a list of identifiers separated by either comma or semicolon. A parameter is given a type by : typename. The type applies to all parameters immediately before it, until either the beginning of the parameter list, a semicolon separator, or an already typed parameter, is reached. The semicolon can be used to make separation of types and subsequent identifiers more distinct.

+

# Using only commas
+proc foo(a, b: int, c, d: bool): int
+
+# Using semicolon for visual distinction
+proc foo(a, b: int; c, d: bool): int
+
+# Will fail: a is untyped since ';' stops type propagation.
+proc foo(a; b: int; c, d: bool): int

+

A parameter may be declared with a default value which is used if the caller does not provide a value for the argument. The value will be reevaluated every time the function is called.

+

# b is optional with 47 as its default value.
+proc foo(a: int, b: int = 47): int

+

Parameters can be declared mutable and so allow the proc to modify those arguments, by using the type modifier var.

+

# "returning" a value to the caller through the 2nd argument
+# Notice that the function uses no actual return value at all (ie void)
+proc foo(inp: int, outp: var int) =
+  outp = inp + 47

+

If the proc declaration doesn't have a body, it is a forward declaration. If the proc returns a value, the procedure body can access an implicitly declared variable named result that represents the return value. Procs can be overloaded. The overloading resolution algorithm determines which proc is the best match for the arguments. Example:

+

proc toLower(c: char): char = # toLower for characters
+  if c in {'A'..'Z'}:
+    result = chr(ord(c) + (ord('a') - ord('A')))
+  else:
+    result = c
+
+proc toLower(s: string): string = # toLower for strings
+  result = newString(len(s))
+  for i in 0..len(s) - 1:
+    result[i] = toLower(s[i]) # calls toLower for characters; no recursion!

+

Calling a procedure can be done in many ways:

+

proc callme(x, y: int, s: string = "", c: char, b: bool = false) = ...
+
+# call with positional arguments      # parameter bindings:
+callme(0, 1, "abc", '\t', true)       # (x=0, y=1, s="abc", c='\t', b=true)
+# call with named and positional arguments:
+callme(y=1, x=0, "abd", '\t')         # (x=0, y=1, s="abd", c='\t', b=false)
+# call with named arguments (order is not relevant):
+callme(c='\t', y=1, x=0)              # (x=0, y=1, s="", c='\t', b=false)
+# call as a command statement: no () needed:
+callme 0, 1, "abc", '\t'              # (x=0, y=1, s="abc", c='\t', b=false)

+

A procedure may call itself recursively.

+

Operators are procedures with a special operator symbol as identifier:

+

proc `$` (x: int): string =
+  # converts an integer to a string; this is a prefix operator.
+  result = intToStr(x)

+

Operators with one parameter are prefix operators, operators with two parameters are infix operators. (However, the parser distinguishes these from the operator's position within an expression.) There is no way to declare postfix operators: all postfix operators are built-in and handled by the grammar explicitly.

+

Any operator can be called like an ordinary proc with the `opr` notation. (Thus an operator can have more than two parameters):

+

proc `*+` (a, b, c: int): int =
+  # Multiply and add
+  result = a * b + c
+
+assert `*+`(3, 4, 6) == `+`(`*`(a, b), c)

+ +

Export marker

If a declared symbol is marked with an asterisk it is exported from the current module:

+

proc exportedEcho*(s: string) = echo s
+proc `*`*(a: string; b: int): string =
+  result = newStringOfCap(a.len * b)
+  for i in 1..b: result.add a
+
+var exportedVar*: int
+const exportedConst* = 78
+type
+  ExportedType* = object
+    exportedField*: int

+ +

Method call syntax

For object-oriented programming, the syntax obj.methodName(args) can be used instead of methodName(obj, args). The parentheses can be omitted if there are no remaining arguments: obj.len (instead of len(obj)).

+

This method call syntax is not restricted to objects, it can be used to supply any type of first argument for procedures:

+

echo "abc".len # is the same as echo len "abc"
+echo "abc".toUpper()
+echo {'a', 'b', 'c'}.card
+stdout.writeLine("Hallo") # the same as writeLine(stdout, "Hallo")

+

Another way to look at the method call syntax is that it provides the missing postfix notation.

+

The method call syntax conflicts with explicit generic instantiations: p[T](x) cannot be written as x.p[T] because x.p[T] is always parsed as (x.p)[T].

+

See also: Limitations of the method call syntax.

+

The [: ] notation has been designed to mitigate this issue: x.p[:T] is rewritten by the parser to p[T](x), x.p[:T](y) is rewritten to p[T](x, y). Note that [: ] has no AST representation, the rewrite is performed directly in the parsing step.

+ +

Properties

Nim has no need for get-properties: Ordinary get-procedures that are called with the method call syntax achieve the same. But setting a value is different; for this, a special setter syntax is needed:

+

# Module asocket
+type
+  Socket* = ref object of RootObj
+    host: int # cannot be accessed from the outside of the module
+
+proc `host=`*(s: var Socket, value: int) {.inline.} =
+  ## setter of hostAddr.
+  ## This accesses the 'host' field and is not a recursive call to
+  ## `host=` because the builtin dot access is preferred if it is
+  ## available:
+  s.host = value
+
+proc host*(s: Socket): int {.inline.} =
+  ## getter of hostAddr
+  ## This accesses the 'host' field and is not a recursive call to
+  ## `host` because the builtin dot access is preferred if it is
+  ## available:
+  s.host

+

# module B
+import asocket
+var s: Socket
+new s
+s.host = 34  # same as `host=`(s, 34)

+

A proc defined as f= (with the trailing =) is called a setter. A setter can be called explicitly via the common backticks notation:

+

proc `f=`(x: MyObject; value: string) =
+  discard
+
+`f=`(myObject, "value")

+

f= can be called implicitly in the pattern x.f = value if and only if the type of x does not have a field named f or if f is not visible in the current module. These rules ensure that object fields and accessors can have the same name. Within the module x.f is then always interpreted as field access and outside the module it is interpreted as an accessor proc call.

+ +

Command invocation syntax

Routines can be invoked without the () if the call is syntactically a statement. This command invocation syntax also works for expressions, but then only a single argument may follow. This restriction means echo f 1, f 2 is parsed as echo(f(1), f(2)) and not as echo(f(1, f(2))). The method call syntax may be used to provide one more argument in this case:

+

proc optarg(x: int, y: int = 0): int = x + y
+proc singlearg(x: int): int = 20*x
+
+echo optarg 1, " ", singlearg 2  # prints "1 40"
+
+let fail = optarg 1, optarg 8   # Wrong. Too many arguments for a command call
+let x = optarg(1, optarg 8)  # traditional procedure call with 2 arguments
+let y = 1.optarg optarg 8    # same thing as above, w/o the parenthesis
+assert x == y

+

The command invocation syntax also can't have complex expressions as arguments. For example: anonymous procedures, if, case or try. Function calls with no arguments still need () to distinguish between a call and the function itself as a first-class value.

+ +

Closures

Procedures can appear at the top level in a module as well as inside other scopes, in which case they are called nested procs. A nested proc can access local variables from its enclosing scope and if it does so it becomes a closure. Any captured variables are stored in a hidden additional argument to the closure (its environment) and they are accessed by reference by both the closure and its enclosing scope (i.e. any modifications made to them are visible in both places). The closure environment may be allocated on the heap or on the stack if the compiler determines that this would be safe.

+ +

Creating closures in loops

Since closures capture local variables by reference it is often not wanted behavior inside loop bodies. See closureScope and capture for details on how to change this behavior.

+ +

Anonymous procedures

Unnamed procedures can be used as lambda expressions to pass into other procedures:

+

var cities = @["Frankfurt", "Tokyo", "New York", "Kyiv"]
+
+cities.sort(proc (x, y: string): int =
+  cmp(x.len, y.len))

+

Procs as expressions can appear both as nested procs and inside top-level executable code. The sugar module contains the => macro which enables a more succinct syntax for anonymous procedures resembling lambdas as they are in languages like JavaScript, C#, etc.

+ +

Do notation

As a special convenience notation that keeps most elements of a regular proc expression, the do keyword can be used to pass anonymous procedures to routines:

+

var cities = @["Frankfurt", "Tokyo", "New York", "Kyiv"]
+
+sort(cities) do (x, y: string) -> int:
+  cmp(x.len, y.len)
+
+# Less parentheses using the method plus command syntax:
+cities = cities.map do (x: string) -> string:
+  "City of " & x

+

do is written after the parentheses enclosing the regular proc parameters. The proc expression represented by the do block is appended to the routine call as the last argument. In calls using the command syntax, the do block will bind to the immediately preceding expression rather than the command call.

+

do with a parameter list or pragma list corresponds to an anonymous proc, however do without parameters or pragmas is treated as a normal statement list. This allows macros to receive both indented statement lists as an argument in inline calls, as well as a direct mirror of Nim's routine syntax.

+

# Passing a statement list to an inline macro:
+macroResults.add quote do:
+  if not `ex`:
+    echo `info`, ": Check failed: ", `expString`
+
+# Processing a routine definition in a macro:
+rpc(router, "add") do (a, b: int) -> int:
+  result = a + b

+ +

Func

The func keyword introduces a shortcut for a noSideEffect proc.

+

func binarySearch[T](a: openArray[T]; elem: T): int

+

Is short for:

+

proc binarySearch[T](a: openArray[T]; elem: T): int {.noSideEffect.}

+ +

Routines

A routine is a symbol of kind: proc, func, method, iterator, macro, template, converter.

+ +

Type bound operators

A type bound operator is a proc or func whose name starts with = but isn't an operator (i.e. containing only symbols, such as ==). These are unrelated to setters (see Properties), which instead end in =. A type bound operator declared for a type applies to the type regardless of whether the operator is in scope (including if it is private).

+

# foo.nim:
+var witness* = 0
+type Foo[T] = object
+proc initFoo*(T: typedesc): Foo[T] = discard
+proc `=destroy`[T](x: var Foo[T]) = witness.inc # type bound operator
+
+# main.nim:
+import foo
+block:
+  var a = initFoo(int)
+  doAssert witness == 0
+doAssert witness == 1
+block:
+  var a = initFoo(int)
+  doAssert witness == 1
+  `=destroy`(a) # can be called explicitly, even without being in scope
+  doAssert witness == 2
+# will still be called upon exiting scope
+doAssert witness == 3

+

Type bound operators are: =destroy, =copy, =sink, =trace, =deepcopy, =wasMoved, =dup.

+

These operations can be overridden instead of overloaded. This means that the implementation is automatically lifted to structured types. For instance, if the type T has an overridden assignment operator =, this operator is also used for assignments of the type seq[T].

+

Since these operations are bound to a type, they have to be bound to a nominal type for reasons of simplicity of implementation; this means an overridden deepCopy for ref T is really bound to T and not to ref T. This also means that one cannot override deepCopy for both ptr T and ref T at the same time, instead a distinct or object helper type has to be used for one pointer type.

+

For more details on some of those procs, see Lifetime-tracking hooks.

+ +

Nonoverloadable builtins

The following built-in procs cannot be overloaded for reasons of implementation simplicity (they require specialized semantic checking):

+
declared, defined, definedInScope, compiles, sizeof,
+is, shallowCopy, getAst, astToStr, spawn, procCall
+

Thus, they act more like keywords than like ordinary identifiers; unlike a keyword however, a redefinition may shadow the definition in the system module. From this list the following should not be written in dot notation x.f since x cannot be type-checked before it gets passed to f:

+
declared, defined, definedInScope, compiles, getAst, astToStr
+ +

Var parameters

The type of a parameter may be prefixed with the var keyword:

+

proc divmod(a, b: int; res, remainder: var int) =
+  res = a div b
+  remainder = a mod b
+
+var
+  x, y: int
+
+divmod(8, 5, x, y) # modifies x and y
+assert x == 1
+assert y == 3

+

In the example, res and remainder are var parameters. Var parameters can be modified by the procedure and the changes are visible to the caller. The argument passed to a var parameter has to be an l-value. Var parameters are implemented as hidden pointers. The above example is equivalent to:

+

proc divmod(a, b: int; res, remainder: ptr int) =
+  res[] = a div b
+  remainder[] = a mod b
+
+var
+  x, y: int
+divmod(8, 5, addr(x), addr(y))
+assert x == 1
+assert y == 3

+

In the examples, var parameters or pointers are used to provide two return values. This can be done in a cleaner way by returning a tuple:

+

proc divmod(a, b: int): tuple[res, remainder: int] =
+  (a div b, a mod b)
+
+var t = divmod(8, 5)
+
+assert t.res == 1
+assert t.remainder == 3

+

One can use tuple unpacking to access the tuple's fields:

+

var (x, y) = divmod(8, 5) # tuple unpacking
+assert x == 1
+assert y == 3

+

Note: var parameters are never necessary for efficient parameter passing. Since non-var parameters cannot be modified the compiler is always free to pass arguments by reference if it considers it can speed up execution.

+ +

Var return type

A proc, converter, or iterator may return a var type which means that the returned value is an l-value and can be modified by the caller:

+

var g = 0
+
+proc writeAccessToG(): var int =
+  result = g
+
+writeAccessToG() = 6
+assert g == 6

+

It is a static error if the implicitly introduced pointer could be used to access a location beyond its lifetime:

+

proc writeAccessToG(): var int =
+  var g = 0
+  result = g # Error!

+

For iterators, a component of a tuple return type can have a var type too:

+

iterator mpairs(a: var seq[string]): tuple[key: int, val: var string] =
+  for i in 0..a.high:
+    yield (i, a[i])

+

In the standard library every name of a routine that returns a var type starts with the prefix m per convention.

+

Memory safety for returning by var T is ensured by a simple borrowing rule: If result does not refer to a location pointing to the heap (that is in result = X the X involves a ptr or ref access) then it has to be derived from the routine's first parameter:

+

proc forward[T](x: var T): var T =
+  result = x # ok, derived from the first parameter.
+
+proc p(param: var int): var int =
+  var x: int
+  # we know 'forward' provides a view into the location derived from
+  # its first argument 'x'.
+  result = forward(x) # Error: location is derived from `x`
+                      # which is not p's first parameter and lives
+                      # on the stack.

+

In other words, the lifetime of what result points to is attached to the lifetime of the first parameter and that is enough knowledge to verify memory safety at the call site.

+ +

Future directions

Later versions of Nim can be more precise about the borrowing rule with a syntax like:

+

proc foo(other: Y; container: var X): var T from container

+

Here var T from container explicitly exposes that the location is derived from the second parameter (called 'container' in this case). The syntax var T from p specifies a type varTy[T, 2] which is incompatible with varTy[T, 1].

+ +

NRVO

Note: This section describes the current implementation. This part of the language specification will be changed. See https://github.com/nim-lang/RFCs/issues/230 for more information.

+

The return value is represented inside the body of a routine as the special result variable. This allows for a mechanism much like C++'s "named return value optimization" (NRVO). NRVO means that the stores to result inside p directly affect the destination dest in let/var dest = p(args) (definition of dest) and also in dest = p(args) (assignment to dest). This is achieved by rewriting dest = p(args) to p'(args, dest) where p' is a variation of p that returns void and receives a hidden mutable parameter representing result.

+

Informally:

+

proc p(): BigT = ...
+
+var x = p()
+x = p()
+
+# is roughly turned into:
+
+proc p(result: var BigT) = ...
+
+var x; p(x)
+p(x)

+

Let T's be p's return type. NRVO applies for T if sizeof(T) >= N (where N is implementation dependent), in other words, it applies for "big" structures.

+

If p can raise an exception, NRVO applies regardless. This can produce observable differences in behavior:

+

type
+  BigT = array[16, int]
+
+proc p(raiseAt: int): BigT =
+  for i in 0..high(result):
+    if i == raiseAt: raise newException(ValueError, "interception")
+    result[i] = i
+
+proc main =
+  var x: BigT
+  try:
+    x = p(8)
+  except ValueError:
+    doAssert x == [0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0]
+
+main()

+

The compiler can produce a warning in these cases, however this behavior is turned off by default. It can be enabled for a section of code via the warning[ObservableStores] and push/pop pragmas. Take the above code as an example:

+

{.push warning[ObservableStores]: on.}
+main()
+{.pop.}

+ +

Overloading of the subscript operator

The [] subscript operator for arrays/openarrays/sequences can be overloaded for any type (with some exceptions) by defining a routine with the name [].

+

type Foo = object
+  data: seq[int]
+
+proc `[]`(foo: Foo, i: int): int =
+  result = foo.data[i]
+
+let foo = Foo(data: @[1, 2, 3])
+echo foo[1] # 2

+

Assignment to subscripts can also be overloaded by naming a routine []=, which has precedence over assigning to the result of [].

+

type Foo = object
+  data: seq[int]
+
+proc `[]`(foo: Foo, i: int): int =
+  result = foo.data[i]
+proc `[]=`(foo: var Foo, i: int, val: int) =
+  foo.data[i] = val
+
+var foo = Foo(data: @[1, 2, 3])
+echo foo[1] # 2
+foo[1] = 5
+echo foo.data # @[1, 5, 3]
+echo foo[1] # 5

+

Overloads of the subscript operator cannot be applied to routine or type symbols themselves, as this conflicts with the syntax for instantiating generic parameters, i.e. foo[int](1, 2, 3) or Foo[int].

+ +

Methods

Procedures always use static dispatch. Methods use dynamic dispatch. For dynamic dispatch to work on an object it should be a reference type.

+

type
+  Expression = ref object of RootObj ## abstract base class for an expression
+  Literal = ref object of Expression
+    x: int
+  PlusExpr = ref object of Expression
+    a, b: Expression
+
+method eval(e: Expression): int {.base.} =
+  # override this base method
+  raise newException(CatchableError, "Method without implementation override")
+
+method eval(e: Literal): int = return e.x
+
+method eval(e: PlusExpr): int =
+  # watch out: relies on dynamic binding
+  result = eval(e.a) + eval(e.b)
+
+proc newLit(x: int): Literal =
+  new(result)
+  result.x = x
+
+proc newPlus(a, b: Expression): PlusExpr =
+  new(result)
+  result.a = a
+  result.b = b
+
+echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4)))

+

In the example the constructors newLit and newPlus are procs because they should use static binding, but eval is a method because it requires dynamic binding.

+

As can be seen in the example, base methods have to be annotated with the base pragma. The base pragma also acts as a reminder for the programmer that a base method m is used as the foundation to determine all the effects that a call to m might cause.

+

Note: Compile-time execution is not (yet) supported for methods.

+

Note: Starting from Nim 0.20, generic methods are deprecated.

+ +

Multi-methods

Note: Starting from Nim 0.20, to use multi-methods one must explicitly pass --multimethods:on when compiling.

+

In a multi-method, all parameters that have an object type are used for the dispatching:

+

type
+  Thing = ref object of RootObj
+  Unit = ref object of Thing
+    x: int
+
+method collide(a, b: Thing) {.base, inline.} =
+  quit "to override!"
+
+method collide(a: Thing, b: Unit) {.inline.} =
+  echo "1"
+
+method collide(a: Unit, b: Thing) {.inline.} =
+  echo "2"
+
+var a, b: Unit
+new a
+new b
+collide(a, b) # output: 2

+ +

Inhibit dynamic method resolution via procCall

Dynamic method resolution can be inhibited via the builtin system.procCall. This is somewhat comparable to the super keyword that traditional OOP languages offer.

+

type
+  Thing = ref object of RootObj
+  Unit = ref object of Thing
+    x: int
+
+method m(a: Thing) {.base.} =
+  echo "base"
+
+method m(a: Unit) =
+  # Call the base method:
+  procCall m(Thing(a))
+  echo "1"

+ +

Iterators and the for statement

The for statement is an abstract mechanism to iterate over the elements of a container. It relies on an iterator to do so. Like while statements, for statements open an implicit block so that they can be left with a break statement.

+

The for loop declares iteration variables - their scope reaches until the end of the loop body. The iteration variables' types are inferred by the return type of the iterator.

+

An iterator is similar to a procedure, except that it can be called in the context of a for loop. Iterators provide a way to specify the iteration over an abstract type. The yield statement in the called iterator plays a key role in the execution of a for loop. Whenever a yield statement is reached, the data is bound to the for loop variables and control continues in the body of the for loop. The iterator's local variables and execution state are automatically saved between calls. Example:

+

# this definition exists in the system module
+iterator items*(a: string): char {.inline.} =
+  var i = 0
+  while i < len(a):
+    yield a[i]
+    inc(i)
+
+for ch in items("hello world"): # `ch` is an iteration variable
+  echo ch

+

The compiler generates code as if the programmer had written this:

+

var i = 0
+while i < len(a):
+  var ch = a[i]
+  echo ch
+  inc(i)

+

If the iterator yields a tuple, there can be as many iteration variables as there are components in the tuple. The i'th iteration variable's type is the type of the i'th component. In other words, implicit tuple unpacking in a for loop context is supported.

+ +

Implicit items/pairs invocations

If the for loop expression e does not denote an iterator and the for loop has exactly 1 variable, the for loop expression is rewritten to items(e); i.e. an items iterator is implicitly invoked:

+

for x in [1,2,3]: echo x

+

If the for loop has exactly 2 variables, a pairs iterator is implicitly invoked.

+

Symbol lookup of the identifiers items/pairs is performed after the rewriting step, so that all overloads of items/pairs are taken into account.

+ +

First-class iterators

There are 2 kinds of iterators in Nim: inline and closure iterators. An inline iterator is an iterator that's always inlined by the compiler leading to zero overhead for the abstraction, but may result in a heavy increase in code size.

+

Caution: the body of a for loop over an inline iterator is inlined into each yield statement appearing in the iterator code, so ideally the code should be refactored to contain a single yield when possible to avoid code bloat.

+

Inline iterators are second class citizens; They can be passed as parameters only to other inlining code facilities like templates, macros, and other inline iterators.

+

In contrast to that, a closure iterator can be passed around more freely:

+

iterator count0(): int {.closure.} =
+  yield 0
+
+iterator count2(): int {.closure.} =
+  var x = 1
+  yield x
+  inc x
+  yield x
+
+proc invoke(iter: iterator(): int {.closure.}) =
+  for x in iter(): echo x
+
+invoke(count0)
+invoke(count2)

+

Closure iterators and inline iterators have some restrictions:

+
  1. For now, a closure iterator cannot be executed at compile time.
  2. +
  3. return is allowed in a closure iterator but not in an inline iterator (but rarely useful) and ends the iteration.
  4. +
  5. Inline iterators cannot be recursive.
  6. +
  7. Neither inline nor closure iterators have the special result variable.
  8. +
+

Iterators that are neither marked {.closure.} nor {.inline.} explicitly default to being inline, but this may change in future versions of the implementation.

+

The iterator type is always of the calling convention closure implicitly; the following example shows how to use iterators to implement a collaborative tasking system:

+

# simple tasking:
+type
+  Task = iterator (ticker: int)
+
+iterator a1(ticker: int) {.closure.} =
+  echo "a1: A"
+  yield
+  echo "a1: B"
+  yield
+  echo "a1: C"
+  yield
+  echo "a1: D"
+
+iterator a2(ticker: int) {.closure.} =
+  echo "a2: A"
+  yield
+  echo "a2: B"
+  yield
+  echo "a2: C"
+
+proc runTasks(t: varargs[Task]) =
+  var ticker = 0
+  while true:
+    let x = t[ticker mod t.len]
+    if finished(x): break
+    x(ticker)
+    inc ticker
+
+runTasks(a1, a2)

+

The builtin system.finished can be used to determine if an iterator has finished its operation; no exception is raised on an attempt to invoke an iterator that has already finished its work.

+

Note that system.finished is error-prone to use because it only returns true one iteration after the iterator has finished:

+

iterator mycount(a, b: int): int {.closure.} =
+  var x = a
+  while x <= b:
+    yield x
+    inc x
+
+var c = mycount # instantiate the iterator
+while not finished(c):
+  echo c(1, 3)
+
+# Produces
+1
+2
+3
+0

+

Instead, this code has to be used:

+

var c = mycount # instantiate the iterator
+while true:
+  let value = c(1, 3)
+  if finished(c): break # and discard 'value'!
+  echo value

+

It helps to think that the iterator actually returns a pair (value, done) and finished is used to access the hidden done field.

+

Closure iterators are resumable functions and so one has to provide the arguments to every call. To get around this limitation one can capture parameters of an outer factory proc:

+

proc mycount(a, b: int): iterator (): int =
+  result = iterator (): int =
+    var x = a
+    while x <= b:
+      yield x
+      inc x
+
+let foo = mycount(1, 4)
+
+for f in foo():
+  echo f

+

The call can be made more like an inline iterator with a for loop macro:

+

import std/macros
+macro toItr(x: ForLoopStmt): untyped =
+  let expr = x[0]
+  let call = x[1][1] # Get foo out of toItr(foo)
+  let body = x[2]
+  result = quote do:
+    block:
+      let itr = `call`
+      for `expr` in itr():
+          `body`
+
+for f in toItr(mycount(1, 4)): # using early `proc mycount`
+  echo f

+

Because of full backend function call apparatus involvement, closure iterator invocation is typically higher cost than inline iterators. Adornment by a macro wrapper at the call site like this is a possibly useful reminder.

+

The factory proc, as an ordinary procedure, can be recursive. The above macro allows such recursion to look much like a recursive iterator would. For example:

+

proc recCountDown(n: int): iterator(): int =
+  result = iterator(): int =
+    if n > 0:
+      yield n
+      for e in toItr(recCountDown(n - 1)):
+        yield e
+
+for i in toItr(recCountDown(6)): # Emits: 6 5 4 3 2 1
+  echo i

+

See also iterable for passing iterators to templates and macros.

+ +

Converters

A converter is like an ordinary proc except that it enhances the "implicitly convertible" type relation (see Convertible relation):

+

# bad style ahead: Nim is not C.
+converter toBool(x: int): bool = x != 0
+
+if 4:
+  echo "compiles"

+

A converter can also be explicitly invoked for improved readability. Note that implicit converter chaining is not supported: If there is a converter from type A to type B and from type B to type C, the implicit conversion from A to C is not provided.

+ +

Type sections

Example:

+

type # example demonstrating mutually recursive types
+  Node = ref object  # an object managed by the garbage collector (ref)
+    le, ri: Node     # left and right subtrees
+    sym: ref Sym     # leaves contain a reference to a Sym
+  
+  Sym = object       # a symbol
+    name: string     # the symbol's name
+    line: int        # the line the symbol was declared in
+    code: Node       # the symbol's abstract syntax tree

+

A type section begins with the type keyword. It contains multiple type definitions. A type definition binds a type to a name. Type definitions can be recursive or even mutually recursive. Mutually recursive types are only possible within a single type section. Nominal types like objects or enums can only be defined in a type section.

+ +

Exception handling

+

Try statement

Example:

+

# read the first two lines of a text file that should contain numbers
+# and tries to add them
+var
+  f: File
+if open(f, "numbers.txt"):
+  try:
+    var a = readLine(f)
+    var b = readLine(f)
+    echo "sum: " & $(parseInt(a) + parseInt(b))
+  except OverflowDefect:
+    echo "overflow!"
+  except ValueError, IOError:
+    echo "catch multiple exceptions!"
+  except CatchableError:
+    echo "Catchable exception!"
+  finally:
+    close(f)

+

The statements after the try are executed in sequential order unless an exception e is raised. If the exception type of e matches any listed in an except clause, the corresponding statements are executed. The statements following the except clauses are called exception handlers.

+

If there is a finally clause, it is always executed after the exception handlers.

+

The exception is consumed in an exception handler. However, an exception handler may raise another exception. If the exception is not handled, it is propagated through the call stack. This means that often the rest of the procedure - that is not within a finally clause - is not executed (if an exception occurs).

+ +

Try expression

Try can also be used as an expression; the type of the try branch then needs to fit the types of except branches, but the type of the finally branch always has to be void:

+

from std/strutils import parseInt
+
+let x = try: parseInt("133a")
+        except ValueError: -1
+        finally: echo "hi"

+

To prevent confusing code there is a parsing limitation; if the try follows a ( it has to be written as a one liner:

+

from std/strutils import parseInt
+let x = (try: parseInt("133a") except ValueError: -1)

+ +

Except clauses

Within an except clause it is possible to access the current exception using the following syntax:

+

try:
+  # ...
+except IOError as e:
+  # Now use "e"
+  echo "I/O error: " & e.msg

+

Alternatively, it is possible to use getCurrentException to retrieve the exception that has been raised:

+

try:
+  # ...
+except IOError:
+  let e = getCurrentException()
+  # Now use "e"

+

Note that getCurrentException always returns a ref Exception type. If a variable of the proper type is needed (in the example above, IOError), one must convert it explicitly:

+

try:
+  # ...
+except IOError:
+  let e = (ref IOError)(getCurrentException())
+  # "e" is now of the proper type

+

However, this is seldom needed. The most common case is to extract an error message from e, and for such situations, it is enough to use getCurrentExceptionMsg:

+

try:
+  # ...
+except CatchableError:
+  echo getCurrentExceptionMsg()

+ +

Custom exceptions

It is possible to create custom exceptions. A custom exception is a custom type:

+

type
+  LoadError* = object of Exception

+

Ending the custom exception's name with Error is recommended.

+

Custom exceptions can be raised just like any other exception, e.g.:

+

raise newException(LoadError, "Failed to load data")

+ +

Defer statement

Instead of a try finally statement a defer statement can be used, which avoids lexical nesting and offers more flexibility in terms of scoping as shown below.

+

Any statements following the defer will be considered to be in an implicit try block in the current block:

+

proc main =
+  var f = open("numbers.txt", fmWrite)
+  defer: close(f)
+  f.write "abc"
+  f.write "def"

+

Is rewritten to:

+

proc main =
+  var f = open("numbers.txt")
+  try:
+    f.write "abc"
+    f.write "def"
+  finally:
+    close(f)

+

When defer is at the outermost scope of a template/macro, its scope extends to the block where the template/macro is called from:

+

template safeOpenDefer(f, path) =
+  var f = open(path, fmWrite)
+  defer: close(f)
+
+template safeOpenFinally(f, path, body) =
+  var f = open(path, fmWrite)
+  try: body # without `defer`, `body` must be specified as parameter
+  finally: close(f)
+
+block:
+  safeOpenDefer(f, "/tmp/z01.txt")
+  f.write "abc"
+block:
+  safeOpenFinally(f, "/tmp/z01.txt"):
+    f.write "abc" # adds a lexical scope
+block:
+  var f = open("/tmp/z01.txt", fmWrite)
+  try:
+    f.write "abc" # adds a lexical scope
+  finally: close(f)

+

Top-level defer statements are not supported since it's unclear what such a statement should refer to.

+ +

Raise statement

Example:

+

raise newException(IOError, "IO failed")

+

Apart from built-in operations like array indexing, memory allocation, etc. the raise statement is the only way to raise an exception.

+

If no exception name is given, the current exception is re-raised. The ReraiseDefect exception is raised if there is no exception to re-raise. It follows that the raise statement always raises an exception.

+ +

Exception hierarchy

The exception tree is defined in the system module. Every exception inherits from system.Exception. Exceptions that indicate programming bugs inherit from system.Defect (which is a subtype of Exception) and are strictly speaking not catchable as they can also be mapped to an operation that terminates the whole process. If panics are turned into exceptions, these exceptions inherit from Defect.

+

Exceptions that indicate any other runtime error that can be caught inherit from system.CatchableError (which is a subtype of Exception).

+

Exception
+|-- CatchableError
+|   |-- IOError
+|   |   `-- EOFError
+|   |-- OSError
+|   |-- ResourceExhaustedError
+|   `-- ValueError
+|       `-- KeyError
+`-- Defect
+    |-- AccessViolationDefect
+    |-- ArithmeticDefect
+    |   |-- DivByZeroDefect
+    |   `-- OverflowDefect
+    |-- AssertionDefect
+    |-- DeadThreadDefect
+    |-- FieldDefect
+    |-- FloatingPointDefect
+    |   |-- FloatDivByZeroDefect
+    |   |-- FloatInvalidOpDefect
+    |   |-- FloatOverflowDefect
+    |   |-- FloatUnderflowDefect
+    |   `-- InexactDefect
+    |-- IndexDefect
+    |-- NilAccessDefect
+    |-- ObjectAssignmentDefect
+    |-- ObjectConversionDefect
+    |-- OutOfMemoryDefect
+    |-- RangeDefect
+    |-- ReraiseDefect
+    `-- StackOverflowDefect

+ +

Imported exceptions

It is possible to raise/catch imported C++ exceptions. Types imported using importcpp can be raised or caught. Exceptions are raised by value and caught by reference. Example:

+

type
+  CStdException {.importcpp: "std::exception", header: "<exception>", inheritable.} = object
+    ## does not inherit from `RootObj`, so we use `inheritable` instead
+  CRuntimeError {.requiresInit, importcpp: "std::runtime_error", header: "<stdexcept>".} = object of CStdException
+    ## `CRuntimeError` has no default constructor => `requiresInit`
+proc what(s: CStdException): cstring {.importcpp: "((char *)#.what())".}
+proc initRuntimeError(a: cstring): CRuntimeError {.importcpp: "std::runtime_error(@)", constructor.}
+proc initStdException(): CStdException {.importcpp: "std::exception()", constructor.}
+
+proc fn() =
+  let a = initRuntimeError("foo")
+  doAssert $a.what == "foo"
+  var b: cstring
+  try: raise initRuntimeError("foo2")
+  except CStdException as e:
+    doAssert e is CStdException
+    b = e.what()
+  doAssert $b == "foo2"
+  
+  try: raise initStdException()
+  except CStdException: discard
+  
+  try: raise initRuntimeError("foo3")
+  except CRuntimeError as e:
+    b = e.what()
+  except CStdException:
+    doAssert false
+  doAssert $b == "foo3"
+
+fn()

+

Note: getCurrentException() and getCurrentExceptionMsg() are not available for imported exceptions from C++. One needs to use the except ImportedException as x: syntax and rely on functionality of the x object to get exception details.

+ +

Effect system

Note: The rules for effect tracking changed with the release of version 1.6 of the Nim compiler.

+ +

Exception tracking

Nim supports exception tracking. The raises pragma can be used to explicitly define which exceptions a proc/iterator/method/converter is allowed to raise. The compiler verifies this:

+

proc p(what: bool) {.raises: [IOError, OSError].} =
+  if what: raise newException(IOError, "IO")
+  else: raise newException(OSError, "OS")

+

An empty raises list (raises: []) means that no exception may be raised:

+

proc p(): bool {.raises: [].} =
+  try:
+    unsafeCall()
+    result = true
+  except CatchableError:
+    result = false

+

A raises list can also be attached to a proc type. This affects type compatibility:

+

type
+  Callback = proc (s: string) {.raises: [IOError].}
+var
+  c: Callback
+
+proc p(x: string) =
+  raise newException(OSError, "OS")
+
+c = p # type error

+

For a routine p, the compiler uses inference rules to determine the set of possibly raised exceptions; the algorithm operates on p's call graph:

+
  1. Every indirect call via some proc type T is assumed to raise system.Exception (the base type of the exception hierarchy) and thus any exception unless T has an explicit raises list. However, if the call is of the form f(...) where f is a parameter of the currently analyzed routine that is marked as .effectsOf: f, it is ignored. The call is optimistically assumed to have no effect. Rule 2 compensates for this case.
  2. +
  3. Every expression e of some proc type within a call that is passed to parameter marked as .effectsOf of proc p is assumed to be called indirectly and thus its raises list is added to p's raises list.
  4. +
  5. Every call to a proc q which has an unknown body (due to a forward declaration) is assumed to raise system.Exception unless q has an explicit raises list. Procs that are importc'ed are assumed to have .raises: [], unless explicitly declared otherwise.
  6. +
  7. Every call to a method m is assumed to raise system.Exception unless m has an explicit raises list.
  8. +
  9. For every other call, the analysis can determine an exact raises list.
  10. +
  11. For determining a raises list, the raise and try statements of p are taken into consideration.
  12. +
+

Exceptions inheriting from system.Defect are not tracked with the .raises: [] exception tracking mechanism. This is more consistent with the built-in operations. The following code is valid:

+

proc mydiv(a, b): int {.raises: [].} =
+  a div b # can raise an DivByZeroDefect

+

And so is:

+

proc mydiv(a, b): int {.raises: [].} =
+  if b == 0: raise newException(DivByZeroDefect, "division by zero")
+  else: result = a div b

+

The reason for this is that DivByZeroDefect inherits from Defect and with --panics:on Defects become unrecoverable errors. (Since version 1.4 of the language.)

+ +

EffectsOf annotation

Rules 1-2 of the exception tracking inference rules (see the previous section) ensure the following works:

+

proc weDontRaiseButMaybeTheCallback(callback: proc()) {.raises: [], effectsOf: callback.} =
+  callback()
+
+proc doRaise() {.raises: [IOError].} =
+  raise newException(IOError, "IO")
+
+proc use() {.raises: [].} =
+  # doesn't compile! Can raise IOError!
+  weDontRaiseButMaybeTheCallback(doRaise)

+

As can be seen from the example, a parameter of type proc (...) can be annotated as .effectsOf. Such a parameter allows for effect polymorphism: The proc weDontRaiseButMaybeTheCallback raises the exceptions that callback raises.

+

So in many cases a callback does not cause the compiler to be overly conservative in its effect analysis:

+

{.push warningAsError[Effect]: on.}
+
+import std/algorithm
+
+type
+  MyInt = distinct int
+
+var toSort = @[MyInt 1, MyInt 2, MyInt 3]
+
+proc cmpN(a, b: MyInt): int =
+  cmp(a.int, b.int)
+
+proc harmless {.raises: [].} =
+  toSort.sort cmpN
+
+proc cmpE(a, b: MyInt): int {.raises: [Exception].} =
+  cmp(a.int, b.int)
+
+proc harmful {.raises: [].} =
+  # does not compile, `sort` can now raise Exception
+  toSort.sort cmpE

+ +

Tag tracking

Exception tracking is part of Nim's effect system. Raising an exception is an effect. Other effects can also be defined. A user defined effect is a means to tag a routine and to perform checks against this tag:

+

type IO = object ## input/output effect
+proc readLine(): string {.tags: [IO].} = discard
+
+proc no_effects_please() {.tags: [].} =
+  # the compiler prevents this:
+  let x = readLine()

+

A tag has to be a type name. A tags list - like a raises list - can also be attached to a proc type. This affects type compatibility.

+

The inference for tag tracking is analogous to the inference for exception tracking.

+

There is also a way which can be used to forbid certain effects:

+

type IO = object ## input/output effect
+proc readLine(): string {.tags: [IO].} = discard
+proc echoLine(): void = discard
+
+proc no_IO_please() {.forbids: [IO].} =
+  # this is OK because it didn't define any tag:
+  echoLine()
+  # the compiler prevents this:
+  let y = readLine()

+

The forbids pragma defines a list of illegal effects - if any statement invokes any of those effects, the compilation will fail. Procedure types with any disallowed effect are the subtypes of equal procedure types without such lists:

+

type MyEffect = object
+type ProcType1 = proc (i: int): void {.forbids: [MyEffect].}
+type ProcType2 = proc (i: int): void
+
+proc caller1(p: ProcType1): void = p(1)
+proc caller2(p: ProcType2): void = p(1)
+
+proc effectful(i: int): void {.tags: [MyEffect].} = echo $i
+proc effectless(i: int): void {.forbids: [MyEffect].} = echo $i
+
+proc toBeCalled1(i: int): void = effectful(i)
+proc toBeCalled2(i: int): void = effectless(i)
+
+## this will fail because toBeCalled1 uses MyEffect which was forbidden by ProcType1:
+caller1(toBeCalled1)
+## this is OK because both toBeCalled2 and ProcType1 have the same requirements:
+caller1(toBeCalled2)
+## these are OK because ProcType2 doesn't have any effect requirement:
+caller2(toBeCalled1)
+caller2(toBeCalled2)

+

ProcType2 is a subtype of ProcType1. Unlike with the tags pragma, the parent context - the function which calls other functions with forbidden effects - doesn't inherit the forbidden list of effects.

+ +

Side effects

The noSideEffect pragma is used to mark a proc/iterator that can have only side effects through parameters. This means that the proc/iterator only changes locations that are reachable from its parameters and the return value only depends on the parameters. If none of its parameters have the type var, ref, ptr, cstring, or proc, then no locations are modified.

+

In other words, a routine has no side effects if it does not access a threadlocal or global variable and it does not call any routine that has a side effect.

+

It is a static error to mark a proc/iterator to have no side effect if the compiler cannot verify this.

+

As a special semantic rule, the built-in debugEcho pretends to be free of side effects so that it can be used for debugging routines marked as noSideEffect.

+

func is syntactic sugar for a proc with no side effects:

+

func `+` (x, y: int): int

+

To override the compiler's side effect analysis a {.noSideEffect.} cast pragma block can be used:

+

func f() =
+  {.cast(noSideEffect).}:
+    echo "test"

+

Side effects are usually inferred. The inference for side effects is analogous to the inference for exception tracking.

+

When the compiler cannot infer side effects, as is the case for imported functions, one can annotate them with the sideEffect pragma.

+ +

GC safety effect

We call a proc p GC safe when it doesn't access any global variable that contains GC'ed memory (string, seq, ref or a closure) either directly or indirectly through a call to a GC unsafe proc.

+

The GC safety property is usually inferred. The inference for GC safety is analogous to the inference for exception tracking.

+

The gcsafe annotation can be used to mark a proc to be gcsafe, otherwise this property is inferred by the compiler. Note that noSideEffect implies gcsafe.

+

Routines that are imported from C are always assumed to be gcsafe.

+

To override the compiler's gcsafety analysis a {.cast(gcsafe).} pragma block can be used:

+

var
+  someGlobal: string = "some string here"
+  perThread {.threadvar.}: string
+
+proc setPerThread() =
+  {.cast(gcsafe).}:
+    deepCopy(perThread, someGlobal)

+

See also:

+ + +

Effects pragma

The effects pragma has been designed to assist the programmer with the effects analysis. It is a statement that makes the compiler output all inferred effects up to the effects's position:

+

proc p(what: bool) =
+  if what:
+    raise newException(IOError, "IO")
+    {.effects.}
+  else:
+    raise newException(OSError, "OS")

+

The compiler produces a hint message that IOError can be raised. OSError is not listed as it cannot be raised in the branch the effects pragma appears in.

+ +

Generics

Generics are Nim's means to parametrize procs, iterators or types with type parameters. Depending on the context, the brackets are used either to introduce type parameters or to instantiate a generic proc, iterator, or type.

+

The following example shows how a generic binary tree can be modeled:

+

type
+  BinaryTree*[T] = ref object # BinaryTree is a generic type with
+                              # generic parameter `T`
+    le, ri: BinaryTree[T]     # left and right subtrees; may be nil
+    data: T                   # the data stored in a node
+
+proc newNode*[T](data: T): BinaryTree[T] =
+  # constructor for a node
+  result = BinaryTree[T](le: nil, ri: nil, data: data)
+
+proc add*[T](root: var BinaryTree[T], n: BinaryTree[T]) =
+  # insert a node into the tree
+  if root == nil:
+    root = n
+  else:
+    var it = root
+    while it != nil:
+      # compare the data items; uses the generic `cmp` proc
+      # that works for any type that has a `==` and `<` operator
+      var c = cmp(it.data, n.data)
+      if c < 0:
+        if it.le == nil:
+          it.le = n
+          return
+        it = it.le
+      else:
+        if it.ri == nil:
+          it.ri = n
+          return
+        it = it.ri
+
+proc add*[T](root: var BinaryTree[T], data: T) =
+  # convenience proc:
+  add(root, newNode(data))
+
+iterator preorder*[T](root: BinaryTree[T]): T =
+  # Preorder traversal of a binary tree.
+  # This uses an explicit stack (which is more efficient than
+  # a recursive iterator factory).
+  var stack: seq[BinaryTree[T]] = @[root]
+  while stack.len > 0:
+    var n = stack.pop()
+    while n != nil:
+      yield n.data
+      add(stack, n.ri)  # push right subtree onto the stack
+      n = n.le          # and follow the left pointer
+
+var
+  root: BinaryTree[string] # instantiate a BinaryTree with `string`
+add(root, newNode("hello")) # instantiates `newNode` and `add`
+add(root, "world")          # instantiates the second `add` proc
+for str in preorder(root):
+  stdout.writeLine(str)

+

The T is called a generic type parameter or a type variable.

+ +

Generic Procs

Let's consider the anatomy of a generic proc to agree on defined terminology.

+

p[T: t](arg1: f): y

+
  • p: Callee symbol
  • +
  • [...]: Generic parameters
  • +
  • T: t: Generic constraint
  • +
  • T: Type variable
  • +
  • [T: t](arg1: f): y: Formal signature
  • +
  • arg1: f: Formal parameter
  • +
  • f: Formal parameter type
  • +
  • y: Formal return type
  • +
+

The use of the word "formal" here is to denote the symbols as they are defined by the programmer, not as they may be at compile time contextually. Since generics may be instantiated and types bound, we have more than one entity to think about when generics are involved.

+

The usage of a generic will resolve the formally defined expression into an instance of that expression bound to only concrete types. This process is called "instantiation".

+

Brackets at the site of a generic's formal definition specify the "constraints" as in:

+

type Foo[T] = object
+proc p[H;T: Foo[H]](param: T): H

+

A constraint definition may have more than one symbol defined by separating each definition by a ;. Notice how T is composed of H and the return type of p is defined as H. When this generic proc is instantiated H will be bound to a concrete type, thus making T concrete and the return type of p will be bound to the same concrete type used to define H.

+

Brackets at the site of usage can be used to supply concrete types to instantiate the generic in the same order that the symbols are defined in the constraint. Alternatively, type bindings may be inferred by the compiler in some situations, allowing for cleaner code.

+ +

Is operator

The is operator is evaluated during semantic analysis to check for type equivalence. It is therefore very useful for type specialization within generic code:

+

type
+  Table[Key, Value] = object
+    keys: seq[Key]
+    values: seq[Value]
+    when not (Key is string): # empty value for strings used for optimization
+      deletedKeys: seq[bool]

+ +

Type classes

A type class is a special pseudo-type that can be used to match against types in the context of overload resolution or the is operator. Nim supports the following built-in type classes:

+ + + + + + + + + + + + + + +
type classmatches
objectany object type
tupleany tuple type
enumany enumeration
procany proc type
iteratorany iterator type
refany ref type
ptrany ptr type
varany var type
distinctany distinct type
arrayany array type
setany set type
seqany seq type
autoany type

Furthermore, every generic type automatically creates a type class of the same name that will match any instantiation of the generic type.

+

Type classes can be combined using the standard boolean operators to form more complex type classes:

+

# create a type class that will match all tuple and object types
+type RecordType = (tuple or object)
+
+proc printFields[T: RecordType](rec: T) =
+  for key, value in fieldPairs(rec):
+    echo key, " = ", value

+

Type constraints on generic parameters can be grouped with , and propagation stops with ;, similarly to parameters for macros and templates:

+

proc fn1[T; U, V: SomeFloat]() = discard # T is unconstrained
+template fn2(t; u, v: SomeFloat) = discard # t is unconstrained

+

Whilst the syntax of type classes appears to resemble that of ADTs/algebraic data types in ML-like languages, it should be understood that type classes are static constraints to be enforced at type instantiations. Type classes are not really types in themselves but are instead a system of providing generic "checks" that ultimately resolve to some singular type. Type classes do not allow for runtime type dynamism, unlike object variants or methods.

+

As an example, the following would not compile:

+

type TypeClass = int | string
+var foo: TypeClass = 2 # foo's type is resolved to an int here
+foo = "this will fail" # error here, because foo is an int

+

Nim allows for type classes and regular types to be specified as type constraints of the generic type parameter:

+

proc onlyIntOrString[T: int|string](x, y: T) = discard
+
+onlyIntOrString(450, 616) # valid
+onlyIntOrString(5.0, 0.0) # type mismatch
+onlyIntOrString("xy", 50) # invalid as 'T' cannot be both at the same time

+

proc and iterator type classes also accept a calling convention pragma to restrict the calling convention of the matching proc or iterator type.

+

proc onlyClosure[T: proc {.closure.}](x: T) = discard
+
+onlyClosure(proc() = echo "hello") # valid
+proc foo() {.nimcall.} = discard
+onlyClosure(foo) # type mismatch

+ +

Implicit generics

A type class can be used directly as the parameter's type.

+

# create a type class that will match all tuple and object types
+type RecordType = (tuple or object)
+
+proc printFields(rec: RecordType) =
+  for key, value in fieldPairs(rec):
+    echo key, " = ", value

+

Procedures utilizing type classes in such a manner are considered to be implicitly generic. They will be instantiated once for each unique combination of parameter types used within the program.

+

By default, during overload resolution, each named type class will bind to exactly one concrete type. We call such type classes bind once types. Here is an example taken directly from the system module to illustrate this:

+

proc `==`*(x, y: tuple): bool =
+  ## requires `x` and `y` to be of the same tuple type
+  ## generic `==` operator for tuples that is lifted from the components
+  ## of `x` and `y`.
+  result = true
+  for a, b in fields(x, y):
+    if a != b: result = false

+

Alternatively, the distinct type modifier can be applied to the type class to allow each parameter matching the type class to bind to a different type. Such type classes are called bind many types.

+

Procs written with the implicitly generic style will often need to refer to the type parameters of the matched generic type. They can be easily accessed using the dot syntax:

+

type Matrix[T, Rows, Columns] = object
+  ...
+
+proc `[]`(m: Matrix, row, col: int): Matrix.T =
+  m.data[col * high(Matrix.Columns) + row]

+

Here are more examples that illustrate implicit generics:

+

proc p(t: Table; k: Table.Key): Table.Value
+
+# is roughly the same as:
+
+proc p[Key, Value](t: Table[Key, Value]; k: Key): Value

+

proc p(a: Table, b: Table)
+
+# is roughly the same as:
+
+proc p[Key, Value](a, b: Table[Key, Value])

+

proc p(a: Table, b: distinct Table)
+
+# is roughly the same as:
+
+proc p[Key, Value, KeyB, ValueB](a: Table[Key, Value], b: Table[KeyB, ValueB])

+

typedesc used as a parameter type also introduces an implicit generic. typedesc has its own set of rules:

+

proc p(a: typedesc)
+
+# is roughly the same as:
+
+proc p[T](a: typedesc[T])

+

typedesc is a "bind many" type class:

+

proc p(a, b: typedesc)
+
+# is roughly the same as:
+
+proc p[T, T2](a: typedesc[T], b: typedesc[T2])

+

A parameter of type typedesc is itself usable as a type. If it is used as a type, it's the underlying type. In other words, one level of "typedesc"-ness is stripped off:

+

proc p(a: typedesc; b: a) = discard
+
+# is roughly the same as:
+proc p[T](a: typedesc[T]; b: T) = discard
+
+# hence this is a valid call:
+p(int, 4)
+# as parameter 'a' requires a type, but 'b' requires a value.

+ +

Generic inference restrictions

The types var T and typedesc[T] cannot be inferred in a generic instantiation. The following is not allowed:

+

proc g[T](f: proc(x: T); x: T) =
+  f(x)
+
+proc c(y: int) = echo y
+proc v(y: var int) =
+  y += 100
+var i: int
+
+# allowed: infers 'T' to be of type 'int'
+g(c, 42)
+
+# not valid: 'T' is not inferred to be of type 'var int'
+g(v, i)
+
+# also not allowed: explicit instantiation via 'var int'
+g[var int](v, i)

+ +

Symbol lookup in generics

+

Open and Closed symbols

The symbol binding rules in generics are slightly subtle: There are "open" and "closed" symbols. A "closed" symbol cannot be re-bound in the instantiation context, an "open" symbol can. Per default, overloaded symbols are open and every other symbol is closed.

+

Open symbols are looked up in two different contexts: Both the context at definition and the context at instantiation are considered:

+

type
+  Index = distinct int
+
+proc `==` (a, b: Index): bool {.borrow.}
+
+var a = (0, 0.Index)
+var b = (0, 0.Index)
+
+echo a == b # works!

+

In the example, the generic `==` for tuples (as defined in the system module) uses the == operators of the tuple's components. However, the == for the Index type is defined after the == for tuples; yet the example compiles as the instantiation takes the currently defined symbols into account too.

+ +

Mixin statement

A symbol can be forced to be open by a mixin declaration:

+

proc create*[T](): ref T =
+  # there is no overloaded 'init' here, so we need to state that it's an
+  # open symbol explicitly:
+  mixin init
+  new result
+  init result

+

mixin statements only make sense in templates and generics.

+ +

Bind statement

The bind statement is the counterpart to the mixin statement. It can be used to explicitly declare identifiers that should be bound early (i.e. the identifiers should be looked up in the scope of the template/generic definition):

+

# Module A
+var
+  lastId = 0
+
+template genId*: untyped =
+  bind lastId
+  inc(lastId)
+  lastId

+

# Module B
+import A
+
+echo genId()

+

But a bind is rarely useful because symbol binding from the definition scope is the default.

+

bind statements only make sense in templates and generics.

+ +

Delegating bind statements

The following example outlines a problem that can arise when generic instantiations cross multiple different modules:

+

# module A
+proc genericA*[T](x: T) =
+  mixin init
+  init(x)

+

import C
+
+# module B
+proc genericB*[T](x: T) =
+  # Without the `bind init` statement C's init proc is
+  # not available when `genericB` is instantiated:
+  bind init
+  genericA(x)

+

# module C
+type O = object
+proc init*(x: var O) = discard

+

# module main
+import B, C
+
+genericB O()

+

In module B has an init proc from module C in its scope that is not taken into account when genericB is instantiated which leads to the instantiation of genericA. The solution is to forward these symbols by a bind statement inside genericB.

+ +

Templates

A template is a simple form of a macro: It is a simple substitution mechanism that operates on Nim's abstract syntax trees. It is processed in the semantic pass of the compiler.

+

The syntax to invoke a template is the same as calling a procedure.

+

Example:

+

template `!=` (a, b: untyped): untyped =
+  # this definition exists in the system module
+  not (a == b)
+
+assert(5 != 6) # the compiler rewrites that to: assert(not (5 == 6))

+

The !=, >, >=, in, notin, isnot operators are in fact templates:

+

a > b is transformed into b < a.
a in b is transformed into contains(b, a).
notin and isnot have the obvious meanings.

The "types" of templates can be the symbols untyped, typed or typedesc. These are "meta types", they can only be used in certain contexts. Regular types can be used too; this implies that typed expressions are expected.

+ +

Typed vs untyped parameters

An untyped parameter means that symbol lookups and type resolution is not performed before the expression is passed to the template. This means that undeclared identifiers, for example, can be passed to the template:

+

template declareInt(x: untyped) =
+  var x: int
+
+declareInt(x) # valid
+x = 3

+

template declareInt(x: typed) =
+  var x: int
+
+declareInt(x) # invalid, because x has not been declared and so it has no type

+

A template where every parameter is untyped is called an immediate template. For historical reasons, templates can be explicitly annotated with an immediate pragma and then these templates do not take part in overloading resolution and the parameters' types are ignored by the compiler. Explicit immediate templates are now deprecated.

+

Note: For historical reasons, stmt was an alias for typed and expr was an alias for untyped, but they are removed.

+ +

Passing a code block to a template

One can pass a block of statements as the last argument to a template following the special : syntax:

+

template withFile(f, fn, mode, actions: untyped): untyped =
+  var f: File
+  if open(f, fn, mode):
+    try:
+      actions
+    finally:
+      close(f)
+  else:
+    quit("cannot open: " & fn)
+
+withFile(txt, "ttempl3.txt", fmWrite):  # special colon
+  txt.writeLine("line 1")
+  txt.writeLine("line 2")

+

In the example, the two writeLine statements are bound to the actions parameter.

+

Usually, to pass a block of code to a template, the parameter that accepts the block needs to be of type untyped. Because symbol lookups are then delayed until template instantiation time:

+

template t(body: typed) =
+  proc p = echo "hey"
+  block:
+    body
+
+t:
+  p()  # fails with 'undeclared identifier: p'

+

The above code fails with the error message that p is not declared. The reason for this is that the p() body is type-checked before getting passed to the body parameter and type checking in Nim implies symbol lookups. The same code works with untyped as the passed body is not required to be type-checked:

+

template t(body: untyped) =
+  proc p = echo "hey"
+  block:
+    body
+
+t:
+  p()  # compiles

+ +

Varargs of untyped

In addition to the untyped meta-type that prevents type checking, there is also varargs[untyped] so that not even the number of parameters is fixed:

+

template hideIdentifiers(x: varargs[untyped]) = discard
+
+hideIdentifiers(undeclared1, undeclared2)

+

However, since a template cannot iterate over varargs, this feature is generally much more useful for macros.

+ +

Symbol binding in templates

A template is a hygienic macro and so opens a new scope. Most symbols are bound from the definition scope of the template:

+

# Module A
+var
+  lastId = 0
+
+template genId*: untyped =
+  inc(lastId)
+  lastId

+

# Module B
+import A
+
+echo genId() # Works as 'lastId' has been bound in 'genId's defining scope

+

As in generics, symbol binding can be influenced via mixin or bind statements.

+ +

Identifier construction

In templates, identifiers can be constructed with the backticks notation:

+

template typedef(name: untyped, typ: typedesc) =
+  type
+    `T name`* {.inject.} = typ
+    `P name`* {.inject.} = ref `T name`
+
+typedef(myint, int)
+var x: PMyInt

+

In the example, name is instantiated with myint, so `T name` becomes Tmyint.

+ +

Lookup rules for template parameters

A parameter p in a template is even substituted in the expression x.p. Thus, template arguments can be used as field names and a global symbol can be shadowed by the same argument name even when fully qualified:

+

# module 'm'
+
+type
+  Lev = enum
+    levA, levB
+
+var abclev = levB
+
+template tstLev(abclev: Lev) =
+  echo abclev, " ", m.abclev
+
+tstLev(levA)
+# produces: 'levA levA'

+

But the global symbol can properly be captured by a bind statement:

+

# module 'm'
+
+type
+  Lev = enum
+    levA, levB
+
+var abclev = levB
+
+template tstLev(abclev: Lev) =
+  bind m.abclev
+  echo abclev, " ", m.abclev
+
+tstLev(levA)
+# produces: 'levA levB'

+ +

Hygiene in templates

Per default, templates are hygienic: Local identifiers declared in a template cannot be accessed in the instantiation context:

+

template newException*(exceptn: typedesc, message: string): untyped =
+  var
+    e: ref exceptn  # e is implicitly gensym'ed here
+  new(e)
+  e.msg = message
+  e
+
+# so this works:
+let e = "message"
+raise newException(IoError, e)

+

Whether a symbol that is declared in a template is exposed to the instantiation scope is controlled by the inject and gensym pragmas: gensym'ed symbols are not exposed but inject'ed symbols are.

+

The default for symbols of entity type, var, let and const is gensym. For proc, iterator, converter, template, macro, the default is inject, but if a gensym symbol with the same name is defined in the same syntax-level scope, it will be gensym by default. This can be overriden by marking the routine as inject.

+

If the name of the entity is passed as a template parameter, it is an inject'ed symbol:

+

template withFile(f, fn, mode: untyped, actions: untyped): untyped =
+  block:
+    var f: File  # since 'f' is a template parameter, it's injected implicitly
+    ...
+
+withFile(txt, "ttempl3.txt", fmWrite):
+  txt.writeLine("line 1")
+  txt.writeLine("line 2")

+

The inject and gensym pragmas are second class annotations; they have no semantics outside a template definition and cannot be abstracted over:

+

{.pragma myInject: inject.}
+
+template t() =
+  var x {.myInject.}: int # does NOT work

+

To get rid of hygiene in templates, one can use the dirty pragma for a template. inject and gensym have no effect in dirty templates.

+

gensym'ed symbols cannot be used as field in the x.field syntax. Nor can they be used in the ObjectConstruction(field: value) and namedParameterCall(field = value) syntactic constructs.

+

The reason for this is that code like

+

type
+  T = object
+    f: int
+
+template tmp(x: T) =
+  let f = 34
+  echo x.f, T(f: 4)

+

should work as expected.

+

However, this means that the method call syntax is not available for gensym'ed symbols:

+

template tmp(x) =
+  type
+    T {.gensym.} = int
+  
+  echo x.T # invalid: instead use:  'echo T(x)'.
+
+tmp(12)

+ +

Limitations of the method call syntax

The expression x in x.f needs to be semantically checked (that means symbol lookup and type checking) before it can be decided that it needs to be rewritten to f(x). Therefore, the dot syntax has some limitations when it is used to invoke templates/macros:

+

template declareVar(name: untyped) =
+  const name {.inject.} = 45
+
+# Doesn't compile:
+unknownIdentifier.declareVar

+

It is also not possible to use fully qualified identifiers with module symbol in method call syntax. The order in which the dot operator binds to symbols prohibits this.

+

import std/sequtils
+
+var myItems = @[1,3,3,7]
+let N1 = count(myItems, 3) # OK
+let N2 = sequtils.count(myItems, 3) # fully qualified, OK
+let N3 = myItems.count(3) # OK
+let N4 = myItems.sequtils.count(3) # illegal, `myItems.sequtils` can't be resolved

+

This means that when for some reason a procedure needs a disambiguation through the module name, the call needs to be written in function call syntax.

+ +

Macros

A macro is a special function that is executed at compile time. Normally, the input for a macro is an abstract syntax tree (AST) of the code that is passed to it. The macro can then do transformations on it and return the transformed AST. This can be used to add custom language features and implement domain-specific languages.

+

Macro invocation is a case where semantic analysis does not entirely proceed top to bottom and left to right. Instead, semantic analysis happens at least twice:

+
  • Semantic analysis recognizes and resolves the macro invocation.
  • +
  • The compiler executes the macro body (which may invoke other procs).
  • +
  • It replaces the AST of the macro invocation with the AST returned by the macro.
  • +
  • It repeats semantic analysis of that region of the code.
  • +
  • If the AST returned by the macro contains other macro invocations, this process iterates.
  • +
+

While macros enable advanced compile-time code transformations, they cannot change Nim's syntax.

+

Style note: For code readability, it is best to use the least powerful programming construct that remains expressive. So the "check list" is:

+
  1. Use an ordinary proc/iterator, if possible.
  2. +
  3. Else: Use a generic proc/iterator, if possible.
  4. +
  5. Else: Use a template, if possible.
  6. +
  7. Else: Use a macro.
  8. +
+ +

Debug example

The following example implements a powerful debug command that accepts a variable number of arguments:

+

# to work with Nim syntax trees, we need an API that is defined in the
+# `macros` module:
+import std/macros
+
+macro debug(args: varargs[untyped]): untyped =
+  # `args` is a collection of `NimNode` values that each contain the
+  # AST for an argument of the macro. A macro always has to
+  # return a `NimNode`. A node of kind `nnkStmtList` is suitable for
+  # this use case.
+  result = nnkStmtList.newTree()
+  # iterate over any argument that is passed to this macro:
+  for n in args:
+    # add a call to the statement list that writes the expression;
+    # `toStrLit` converts an AST to its string representation:
+    result.add newCall("write", newIdentNode("stdout"), newLit(n.repr))
+    # add a call to the statement list that writes ": "
+    result.add newCall("write", newIdentNode("stdout"), newLit(": "))
+    # add a call to the statement list that writes the expressions value:
+    result.add newCall("writeLine", newIdentNode("stdout"), n)
+
+var
+  a: array[0..10, int]
+  x = "some string"
+a[0] = 42
+a[1] = 45
+
+debug(a[0], a[1], x)

+

The macro call expands to:

+

write(stdout, "a[0]")
+write(stdout, ": ")
+writeLine(stdout, a[0])
+
+write(stdout, "a[1]")
+write(stdout, ": ")
+writeLine(stdout, a[1])
+
+write(stdout, "x")
+write(stdout, ": ")
+writeLine(stdout, x)

+

Arguments that are passed to a varargs parameter are wrapped in an array constructor expression. This is why debug iterates over all of args's children.

+ +

bindSym

The above debug macro relies on the fact that write, writeLine and stdout are declared in the system module and are thus visible in the instantiating context. There is a way to use bound identifiers (aka symbols) instead of using unbound identifiers. The bindSym builtin can be used for that:

+

import std/macros
+
+macro debug(n: varargs[typed]): untyped =
+  result = newNimNode(nnkStmtList, n)
+  for x in n:
+    # we can bind symbols in scope via 'bindSym':
+    add(result, newCall(bindSym"write", bindSym"stdout", toStrLit(x)))
+    add(result, newCall(bindSym"write", bindSym"stdout", newStrLitNode(": ")))
+    add(result, newCall(bindSym"writeLine", bindSym"stdout", x))
+
+var
+  a: array[0..10, int]
+  x = "some string"
+a[0] = 42
+a[1] = 45
+
+debug(a[0], a[1], x)

+

The macro call expands to:

+

write(stdout, "a[0]")
+write(stdout, ": ")
+writeLine(stdout, a[0])
+
+write(stdout, "a[1]")
+write(stdout, ": ")
+writeLine(stdout, a[1])
+
+write(stdout, "x")
+write(stdout, ": ")
+writeLine(stdout, x)

+

In this version of debug, the symbols write, writeLine and stdout are already bound and are not looked up again. As the example shows, bindSym does work with overloaded symbols implicitly.

+

Note that the symbol names passed to bindSym have to be constant. The experimental feature dynamicBindSym (experimental manual) allows this value to be computed dynamically.

+ +

Post-statement blocks

Macros can receive of, elif, else, except, finally and do blocks (including their different forms such as do with routine parameters) as arguments if called in statement form.

+

macro performWithUndo(task, undo: untyped) = ...
+
+performWithUndo do:
+  # multiple-line block of code
+  # to perform the task
+do:
+  # code to undo it
+
+let num = 12
+# a single colon may be used if there is no initial block
+match (num mod 3, num mod 5):
+of (0, 0):
+  echo "FizzBuzz"
+of (0, _):
+  echo "Fizz"
+of (_, 0):
+  echo "Buzz"
+else:
+  echo num

+ +

For loop macro

A macro that takes as its only input parameter an expression of the special type system.ForLoopStmt can rewrite the entirety of a for loop:

+

import std/macros
+
+macro example(loop: ForLoopStmt) =
+  result = newTree(nnkForStmt)    # Create a new For loop.
+  result.add loop[^3]             # This is "item".
+  result.add loop[^2][^1]         # This is "[1, 2, 3]".
+  result.add newCall(bindSym"echo", loop[0])
+
+for item in example([1, 2, 3]): discard

+

Expands to:

+

for item in items([1, 2, 3]):
+  echo item

+

Another example:

+

import std/macros
+
+macro enumerate(x: ForLoopStmt): untyped =
+  expectKind x, nnkForStmt
+  # check if the starting count is specified:
+  var countStart = if x[^2].len == 2: newLit(0) else: x[^2][1]
+  result = newStmtList()
+  # we strip off the first for loop variable and use it as an integer counter:
+  result.add newVarStmt(x[0], countStart)
+  var body = x[^1]
+  if body.kind != nnkStmtList:
+    body = newTree(nnkStmtList, body)
+  body.add newCall(bindSym"inc", x[0])
+  var newFor = newTree(nnkForStmt)
+  for i in 1..x.len-3:
+    newFor.add x[i]
+  # transform enumerate(X) to 'X'
+  newFor.add x[^2][^1]
+  newFor.add body
+  result.add newFor
+  # now wrap the whole macro in a block to create a new scope
+  result = quote do:
+    block: `result`
+
+for a, b in enumerate(items([1, 2, 3])):
+  echo a, " ", b
+
+# without wrapping the macro in a block, we'd need to choose different
+# names for `a` and `b` here to avoid redefinition errors
+for a, b in enumerate(10, [1, 2, 3, 5]):
+  echo a, " ", b

+ +

Case statement macros

Macros named `` case `` can provide implementations of case statements for certain types. The following is an example of such an implementation for tuples, leveraging the existing equality operator for tuples (as provided in system.==):

+

import std/macros
+
+macro `case`(n: tuple): untyped =
+  result = newTree(nnkIfStmt)
+  let selector = n[0]
+  for i in 1 ..< n.len:
+    let it = n[i]
+    case it.kind
+    of nnkElse, nnkElifBranch, nnkElifExpr, nnkElseExpr:
+      result.add it
+    of nnkOfBranch:
+      for j in 0..it.len-2:
+        let cond = newCall("==", selector, it[j])
+        result.add newTree(nnkElifBranch, cond, it[^1])
+    else:
+      error "custom 'case' for tuple cannot handle this node", it
+
+case ("foo", 78)
+of ("foo", 78): echo "yes"
+of ("bar", 88): echo "no"
+else: discard

+

case macros are subject to overload resolution. The type of the case statement's selector expression is matched against the type of the first argument of the case macro. Then the complete case statement is passed in place of the argument and the macro is evaluated.

+

In other words, the macro needs to transform the full case statement but only the statement's selector expression is used to determine which macro to call.

+ +

Special Types

+

static[T]

As their name suggests, static parameters must be constant expressions:

+

proc precompiledRegex(pattern: static string): RegEx =
+  var res {.global.} = re(pattern)
+  return res
+
+precompiledRegex("/d+") # Replaces the call with a precompiled
+                        # regex, stored in a global variable
+
+precompiledRegex(paramStr(1)) # Error, command-line options
+                              # are not constant expressions

+

For the purposes of code generation, all static parameters are treated as generic parameters - the proc will be compiled separately for each unique supplied value (or combination of values).

+

Static parameters can also appear in the signatures of generic types:

+

type
+  Matrix[M,N: static int; T: Number] = array[0..(M*N - 1), T]
+    # Note how `Number` is just a type constraint here, while
+    # `static int` requires us to supply an int value
+  
+  AffineTransform2D[T] = Matrix[3, 3, T]
+  AffineTransform3D[T] = Matrix[4, 4, T]
+
+var m1: AffineTransform3D[float]  # OK
+var m2: AffineTransform2D[string] # Error, `string` is not a `Number`

+

Please note that static T is just a syntactic convenience for the underlying generic type static[T]. The type parameter can be omitted to obtain the type class of all constant expressions. A more specific type class can be created by instantiating static with another type class.

+

One can force an expression to be evaluated at compile time as a constant expression by coercing it to a corresponding static type:

+

import std/math
+
+echo static(fac(5)), " ", static[bool](16.isPowerOfTwo)

+

The compiler will report any failure to evaluate the expression or a possible type mismatch error.

+ +

typedesc[T]

In many contexts, Nim treats the names of types as regular values. These values exist only during the compilation phase, but since all values must have a type, typedesc is considered their special type.

+

typedesc acts as a generic type. For instance, the type of the symbol int is typedesc[int]. Just like with regular generic types, when the generic parameter is omitted, typedesc denotes the type class of all types. As a syntactic convenience, one can also use typedesc as a modifier.

+

Procs featuring typedesc parameters are considered implicitly generic. They will be instantiated for each unique combination of supplied types, and within the body of the proc, the name of each parameter will refer to the bound concrete type:

+

proc new(T: typedesc): ref T =
+  echo "allocating ", T.name
+  new(result)
+
+var n = Node.new
+var tree = new(BinaryTree[int])

+

When multiple type parameters are present, they will bind freely to different types. To force a bind-once behavior, one can use an explicit generic parameter:

+

proc acceptOnlyTypePairs[T, U](A, B: typedesc[T]; C, D: typedesc[U])

+

Once bound, type parameters can appear in the rest of the proc signature:

+

template declareVariableWithType(T: typedesc, value: T) =
+  var x: T = value
+
+declareVariableWithType int, 42

+

Overload resolution can be further influenced by constraining the set of types that will match the type parameter. This works in practice by attaching attributes to types via templates. The constraint can be a concrete type or a type class.

+

template maxval(T: typedesc[int]): int = high(int)
+template maxval(T: typedesc[float]): float = Inf
+
+var i = int.maxval
+var f = float.maxval
+when false:
+  var s = string.maxval # error, maxval is not implemented for string
+
+template isNumber(t: typedesc[object]): string = "Don't think so."
+template isNumber(t: typedesc[SomeInteger]): string = "Yes!"
+template isNumber(t: typedesc[SomeFloat]): string = "Maybe, could be NaN."
+
+echo "is int a number? ", isNumber(int)
+echo "is float a number? ", isNumber(float)
+echo "is RootObj a number? ", isNumber(RootObj)

+

Passing typedesc is almost identical, just with the difference that the macro is not instantiated generically. The type expression is simply passed as a NimNode to the macro, like everything else.

+

import std/macros
+
+macro forwardType(arg: typedesc): typedesc =
+  # `arg` is of type `NimNode`
+  let tmp: NimNode = arg
+  result = tmp
+
+var tmp: forwardType(int)

+ +

typeof operator

Note: typeof(x) can for historical reasons also be written as type(x) but type(x) is discouraged.

+

One can obtain the type of a given expression by constructing a typeof value from it (in many other languages this is known as the typeof operator):

+

var x = 0
+var y: typeof(x) # y has type int

+

If typeof is used to determine the result type of a proc/iterator/converter call c(X) (where X stands for a possibly empty list of arguments), the interpretation, where c is an iterator, is preferred over the other interpretations, but this behavior can be changed by passing typeOfProc as the second argument to typeof:

+

iterator split(s: string): string = discard
+proc split(s: string): seq[string] = discard
+
+# since an iterator is the preferred interpretation, this has the type `string`:
+assert typeof("a b c".split) is string
+
+assert typeof("a b c".split, typeOfProc) is seq[string]

+ +

Modules

Nim supports splitting a program into pieces by a module concept. Each module needs to be in its own file and has its own namespace. Modules enable information hiding and separate compilation. A module may gain access to the symbols of another module by the import statement. Recursive module dependencies are allowed, but are slightly subtle. Only top-level symbols that are marked with an asterisk (*) are exported. A valid module name can only be a valid Nim identifier (and thus its filename is identifier.nim).

+

The algorithm for compiling modules is:

+
  • Compile the whole module as usual, following import statements recursively.
  • +
  • If there is a cycle, only import the already parsed symbols (that are exported); if an unknown identifier occurs then abort.
  • +
+

This is best illustrated by an example:

+

# Module A
+type
+  T1* = int  # Module A exports the type `T1`
+import B     # the compiler starts parsing B
+
+proc main() =
+  var i = p(3) # works because B has been parsed completely here
+
+main()

+

# Module B
+import A  # A is not parsed here! Only the already known symbols
+          # of A are imported.
+
+proc p*(x: A.T1): A.T1 =
+  # this works because the compiler has already
+  # added T1 to A's interface symbol table
+  result = x + 1

+ +

Import statement

After the import keyword, a list of module names can follow or a single module name followed by an except list to prevent some symbols from being imported:

+

import std/strutils except `%`, toUpperAscii
+
+# doesn't work then:
+echo "$1" % "abc".toUpperAscii

+

It is not checked that the except list is really exported from the module. This feature allows us to compile against different versions of the module, even when one version does not export some of these identifiers.

+

The import statement is only allowed at the top level.

+

String literals can be used for import/include statements. The compiler performs path substitution when used.

+ +

Include statement

The include statement does something fundamentally different than importing a module: it merely includes the contents of a file. The include statement is useful to split up a large module into several files:

+

include fileA, fileB, fileC

+

The include statement can be used outside the top level, as such:

+

# Module A
+echo "Hello World!"

+

# Module B
+proc main() =
+  include A
+
+main() # => Hello World!

+ +

Module names in imports

A module alias can be introduced via the as keyword, after which the original module name is inaccessible:

+

import std/strutils as su, std/sequtils as qu
+
+echo su.format("$1", "lalelu")

+

The notations path/to/module or "path/to/module" can be used to refer to a module in subdirectories:

+

import lib/pure/os, "lib/pure/times"

+

Note that the module name is still strutils and not lib/pure/strutils, thus one cannot do:

+

import lib/pure/strutils
+echo lib/pure/strutils.toUpperAscii("abc")

+

Likewise, the following does not make sense as the name is strutils already:

+

import lib/pure/strutils as strutils

+ +

Collective imports from a directory

The syntax import dir / [moduleA, moduleB] can be used to import multiple modules from the same directory.

+

Path names are syntactically either Nim identifiers or string literals. If the path name is not a valid Nim identifier it needs to be a string literal:

+

import "gfx/3d/somemodule" # in quotes because '3d' is not a valid Nim identifier

+ +

Pseudo import/include paths

A directory can also be a so-called "pseudo directory". They can be used to avoid ambiguity when there are multiple modules with the same path.

+

There are two pseudo directories:

+
  1. std: The std pseudo directory is the abstract location of Nim's standard library. For example, the syntax import std / strutils is used to unambiguously refer to the standard library's strutils module.
  2. +
  3. pkg: The pkg pseudo directory is used to unambiguously refer to a Nimble package. However, for technical details that lie outside the scope of this document, its semantics are: Use the search path to look for module name but ignore the standard library locations. In other words, it is the opposite of std.
  4. +
+

It is recommended and preferred but not currently enforced that all stdlib module imports include the std/ "pseudo directory" as part of the import name.

+ +

From import statement

After the from keyword, a module name followed by an import to list the symbols one likes to use without explicit full qualification:

+

from std/strutils import `%`
+
+echo "$1" % "abc"
+# always possible: full qualification:
+echo strutils.replace("abc", "a", "z")

+

It's also possible to use from module import nil if one wants to import the module but wants to enforce fully qualified access to every symbol in module.

+ +

Export statement

An export statement can be used for symbol forwarding so that client modules don't need to import a module's dependencies:

+

# module B
+type MyObject* = object

+

# module A
+import B
+export B.MyObject
+
+proc `$`*(x: MyObject): string = "my object"

+

# module C
+import A
+
+# B.MyObject has been imported implicitly here:
+var x: MyObject
+echo $x

+

When the exported symbol is another module, all of its definitions will be forwarded. One can use an except list to exclude some of the symbols.

+

Notice that when exporting, one needs to specify only the module name:

+

import foo/bar/baz
+export baz

+ +

Scope rules

Identifiers are valid from the point of their declaration until the end of the block in which the declaration occurred. The range where the identifier is known is the scope of the identifier. The exact scope of an identifier depends on the way it was declared.

+ +

Block scope

The scope of a variable declared in the declaration part of a block is valid from the point of declaration until the end of the block. If a block contains a second block, in which the identifier is redeclared, then inside this block, the second declaration will be valid. Upon leaving the inner block, the first declaration is valid again. An identifier cannot be redefined in the same block, except if valid for procedure or iterator overloading purposes.

+ +

Tuple or object scope

The field identifiers inside a tuple or object definition are valid in the following places:

+
  • To the end of the tuple/object definition.
  • +
  • Field designators of a variable of the given tuple/object type.
  • +
  • In all descendant types of the object type.
  • +
+ +

Module scope

All identifiers of a module are valid from the point of declaration until the end of the module. Identifiers from indirectly dependent modules are not available. The system module is automatically imported in every module.

+

If a module imports the same identifier from two different modules, the identifier is considered ambiguous, which can be resolved in the following ways:

+
  • Qualifying the identifier as module.identifier resolves ambiguity between modules. (See below for the case that the module name itself is ambiguous.)
  • +
  • Calling the identifier as a routine makes overload resolution take place, which resolves ambiguity in the case that one overload matches stronger than the others.
  • +
  • Using the identifier in a context where the compiler can infer the type of the identifier resolves ambiguity in the case that one definition matches the type stronger than the others.

    +

    # Module A
    +var x*: string
    +proc foo*(a: string) =
    +  echo "A: ", a

    +

    # Module B
    +var x*: int
    +proc foo*(b: int) =
    +  echo "B: ", b

    +

    # Module C
    +import A, B
    +
    +foo("abc") # A: abc
    +foo(123) # B: 123
    +let inferred: proc (x: string) = foo
    +foo("def") # A: def
    +
    +write(stdout, x) # error: x is ambiguous
    +write(stdout, A.x) # no error: qualifier used
    +
    +proc bar(a: int): int = a + 1
    +assert bar(x) == x + 1 # no error: only A.x of type int matches
    +
    +var x = 4
    +write(stdout, x) # not ambiguous: uses the module C's x

    +
  • +
+

Modules can share their name, however, when trying to qualify an identifier with the module name the compiler will fail with ambiguous identifier error. One can qualify the identifier by aliasing the module.

+

# Module A/C
+proc fb* = echo "fizz"

+

# Module B/C
+proc fb* = echo "buzz"

+

import A/C
+import B/C
+
+C.fb() # Error: ambiguous identifier: 'C'

+

import A/C as fizz
+import B/C
+
+fizz.fb() # Works

+ +

Packages

A collection of modules in a file tree with an identifier.nimble file in the root of the tree is called a Nimble package. A valid package name can only be a valid Nim identifier and thus its filename is identifier.nimble where identifier is the desired package name. A module without a .nimble file is assigned the package identifier: unknown.

+

The distinction between packages allows diagnostic compiler messages to be scoped to the current project's package vs foreign packages.

+ +

Compiler Messages

The Nim compiler emits different kinds of messages: hint, warning, and error messages. An error message is emitted if the compiler encounters any static error.

+ +

Pragmas

Pragmas are Nim's method to give the compiler additional information / commands without introducing a massive number of new keywords. Pragmas are processed on the fly during semantic checking. Pragmas are enclosed in the special {. and .} curly brackets. Pragmas are also often used as a first implementation to play with a language feature before a nicer syntax to access the feature becomes available.

+ +

deprecated pragma

The deprecated pragma is used to mark a symbol as deprecated:

+

proc p() {.deprecated.}
+var x {.deprecated.}: char

+

This pragma can also take in an optional warning string to relay to developers.

+

proc thing(x: bool) {.deprecated: "use thong instead".}

+ +

compileTime pragma

The compileTime pragma is used to mark a proc or variable to be used only during compile-time execution. No code will be generated for it. Compile-time procs are useful as helpers for macros. Since version 0.12.0 of the language, a proc that uses system.NimNode within its parameter types is implicitly declared compileTime:

+

proc astHelper(n: NimNode): NimNode =
+  result = n

+

Is the same as:

+

proc astHelper(n: NimNode): NimNode {.compileTime.} =
+  result = n

+

compileTime variables are available at runtime too. This simplifies certain idioms where variables are filled at compile-time (for example, lookup tables) but accessed at runtime:

+

import std/macros
+
+var nameToProc {.compileTime.}: seq[(string, proc (): string {.nimcall.})]
+
+macro registerProc(p: untyped): untyped =
+  result = newTree(nnkStmtList, p)
+  
+  let procName = p[0]
+  let procNameAsStr = $p[0]
+  result.add quote do:
+    nameToProc.add((`procNameAsStr`, `procName`))
+
+proc foo: string {.registerProc.} = "foo"
+proc bar: string {.registerProc.} = "bar"
+proc baz: string {.registerProc.} = "baz"
+
+doAssert nameToProc[2][1]() == "baz"

+ +

noreturn pragma

The noreturn pragma is used to mark a proc that never returns.

+ +

acyclic pragma

The acyclic pragma can be used for object types to mark them as acyclic even though they seem to be cyclic. This is an optimization for the garbage collector to not consider objects of this type as part of a cycle:

+

type
+  Node = ref NodeObj
+  NodeObj {.acyclic.} = object
+    left, right: Node
+    data: string

+

Or if we directly use a ref object:

+

type
+  Node {.acyclic.} = ref object
+    left, right: Node
+    data: string

+

In the example, a tree structure is declared with the Node type. Note that the type definition is recursive and the GC has to assume that objects of this type may form a cyclic graph. The acyclic pragma passes the information that this cannot happen to the GC. If the programmer uses the acyclic pragma for data types that are in reality cyclic, this may result in memory leaks, but memory safety is preserved.

+ +

final pragma

The final pragma can be used for an object type to specify that it cannot be inherited from. Note that inheritance is only available for objects that inherit from an existing object (via the object of SuperType syntax) or that have been marked as inheritable.

+ +

shallow pragma

The shallow pragma affects the semantics of a type: The compiler is allowed to make a shallow copy. This can cause serious semantic issues and break memory safety! However, it can speed up assignments considerably, because the semantics of Nim require deep copying of sequences and strings. This can be expensive, especially if sequences are used to build a tree structure:

+

type
+  NodeKind = enum nkLeaf, nkInner
+  Node {.shallow.} = object
+    case kind: NodeKind
+    of nkLeaf:
+      strVal: string
+    of nkInner:
+      children: seq[Node]

+ +

pure pragma

An object type can be marked with the pure pragma so that its type field which is used for runtime type identification is omitted. This used to be necessary for binary compatibility with other compiled languages.

+

An enum type can be marked as pure. Then access of its fields always requires full qualification.

+ +

asmNoStackFrame pragma

A proc can be marked with the asmNoStackFrame pragma to tell the compiler it should not generate a stack frame for the proc. There are also no exit statements like return result; generated and the generated C function is declared as __declspec(naked) or __attribute__((naked)) (depending on the used C compiler).

+

Note: This pragma should only be used by procs which consist solely of assembler statements.

+ +

error pragma

The error pragma is used to make the compiler output an error message with the given content. The compilation does not necessarily abort after an error though.

+

The error pragma can also be used to annotate a symbol (like an iterator or proc). The usage of the symbol then triggers a static error. This is especially useful to rule out that some operation is valid due to overloading and type conversions:

+

## check that underlying int values are compared and not the pointers:
+proc `==`(x, y: ptr int): bool {.error.}

+ +

fatal pragma

The fatal pragma is used to make the compiler output an error message with the given content. In contrast to the error pragma, the compilation is guaranteed to be aborted by this pragma. Example:

+

when not defined(objc):
+  {.fatal: "Compile this program with the objc command!".}

+ +

warning pragma

The warning pragma is used to make the compiler output a warning message with the given content. Compilation continues after the warning.

+ +

hint pragma

The hint pragma is used to make the compiler output a hint message with the given content. Compilation continues after the hint.

+ +

line pragma

The line pragma can be used to affect line information of the annotated statement, as seen in stack backtraces:

+

template myassert*(cond: untyped, msg = "") =
+  if not cond:
+    # change run-time line information of the 'raise' statement:
+    {.line: instantiationInfo().}:
+      raise newException(AssertionDefect, msg)

+

If the line pragma is used with a parameter, the parameter needs to be a tuple[filename: string, line: int]. If it is used without a parameter, system.instantiationInfo() is used.

+ +

linearScanEnd pragma

The linearScanEnd pragma can be used to tell the compiler how to compile a Nim case statement. Syntactically it has to be used as a statement:

+

case myInt
+of 0:
+  echo "most common case"
+of 1:
+  {.linearScanEnd.}
+  echo "second most common case"
+of 2: echo "unlikely: use branch table"
+else: echo "unlikely too: use branch table for ", myInt

+

In the example, the case branches 0 and 1 are much more common than the other cases. Therefore, the generated assembler code should test for these values first so that the CPU's branch predictor has a good chance to succeed (avoiding an expensive CPU pipeline stall). The other cases might be put into a jump table for O(1) overhead but at the cost of a (very likely) pipeline stall.

+

The linearScanEnd pragma should be put into the last branch that should be tested against via linear scanning. If put into the last branch of the whole case statement, the whole case statement uses linear scanning.

+ +

computedGoto pragma

The computedGoto pragma can be used to tell the compiler how to compile a Nim case in a while true statement. Syntactically it has to be used as a statement inside the loop:

+

type
+  MyEnum = enum
+    enumA, enumB, enumC, enumD, enumE
+
+proc vm() =
+  var instructions: array[0..100, MyEnum]
+  instructions[2] = enumC
+  instructions[3] = enumD
+  instructions[4] = enumA
+  instructions[5] = enumD
+  instructions[6] = enumC
+  instructions[7] = enumA
+  instructions[8] = enumB
+  
+  instructions[12] = enumE
+  var pc = 0
+  while true:
+    {.computedGoto.}
+    let instr = instructions[pc]
+    case instr
+    of enumA:
+      echo "yeah A"
+    of enumC, enumD:
+      echo "yeah CD"
+    of enumB:
+      echo "yeah B"
+    of enumE:
+      break
+    inc(pc)
+
+vm()

+

As the example shows, computedGoto is mostly useful for interpreters. If the underlying backend (C compiler) does not support the computed goto extension the pragma is simply ignored.

+ +

immediate pragma

The immediate pragma is obsolete. See Typed vs untyped parameters.

+ +

redefine pragma

Redefinition of template symbols with the same signature is allowed. This can be made explicit with the redefine pragma:

+

template foo: int = 1
+echo foo() # 1
+template foo: int {.redefine.} = 2
+echo foo() # 2
+# warning: implicit redefinition of template
+template foo: int = 3

+

This is mostly intended for macro generated code.

+ +

compilation option pragmas

The listed pragmas here can be used to override the code generation options for a proc/method/converter.

+

The implementation currently provides the following possible options (various others may be added later).

+ + + + + + + + + + + +
pragmaallowed valuesdescription
checkson|off Turns the code generation for all runtime checks on or off.
boundCheckson|off Turns the code generation for array bound checks on or off.
overflowCheckson|off Turns the code generation for over- or underflow checks on or off.
nilCheckson|off Turns the code generation for nil pointer checks on or off.
assertionson|off Turns the code generation for assertions on or off.
warningson|off Turns the warning messages of the compiler on or off.
hintson|off Turns the hint messages of the compiler on or off.
optimizationnone|speed|size Optimize the code for speed or size, or disable optimization.
patternson|off Turns the term rewriting templates/macros on or off.
callconvcdecl|...Specifies the default calling convention for all procedures (and procedure types) that follow.

Example:

+

{.checks: off, optimization: speed.}
+# compile without runtime checks and optimize for speed

+ +

push and pop pragmas

The push/pop pragmas are very similar to the option directive, but are used to override the settings temporarily. Example:

+

{.push checks: off.}
+# compile this section without runtime checks as it is
+# speed critical
+# ... some code ...
+{.pop.} # restore old settings

+

push/pop can switch on/off some standard library pragmas, example:

+

{.push inline.}
+proc thisIsInlined(): int = 42
+func willBeInlined(): float = 42.0
+{.pop.}
+proc notInlined(): int = 9
+
+{.push discardable, boundChecks: off, compileTime, noSideEffect, experimental.}
+template example(): string = "https://nim-lang.org"
+{.pop.}
+
+{.push deprecated, used, stackTrace: off.}
+proc sample(): bool = true
+{.pop.}

+

For third party pragmas, it depends on its implementation but uses the same syntax.

+ +

register pragma

The register pragma is for variables only. It declares the variable as register, giving the compiler a hint that the variable should be placed in a hardware register for faster access. C compilers usually ignore this though and for good reasons: Often they do a better job without it anyway.

+

However, in highly specific cases (a dispatch loop of a bytecode interpreter for example) it may provide benefits.

+ +

global pragma

The global pragma can be applied to a variable within a proc to instruct the compiler to store it in a global location and initialize it once at program startup.

+

proc isHexNumber(s: string): bool =
+  var pattern {.global.} = re"[0-9a-fA-F]+"
+  result = s.match(pattern)

+

When used within a generic proc, a separate unique global variable will be created for each instantiation of the proc. The order of initialization of the created global variables within a module is not defined, but all of them will be initialized after any top-level variables in their originating module and before any variable in a module that imports it.

+ +

Disabling certain messages

Nim generates some warnings and hints that may annoy the user. A mechanism for disabling certain messages is provided: Each hint and warning message is associated with a symbol. This is the message's identifier, which can be used to enable or disable the message by putting it in brackets following the pragma:

+

{.hint[XDeclaredButNotUsed]: off.} # Turn off the hint about declared but not used symbols.

+

This is often better than disabling all warnings at once.

+ +

used pragma

Nim produces a warning for symbols that are not exported and not used either. The used pragma can be attached to a symbol to suppress this warning. This is particularly useful when the symbol was generated by a macro:

+

template implementArithOps(T) =
+  proc echoAdd(a, b: T) {.used.} =
+    echo a + b
+  proc echoSub(a, b: T) {.used.} =
+    echo a - b
+
+# no warning produced for the unused 'echoSub'
+implementArithOps(int)
+echoAdd 3, 5

+

used can also be used as a top-level statement to mark a module as "used". This prevents the "Unused import" warning:

+

# module: debughelper.nim
+when defined(nimHasUsed):
+  # 'import debughelper' is so useful for debugging
+  # that Nim shouldn't produce a warning for that import,
+  # even if currently unused:
+  {.used.}

+ +

experimental pragma

The experimental pragma enables experimental language features. Depending on the concrete feature, this means that the feature is either considered too unstable for an otherwise stable release or that the future of the feature is uncertain (it may be removed at any time). See the experimental manual for more details.

+

Example:

+

import std/threadpool
+{.experimental: "parallel".}
+
+proc threadedEcho(s: string, i: int) =
+  echo(s, " ", $i)
+
+proc useParallel() =
+  parallel:
+    for i in 0..4:
+      spawn threadedEcho("echo in parallel", i)
+
+useParallel()

+

As a top-level statement, the experimental pragma enables a feature for the rest of the module it's enabled in. This is problematic for macro and generic instantiations that cross a module scope. Currently, these usages have to be put into a .push/pop environment:

+

# client.nim
+proc useParallel*[T](unused: T) =
+  # use a generic T here to show the problem.
+  {.push experimental: "parallel".}
+  parallel:
+    for i in 0..4:
+      echo "echo in parallel"
+  
+  {.pop.}

+

import client
+useParallel(1)

+ +

Implementation Specific Pragmas

This section describes additional pragmas that the current Nim implementation supports but which should not be seen as part of the language specification.

+ +

Bitsize pragma

The bitsize pragma is for object field members. It declares the field as a bitfield in C/C++.

+

type
+  mybitfield = object
+    flag {.bitsize:1.}: cuint

+

generates:

+

struct mybitfield {
+  unsigned int flag:1;
+};

+ +

size pragma

Nim automatically determines the size of an enum. But when wrapping a C enum type, it needs to be of a specific size. The size pragma allows specifying the size of the enum type.

+

type
+  EventType* {.size: sizeof(uint32).} = enum
+    QuitEvent,
+    AppTerminating,
+    AppLowMemory
+
+doAssert sizeof(EventType) == sizeof(uint32)

+

The size pragma can also specify the size of an importc incomplete object type so that one can get the size of it at compile time even if it was declared without fields.

+

  type
+    AtomicFlag* {.importc: "atomic_flag", header: "<stdatomic.h>", size: 1.} = object
+  
+  static:
+    # if AtomicFlag didn't have the size pragma, this code would result in a compile time error.
+    echo sizeof(AtomicFlag)

+

The size pragma accepts only the values 1, 2, 4 or 8.

+ +

Align pragma

The align pragma is for variables and object field members. It modifies the alignment requirement of the entity being declared. The argument must be a constant power of 2. Valid non-zero alignments that are weaker than other align pragmas on the same declaration are ignored. Alignments that are weaker than the alignment requirement of the type are ignored.

+

type
+  sseType = object
+    sseData {.align(16).}: array[4, float32]
+  
+  # every object will be aligned to 128-byte boundary
+  Data = object
+    x: char
+    cacheline {.align(128).}: array[128, char] # over-aligned array of char,
+
+proc main() =
+  echo "sizeof(Data) = ", sizeof(Data), " (1 byte + 127 bytes padding + 128-byte array)"
+  # output: sizeof(Data) = 256 (1 byte + 127 bytes padding + 128-byte array)
+  echo "alignment of sseType is ", alignof(sseType)
+  # output: alignment of sseType is 16
+  var d {.align(2048).}: Data # this instance of data is aligned even stricter
+
+main()

+

This pragma has no effect on the JS backend.

+ +

Noalias pragma

Since version 1.4 of the Nim compiler, there is a .noalias annotation for variables and parameters. It is mapped directly to C/C++'s restrict keyword and means that the underlying pointer is pointing to a unique location in memory, no other aliases to this location exist. It is unchecked that this alias restriction is followed. If the restriction is violated, the backend optimizer is free to miscompile the code. This is an unsafe language feature.

+

Ideally in later versions of the language, the restriction will be enforced at compile time. (This is also why the name noalias was chosen instead of a more verbose name like unsafeAssumeNoAlias.)

+ +

Volatile pragma

The volatile pragma is for variables only. It declares the variable as volatile, whatever that means in C/C++ (its semantics are not well-defined in C/C++).

+

Note: This pragma will not exist for the LLVM backend.

+ +

nodecl pragma

The nodecl pragma can be applied to almost any symbol (variable, proc, type, etc.) and is sometimes useful for interoperability with C: It tells Nim that it should not generate a declaration for the symbol in the C code. For example:

+

var
+  EACCES {.importc, nodecl.}: cint # pretend EACCES was a variable, as
+                                   # Nim does not know its value

+

However, the header pragma is often the better alternative.

+

Note: This will not work for the LLVM backend.

+ +

Header pragma

The header pragma is very similar to the nodecl pragma: It can be applied to almost any symbol and specifies that it should not be declared and instead, the generated code should contain an #include:

+

type
+  PFile {.importc: "FILE*", header: "<stdio.h>".} = distinct pointer
+    # import C's FILE* type; Nim will treat it as a new pointer type

+

The header pragma always expects a string constant. The string constant contains the header file: As usual for C, a system header file is enclosed in angle brackets: <>. If no angle brackets are given, Nim encloses the header file in "" in the generated C code.

+

Note: This will not work for the LLVM backend.

+ +

IncompleteStruct pragma

The incompleteStruct pragma tells the compiler to not use the underlying C struct in a sizeof expression:

+

type
+  DIR* {.importc: "DIR", header: "<dirent.h>",
+         pure, incompleteStruct.} = object

+ +

Compile pragma

The compile pragma can be used to compile and link a C/C++ source file with the project:

+

This pragma can take three forms. The first is a simple file input:

+

{.compile: "myfile.cpp".}

+

The second form is a tuple where the second arg is the output name strutils formatter:

+

{.compile: ("file.c", "$1.o").}

+

Note: Nim computes a SHA1 checksum and only recompiles the file if it has changed. One can use the -f command-line option to force the recompilation of the file.

+

Since 1.4 the compile pragma is also available with this syntax:

+

{.compile("myfile.cpp", "--custom flags here").}

+

As can be seen in the example, this new variant allows for custom flags that are passed to the C compiler when the file is recompiled.

+ +

Link pragma

The link pragma can be used to link an additional file with the project:

+

{.link: "myfile.o".}

+ +

passc pragma

The passc pragma can be used to pass additional parameters to the C compiler like one would use the command-line switch --passc:

+

{.passc: "-Wall -Werror".}

+

Note that one can use gorge from the system module to embed parameters from an external command that will be executed during semantic analysis:

+

{.passc: gorge("pkg-config --cflags sdl").}

+ +

localPassC pragma

The localPassC pragma can be used to pass additional parameters to the C compiler, but only for the C/C++ file that is produced from the Nim module the pragma resides in:

+

# Module A.nim
+# Produces: A.nim.cpp
+{.localPassC: "-Wall -Werror".} # Passed when compiling A.nim.cpp

+ +

passl pragma

The passl pragma can be used to pass additional parameters to the linker like one would be using the command-line switch --passl:

+

{.passl: "-lSDLmain -lSDL".}

+

Note that one can use gorge from the system module to embed parameters from an external command that will be executed during semantic analysis:

+

{.passl: gorge("pkg-config --libs sdl").}

+ +

Emit pragma

The emit pragma can be used to directly affect the output of the compiler's code generator. The code is then unportable to other code generators/backends. Its usage is highly discouraged! However, it can be extremely useful for interfacing with C++ or Objective C code.

+

Example:

+

{.emit: """
+static int cvariable = 420;
+""".}
+
+{.push stackTrace:off.}
+proc embedsC() =
+  var nimVar = 89
+  # access Nim symbols within an emit section outside of string literals:
+  {.emit: ["""fprintf(stdout, "%d\n", cvariable + (int)""", nimVar, ");"].}
+{.pop.}
+
+embedsC()

+

nimbase.h defines NIM_EXTERNC C macro that can be used for extern "C" code to work with both nim c and nim cpp, e.g.:

+

proc foobar() {.importc:"$1".}
+{.emit: """
+#include <stdio.h>
+NIM_EXTERNC
+void fun(){}
+""".}

+
Note: +For backward compatibility, if the argument to the emit statement is a single string literal, Nim symbols can be referred to via backticks. This usage is however deprecated.
+

For a top-level emit statement, the section where in the generated C/C++ file the code should be emitted can be influenced via the prefixes /*TYPESECTION*/ or /*VARSECTION*/ or /*INCLUDESECTION*/:

+

{.emit: """/*TYPESECTION*/
+struct Vector3 {
+public:
+  Vector3(): x(5) {}
+  Vector3(float x_): x(x_) {}
+  float x;
+};
+""".}
+
+type Vector3 {.importcpp: "Vector3", nodecl} = object
+  x: cfloat
+
+proc constructVector3(a: cfloat): Vector3 {.importcpp: "Vector3(@)", nodecl}

+ +

ImportCpp pragma

Note: c2nim can parse a large subset of C++ and knows about the importcpp pragma pattern language. It is not necessary to know all the details described here.

+

Similar to the importc pragma for C, the importcpp pragma can be used to import C++ methods or C++ symbols in general. The generated code then uses the C++ method calling syntax: obj->method(arg). In combination with the header and emit pragmas this allows sloppy interfacing with libraries written in C++:

+

# Horrible example of how to interface with a C++ engine ... ;-)
+
+{.link: "/usr/lib/libIrrlicht.so".}
+
+{.emit: """
+using namespace irr;
+using namespace core;
+using namespace scene;
+using namespace video;
+using namespace io;
+using namespace gui;
+""".}
+
+const
+  irr = "<irrlicht/irrlicht.h>"
+
+type
+  IrrlichtDeviceObj {.header: irr,
+                      importcpp: "IrrlichtDevice".} = object
+  IrrlichtDevice = ptr IrrlichtDeviceObj
+
+proc createDevice(): IrrlichtDevice {.
+  header: irr, importcpp: "createDevice(@)".}
+proc run(device: IrrlichtDevice): bool {.
+  header: irr, importcpp: "#.run(@)".}

+

The compiler needs to be told to generate C++ (command cpp) for this to work. The conditional symbol cpp is defined when the compiler emits C++ code.

+ +

Namespaces

The sloppy interfacing example uses .emit to produce using namespace declarations. It is usually much better to instead refer to the imported name via the namespace::identifier notation:

+

type
+  IrrlichtDeviceObj {.header: irr,
+                      importcpp: "irr::IrrlichtDevice".} = object

+ +

Importcpp for enums

When importcpp is applied to an enum type the numerical enum values are annotated with the C++ enum type, like in this example: ((TheCppEnum)(3)). (This turned out to be the simplest way to implement it.)

+ +

Importcpp for procs

Note that the importcpp variant for procs uses a somewhat cryptic pattern language for maximum flexibility:

+
  • A hash # symbol is replaced by the first or next argument.
  • +
  • A dot following the hash #. indicates that the call should use C++'s dot or arrow notation.
  • +
  • An at symbol @ is replaced by the remaining arguments, separated by commas.
  • +
+

For example:

+

proc cppMethod(this: CppObj, a, b, c: cint) {.importcpp: "#.CppMethod(@)".}
+var x: ptr CppObj
+cppMethod(x[], 1, 2, 3)

+

Produces:

+

x->CppMethod(1, 2, 3)

+

As a special rule to keep backward compatibility with older versions of the importcpp pragma, if there is no special pattern character (any of # ' @) at all, C++'s dot or arrow notation is assumed, so the above example can also be written as:

+

proc cppMethod(this: CppObj, a, b, c: cint) {.importcpp: "CppMethod".}

+

Note that the pattern language naturally also covers C++'s operator overloading capabilities:

+

proc vectorAddition(a, b: Vec3): Vec3 {.importcpp: "# + #".}
+proc dictLookup(a: Dict, k: Key): Value {.importcpp: "#[#]".}

+
  • An apostrophe ' followed by an integer i in the range 0..9 is replaced by the i'th parameter type. The 0th position is the result type. This can be used to pass types to C++ function templates. Between the ' and the digit, an asterisk can be used to get to the base type of the type. (So it "takes away a star" from the type; T* becomes T.) Two stars can be used to get to the element type of the element type etc.
  • +
+

For example:

+

type Input {.importcpp: "System::Input".} = object
+proc getSubsystem*[T](): ptr T {.importcpp: "SystemManager::getSubsystem<'*0>()", nodecl.}
+
+let x: ptr Input = getSubsystem[Input]()

+

Produces:

+

x = SystemManager::getSubsystem<System::Input>()

+
  • #@ is a special case to support a cnew operation. It is required so that the call expression is inlined directly, without going through a temporary location. This is only required to circumvent a limitation of the current code generator.
  • +
+

For example C++'s new operator can be "imported" like this:

+

proc cnew*[T](x: T): ptr T {.importcpp: "(new '*0#@)", nodecl.}
+
+# constructor of 'Foo':
+proc constructFoo(a, b: cint): Foo {.importcpp: "Foo(@)".}
+
+let x = cnew constructFoo(3, 4)

+

Produces:

+

x = new Foo(3, 4)

+

However, depending on the use case new Foo can also be wrapped like this instead:

+

proc newFoo(a, b: cint): ptr Foo {.importcpp: "new Foo(@)".}
+
+let x = newFoo(3, 4)

+ +

Wrapping constructors

Sometimes a C++ class has a private copy constructor and so code like Class c = Class(1,2); must not be generated but instead Class c(1,2);. For this purpose the Nim proc that wraps a C++ constructor needs to be annotated with the constructor pragma. This pragma also helps to generate faster C++ code since construction then doesn't invoke the copy constructor:

+

# a better constructor of 'Foo':
+proc constructFoo(a, b: cint): Foo {.importcpp: "Foo(@)", constructor.}

+ +

Wrapping destructors

Since Nim generates C++ directly, any destructor is called implicitly by the C++ compiler at the scope exits. This means that often one can get away with not wrapping the destructor at all! However, when it needs to be invoked explicitly, it needs to be wrapped. The pattern language provides everything that is required:

+

proc destroyFoo(this: var Foo) {.importcpp: "#.~Foo()".}

+ +

Importcpp for objects

Generic importcpp'ed objects are mapped to C++ templates. This means that one can import C++'s templates rather easily without the need for a pattern language for object types:

+

type
+  StdMap[K, V] {.importcpp: "std::map", header: "<map>".} = object
+proc `[]=`[K, V](this: var StdMap[K, V]; key: K; val: V) {.
+  importcpp: "#[#] = #", header: "<map>".}
+
+var x: StdMap[cint, cdouble]
+x[6] = 91.4

+

Produces:

+

std::map<int, double> x;
+x[6] = 91.4;

+
  • If more precise control is needed, the apostrophe ' can be used in the supplied pattern to denote the concrete type parameters of the generic type. See the usage of the apostrophe operator in proc patterns for more details.

    +

    type
    +  VectorIterator[T] {.importcpp: "std::vector<'0>::iterator".} = object
    +
    +var x: VectorIterator[cint]

    +

    Produces:

    +

    +std::vector<int>::iterator x;

    +
  • +
+ +

ImportJs pragma

Similar to the importcpp pragma for C++, the importjs pragma can be used to import Javascript methods or symbols in general. The generated code then uses the Javascript method calling syntax: obj.method(arg).

+ +

ImportObjC pragma

Similar to the importc pragma for C, the importobjc pragma can be used to import Objective C methods. The generated code then uses the Objective C method calling syntax: [obj method param1: arg]. In addition with the header and emit pragmas this allows sloppy interfacing with libraries written in Objective C:

+

# horrible example of how to interface with GNUStep ...
+
+{.passl: "-lobjc".}
+{.emit: """
+#include <objc/Object.h>
+@interface Greeter:Object
+{
+}
+
+- (void)greet:(long)x y:(long)dummy;
+@end
+
+#include <stdio.h>
+@implementation Greeter
+
+- (void)greet:(long)x y:(long)dummy
+{
+  printf("Hello, World!\n");
+}
+@end
+
+#include <stdlib.h>
+""".}
+
+type
+  Id {.importc: "id", header: "<objc/Object.h>", final.} = distinct int
+
+proc newGreeter: Id {.importobjc: "Greeter new", nodecl.}
+proc greet(self: Id, x, y: int) {.importobjc: "greet", nodecl.}
+proc free(self: Id) {.importobjc: "free", nodecl.}
+
+var g = newGreeter()
+g.greet(12, 34)
+g.free()

+

The compiler needs to be told to generate Objective C (command objc) for this to work. The conditional symbol objc is defined when the compiler emits Objective C code.

+ +

CodegenDecl pragma

The codegenDecl pragma can be used to directly influence Nim's code generator. It receives a format string that determines how the variable, proc or object type is declared in the generated code.

+

For variables, $1 in the format string represents the type of the variable, $2 is the name of the variable, and each appearance of $# represents $1/$2 respectively according to its position.

+

The following Nim code:

+

var
+  a {.codegenDecl: "$# progmem $#".}: int

+

will generate this C code:

+

int progmem a

+

For procedures, $1 is the return type of the procedure, $2 is the name of the procedure, $3 is the parameter list, and each appearance of $# represents $1/$2/$3 respectively according to its position.

+

The following nim code:

+

proc myinterrupt() {.codegenDecl: "__interrupt $# $#$#".} =
+  echo "realistic interrupt handler"

+

will generate this code:

+

__interrupt void myinterrupt()

+

For object types, the $1 represents the name of the object type, $2 is the list of fields and $3 is the base type.

+

+const strTemplate = """
+  struct $1 {
+    $2
+  };
+"""
+type Foo {.codegenDecl:strTemplate.} = object
+  a, b: int

+

will generate this code:

+

struct Foo {
+  NI a;
+  NI b;
+};

+ +

cppNonPod pragma

The cppNonPod pragma should be used for non-POD importcpp types so that they work properly (in particular regarding constructor and destructor) for threadvar variables. This requires --tlsEmulation:off.

+

type Foo {.cppNonPod, importcpp, header: "funs.h".} = object
+  x: cint
+proc main()=
+  var a {.threadvar.}: Foo

+ +

compile-time define pragmas

The pragmas listed here can be used to optionally accept values from the -d/--define option at compile time.

+

The implementation currently provides the following possible options (various others may be added later).

+ + + + +
pragmadescription
intdefineReads in a build-time define as an integer
strdefineReads in a build-time define as a string
booldefineReads in a build-time define as a bool

const FooBar {.intdefine.}: int = 5
+echo FooBar

+

nim c -d:FooBar=42 foobar.nim

+

In the above example, providing the -d flag causes the symbol FooBar to be overwritten at compile-time, printing out 42. If the -d:FooBar=42 were to be omitted, the default value of 5 would be used. To see if a value was provided, defined(FooBar) can be used.

+

The syntax -d:flag is actually just a shortcut for -d:flag=true.

+

These pragmas also accept an optional string argument for qualified define names.

+

const FooBar {.intdefine: "package.FooBar".}: int = 5
+echo FooBar

+

nim c -d:package.FooBar=42 foobar.nim

+

This helps disambiguate define names in different packages.

+

See also the generic `define` pragma for a version of these pragmas that detects the type of the define based on the constant value.

+ +

User-defined pragmas

+

pragma pragma

The pragma pragma can be used to declare user-defined pragmas. This is useful because Nim's templates and macros do not affect pragmas. User-defined pragmas are in a different module-wide scope than all other symbols. They cannot be imported from a module.

+

Example:

+

when appType == "lib":
+  {.pragma: rtl, exportc, dynlib, cdecl.}
+else:
+  {.pragma: rtl, importc, dynlib: "client.dll", cdecl.}
+
+proc p*(a, b: int): int {.rtl.} =
+  result = a + b

+

In the example, a new pragma named rtl is introduced that either imports a symbol from a dynamic library or exports the symbol for dynamic library generation.

+ +

Custom annotations

It is possible to define custom typed pragmas. Custom pragmas do not affect code generation directly, but their presence can be detected by macros. Custom pragmas are defined using templates annotated with pragma pragma:

+

template dbTable(name: string, table_space: string = "") {.pragma.}
+template dbKey(name: string = "", primary_key: bool = false) {.pragma.}
+template dbForeignKey(t: typedesc) {.pragma.}
+template dbIgnore {.pragma.}

+

Consider this stylized example of a possible Object Relation Mapping (ORM) implementation:

+

const tblspace {.strdefine.} = "dev" # switch for dev, test and prod environments
+
+type
+  User {.dbTable("users", tblspace).} = object
+    id {.dbKey(primary_key = true).}: int
+    name {.dbKey"full_name".}: string
+    is_cached {.dbIgnore.}: bool
+    age: int
+  
+  UserProfile {.dbTable("profiles", tblspace).} = object
+    id {.dbKey(primary_key = true).}: int
+    user_id {.dbForeignKey: User.}: int
+    read_access: bool
+    write_access: bool
+    admin_access: bool

+

In this example, custom pragmas are used to describe how Nim objects are mapped to the schema of the relational database. Custom pragmas can have zero or more arguments. In order to pass multiple arguments use one of template call syntaxes. All arguments are typed and follow standard overload resolution rules for templates. Therefore, it is possible to have default values for arguments, pass by name, varargs, etc.

+

Custom pragmas can be used in all locations where ordinary pragmas can be specified. It is possible to annotate procs, templates, type and variable definitions, statements, etc.

+

The macros module includes helpers which can be used to simplify custom pragma access hasCustomPragma, getCustomPragmaVal. Please consult the macros module documentation for details. These macros are not magic, everything they do can also be achieved by walking the AST of the object representation.

+

More examples with custom pragmas:

+
  • Better serialization/deserialization control:

    +

    type MyObj = object
    +  a {.dontSerialize.}: int
    +  b {.defaultDeserialize: 5.}: int
    +  c {.serializationKey: "_c".}: string

    +
  • +
  • Adopting type for gui inspector in a game engine:

    +

    type MyComponent = object
    +  position {.editable, animatable.}: Vector3
    +  alpha {.editRange: [0.0..1.0], animatable.}: float32

    +
  • +
+ +

Macro pragmas

Macros and templates can sometimes be called with the pragma syntax. Cases where this is possible include when attached to routine (procs, iterators, etc.) declarations or routine type expressions. The compiler will perform the following simple syntactic transformations:

+

template command(name: string, def: untyped) = discard
+
+proc p() {.command("print").} = discard

+

This is translated to:

+

command("print"):
+  proc p() = discard

+
+

type
+  AsyncEventHandler = proc (x: Event) {.async.}

+

This is translated to:

+

type
+  AsyncEventHandler = async(proc (x: Event))

+
+

When multiple macro pragmas are applied to the same definition, the first one from left to right will be evaluated. This macro can then choose to keep the remaining macro pragmas in its output, and those will be evaluated in the same way.

+

There are a few more applications of macro pragmas, such as in type, variable and constant declarations, but this behavior is considered to be experimental and is documented in the experimental manual instead.

+ +

Foreign function interface

Nim's FFI (foreign function interface) is extensive and only the parts that scale to other future backends (like the LLVM/JavaScript backends) are documented here.

+ +

Importc pragma

The importc pragma provides a means to import a proc or a variable from C. The optional argument is a string containing the C identifier. If the argument is missing, the C name is the Nim identifier exactly as spelled:

+

proc printf(formatstr: cstring) {.header: "<stdio.h>", importc: "printf", varargs.}

+

When importc is applied to a let statement it can omit its value which will then be expected to come from C. This can be used to import a C const:

+

{.emit: "const int cconst = 42;".}
+
+let cconst {.importc, nodecl.}: cint
+
+assert cconst == 42

+

Note that this pragma has been abused in the past to also work in the JS backend for JS objects and functions. Other backends do provide the same feature under the same name. Also, when the target language is not set to C, other pragmas are available:

+ +

The string literal passed to importc can be a format string:

+

proc p(s: cstring) {.importc: "prefix$1".}

+

In the example, the external name of p is set to prefixp. Only $1 is available and a literal dollar sign must be written as $$.

+ +

Exportc pragma

The exportc pragma provides a means to export a type, a variable, or a procedure to C. Enums and constants can't be exported. The optional argument is a string containing the C identifier. If the argument is missing, the C name is the Nim identifier exactly as spelled:

+

proc callme(formatstr: cstring) {.exportc: "callMe", varargs.}

+

Note that this pragma is somewhat of a misnomer: Other backends do provide the same feature under the same name.

+

The string literal passed to exportc can be a format string:

+

proc p(s: string) {.exportc: "prefix$1".} =
+  echo s

+

In the example, the external name of p is set to prefixp. Only $1 is available and a literal dollar sign must be written as $$.

+

If the symbol should also be exported to a dynamic library, the dynlib pragma should be used in addition to the exportc pragma. See Dynlib pragma for export.

+ +

Exportcpp pragma

The exportcpp pragma works like the exportc pragma but it requires the cpp backend. When compiled with the cpp backend, the exportc pragma adds export "C" to the declaration in the generated code so that it can be called from both C and C++ code. exportcpp pragma doesn't add export "C".

+ +

Extern pragma

Like exportc or importc, the extern pragma affects name mangling. The string literal passed to extern can be a format string:

+

proc p(s: string) {.extern: "prefix$1".} =
+  echo s

+

In the example, the external name of p is set to prefixp. Only $1 is available and a literal dollar sign must be written as $$.

+ +

Bycopy pragma

The bycopy pragma can be applied to an object or tuple type or a proc param. It instructs the compiler to pass the type by value to procs:

+

type
+  Vector {.bycopy.} = object
+    x, y, z: float

+

The Nim compiler automatically determines whether a parameter is passed by value or by reference based on the parameter type's size. If a parameter must be passed by value or by reference, (such as when interfacing with a C library) use the bycopy or byref pragmas. Notice params marked as byref takes precedence over types marked as bycopy.

+ +

Byref pragma

The byref pragma can be applied to an object or tuple type or a proc param. When applied to a type it instructs the compiler to pass the type by reference (hidden pointer) to procs. When applied to a param it will take precedence, even if the the type was marked as bycopy. When an importc type has a byref pragma or parameters are marked as byref in an importc proc, these params translate to pointers. When an importcpp type has a byref pragma, these params translate to C++ references &.

+

{.emit: """/*TYPESECTION*/
+typedef struct {
+  int x;
+} CStruct;
+""".}
+
+{.emit: """
+#ifdef __cplusplus
+extern "C"
+#endif
+int takesCStruct(CStruct* x) {
+  return x->x;
+}
+""".}
+
+type
+  CStruct {.importc, byref.} = object
+    x: cint
+
+proc takesCStruct(x: CStruct): cint {.importc.}

+

or

+

type
+  CStruct {.importc.} = object
+    x: cint
+
+proc takesCStruct(x {.byref.}: CStruct): cint {.importc.}

+

{.emit: """/*TYPESECTION*/
+struct CppStruct {
+  int x;
+  
+  int takesCppStruct(CppStruct& y) {
+    return x + y.x;
+  }
+};
+""".}
+
+type
+  CppStruct {.importcpp, byref.} = object
+    x: cint
+
+proc takesCppStruct(x, y: CppStruct): cint {.importcpp.}

+ +

Varargs pragma

The varargs pragma can be applied to procedures only (and procedure types). It tells Nim that the proc can take a variable number of parameters after the last specified parameter. Nim string values will be converted to C strings automatically:

+

proc printf(formatstr: cstring) {.header: "<stdio.h>", varargs.}
+
+printf("hallo %s", "world") # "world" will be passed as C string

+ +

Union pragma

The union pragma can be applied to any object type. It means all of an object's fields are overlaid in memory. This produces a union instead of a struct in the generated C/C++ code. The object declaration then must not use inheritance or any GC'ed memory but this is currently not checked.

+

Future directions: GC'ed memory should be allowed in unions and the GC should scan unions conservatively.

+ +

Packed pragma

The packed pragma can be applied to any object type. It ensures that the fields of an object are packed back-to-back in memory. It is useful to store packets or messages from/to network or hardware drivers, and for interoperability with C. Combining packed pragma with inheritance is not defined, and it should not be used with GC'ed memory (ref's).

+

Future directions: Using GC'ed memory in packed pragma will result in a static error. Usage with inheritance should be defined and documented.

+ +

Dynlib pragma for import

With the dynlib pragma, a procedure or a variable can be imported from a dynamic library (.dll files for Windows, lib*.so files for UNIX). The non-optional argument has to be the name of the dynamic library:

+

proc gtk_image_new(): PGtkWidget
+  {.cdecl, dynlib: "libgtk-x11-2.0.so", importc.}

+

In general, importing a dynamic library does not require any special linker options or linking with import libraries. This also implies that no devel packages need to be installed.

+

The dynlib import mechanism supports a versioning scheme:

+

proc Tcl_Eval(interp: pTcl_Interp, script: cstring): int {.cdecl,
+  importc, dynlib: "libtcl(|8.5|8.4|8.3).so.(1|0)".}

+

At runtime, the dynamic library is searched for (in this order):

+
libtcl.so.1
+libtcl.so.0
+libtcl8.5.so.1
+libtcl8.5.so.0
+libtcl8.4.so.1
+libtcl8.4.so.0
+libtcl8.3.so.1
+libtcl8.3.so.0
+

The dynlib pragma supports not only constant strings as an argument but also string expressions in general:

+

import std/os
+
+proc getDllName: string =
+  result = "mylib.dll"
+  if fileExists(result): return
+  result = "mylib2.dll"
+  if fileExists(result): return
+  quit("could not load dynamic library")
+
+proc myImport(s: cstring) {.cdecl, importc, dynlib: getDllName().}

+

Note: Patterns like libtcl(|8.5|8.4).so are only supported in constant strings, because they are precompiled.

+

Note: Passing variables to the dynlib pragma will fail at runtime because of order of initialization problems.

+

Note: A dynlib import can be overridden with the --dynlibOverride:name command-line option. The Compiler User Guide contains further information.

+ +

Dynlib pragma for export

With the dynlib pragma, a procedure can also be exported to a dynamic library. The pragma then has no argument and has to be used in conjunction with the exportc pragma:

+

proc exportme(): int {.cdecl, exportc, dynlib.}

+

This is only useful if the program is compiled as a dynamic library via the --app:lib command-line option.

+ +

Threads

The --threads:on command-line switch is enabled by default. The typedthreads module module then contains several threading primitives. See spawn for further details.

+

The only ways to create a thread is via spawn or createThread.

+ +

Thread pragma

A proc that is executed as a new thread of execution should be marked by the thread pragma for reasons of readability. The compiler checks for violations of the no heap sharing restriction: This restriction implies that it is invalid to construct a data structure that consists of memory allocated from different (thread-local) heaps.

+

A thread proc can be passed to createThread or spawn.

+ +

Threadvar pragma

A variable can be marked with the threadvar pragma, which makes it a thread-local variable; Additionally, this implies all the effects of the global pragma.

+

var checkpoints* {.threadvar.}: seq[string]

+

Due to implementation restrictions, thread-local variables cannot be initialized within the var section. (Every thread-local variable needs to be replicated at thread creation.)

+ +

Threads and exceptions

The interaction between threads and exceptions is simple: A handled exception in one thread cannot affect any other thread. However, an unhandled exception in one thread terminates the whole process.

+ +

Guards and locks

Nim provides common low level concurrency mechanisms like locks, atomic intrinsics or condition variables.

+

Nim significantly improves on the safety of these features via additional pragmas:

+
  1. A guard annotation is introduced to prevent data races.
  2. +
  3. Every access of a guarded memory location needs to happen in an appropriate locks statement.
  4. +
+ +

Guards and locks sections

+

Protecting global variables

Object fields and global variables can be annotated via a guard pragma:

+

import std/locks
+
+var glock: Lock
+var gdata {.guard: glock.}: int

+

The compiler then ensures that every access of gdata is within a locks section:

+

proc invalid =
+  # invalid: unguarded access:
+  echo gdata
+
+proc valid =
+  # valid access:
+  {.locks: [glock].}:
+    echo gdata

+

Top level accesses to gdata are always allowed so that it can be initialized conveniently. It is assumed (but not enforced) that every top level statement is executed before any concurrent action happens.

+

The locks section deliberately looks ugly because it has no runtime semantics and should not be used directly! It should only be used in templates that also implement some form of locking at runtime:

+

template lock(a: Lock; body: untyped) =
+  pthread_mutex_lock(a)
+  {.locks: [a].}:
+    try:
+      body
+    finally:
+      pthread_mutex_unlock(a)

+

The guard does not need to be of any particular type. It is flexible enough to model low level lockfree mechanisms:

+

var dummyLock {.compileTime.}: int
+var atomicCounter {.guard: dummyLock.}: int
+
+template atomicRead(x): untyped =
+  {.locks: [dummyLock].}:
+    memoryReadBarrier()
+    x
+
+echo atomicRead(atomicCounter)

+

The locks pragma takes a list of lock expressions locks: [a, b, ...] in order to support multi lock statements.

+ +

Protecting general locations

The guard annotation can also be used to protect fields within an object. The guard then needs to be another field within the same object or a global variable.

+

Since objects can reside on the heap or on the stack, this greatly enhances the expressiveness of the language:

+

import std/locks
+
+type
+  ProtectedCounter = object
+    v {.guard: L.}: int
+    L: Lock
+
+proc incCounters(counters: var openArray[ProtectedCounter]) =
+  for i in 0..counters.high:
+    lock counters[i].L:
+      inc counters[i].v

+

The access to field x.v is allowed since its guard x.L is active. After template expansion, this amounts to:

+

proc incCounters(counters: var openArray[ProtectedCounter]) =
+  for i in 0..counters.high:
+    pthread_mutex_lock(counters[i].L)
+    {.locks: [counters[i].L].}:
+      try:
+        inc counters[i].v
+      finally:
+        pthread_mutex_unlock(counters[i].L)

+

There is an analysis that checks that counters[i].L is the lock that corresponds to the protected location counters[i].v. This analysis is called path analysis because it deals with paths to locations like obj.field[i].fieldB[j].

+

The path analysis is currently unsound, but that doesn't make it useless. Two paths are considered equivalent if they are syntactically the same.

+

This means the following compiles (for now) even though it really should not:

+

{.locks: [a[i].L].}:
+  inc i
+  access a[i].v

+

+ +
+
+ + +
+
+ + + + diff --git a/manual.idx b/manual.idx new file mode 100644 index 0000000000000..0b21da0a629f2 --- /dev/null +++ b/manual.idx @@ -0,0 +1,459 @@ +markupTitle Nim Manual manual.html Nim Manual 0 +heading About this document manual.html#about-this-document About this document 0 +heading Definitions manual.html#definitions Definitions 0 +idx locations manual.html#locations_1 Definitions 0 +idx type manual.html#type_1 Definitions 0 +idx static type manual.html#static-type_1 Definitions 0 +idx dynamic type manual.html#dynamic-type_1 Definitions 0 +idx identifier manual.html#identifier_1 Definitions 0 +idx scope manual.html#scope_1 Definitions 0 +idx l-values manual.html#lminusvalues_1 Definitions 0 +idx program manual.html#program_1 Definitions 0 +idx source files manual.html#source-files_1 Definitions 0 +idx compiler manual.html#compiler_1 Definitions 0 +idx executable manual.html#executable_1 Definitions 0 +idx compile-time manual.html#compileminustime_1 Definitions 0 +idx runtime manual.html#runtime_1 Definitions 0 +idx abstract syntax tree manual.html#abstract-syntax-tree_1 Definitions 0 +idx AST manual.html#ast_1 Definitions 0 +idx semantic analysis manual.html#semantic-analysis_1 Definitions 0 +idx static error manual.html#static-error_1 Definitions 0 +idx panic manual.html#panic_1 Definitions 0 +idx runtime checks manual.html#runtime-checks_1 Definitions 0 +idx unchecked runtime error manual.html#unchecked-runtime-error_1 Definitions 0 +idx safe manual.html#safe_1 Definitions 0 +idx constant expression manual.html#constant-expression_1 Definitions 0 +heading Lexical Analysis manual.html#lexical-analysis Lexical Analysis 0 +heading Encoding manual.html#lexical-analysis-encoding Encoding 0 +heading Indentation manual.html#lexical-analysis-indentation Indentation 0 +idx indentation sensitive manual.html#indentation-sensitive_1 Indentation 0 +heading Comments manual.html#lexical-analysis-comments Comments 0 +idx comment pieces manual.html#comment-pieces_1 Comments 0 +idx Documentation comments manual.html#documentation-comments_1 Comments 0 +heading Multiline comments manual.html#lexical-analysis-multiline-comments Multiline comments 0 +heading Identifiers & Keywords manual.html#lexical-analysis-identifiers-amp-keywords Identifiers & Keywords 0 +heading Identifier equality manual.html#lexical-analysis-identifier-equality Identifier equality 0 +idx partial case-insensitivity manual.html#partial-caseminusinsensitivity_1 Identifier equality 0 +idx style-insensitive manual.html#styleminusinsensitive_1 Identifier equality 0 +heading Keywords as identifiers manual.html#lexical-analysis-keywords-as-identifiers Keywords as identifiers 0 +heading String literals manual.html#lexical-analysis-string-literals String literals 0 +idx escape sequences manual.html#escape-sequences_1 String literals 0 +idx carriage return manual.html#carriage-return_1 String literals 0 +idx line feed manual.html#line-feed_1 String literals 0 +idx newline manual.html#newline_1 String literals 0 +idx form feed manual.html#form-feed_1 String literals 0 +idx tabulator manual.html#tabulator_1 String literals 0 +idx vertical tabulator manual.html#vertical-tabulator_1 String literals 0 +idx backslash manual.html#backslash_1 String literals 0 +idx quotation mark manual.html#quotation-mark_1 String literals 0 +idx apostrophe manual.html#apostrophe_1 String literals 0 +idx character with decimal value d manual.html#character-with-decimal-value-d_1 String literals 0 +idx alert manual.html#alert_1 String literals 0 +idx backspace manual.html#backspace_1 String literals 0 +idx escape manual.html#escape_1 String literals 0 +idx [ESC] manual.html#esc_1 String literals 0 +idx character with hex value HH manual.html#character-with-hex-value-hh_1 String literals 0 +idx unicode codepoint with hex value HHHH manual.html#unicode-codepoint-with-hex-value-hhhh_1 String literals 0 +idx unicode codepoint manual.html#unicode-codepoint_1 String literals 0 +heading Triple quoted string literals manual.html#lexical-analysis-triple-quoted-string-literals Triple quoted string literals 0 +heading Raw string literals manual.html#lexical-analysis-raw-string-literals Raw string literals 0 +heading Generalized raw string literals manual.html#lexical-analysis-generalized-raw-string-literals Generalized raw string literals 0 +heading Character literals manual.html#lexical-analysis-character-literals Character literals 0 +idx newline manual.html#newline_2 Character literals 0 +idx escape sequences manual.html#escape-sequences_2 Character literals 0 +idx carriage return manual.html#carriage-return_2 Character literals 0 +idx line feed manual.html#line-feed_2 Character literals 0 +idx form feed manual.html#form-feed_2 Character literals 0 +idx tabulator manual.html#tabulator_2 Character literals 0 +idx vertical tabulator manual.html#vertical-tabulator_2 Character literals 0 +idx backslash manual.html#backslash_2 Character literals 0 +idx quotation mark manual.html#quotation-mark_2 Character literals 0 +idx apostrophe manual.html#apostrophe_2 Character literals 0 +idx character with decimal value d manual.html#character-with-decimal-value-d_2 Character literals 0 +idx alert manual.html#alert_2 Character literals 0 +idx backspace manual.html#backspace_2 Character literals 0 +idx escape manual.html#escape_2 Character literals 0 +idx [ESC] manual.html#esc_2 Character literals 0 +idx character with hex value HH manual.html#character-with-hex-value-hh_2 Character literals 0 +heading Numeric literals manual.html#lexical-analysis-numeric-literals Numeric literals 0 +idx type suffix manual.html#type-suffix_1 Numeric literals 0 +heading Custom numeric literals manual.html#numeric-literals-custom-numeric-literals Custom numeric literals 0 +heading Operators manual.html#lexical-analysis-operators Operators 0 +heading Unicode Operators manual.html#lexical-analysis-unicode-operators Unicode Operators 0 +heading Other tokens manual.html#lexical-analysis-other-tokens Other tokens 0 +idx slice manual.html#slice_1 Other tokens 0 +heading Syntax manual.html#syntax Syntax 0 +heading Associativity manual.html#syntax-associativity Associativity 0 +heading Precedence manual.html#syntax-precedence Precedence 0 +idx sigil-like manual.html#sigilminuslike_1 Precedence 0 +idx arrow like manual.html#arrow-like_1 Precedence 0 +heading Dot-like operators manual.html#syntax-dotminuslike-operators Dot-like operators 0 +heading Grammar manual.html#syntax-grammar Grammar 0 +heading Order of evaluation manual.html#order-of-evaluation Order of evaluation 0 +heading Constants and Constant Expressions manual.html#constants-and-constant-expressions Constants and Constant Expressions 0 +idx constant manual.html#constant_1 Constants and Constant Expressions 0 +heading Restrictions on Compile-Time Execution manual.html#restrictions-on-compileminustime-execution Restrictions on Compile-Time Execution 0 +heading Types manual.html#types Types 0 +heading Ordinal types manual.html#types-ordinal-types Ordinal types 0 +heading Pre-defined integer types manual.html#types-preminusdefined-integer-types Pre-defined integer types 0 +idx unsigned integer manual.html#unsigned-integer_1 Pre-defined integer types 0 +idx Automatic type conversion manual.html#automatic-type-conversion_1 Pre-defined integer types 0 +idx narrowing type conversion manual.html#narrowing-type-conversion_1 Pre-defined integer types 0 +idx widening type conversion manual.html#widening-type-conversion_1 Pre-defined integer types 0 +heading Subrange types manual.html#types-subrange-types Subrange types 0 +heading Pre-defined floating-point types manual.html#types-preminusdefined-floatingminuspoint-types Pre-defined floating-point types 0 +idx FloatInvalidOpDefect manual.html#floatinvalidopdefect_1 Pre-defined floating-point types 0 +idx FloatDivByZeroDefect manual.html#floatdivbyzerodefect_1 Pre-defined floating-point types 0 +idx FloatOverflowDefect manual.html#floatoverflowdefect_1 Pre-defined floating-point types 0 +idx FloatUnderflowDefect manual.html#floatunderflowdefect_1 Pre-defined floating-point types 0 +idx FloatInexactDefect manual.html#floatinexactdefect_1 Pre-defined floating-point types 0 +idx FloatingPointDefect manual.html#floatingpointdefect_1 Pre-defined floating-point types 0 +idx nanChecks manual.html#nanchecks_1 Pre-defined floating-point types 0 +idx infChecks manual.html#infchecks_1 Pre-defined floating-point types 0 +idx floatChecks manual.html#floatchecks_1 Pre-defined floating-point types 0 +heading Boolean type manual.html#types-boolean-type Boolean type 0 +idx bool manual.html#bool_1 Boolean type 0 +heading Character type manual.html#types-character-type Character type 0 +heading Enumeration types manual.html#types-enumeration-types Enumeration types 0 +heading String type manual.html#types-string-type String type 0 +heading cstring type manual.html#types-cstring-type cstring type 0 +heading Structured types manual.html#types-structured-types Structured types 0 +heading Array and sequence types manual.html#types-array-and-sequence-types Array and sequence types 0 +heading Open arrays manual.html#types-open-arrays Open arrays 0 +idx openarray manual.html#openarray_1 Open arrays 0 +heading Varargs manual.html#types-varargs Varargs 0 +heading Unchecked arrays manual.html#types-unchecked-arrays Unchecked arrays 0 +heading Tuples and object types manual.html#types-tuples-and-object-types Tuples and object types 0 +heading Object construction manual.html#types-object-construction Object construction 0 +idx object construction expression manual.html#object-construction-expression_1 Object construction 0 +heading Object variants manual.html#types-object-variants Object variants 0 +idx discriminator manual.html#discriminator_1 Object variants 0 +heading cast uncheckedAssign manual.html#types-cast-uncheckedassign cast uncheckedAssign 0 +heading Default values for object fields manual.html#types-default-values-for-object-fields Default values for object fields 0 +heading Set type manual.html#types-set-type Set type 0 +heading Bit fields manual.html#set-type-bit-fields Bit fields 0 +heading Reference and pointer types manual.html#types-reference-and-pointer-types Reference and pointer types 0 +idx aliasing manual.html#aliasing_1 Reference and pointer types 0 +idx traced manual.html#traced_1 Reference and pointer types 0 +idx untraced manual.html#untraced_1 Reference and pointer types 0 +heading Nil manual.html#types-nil Nil 0 +heading Mixing GC'ed memory with nimptr manual.html#types-mixing-gc-ed-memory-with-nimptr Mixing GC'ed memory with ptr 0 +heading Procedural type manual.html#types-procedural-type Procedural type 0 +idx calling conventions manual.html#calling-conventions_1 Procedural type 0 +idx nimcall manual.html#nimcall_1 Procedural type 0 +idx closure manual.html#closure_1 Procedural type 0 +idx stdcall manual.html#stdcall_1 Procedural type 0 +idx cdecl manual.html#cdecl_1 Procedural type 0 +idx safecall manual.html#safecall_1 Procedural type 0 +idx inline manual.html#inline_1 Procedural type 0 +idx noinline manual.html#noinline_1 Procedural type 0 +idx fastcall manual.html#fastcall_1 Procedural type 0 +idx thiscall manual.html#thiscall_1 Procedural type 0 +idx syscall manual.html#syscall_1 Procedural type 0 +idx noconv manual.html#noconv_1 Procedural type 0 +heading Distinct type manual.html#types-distinct-type Distinct type 0 +idx base type manual.html#base-type_1 Distinct type 0 +heading Modeling currencies manual.html#distinct-type-modeling-currencies Modeling currencies 0 +idx units manual.html#units_1 Modeling currencies 0 +idx borrow manual.html#borrow_1 Modeling currencies 0 +heading Avoiding SQL injection attacks manual.html#distinct-type-avoiding-sql-injection-attacks Avoiding SQL injection attacks 0 +idx SQL injection attack manual.html#sql-injection-attack_1 Avoiding SQL injection attacks 0 +heading Auto type manual.html#types-auto-type Auto type 0 +heading Type relations manual.html#type-relations Type relations 0 +heading Type equality manual.html#type-relations-type-equality Type equality 0 +heading Subtype relation manual.html#type-relations-subtype-relation Subtype relation 0 +heading Convertible relation manual.html#type-relations-convertible-relation Convertible relation 0 +idx converter manual.html#converter_1 Convertible relation 0 +heading Assignment compatibility manual.html#type-relations-assignment-compatibility Assignment compatibility 0 +heading Overload resolution manual.html#overload-resolution Overload resolution 0 +heading First Trial: Category matching manual.html#overload-resolution-first-trialcolon-category-matching First Trial: Category matching 0 +heading Second Trial: Hierarchical Order Comparison manual.html#overload-resolution-second-trialcolon-hierarchical-order-comparison Second Trial: Hierarchical Order Comparison 0 +heading Third Trial: Complexity Analysis manual.html#overload-resolution-third-trialcolon-complexity-analysis Third Trial: Complexity Analysis 0 +heading Some Examples manual.html#overload-resolution-some-examples Some Examples 0 +heading Type variables match manual.html#overload-resolution-type-variables-match Type variables match 0 +heading Overloading based on 'var T' manual.html#overload-resolution-overloading-based-on-var-t Overloading based on 'var T' 0 +idx l-value manual.html#lminusvalue_1 Overloading based on 'var T' 0 +heading Lazy type resolution for untyped manual.html#overload-resolution-lazy-type-resolution-for-untyped Lazy type resolution for untyped 0 +idx unresolved manual.html#unresolved_1 Lazy type resolution for untyped 0 +heading Varargs matching manual.html#overload-resolution-varargs-matching Varargs matching 0 +heading iterable manual.html#overload-resolution-iterable iterable 0 +heading Overload disambiguation manual.html#overload-disambiguation Overload disambiguation 0 +heading Named argument overloading manual.html#overload-disambiguation-named-argument-overloading Named argument overloading 0 +heading Statements and expressions manual.html#statements-and-expressions Statements and expressions 0 +idx simple statements manual.html#simple-statements_1 Statements and expressions 0 +idx complex statements manual.html#complex-statements_1 Statements and expressions 0 +idx dangling else problem manual.html#dangling-else-problem_1 Statements and expressions 0 +heading Statement list expression manual.html#statements-and-expressions-statement-list-expression Statement list expression 0 +heading Discard statement manual.html#statements-and-expressions-discard-statement Discard statement 0 +idx discardable manual.html#discardable_1 Discard statement 0 +heading Void context manual.html#statements-and-expressions-void-context Void context 0 +heading Var statement manual.html#statements-and-expressions-var-statement Var statement 0 +idx noinit manual.html#noinit_1 Var statement 0 +idx requiresInit manual.html#requiresinit_1 Var statement 0 +idx control flow analysis manual.html#control-flow-analysis_1 Var statement 0 +heading Let statement manual.html#statements-and-expressions-let-statement Let statement 0 +idx single assignment manual.html#single-assignment_1 Let statement 0 +heading Special identifier nim_ (underscore) manual.html#statements-and-expressions-special-identifier-nim-underscore Special identifier _ (underscore) 0 +heading Tuple unpacking manual.html#statements-and-expressions-tuple-unpacking Tuple unpacking 0 +heading Const section manual.html#statements-and-expressions-const-section Const section 0 +heading Static statement/expression manual.html#statements-and-expressions-static-statementslashexpression Static statement/expression 0 +heading If statement manual.html#statements-and-expressions-if-statement If statement 0 +heading Case statement manual.html#statements-and-expressions-case-statement Case statement 0 +heading When statement manual.html#statements-and-expressions-when-statement When statement 0 +heading When nimvm statement manual.html#statements-and-expressions-when-nimvm-statement When nimvm statement 0 +heading Return statement manual.html#statements-and-expressions-return-statement Return statement 0 +idx result manual.html#result_1 Return statement 0 +heading Yield statement manual.html#statements-and-expressions-yield-statement Yield statement 0 +heading Block statement manual.html#statements-and-expressions-block-statement Block statement 0 +heading Break statement manual.html#statements-and-expressions-break-statement Break statement 0 +heading While statement manual.html#statements-and-expressions-while-statement While statement 0 +heading Continue statement manual.html#statements-and-expressions-continue-statement Continue statement 0 +heading Assembler statement manual.html#statements-and-expressions-assembler-statement Assembler statement 0 +heading Using statement manual.html#statements-and-expressions-using-statement Using statement 0 +heading If expression manual.html#statements-and-expressions-if-expression If expression 0 +heading When expression manual.html#statements-and-expressions-when-expression When expression 0 +heading Case expression manual.html#statements-and-expressions-case-expression Case expression 0 +heading Block expression manual.html#statements-and-expressions-block-expression Block expression 0 +heading Table constructor manual.html#statements-and-expressions-table-constructor Table constructor 0 +heading Type conversions manual.html#statements-and-expressions-type-conversions Type conversions 0 +heading Type casts manual.html#statements-and-expressions-type-casts Type casts 0 +heading The addr operator manual.html#statements-and-expressions-the-addr-operator The addr operator 0 +heading The unsafeAddr operator manual.html#statements-and-expressions-the-unsafeaddr-operator The unsafeAddr operator 0 +heading Procedures manual.html#procedures Procedures 0 +idx methods manual.html#methods_1 Procedures 0 +idx functions manual.html#functions_1 Procedures 0 +idx procedures manual.html#procedures_1 Procedures 0 +idx forward manual.html#forward_1 Procedures 0 +idx result manual.html#result_2 Procedures 0 +idx Operators manual.html#operators_1 Procedures 0 +heading Export marker manual.html#procedures-export-marker Export marker 0 +idx asterisk manual.html#asterisk_1 Export marker 0 +heading Method call syntax manual.html#procedures-method-call-syntax Method call syntax 0 +heading Properties manual.html#procedures-properties Properties 0 +idx setter manual.html#setter_1 Properties 0 +heading Command invocation syntax manual.html#procedures-command-invocation-syntax Command invocation syntax 0 +heading Closures manual.html#procedures-closures Closures 0 +heading Creating closures in loops manual.html#closures-creating-closures-in-loops Creating closures in loops 0 +heading Anonymous procedures manual.html#procedures-anonymous-procedures Anonymous procedures 0 +heading Do notation manual.html#procedures-do-notation Do notation 0 +heading Func manual.html#procedures-func Func 0 +idx noSideEffect manual.html#nosideeffect_1 Func 0 +heading Routines manual.html#procedures-routines Routines 0 +heading Type bound operators manual.html#procedures-type-bound-operators Type bound operators 0 +heading Nonoverloadable builtins manual.html#procedures-nonoverloadable-builtins Nonoverloadable builtins 0 +idx shadow manual.html#shadow_1 Nonoverloadable builtins 0 +heading Var parameters manual.html#procedures-var-parameters Var parameters 0 +idx tuple unpacking manual.html#tuple-unpacking_1 Var parameters 0 +heading Var return type manual.html#procedures-var-return-type Var return type 0 +heading Future directions manual.html#var-return-type-future-directions Future directions 0 +heading NRVO manual.html#procedures-nrvo NRVO 0 +idx result manual.html#result_3 NRVO 0 +idx NRVO manual.html#nrvo_1 NRVO 0 +heading Overloading of the subscript operator manual.html#procedures-overloading-of-the-subscript-operator Overloading of the subscript operator 0 +heading Methods manual.html#methods Methods 0 +idx base manual.html#base_1 Methods 0 +heading Multi-methods manual.html#methods-multiminusmethods Multi-methods 0 +heading Inhibit dynamic method resolution via procCall manual.html#methods-inhibit-dynamic-method-resolution-via-proccall Inhibit dynamic method resolution via procCall 0 +idx system.procCall manual.html#systemdotproccall_1 Inhibit dynamic method resolution via procCall 0 +idx super manual.html#super_1 Inhibit dynamic method resolution via procCall 0 +heading Iterators and the for statement manual.html#iterators-and-the-for-statement Iterators and the for statement 0 +idx for manual.html#for_1 Iterators and the for statement 0 +idx iterator manual.html#iterator_1 Iterators and the for statement 0 +idx implicit block manual.html#implicit-block_1 Iterators and the for statement 0 +heading Implicit items/pairs invocations manual.html#iterators-and-the-for-statement-implicit-itemsslashpairs-invocations Implicit items/pairs invocations 0 +heading First-class iterators manual.html#iterators-and-the-for-statement-firstminusclass-iterators First-class iterators 0 +idx inline iterator manual.html#inline-iterator_1 First-class iterators 0 +idx closure iterator manual.html#closure-iterator_1 First-class iterators 0 +idx collaborative tasking manual.html#collaborative-tasking_1 First-class iterators 0 +heading Converters manual.html#converters Converters 0 +heading Type sections manual.html#type-sections Type sections 0 +heading Exception handling manual.html#exception-handling Exception handling 0 +heading Try statement manual.html#exception-handling-try-statement Try statement 0 +idx exception handlers manual.html#exception-handlers_1 Try statement 0 +idx finally manual.html#finally_1 Try statement 0 +heading Try expression manual.html#exception-handling-try-expression Try expression 0 +heading Except clauses manual.html#exception-handling-except-clauses Except clauses 0 +heading Custom exceptions manual.html#exception-handling-custom-exceptions Custom exceptions 0 +heading Defer statement manual.html#exception-handling-defer-statement Defer statement 0 +heading Raise statement manual.html#exception-handling-raise-statement Raise statement 0 +idx re-raised manual.html#reminusraised_1 Raise statement 0 +idx ReraiseDefect manual.html#reraisedefect_1 Raise statement 0 +heading Exception hierarchy manual.html#exception-handling-exception-hierarchy Exception hierarchy 0 +heading Imported exceptions manual.html#exception-handling-imported-exceptions Imported exceptions 0 +heading Effect system manual.html#effect-system Effect system 0 +heading Exception tracking manual.html#effect-system-exception-tracking Exception tracking 0 +idx raises manual.html#raises_1 Exception tracking 0 +heading EffectsOf annotation manual.html#effect-system-effectsof-annotation EffectsOf annotation 0 +heading Tag tracking manual.html#effect-system-tag-tracking Tag tracking 0 +idx effect system manual.html#effect-system_1 Tag tracking 0 +heading Side effects manual.html#effect-system-side-effects Side effects 0 +heading GC safety effect manual.html#effect-system-gc-safety-effect GC safety effect 0 +idx GC safe manual.html#gc-safe_1 GC safety effect 0 +idx gcsafe manual.html#gcsafe_1 GC safety effect 0 +heading Effects pragma manual.html#effect-system-effects-pragma Effects pragma 0 +heading Generics manual.html#generics Generics 0 +idx type parameters manual.html#type-parameters_1 Generics 0 +idx generic type parameter manual.html#generic-type-parameter_1 Generics 0 +idx type variable manual.html#type-variable_1 Generics 0 +heading Generic Procs manual.html#generics-generic-procs Generic Procs 0 +heading Is operator manual.html#generics-is-operator Is operator 0 +heading Type classes manual.html#generics-type-classes Type classes 0 +idx type constraints manual.html#type-constraints_1 Type classes 0 +heading Implicit generics manual.html#generics-implicit-generics Implicit generics 0 +idx implicitly generic manual.html#implicitly-generic_1 Implicit generics 0 +idx bind once manual.html#bind-once_1 Implicit generics 0 +idx bind many manual.html#bind-many_1 Implicit generics 0 +heading Generic inference restrictions manual.html#generics-generic-inference-restrictions Generic inference restrictions 0 +heading Symbol lookup in generics manual.html#generics-symbol-lookup-in-generics Symbol lookup in generics 0 +heading Open and Closed symbols manual.html#symbol-lookup-in-generics-open-and-closed-symbols Open and Closed symbols 0 +heading Mixin statement manual.html#generics-mixin-statement Mixin statement 0 +idx mixin manual.html#mixin_1 Mixin statement 0 +heading Bind statement manual.html#generics-bind-statement Bind statement 0 +heading Delegating bind statements manual.html#generics-delegating-bind-statements Delegating bind statements 0 +idx forward manual.html#forward_2 Delegating bind statements 0 +heading Templates manual.html#templates Templates 0 +heading Typed vs untyped parameters manual.html#templates-typed-vs-untyped-parameters Typed vs untyped parameters 0 +idx immediate manual.html#immediate_1 Typed vs untyped parameters 0 +heading Passing a code block to a template manual.html#templates-passing-a-code-block-to-a-template Passing a code block to a template 0 +heading Varargs of untyped manual.html#templates-varargs-of-untyped Varargs of untyped 0 +heading Symbol binding in templates manual.html#templates-symbol-binding-in-templates Symbol binding in templates 0 +idx hygienic manual.html#hygienic_1 Symbol binding in templates 0 +heading Identifier construction manual.html#templates-identifier-construction Identifier construction 0 +heading Lookup rules for template parameters manual.html#templates-lookup-rules-for-template-parameters Lookup rules for template parameters 0 +heading Hygiene in templates manual.html#templates-hygiene-in-templates Hygiene in templates 0 +idx hygienic manual.html#hygienic_2 Hygiene in templates 0 +idx inject manual.html#inject_1 Hygiene in templates 0 +idx gensym manual.html#gensym_1 Hygiene in templates 0 +idx dirty manual.html#dirty_1 Hygiene in templates 0 +heading Limitations of the method call syntax manual.html#templates-limitations-of-the-method-call-syntax Limitations of the method call syntax 0 +heading Macros manual.html#macros Macros 0 +idx domain-specific languages manual.html#domainminusspecific-languages_1 Macros 0 +heading Debug example manual.html#macros-debug-example Debug example 0 +heading bindSym manual.html#macros-bindsym bindSym 0 +idx symbols manual.html#symbols_1 bindSym 0 +heading Post-statement blocks manual.html#macros-postminusstatement-blocks Post-statement blocks 0 +heading For loop macro manual.html#macros-for-loop-macro For loop macro 0 +heading Case statement macros manual.html#macros-case-statement-macros Case statement macros 0 +heading Special Types manual.html#special-types Special Types 0 +heading static[T] manual.html#special-types-static-t static[T] 0 +heading typedesc[T] manual.html#special-types-typedesc-t typedesc[T] 0 +heading typeof operator manual.html#special-types-typeof-operator typeof operator 0 +idx typeof manual.html#typeof_1 typeof operator 0 +heading Modules manual.html#modules Modules 0 +idx namespace manual.html#namespace_1 Modules 0 +idx information hiding manual.html#information-hiding_1 Modules 0 +idx separate compilation manual.html#separate-compilation_1 Modules 0 +idx import manual.html#import_1 Modules 0 +idx Recursive module dependencies manual.html#recursive-module-dependencies_1 Modules 0 +heading Import statement manual.html#modules-import-statement Import statement 0 +heading Include statement manual.html#modules-include-statement Include statement 0 +heading Module names in imports manual.html#modules-module-names-in-imports Module names in imports 0 +heading Collective imports from a directory manual.html#modules-collective-imports-from-a-directory Collective imports from a directory 0 +heading Pseudo import/include paths manual.html#modules-pseudo-importslashinclude-paths Pseudo import/include paths 0 +heading From import statement manual.html#modules-from-import-statement From import statement 0 +heading Export statement manual.html#modules-export-statement Export statement 0 +heading Scope rules manual.html#modules-scope-rules Scope rules 0 +heading Block scope manual.html#scope-rules-block-scope Block scope 0 +heading Tuple or object scope manual.html#scope-rules-tuple-or-object-scope Tuple or object scope 0 +heading Module scope manual.html#scope-rules-module-scope Module scope 0 +idx system manual.html#system_1 Module scope 0 +heading Packages manual.html#modules-packages Packages 0 +heading Compiler Messages manual.html#compiler-messages Compiler Messages 0 +idx hint manual.html#hint_1 Compiler Messages 0 +idx warning manual.html#warning_1 Compiler Messages 0 +idx error manual.html#error_1 Compiler Messages 0 +heading Pragmas manual.html#pragmas Pragmas 0 +heading deprecated pragma manual.html#pragmas-deprecated-pragma deprecated pragma 0 +heading compileTime pragma manual.html#pragmas-compiletime-pragma compileTime pragma 0 +heading noreturn pragma manual.html#pragmas-noreturn-pragma noreturn pragma 0 +heading acyclic pragma manual.html#pragmas-acyclic-pragma acyclic pragma 0 +heading final pragma manual.html#pragmas-final-pragma final pragma 0 +heading shallow pragma manual.html#pragmas-shallow-pragma shallow pragma 0 +heading pure pragma manual.html#pragmas-pure-pragma pure pragma 0 +heading asmNoStackFrame pragma manual.html#pragmas-asmnostackframe-pragma asmNoStackFrame pragma 0 +heading error pragma manual.html#pragmas-error-pragma error pragma 0 +heading fatal pragma manual.html#pragmas-fatal-pragma fatal pragma 0 +heading warning pragma manual.html#pragmas-warning-pragma warning pragma 0 +heading hint pragma manual.html#pragmas-hint-pragma hint pragma 0 +heading line pragma manual.html#pragmas-line-pragma line pragma 0 +heading linearScanEnd pragma manual.html#pragmas-linearscanend-pragma linearScanEnd pragma 0 +idx case manual.html#case_1 linearScanEnd pragma 0 +heading computedGoto pragma manual.html#pragmas-computedgoto-pragma computedGoto pragma 0 +idx case manual.html#case_2 computedGoto pragma 0 +heading immediate pragma manual.html#pragmas-immediate-pragma immediate pragma 0 +heading redefine pragma manual.html#pragmas-redefine-pragma redefine pragma 0 +heading compilation option pragmas manual.html#pragmas-compilation-option-pragmas compilation option pragmas 0 +heading push and pop pragmas manual.html#pragmas-push-and-pop-pragmas push and pop pragmas 0 +idx push/pop manual.html#pushslashpop_1 push and pop pragmas 0 +idx push/pop manual.html#pushslashpop_2 push and pop pragmas 0 +heading register pragma manual.html#pragmas-register-pragma register pragma 0 +heading global pragma manual.html#pragmas-global-pragma global pragma 0 +heading Disabling certain messages manual.html#pragmas-disabling-certain-messages Disabling certain messages 0 +heading used pragma manual.html#pragmas-used-pragma used pragma 0 +heading experimental pragma manual.html#pragmas-experimental-pragma experimental pragma 0 +heading Implementation Specific Pragmas manual.html#implementation-specific-pragmas Implementation Specific Pragmas 0 +heading Bitsize pragma manual.html#implementation-specific-pragmas-bitsize-pragma Bitsize pragma 0 +heading size pragma manual.html#implementation-specific-pragmas-size-pragma size pragma 0 +heading Align pragma manual.html#implementation-specific-pragmas-align-pragma Align pragma 0 +idx align manual.html#align_1 Align pragma 0 +heading Noalias pragma manual.html#implementation-specific-pragmas-noalias-pragma Noalias pragma 0 +heading Volatile pragma manual.html#implementation-specific-pragmas-volatile-pragma Volatile pragma 0 +heading nodecl pragma manual.html#implementation-specific-pragmas-nodecl-pragma nodecl pragma 0 +heading Header pragma manual.html#implementation-specific-pragmas-header-pragma Header pragma 0 +heading IncompleteStruct pragma manual.html#implementation-specific-pragmas-incompletestruct-pragma IncompleteStruct pragma 0 +heading Compile pragma manual.html#implementation-specific-pragmas-compile-pragma Compile pragma 0 +heading Link pragma manual.html#implementation-specific-pragmas-link-pragma Link pragma 0 +heading passc pragma manual.html#implementation-specific-pragmas-passc-pragma passc pragma 0 +heading localPassC pragma manual.html#implementation-specific-pragmas-localpassc-pragma localPassC pragma 0 +heading passl pragma manual.html#implementation-specific-pragmas-passl-pragma passl pragma 0 +heading Emit pragma manual.html#implementation-specific-pragmas-emit-pragma Emit pragma 0 +idx C++ manual.html#cplusplus_1 Emit pragma 0 +idx Objective C manual.html#objective-c_1 Emit pragma 0 +heading ImportCpp pragma manual.html#implementation-specific-pragmas-importcpp-pragma ImportCpp pragma 0 +idx C++ manual.html#cplusplus_2 ImportCpp pragma 0 +heading Namespaces manual.html#importcpp-pragma-namespaces Namespaces 0 +heading Importcpp for enums manual.html#importcpp-pragma-importcpp-for-enums Importcpp for enums 0 +heading Importcpp for procs manual.html#importcpp-pragma-importcpp-for-procs Importcpp for procs 0 +heading Wrapping constructors manual.html#importcpp-pragma-wrapping-constructors Wrapping constructors 0 +idx constructor manual.html#constructor_1 Wrapping constructors 0 +heading Wrapping destructors manual.html#importcpp-pragma-wrapping-destructors Wrapping destructors 0 +heading Importcpp for objects manual.html#importcpp-pragma-importcpp-for-objects Importcpp for objects 0 +heading ImportJs pragma manual.html#implementation-specific-pragmas-importjs-pragma ImportJs pragma 0 +heading ImportObjC pragma manual.html#implementation-specific-pragmas-importobjc-pragma ImportObjC pragma 0 +idx Objective C manual.html#objective-c_2 ImportObjC pragma 0 +heading CodegenDecl pragma manual.html#implementation-specific-pragmas-codegendecl-pragma CodegenDecl pragma 0 +heading nimcppNonPod pragma manual.html#implementation-specific-pragmas-nimcppnonpod-pragma cppNonPod pragma 0 +heading compile-time define pragmas manual.html#implementation-specific-pragmas-compileminustime-define-pragmas compile-time define pragmas 0 +idx intdefine manual.html#intdefine_1 compile-time define pragmas 0 +idx strdefine manual.html#strdefine_1 compile-time define pragmas 0 +idx booldefine manual.html#booldefine_1 compile-time define pragmas 0 +heading User-defined pragmas manual.html#userminusdefined-pragmas User-defined pragmas 0 +heading pragma pragma manual.html#userminusdefined-pragmas-pragma-pragma pragma pragma 0 +heading Custom annotations manual.html#userminusdefined-pragmas-custom-annotations Custom annotations 0 +heading Macro pragmas manual.html#userminusdefined-pragmas-macro-pragmas Macro pragmas 0 +heading Foreign function interface manual.html#foreign-function-interface Foreign function interface 0 +idx FFI manual.html#ffi_1 Foreign function interface 0 +heading Importc pragma manual.html#foreign-function-interface-importc-pragma Importc pragma 0 +heading Exportc pragma manual.html#foreign-function-interface-exportc-pragma Exportc pragma 0 +heading Exportcpp pragma manual.html#foreign-function-interface-exportcpp-pragma Exportcpp pragma 0 +heading Extern pragma manual.html#foreign-function-interface-extern-pragma Extern pragma 0 +heading Bycopy pragma manual.html#foreign-function-interface-bycopy-pragma Bycopy pragma 0 +heading Byref pragma manual.html#foreign-function-interface-byref-pragma Byref pragma 0 +heading Varargs pragma manual.html#foreign-function-interface-varargs-pragma Varargs pragma 0 +heading Union pragma manual.html#foreign-function-interface-union-pragma Union pragma 0 +heading Packed pragma manual.html#foreign-function-interface-packed-pragma Packed pragma 0 +heading Dynlib pragma for import manual.html#foreign-function-interface-dynlib-pragma-for-import Dynlib pragma for import 0 +heading Dynlib pragma for export manual.html#foreign-function-interface-dynlib-pragma-for-export Dynlib pragma for export 0 +heading Threads manual.html#threads Threads 0 +heading Thread pragma manual.html#threads-thread-pragma Thread pragma 0 +idx no heap sharing restriction manual.html#no-heap-sharing-restriction_1 Thread pragma 0 +heading Threadvar pragma manual.html#threads-threadvar-pragma Threadvar pragma 0 +idx thread-local manual.html#threadminuslocal_1 Threadvar pragma 0 +heading Threads and exceptions manual.html#threads-threads-and-exceptions Threads and exceptions 0 +heading Guards and locks manual.html#guards-and-locks Guards and locks 0 +idx guard manual.html#guard_1 Guards and locks 0 +idx locks manual.html#locks_1 Guards and locks 0 +heading Guards and locks sections manual.html#guards-and-locks-guards-and-locks-sections Guards and locks sections 0 +heading Protecting global variables manual.html#guards-and-locks-sections-protecting-global-variables Protecting global variables 0 +heading Protecting general locations manual.html#guards-and-locks-sections-protecting-general-locations Protecting general locations 0 +idx path analysis manual.html#path-analysis_1 Protecting general locations 0 diff --git a/manual_experimental.html b/manual_experimental.html new file mode 100644 index 0000000000000..e5def5690e268 --- /dev/null +++ b/manual_experimental.html @@ -0,0 +1,1738 @@ + + + + + + + +Nim Experimental Features + + + + + + + + + + + + + + + + +
+
+

Nim Experimental Features

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + + +
+
+ Source   +Edit   + +
+ +

+ +
Authors:Andreas Rumpf
Version:2.2.1
+

About this document

This document describes features of Nim that are to be considered experimental. Some of these are not covered by the .experimental pragma or --experimental switch because they are already behind a special syntax and one may want to use Nim libraries using these features without using them oneself.

+
Note: +Unless otherwise indicated, these features are not to be removed, but refined and overhauled.
+ +

Void type

The void type denotes the absence of any value, i.e. it is the type that contains no values. Consequently, no value can be provided for parameters of type void, and no value can be returned from a function with return type void:

+

proc nothing(x, y: void): void =
+  echo "ha"
+
+nothing() # writes "ha" to stdout

+

The void type is particularly useful for generic code:

+

proc callProc[T](p: proc (x: T), x: T) =
+  when T is void:
+    p()
+  else:
+    p(x)
+
+proc intProc(x: int) = discard
+proc emptyProc() = discard
+
+callProc[int](intProc, 12)
+callProc[void](emptyProc)

+

However, a void type cannot be inferred in generic code:

+

callProc(emptyProc)
+# Error: type mismatch: got (proc ())
+# but expected one of:
+# callProc(p: proc (T), x: T)

+

The void type is only valid for parameters and return types; other symbols cannot have the type void.

+ +

Generic define pragma

Aside the typed define pragmas for constants, there is a generic {.define.} pragma that interprets the value of the define based on the type of the constant value.

+

const foo {.define: "package.foo".} = 123
+const bar {.define: "package.bar".} = false

+

nim c -d:package.foo=456 -d:package.bar foobar.nim

+

The following types are supported:

+
  • string and cstring
  • +
  • Signed and unsigned integer types
  • +
  • bool
  • +
  • Enums
  • +
+ +

Top-down type inference

In expressions such as:

+

let a: T = ex

+

Normally, the compiler type checks the expression ex by itself, then attempts to statically convert the type-checked expression to the given type T as much as it can, while making sure it matches the type. The extent of this process is limited however due to the expression usually having an assumed type that might clash with the given type.

+

With top-down type inference, the expression is type checked with the extra knowledge that it is supposed to be of type T. For example, the following code is does not compile with the former method, but compiles with top-down type inference:

+

let foo: (float, uint8, cstring) = (1, 2, "abc")

+

The tuple expression has an expected type of (float, uint8, cstring). Since it is a tuple literal, we can use this information to assume the types of its elements. The expected types for the expressions 1, 2 and "abc" are respectively float, uint8, and cstring; and these expressions can be statically converted to these types.

+

Without this information, the type of the tuple expression would have been assumed to be (int, int, string). Thus the type of the tuple expression would not match the type of the variable, and an error would be given.

+

The extent of this varies, but there are some notable special cases.

+ +

Inferred generic parameters

In expressions making use of generic procs or templates, the expected (unbound) types are often able to be inferred based on context. This feature has to be enabled via {.experimental: "inferGenericTypes".}

+

{.experimental: "inferGenericTypes".}
+
+import std/options
+
+var x = newSeq[int](1)
+# Do some work on 'x'...
+
+# Works!
+# 'x' is 'seq[int]' so 'newSeq[int]' is implied
+x = newSeq(10)
+
+# Works!
+# 'T' of 'none' is bound to the 'T' of 'noneProducer', passing it along.
+# Effectively 'none.T = noneProducer.T'
+proc noneProducer[T](): Option[T] = none()
+let myNone = noneProducer[int]()
+
+# Also works
+# 'myOtherNone' binds its 'T' to 'float' and 'noneProducer' inherits it
+# noneProducer.T = myOtherNone.T
+let myOtherNone: Option[float] = noneProducer()
+
+# Works as well
+# none.T = myOtherOtherNone.T
+let myOtherOtherNone: Option[int] = none()

+

This is achieved by reducing the types on the lhs and rhs until the lhs is left with only types such as T. While lhs and rhs are reduced together, this does not mean that the rhs will also only be left with a flat type Z, it may be of the form MyType[Z].

+

After the types have been reduced, the types T are bound to the types that are left on the rhs.

+

If bindings cannot be inferred, compilation will fail and manual specification is required.

+

An example for failing inference can be found when passing a generic expression to a function/template call:

+

{.experimental: "inferGenericTypes".}
+
+proc myProc[T](a, b: T) = discard
+
+# Fails! Unable to infer that 'T' is supposed to be 'int'
+myProc(newSeq[int](), newSeq(1))
+
+# Works! Manual specification of 'T' as 'int' necessary
+myProc(newSeq[int](), newSeq[int](1))

+

Combination of generic inference with the auto type is also unsupported:

+

{.experimental: "inferGenericTypes".}
+
+proc produceValue[T]: auto = default(T)
+let a: int = produceValue() # 'auto' cannot be inferred here

+

Note: The described inference does not permit the creation of overrides based on the return type of a procedure. It is a mapping mechanism that does not attempt to perform deeper inference, nor does it modify what is a valid override.

+

# Doesn't affect the following code, it is invalid either way
+{.experimental: "inferGenericTypes".}
+
+proc a: int = 0
+proc a: float = 1.0 # Fails! Invalid code and not recommended

+ +

Sequence literals

Top-down type inference applies to sequence literals.

+

let x: seq[seq[float]] = @[@[1, 2, 3], @[4, 5, 6]]

+

This behavior is tied to the @ overloads in the system module, so overloading @ can disable this behavior. This can be circumvented by specifying the `` system.@ `` overload.

+

proc `@`(x: string): string = "@" & x
+
+# does not compile:
+let x: seq[float] = @[1, 2, 3]
+# compiles:
+let x: seq[float] = system.`@`([1, 2, 3])

+ +

Package level objects

Every Nim module resides in a (nimble) package. An object type can be attached to the package it resides in. If that is done, the type can be referenced from other modules as an incomplete object type. This feature allows to break up recursive type dependencies across module boundaries. Incomplete object types are always passed byref and can only be used in pointer like contexts (var/ref/ptr IncompleteObject) in general, since the compiler does not yet know the size of the object. To complete an incomplete object, the package pragma has to be used. package implies byref.

+

As long as a type T is incomplete, no runtime type information for T is available.

+

Example:

+

# module A (in an arbitrary package)
+type
+  Pack.SomeObject = object # declare as incomplete object of package 'Pack'
+  Triple = object
+    a, b, c: ref SomeObject # pointers to incomplete objects are allowed
+
+# Incomplete objects can be used as parameters:
+proc myproc(x: SomeObject) = discard

+

# module B (in package "Pack")
+type
+  SomeObject* {.package.} = object # Use 'package' to complete the object
+    s, t: string
+    x, y: int

+

This feature will likely be superseded in the future by support for recursive module dependencies.

+ +

Importing private symbols

In some situations, it may be useful to import all symbols (public or private) from a module. The syntax import foo {.all.} can be used to import all symbols from the module foo. Note that importing private symbols is generally not recommended.

+

See also the experimental importutils module.

+ +

Code reordering

The code reordering feature can implicitly rearrange procedure, template, and macro definitions along with variable declarations and initializations at the top level scope so that, to a large extent, a programmer should not have to worry about ordering definitions correctly or be forced to use forward declarations to preface definitions inside a module.

+

Example:

+

{.experimental: "codeReordering".}
+
+proc foo(x: int) =
+  bar(x)
+
+proc bar(x: int) =
+  echo(x)
+
+foo(10)

+

Variables can also be reordered as well. Variables that are initialized (i.e. variables that have their declaration and assignment combined in a single statement) can have their entire initialization statement reordered. Be wary of what code is executed at the top level:

+

{.experimental: "codeReordering".}
+
+proc a() =
+  echo(foo)
+
+var foo = 5
+
+a() # outputs: "5"

+

It is important to note that reordering only works for symbols at top level scope. Therefore, the following will fail to compile:

+

{.experimental: "codeReordering".}
+
+proc a() =
+  b()
+  proc b() =
+    echo("Hello!")
+
+a()

+

This feature will likely be replaced with a better solution to remove the need for forward declarations.

+ +

Special Operators

+

dot operators

Note: +Dot operators are still experimental and so need to be enabled via {.experimental: "dotOperators".}.
+

Nim offers a special family of dot operators that can be used to intercept and rewrite proc call and field access attempts, referring to previously undeclared symbol names. They can be used to provide a fluent interface to objects lying outside the static confines of the type system such as values from dynamic scripting languages or dynamic file formats such as JSON or XML.

+

When Nim encounters an expression that cannot be resolved by the standard overload resolution rules, the current scope will be searched for a dot operator that can be matched against a re-written form of the expression, where the unknown field or proc name is passed to an untyped parameter:

+

a.b # becomes `.`(a, b)
+a.b(c, d) # becomes `.`(a, b, c, d)

+

The matched dot operators can be symbols of any callable kind (procs, templates and macros), depending on the desired effect:

+

template `.`(js: PJsonNode, field: untyped): JSON = js[astToStr(field)]
+
+var js = parseJson("{ x: 1, y: 2}")
+echo js.x # outputs 1
+echo js.y # outputs 2

+

The following dot operators are available:

+ +

operator .

This operator will be matched against both field accesses and method calls.

+ +

operator .()

This operator will be matched exclusively against method calls. It has higher precedence than the . operator and this allows one to handle expressions like x.y and x.y() differently if one is interfacing with a scripting language for example.

+ +

operator .=

This operator will be matched against assignments to missing fields.

+

a.b = c # becomes `.=`(a, b, c)

+ +

Call operator

The call operator, (), matches all kinds of unresolved calls and takes precedence over dot operators, however it does not match missing overloads for existing routines. The experimental callOperator switch must be enabled to use this operator.

+

{.experimental: "callOperator".}
+
+template `()`(a: int, b: float): untyped = $(a, b)
+
+block:
+  let a = 1.0
+  let b = 2
+  doAssert b(a) == `()`(b, a)
+  doAssert a.b == `()`(b, a)
+
+block:
+  let a = 1.0
+  proc b(): int = 2
+  doAssert not compiles(b(a))
+  doAssert not compiles(a.b) # `()` not called
+
+block:
+  let a = 1.0
+  proc b(x: float): int = int(x + 1)
+  let c = 3.0
+  
+  doAssert not compiles(a.b(c)) # gives a type mismatch error same as b(a, c)
+  doAssert (a.b)(c) == `()`(a.b, c)

+ +

Extended macro pragmas

Macro pragmas as described in the manual can also be applied to type, variable and constant declarations.

+

For types:

+

type
+  MyObject {.schema: "schema.protobuf".} = object

+

This is translated to a call to the schema macro with a nnkTypeDef AST node capturing the left-hand side, remaining pragmas and the right-hand side of the definition. The macro can return either a type section or another nnkTypeDef node, both of which will replace the original row in the type section.

+

In the future, this nnkTypeDef argument may be replaced with a unary type section node containing the type definition, or some other node that may be more convenient to work with. The ability to return nodes other than type definitions may also be supported, however currently this is not convenient when dealing with mutual type recursion. For now, macros can return an unused type definition where the right-hand node is of kind nnkStmtListType. Declarations in this node will be attached to the same scope as the parent scope of the type section.

+
+

For variables and constants, it is largely the same, except a unary node with the same kind as the section containing a single definition is passed to macros, and macros can return any expression.

+

var
+  a = ...
+  b {.importc, foo, nodecl.} = ...
+  c = ...

+

Assuming foo is a macro or a template, this is roughly equivalent to:

+

var a = ...
+foo:
+  var b {.importc, nodecl.} = ...
+var c = ...

+ +

Symbols as template/macro calls (alias syntax)

Templates and macros that have no generic parameters and no required arguments can be called as lone symbols, i.e. without parentheses. This is useful for repeated uses of complex expressions that cannot conveniently be represented as runtime values.

+

type Foo = object
+  bar: int
+
+var foo = Foo(bar: 10)
+template bar: int = foo.bar
+assert bar == 10
+bar = 15
+assert bar == 15

+ +

Not nil annotation

Note: This is an experimental feature. It can be enabled with {.experimental: "notnil".}.

+

All types for which nil is a valid value can be annotated with the not nil annotation to exclude nil as a valid value. Note that only local symbols are checked.

+

{.experimental: "notnil".}
+
+type
+  TObj = object
+  PObject = ref TObj not nil
+  TProc = (proc (x, y: int)) not nil
+
+proc p(x: PObject) =
+  echo "not nil"
+
+# compiler catches this:
+p(nil)
+
+# and also this:
+proc foo =
+  var x: PObject
+  p(x)
+
+foo()

+

The compiler ensures that every code path initializes variables which contain non-nilable pointers. The details of this analysis are still to be specified here.

+ +

Strict not nil checking

Note: This feature is experimental, you need to enable it with

+

{.experimental: "strictNotNil".}

+

or

+

nim c --experimental:strictNotNil <program>

+

In the second case it would check builtin and imported modules as well.

+

It checks the nilability of ref-like types and makes dereferencing safer based on flow typing and not nil annotations.

+

Its implementation is different than the notnil one: defined under strictNotNil. Keep in mind the difference in option names, be careful with distinguishing them.

+

We check several kinds of types for nilability:

+
  • ref types
  • +
  • pointer types
  • +
  • proc types
  • +
  • cstrings
  • +
+ +

nil

The default kind of nilability types is the nilable kind: they can have the value nil. If you have a non-nilable type T, you can use T nil to get a nilable type for it.

+ +

not nil

You can annotate a type where nil isn't a valid value with not nil.

+

  type
+    NilableObject = ref object
+      a: int
+    Object = NilableObject not nil
+    
+    Proc = (proc (x, y: int))
+  
+  proc p(x: Object) =
+    echo x.a # ensured to dereference without an error
+  # compiler catches this:
+  p(nil)
+  # and also this:
+  var x: NilableObject
+  if x.isNil:
+    p(x)
+  else:
+    p(x) # ok

+

If a type can include nil as a valid value, dereferencing values of the type is checked by the compiler: if a value which might be nil is dereferenced, this produces a warning by default, you can turn this into an error using the compiler options --warningAsError:strictNotNil.

+

If a type is nilable, you should dereference its values only after a isNil or equivalent check.

+ +

local turn on/off

You can still turn off nil checking on function/module level by using a {.strictNotNil: off.} pragma.

+ +

nilability state

Currently, a nilable value can be Safe, MaybeNil or Nil : we use internally Parent and Unreachable but this is an implementation detail(a parent layer has the actual nilability).

+
  • Safe means it shouldn't be nil at that point: e.g. after assignment to a non-nil value or not a.isNil check
  • +
  • MaybeNil means it might be nil, but it might not be nil: e.g. an argument, a call argument or a value after an if and else.
  • +
  • Nil means it should be nil at that point; e.g. after an assignment to nil or a .isNil check.
  • +
  • Unreachable means it shouldn't be possible to access this in this branch: so we do generate a warning as well.
  • +
+

We show an error for each dereference ([], .field, [index] () etc.) which is of a tracked expression which is in MaybeNil or Nil state.

+ +

type nilability

Types are either nilable or non-nilable. When you pass a param or a default value, we use the type : for nilable types we return MaybeNil and for non-nilable Safe.

+ +

params rules

Param's nilability is detected based on type nilability. We use the type of the argument to detect the nilability.

+ +

assignment rules

Let's say we have left = right.

+

When we assign, we pass the right's nilability to the left's expression. There should be special handling of aliasing and compound expressions which we specify in their sections. (Assignment is a possible alias move or move out).

+ +

call args rules

When we call with arguments, we have two cases when we might change the nilability.

+

callByVar(a)

+

Here callByVar can re-assign a, so this might change a's nilability, so we change it to MaybeNil. This is also a possible aliasing move out (moving out of a current alias set).

+

call(a)

+

Here call can change a field or element of a, so if we have a dependant expression of a : e.g. a.field. Dependants become MaybeNil.

+ +

branches rules

Branches are the reason we do nil checking like this: with flow checking. Sources of branching are if, while, for, and, or, case, try and combinations with return, break, continue and raise

+

We create a new layer/"scope" for each branch where we map expressions to nilability. This happens when we "fork": usually on the beginning of a construct. When branches "join" we usually unify their expression maps or/and nilabilities.

+

Merging usually merges maps and alias sets: nilabilities are merged like this:

+

template union(l: Nilability, r: Nilability): Nilability =
+  ## unify two states
+  if l == r:
+    l
+  else:
+    MaybeNil

+

Special handling is for .isNil and == nil, also for not, and and or.

+

not reverses the nilability, and is similar to "forking" : the right expression is checked in the layer resulting from the left one and or is similar to "merging": the right and left expression should be both checked in the original layer.

+

isNil, == nil make expressions Nil. If there is a not or != nil, they make them Safe. We also reverse the nilability in the opposite branch: e.g. else.

+ +

compound expressions: field, index expressions

We want to track also field(dot) and index(bracket) expressions.

+

We track some of those compound expressions which might be nilable as dependants of their bases: a.field is changed if a is moved (re-assigned), similarly a[index] is dependent on a and a.field.field on a.field.

+

When we move the base, we update dependants to MaybeNil. Otherwise, we usually start with type nilability.

+

When we call args, we update the nilability of their dependants to MaybeNil as the calls usually can change them. We might need to check for strictFuncs pure funcs and not do that then.

+

For field expressions a.field, we calculate an integer value based on a hash of the tree and just accept equivalent trees as equivalent expressions.

+

For item expression a[index], we also calculate an integer value based on a hash of the tree and accept equivalent trees as equivalent expressions: for static values only. For now, we support only constant indices: we don't track expression with no-const indices. For those we just report a warning even if they are safe for now: one can use a local variable to workaround. For loops this might be annoying: so one should be able to turn off locally the warning using the {.warning[StrictNotNil]:off.}.

+

For bracket expressions, in the future we might count a[<any>] as the same general expression. This means we should the index but otherwise handle it the same for assign (maybe "aliasing" all the non-static elements) and differentiate only for static: e.g. a[0] and a[1].

+ +

element tracking

When we assign an object construction, we should track the fields as well:

+

var a = Nilable(field: Nilable()) # a : Safe, a.field: Safe

+

Usually we just track the result of an expression: probably this should apply for elements in other cases as well. Also related to tracking initialization of expressions/fields.

+ +

unstructured control flow rules

Unstructured control flow keywords as return, break, continue, raise mean that we jump from a branch out. This means that if there is code after the finishing of the branch, it would be run if one hasn't hit the direct parent branch of those: so it is similar to an else. In those cases we should use the reverse nilabilities for the local to the condition expressions. E.g.

+

for a in c:
+  if not a.isNil:
+    b()
+    break
+  code # here a: Nil , because if not, we would have breaked

+ +

aliasing

We support alias detection for local expressions.

+

We track sets of aliased expressions. We start with all nilable local expressions in separate sets. Assignments and other changes to nilability can move / move out expressions of sets.

+

move: Moving left to right means we remove left from its current set and unify it with the right's set. This means it stops being aliased with its previous aliases.

+

var left = b
+left = right # moving left to right

+

move out: Moving out left might remove it from the current set and ensure that it's in its own set as a single element. e.g.

+

var left = b
+left = nil # moving out

+ +

warnings and errors

We show an error for each dereference ([], .field, [index] () etc.) which is of a tracked expression which is in MaybeNil or Nil state.

+

We might also show a history of the transitions and the reasons for them that might change the nilability of the expression.

+ +

Aliasing restrictions in parameter passing

Note: +The aliasing restrictions are currently not enforced by the implementation and need to be fleshed out further.
+

"Aliasing" here means that the underlying storage locations overlap in memory at runtime. An "output parameter" is a parameter of type var T, an input parameter is any parameter that is not of type var.

+
  1. Two output parameters should never be aliased.
  2. +
  3. An input and an output parameter should not be aliased.
  4. +
  5. An output parameter should never be aliased with a global or thread local variable referenced by the called proc.
  6. +
  7. An input parameter should not be aliased with a global or thread local variable updated by the called proc.
  8. +
+

One problem with rules 3 and 4 is that they affect specific global or thread local variables, but Nim's effect tracking only tracks "uses no global variable" via .noSideEffect. The rules 3 and 4 can also be approximated by a different rule:

+
  1. A global or thread local variable (or a location derived from such a location) can only passed to a parameter of a .noSideEffect proc.
  2. +
+ +

Strict funcs

Since version 1.4, a stricter definition of "side effect" is available. In addition to the existing rule that a side effect is calling a function with side effects, the following rule is also enforced:

+

A store to the heap via a ref or ptr indirection is not allowed.

+

For example:

+

{.experimental: "strictFuncs".}
+
+type
+  Node = ref object
+    le, ri: Node
+    data: string
+
+func len(n: Node): int =
+  # valid: len does not have side effects
+  var it = n
+  while it != nil:
+    inc result
+    it = it.ri
+
+func mut(n: Node) =
+  var it = n
+  while it != nil:
+    it.data = "yeah" # forbidden mutation
+    it = it.ri
+

+ +

View types

Tip: +--experimental:views is more effective with --experimental:strictFuncs.
+

A view type is a type that is or contains one of the following types:

+
  • lent T (view into T)
  • +
  • openArray[T] (pair of (pointer to array of T, size))
  • +
+

For example:

+

type
+  View1 = openArray[byte]
+  View2 = lent string
+  View3 = Table[openArray[char], int]

+

Exceptions to this rule are types constructed via ptr or proc. For example, the following types are not view types:

+

type
+  NotView1 = proc (x: openArray[int])
+  NotView2 = ptr openArray[char]
+  NotView3 = ptr array[4, lent int]

+

The mutability aspect of a view type is not part of the type but part of the locations it's derived from. More on this later.

+

A view is a symbol (a let, var, const, etc.) that has a view type.

+

Since version 1.4, Nim allows view types to be used as local variables. This feature needs to be enabled via {.experimental: "views".}.

+

A local variable of a view type borrows from the locations and it is statically enforced that the view does not outlive the location it was borrowed from.

+

For example:

+

{.experimental: "views".}
+
+proc take(a: openArray[int]) =
+  echo a.len
+
+proc main(s: seq[int]) =
+  var x: openArray[int] = s # 'x' is a view into 's'
+  # it is checked that 'x' does not outlive 's' and
+  # that 's' is not mutated.
+  for i in 0 .. high(x):
+    echo x[i]
+  take(x)
+  
+  take(x.toOpenArray(0, 1)) # slicing remains possible
+  let y = x  # create a view from a view
+  take y
+  # it is checked that 'y' does not outlive 'x' and
+  # that 'x' is not mutated as long as 'y' lives.
+
+
+main(@[11, 22, 33])

+

A local variable of a view type can borrow from a location derived from a parameter, another local variable, a global const or let symbol or a thread-local var or let.

+

Let p the proc that is analysed for the correctness of the borrow operation.

+

Let source be one of:

+
  • A formal parameter of p. Note that this does not cover parameters of inner procs.
  • +
  • The result symbol of p.
  • +
  • A local var or let or const of p. Note that this does not cover locals of inner procs.
  • +
  • A thread-local var or let.
  • +
  • A global let or const.
  • +
  • A constant array/seq/object/tuple constructor.
  • +
+ +

Path expressions

A location derived from source is then defined as a path expression that has source as the owner. A path expression e is defined recursively:

+
  • source itself is a path expression.
  • +
  • Container access like e[i] is a path expression.
  • +
  • Tuple access e[0] is a path expression.
  • +
  • Object field access e.field is a path expression.
  • +
  • system.toOpenArray(e, ...) is a path expression.
  • +
  • Pointer dereference e[] is a path expression.
  • +
  • An address addr e is a path expression.
  • +
  • A type conversion T(e) is a path expression.
  • +
  • A cast expression cast[T](e) is a path expression.
  • +
  • f(e, ...) is a path expression if f's return type is a view type. Because the view can only have been borrowed from e, we then know that the owner of f(e, ...) is e.
  • +
+

If a view type is used as a return type, the location must borrow from a location that is derived from the first parameter that is passed to the proc. See the manual for details about how this is done for var T.

+

A mutable view can borrow from a mutable location, an immutable view can borrow from both a mutable or an immutable location.

+

If a view borrows from a mutable location, the view can be used to update the location. Otherwise it cannot be used for mutations.

+

The duration of a borrow is the span of commands beginning from the assignment to the view and ending with the last usage of the view.

+

For the duration of the borrow operation, no mutations to the borrowed locations may be performed except via the view that borrowed from the location. The borrowed location is said to be sealed during the borrow.

+

{.experimental: "views".}
+
+type
+  Obj = object
+    field: string
+
+proc dangerous(s: var seq[Obj]) =
+  let v: lent Obj = s[0] # seal 's'
+  s.setLen 0  # prevented at compile-time because 's' is sealed.
+  echo v.field

+

The scope of the view does not matter:

+

proc valid(s: var seq[Obj]) =
+  let v: lent Obj = s[0]  # begin of borrow
+  echo v.field            # end of borrow
+  s.setLen 0  # valid because 'v' isn't used afterwards

+

The analysis requires as much precision about mutations as is reasonably obtainable, so it is more effective with the experimental strict funcs feature. In other words --experimental:views works better with --experimental:strictFuncs.

+

The analysis is currently control flow insensitive:

+

proc invalid(s: var seq[Obj]) =
+  let v: lent Obj = s[0]
+  if false:
+    s.setLen 0
+  echo v.field

+

In this example, the compiler assumes that s.setLen 0 invalidates the borrow operation of v even though a human being can easily see that it will never do that at runtime.

+ +

Start of a borrow

A borrow starts with one of the following:

+
  • The assignment of a non-view-type to a view-type.
  • +
  • The assignment of a location that is derived from a local parameter to a view-type.
  • +
+ +

End of a borrow

A borrow operation ends with the last usage of the view variable.

+ +

Reborrows

A view v can borrow from multiple different locations. However, the borrow is always the full span of v's lifetime and every location that is borrowed from is sealed during v's lifetime.

+ +

Algorithm

The following section is an outline of the algorithm that the current implementation uses. The algorithm performs two traversals over the AST of the procedure or global section of code that uses a view variable. No fixpoint iterations are performed, the complexity of the analysis is O(N) where N is the number of nodes of the AST.

+

The first pass over the AST computes the lifetime of each local variable based on a notion of an "abstract time", in the implementation it's a simple integer that is incremented for every visited node.

+

In the second pass, information about the underlying object "graphs" is computed. Let v be a parameter or a local variable. Let G(v) be the graph that v belongs to. A graph is defined by the set of variables that belong to the graph. Initially for all v: G(v) = {v}. Every variable can only be part of a single graph.

+

Assignments like a = b "connect" two variables, both variables end up in the same graph {a, b} = G(a) = G(b). Unfortunately, the pattern to look for is much more complex than that and can involve multiple assignment targets and sources:

+
f(x, y) = g(a, b)
+

connects x and y to a and b: G(x) = G(y) = G(a) = G(b) = {x, y, a, b}. A type based alias analysis rules out some of these combinations, for example a string value cannot possibly be connected to a seq[int].

+

A pattern like v[] = value or v.field = value marks G(v) as mutated. After the second pass a set of disjoint graphs was computed.

+

For strict functions it is then enforced that there is no graph that is both mutated and has an element that is an immutable parameter (that is a parameter that is not of type var T).

+

For borrow checking, a different set of checks is performed. Let v be the view and b the location that is borrowed from.

+
  • The lifetime of v must not exceed b's lifetime. Note: The lifetime of a parameter is the complete proc body.
  • +
  • If v is used for a mutation, b must be a mutable location too.
  • +
  • During v's lifetime, G(b) can only be modified by v (and only if v is a mutable view).
  • +
  • If v is result then b has to be a location derived from the first formal parameter or from a constant location.
  • +
  • A view cannot be used for a read or a write access before it was assigned to.
  • +
+ +

Concepts

Concepts, also known as "user-defined type classes", are used to specify an arbitrary set of requirements that the matched type must satisfy.

+

Concepts are written in the following form:

+

type
+  Comparable = concept x, y
+    (x < y) is bool
+  
+  Stack[T] = concept s, var v
+    s.pop() is T
+    v.push(T)
+    
+    s.len is Ordinal
+    
+    for value in s:
+      value is T

+

The concept matches if:

+
  1. all expressions within the body can be compiled for the tested type
  2. +
  3. all statically evaluable boolean expressions in the body are true
  4. +
  5. all type modifiers specified match their respective definitions
  6. +
+

The identifiers following the concept keyword represent instances of the currently matched type. You can apply any of the standard type modifiers such as var, ref, ptr and static to denote a more specific type of instance. You can also apply the type modifier to create a named instance of the type itself:

+

type
+  MyConcept = concept x, var v, ref r, ptr p, static s, type T
+    ...

+

Within the concept body, types can appear in positions where ordinary values and parameters are expected. This provides a more convenient way to check for the presence of callable symbols with specific signatures:

+

type
+  OutputStream = concept var s
+    s.write(string)

+

In order to check for symbols accepting type params, you must prefix the type with the explicit type modifier. The named instance of the type, following the concept keyword is also considered to have the explicit modifier and will be matched only as a type.

+

type
+  # Let's imagine a user-defined casting framework with operators
+  # such as `val.to(string)` and `val.to(JSonValue)`. We can test
+  # for these with the following concept:
+  MyCastables = concept x
+    x.to(type string)
+    x.to(type JSonValue)
+  
+  # Let's define a couple of concepts, known from Algebra:
+  AdditiveMonoid* = concept x, y, type T
+    x + y is T
+    T.zero is T # require a proc such as `int.zero` or 'Position.zero'
+  
+  AdditiveGroup* = concept x, y, type T
+    x is AdditiveMonoid
+    -x is T
+    x - y is T

+

Please note that the is operator allows one to easily verify the precise type signatures of the required operations, but since type inference and default parameters are still applied in the concept body, it's also possible to describe usage protocols that do not reveal implementation details.

+

Much like generics, concepts are instantiated exactly once for each tested type and any static code included within the body is executed only once.

+ +

Concept diagnostics

By default, the compiler will report the matching errors in concepts only when no other overload can be selected and a normal compilation error is produced. When you need to understand why the compiler is not matching a particular concept and, as a result, a wrong overload is selected, you can apply the explain pragma to either the concept body or a particular call-site.

+

type
+  MyConcept {.explain.} = concept ...
+
+overloadedProc(x, y, z) {.explain.}

+

This will provide Hints in the compiler output either every time the concept is not matched or only on the particular call-site.

+ +

Generic concepts and type binding rules

The concept types can be parametric just like the regular generic types:

+

### matrixalgo.nim
+
+import std/typetraits
+
+type
+  AnyMatrix*[R, C: static int; T] = concept m, var mvar, type M
+    M.ValueType is T
+    M.Rows == R
+    M.Cols == C
+    
+    m[int, int] is T
+    mvar[int, int] = T
+    
+    type TransposedType = stripGenericParams(M)[C, R, T]
+  
+  AnySquareMatrix*[N: static int, T] = AnyMatrix[N, N, T]
+  
+  AnyTransform3D* = AnyMatrix[4, 4, float]
+
+proc transposed*(m: AnyMatrix): m.TransposedType =
+  for r in 0 ..< m.R:
+    for c in 0 ..< m.C:
+      result[r, c] = m[c, r]
+
+proc determinant*(m: AnySquareMatrix): int =
+  ...
+
+proc setPerspectiveProjection*(m: AnyTransform3D) =
+  ...
+
+--------------
+### matrix.nim
+
+type
+  Matrix*[M, N: static int; T] = object
+    data: array[M*N, T]
+
+proc `[]`*(M: Matrix; m, n: int): M.T =
+  M.data[m * M.N + n]
+
+proc `[]=`*(M: var Matrix; m, n: int; v: M.T) =
+  M.data[m * M.N + n] = v
+
+# Adapt the Matrix type to the concept's requirements
+template Rows*(M: typedesc[Matrix]): int = M.M
+template Cols*(M: typedesc[Matrix]): int = M.N
+template ValueType*(M: typedesc[Matrix]): typedesc = M.T
+
+-------------
+### usage.nim
+
+import matrix, matrixalgo
+
+var
+  m: Matrix[3, 3, int]
+  projectionMatrix: Matrix[4, 4, float]
+
+echo m.transposed.determinant
+setPerspectiveProjection projectionMatrix

+

When the concept type is matched against a concrete type, the unbound type parameters are inferred from the body of the concept in a way that closely resembles the way generic parameters of callable symbols are inferred on call sites.

+

Unbound types can appear both as params to calls such as s.push(T) and on the right-hand side of the is operator in cases such as x.pop is T and x.data is seq[T].

+

Unbound static params will be inferred from expressions involving the == operator and also when types dependent on them are being matched:

+

type
+  MatrixReducer[M, N: static int; T] = concept x
+    x.reduce(SquareMatrix[N, T]) is array[M, int]

+

The Nim compiler includes a simple linear equation solver, allowing it to infer static params in some situations where integer arithmetic is involved.

+

Just like in regular type classes, Nim discriminates between bind once and bind many types when matching the concept. You can add the distinct modifier to any of the otherwise inferable types to get a type that will be matched without permanently inferring it. This may be useful when you need to match several procs accepting the same wide class of types:

+

type
+  Enumerable[T] = concept e
+    for v in e:
+      v is T
+
+type
+  MyConcept = concept o
+    # this could be inferred to a type such as Enumerable[int]
+    o.foo is distinct Enumerable
+    
+    # this could be inferred to a different type such as Enumerable[float]
+    o.bar is distinct Enumerable
+    
+    # it's also possible to give an alias name to a `bind many` type class
+    type Enum = distinct Enumerable
+    o.baz is Enum

+

On the other hand, using bind once types allows you to test for equivalent types used in multiple signatures, without actually requiring any concrete types, thus allowing you to encode implementation-defined types:

+

type
+  MyConcept = concept x
+    type T1 = auto
+    x.foo(T1)
+    x.bar(T1) # both procs must accept the same type
+    
+    type T2 = seq[SomeNumber]
+    x.alpha(T2)
+    x.omega(T2) # both procs must accept the same type
+                # and it must be a numeric sequence

+

As seen in the previous examples, you can refer to generic concepts such as Enumerable[T] just by their short name. Much like the regular generic types, the concept will be automatically instantiated with the bind once auto type in the place of each missing generic param.

+

Please note that generic concepts such as Enumerable[T] can be matched against concrete types such as string. Nim doesn't require the concept type to have the same number of parameters as the type being matched. If you wish to express a requirement towards the generic parameters of the matched type, you can use a type mapping operator such as genericHead or stripGenericParams within the body of the concept to obtain the uninstantiated version of the type, which you can then try to instantiate in any required way. For example, here is how one might define the classic Functor concept from Haskell and then demonstrate that Nim's Option[T] type is an instance of it:

+

import std/[sugar, typetraits]
+
+type
+  Functor[A] = concept f
+    type MatchedGenericType = genericHead(typeof(f))
+      # `f` will be a value of a type such as `Option[T]`
+      # `MatchedGenericType` will become the `Option` type
+    
+    f.val is A
+      # The Functor should provide a way to obtain
+      # a value stored inside it
+    
+    type T = auto
+    map(f, A -> T) is MatchedGenericType[T]
+      # And it should provide a way to map one instance of
+      # the Functor to a instance of a different type, given
+      # a suitable `map` operation for the enclosed values
+
+import std/options
+echo Option[int] is Functor # prints true

+ +

Concept derived values

All top level constants or types appearing within the concept body are accessible through the dot operator in procs where the concept was successfully matched to a concrete type:

+

type
+  DateTime = concept t1, t2, type T
+    const Min = T.MinDate
+    T.Now is T
+    
+    t1 < t2 is bool
+    
+    type TimeSpan = typeof(t1 - t2)
+    TimeSpan * int is TimeSpan
+    TimeSpan + TimeSpan is TimeSpan
+    
+    t1 + TimeSpan is T
+
+proc eventsJitter(events: Enumerable[DateTime]): float =
+  var
+    # this variable will have the inferred TimeSpan type for
+    # the concrete Date-like value the proc was called with:
+    averageInterval: DateTime.TimeSpan
+    
+    deviation: float
+  ...

+ +

Concept refinement

When the matched type within a concept is directly tested against a different concept, we say that the outer concept is a refinement of the inner concept and thus it is more-specific. When both concepts are matched in a call during overload resolution, Nim will assign a higher precedence to the most specific one. As an alternative way of defining concept refinements, you can use the object inheritance syntax involving the of keyword:

+

type
+  Graph = concept g, type G of EquallyComparable, Copyable
+    type
+      VertexType = G.VertexType
+      EdgeType = G.EdgeType
+    
+    VertexType is Copyable
+    EdgeType is Copyable
+    
+    var
+      v: VertexType
+      e: EdgeType
+  
+  IncidendeGraph = concept of Graph
+    # symbols such as variables and types from the refined
+    # concept are automatically in scope:
+    
+    g.source(e) is VertexType
+    g.target(e) is VertexType
+    
+    g.outgoingEdges(v) is Enumerable[EdgeType]
+  
+  BidirectionalGraph = concept g, type G
+    # The following will also turn the concept into a refinement when it
+    # comes to overload resolution, but it doesn't provide the convenient
+    # symbol inheritance
+    g is IncidendeGraph
+    
+    g.incomingEdges(G.VertexType) is Enumerable[G.EdgeType]
+
+proc f(g: IncidendeGraph)
+proc f(g: BidirectionalGraph) # this one will be preferred if we pass a type
+                              # matching the BidirectionalGraph concept

+ +

Dynamic arguments for bindSym

This experimental feature allows the symbol name argument of macros.bindSym to be computed dynamically.

+

{.experimental: "dynamicBindSym".}
+
+import std/macros
+
+macro callOp(opName, arg1, arg2): untyped =
+  result = newCall(bindSym($opName), arg1, arg2)
+
+echo callOp("+", 1, 2)
+echo callOp("-", 5, 4)

+ +

Term rewriting macros

Term rewriting macros are macros or templates that have not only a name but also a pattern that is searched for after the semantic checking phase of the compiler: This means they provide an easy way to enhance the compilation pipeline with user defined optimizations:

+

template optMul{`*`(a, 2)}(a: int): int = a + a
+
+let x = 3
+echo x * 2

+

The compiler now rewrites x * 2 as x + x. The code inside the curly brackets is the pattern to match against. The operators *, **, |, ~ have a special meaning in patterns if they are written in infix notation, so to match verbatim against * the ordinary function call syntax needs to be used.

+

Term rewriting macros are applied recursively, up to a limit. This means that if the result of a term rewriting macro is eligible for another rewriting, the compiler will try to perform it, and so on, until no more optimizations are applicable. To avoid putting the compiler into an infinite loop, there is a hard limit on how many times a single term rewriting macro can be applied. Once this limit has been passed, the term rewriting macro will be ignored.

+

Unfortunately optimizations are hard to get right and even this tiny example is wrong:

+

template optMul{`*`(a, 2)}(a: int): int = a + a
+
+proc f(): int =
+  echo "side effect!"
+  result = 55
+
+echo f() * 2

+

We cannot duplicate 'a' if it denotes an expression that has a side effect! Fortunately Nim supports side effect analysis:

+

template optMul{`*`(a, 2)}(a: int{noSideEffect}): int = a + a
+
+proc f(): int =
+  echo "side effect!"
+  result = 55
+
+echo f() * 2 # not optimized ;-)

+

You can make one overload matching with a constraint and one without, and the one with a constraint will have precedence, and so you can handle both cases differently.

+

So what about 2 * a? We should tell the compiler * is commutative. We cannot really do that however as the following code only swaps arguments blindly:

+

template mulIsCommutative{`*`(a, b)}(a, b: int): int = b * a

+

What optimizers really need to do is a canonicalization:

+

template canonMul{`*`(a, b)}(a: int{lit}, b: int): int = b * a

+

The int{lit} parameter pattern matches against an expression of type int, but only if it's a literal.

+ +

Parameter constraints

The parameter constraint expression can use the operators | (or), & (and) and ~ (not) and the following predicates:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PredicateMeaning
atomThe matching node has no children.
litThe matching node is a literal like "abc", 12.
symThe matching node must be a symbol (a bound identifier).
identThe matching node must be an identifier (an unbound identifier).
callThe matching AST must be a call/apply expression.
lvalueThe matching AST must be an lvalue.
sideeffectThe matching AST must have a side effect.
nosideeffectThe matching AST must have no side effect.
paramA symbol which is a parameter.
genericparamA symbol which is a generic parameter.
moduleA symbol which is a module.
typeA symbol which is a type.
varA symbol which is a variable.
letA symbol which is a let variable.
constA symbol which is a constant.
resultThe special result variable.
procA symbol which is a proc.
methodA symbol which is a method.
iteratorA symbol which is an iterator.
converterA symbol which is a converter.
macroA symbol which is a macro.
templateA symbol which is a template.
fieldA symbol which is a field in a tuple or an object.
enumfieldA symbol which is a field in an enumeration.
forvarA for loop variable.
labelA label (used in block statements).
nk*The matching AST must have the specified kind. (Example: nkIfStmt denotes an if statement.)
aliasStates that the marked parameter needs to alias with some other parameter.
noaliasStates that every other parameter must not alias with the marked parameter.

Predicates that share their name with a keyword have to be escaped with backticks. The alias and noalias predicates refer not only to the matching AST, but also to every other bound parameter; syntactically they need to occur after the ordinary AST predicates:

+

template ex{a = b + c}(a: int{noalias}, b, c: int) =
+  # this transformation is only valid if 'b' and 'c' do not alias 'a':
+  a = b
+  inc a, c

+

Another example:

+

proc somefunc(s: string)                 = assert s == "variable"
+proc somefunc(s: string{nkStrLit})       = assert s == "literal"
+proc somefunc(s: string{nkRStrLit})      = assert s == r"raw"
+proc somefunc(s: string{nkTripleStrLit}) = assert s == """triple"""
+proc somefunc(s: static[string])         = assert s == "constant"
+
+# Use parameter constraints to provide overloads based on both the input parameter type and form.
+var variable = "variable"
+somefunc(variable)
+const constant = "constant"
+somefunc(constant)
+somefunc("literal")
+somefunc(r"raw")
+somefunc("""triple""")

+ +

Pattern operators

The operators *, **, |, ~ have a special meaning in patterns if they are written in infix notation.

+ +

The | operator

The | operator if used as infix operator creates an ordered choice:

+

template t{0|1}(): untyped = 3
+let a = 1
+# outputs 3:
+echo a

+

The matching is performed after the compiler performed some optimizations like constant folding, so the following does not work:

+

template t{0|1}(): untyped = 3
+# outputs 1:
+echo 1

+

The reason is that the compiler already transformed the 1 into "1" for the echo statement. However, a term rewriting macro should not change the semantics anyway. In fact, they can be deactivated with the --patterns:off command line option or temporarily with the patterns pragma.

+ +

The {} operator

A pattern expression can be bound to a pattern parameter via the expr{param} notation:

+

template t{(0|1|2){x}}(x: untyped): untyped = x + 1
+let a = 1
+# outputs 2:
+echo a

+ +

The ~ operator

The ~ operator is the 'not' operator in patterns:

+

template t{x = (~x){y} and (~x){z}}(x, y, z: bool) =
+  x = y
+  if x: x = z
+
+var
+  a = false
+  b = true
+  c = false
+a = b and c
+echo a

+ +

The * operator

The * operator can flatten a nested binary expression like a & b & c to &(a, b, c):

+

var
+  calls = 0
+
+proc `&&`(s: varargs[string]): string =
+  result = s[0]
+  for i in 1..len(s)-1: result.add s[i]
+  inc calls
+
+template optConc{ `&&` * a }(a: string): untyped = &&a
+
+let space = " "
+echo "my" && (space & "awe" && "some " ) && "concat"
+
+# check that it's been optimized properly:
+doAssert calls == 1

+

The second operator of * must be a parameter; it is used to gather all the arguments. The expression "my" && (space & "awe" && "some " ) && "concat" is passed to optConc in a as a special list (of kind nkArgList) which is flattened into a call expression; thus the invocation of optConc produces:

+

`&&`("my", space & "awe", "some ", "concat")

+ +

The ** operator

The ** is much like the * operator, except that it gathers not only all the arguments, but also the matched operators in reverse polish notation:

+

import std/macros
+
+type
+  Matrix = object
+    dummy: int
+
+proc `*`(a, b: Matrix): Matrix = discard
+proc `+`(a, b: Matrix): Matrix = discard
+proc `-`(a, b: Matrix): Matrix = discard
+proc `$`(a: Matrix): string = result = $a.dummy
+proc mat21(): Matrix =
+  result.dummy = 21
+
+macro optM{ (`+`|`-`|`*`) ** a }(a: Matrix): untyped =
+  echo treeRepr(a)
+  result = newCall(bindSym"mat21")
+
+var x, y, z: Matrix
+
+echo x + y * z - x

+

This passes the expression x + y * z - x to the optM macro as an nnkArgList node containing:

+
Arglist
+  Sym "x"
+  Sym "y"
+  Sym "z"
+  Sym "*"
+  Sym "+"
+  Sym "x"
+  Sym "-"
+

(This is the reverse polish notation of x + y * z - x.)

+ +

Parameters

Parameters in a pattern are type checked in the matching process. If a parameter is of the type varargs, it is treated specially and can match 0 or more arguments in the AST to be matched against:

+

template optWrite{
+  write(f, x)
+  ((write|writeLine){w})(f, y)
+}(x, y: varargs[untyped], f: File, w: untyped) =
+  w(f, x, y)

+ +

noRewrite pragma

Term rewriting macros and templates are currently greedy and they will rewrite as long as there is a match. There was no way to ensure some rewrite happens only once, e.g. when rewriting term to same term plus extra content.

+

noRewrite pragma can actually prevent further rewriting on marked code, e.g. with given example echo("ab") will be rewritten just once:

+

template pwnEcho{echo(x)}(x: untyped) =
+  {.noRewrite.}: echo("pwned!")
+
+echo "ab"

+

noRewrite pragma can be useful to control term-rewriting macros recursion.

+ +

Example: Partial evaluation

The following example shows how some simple partial evaluation can be implemented with term rewriting:

+

proc p(x, y: int; cond: bool): int =
+  result = if cond: x + y else: x - y
+
+template optP1{p(x, y, true)}(x, y: untyped): untyped = x + y
+template optP2{p(x, y, false)}(x, y: untyped): untyped = x - y

+ +

Example: Hoisting

The following example shows how some form of hoisting can be implemented:

+

import std/pegs
+
+template optPeg{peg(pattern)}(pattern: string{lit}): Peg =
+  var gl {.global, gensym.} = peg(pattern)
+  gl
+
+for i in 0 .. 3:
+  echo match("(a b c)", peg"'(' @ ')'")
+  echo match("W_HI_Le", peg"\y 'while'")

+

The optPeg template optimizes the case of a peg constructor with a string literal, so that the pattern will only be parsed once at program startup and stored in a global gl which is then re-used. This optimization is called hoisting because it is comparable to classical loop hoisting.

+ +

AST based overloading

Parameter constraints can also be used for ordinary routine parameters; these constraints then affect ordinary overloading resolution:

+

proc optLit(a: string{lit|`const`}) =
+  echo "string literal"
+proc optLit(a: string) =
+  echo "no string literal"
+
+const
+  constant = "abc"
+
+var
+  variable = "xyz"
+
+optLit("literal")
+optLit(constant)
+optLit(variable)

+

However, the constraints alias and noalias are not available in ordinary routines.

+ +

Parallel & Spawn

Nim has two flavors of parallelism:

+
  1. Structured parallelism via the parallel statement.
  2. +
  3. Unstructured parallelism via the standalone spawn statement.
  4. +
+

Nim has a builtin thread pool that can be used for CPU intensive tasks. For IO intensive tasks the async and await features should be used instead. Both parallel and spawn need the threadpool module to work.

+

Somewhat confusingly, spawn is also used in the parallel statement with slightly different semantics. spawn always takes a call expression of the form f(a, ...). Let T be f's return type. If T is void, then spawn's return type is also void, otherwise it is FlowVar[T].

+

Within a parallel section, the FlowVar[T] is sometimes eliminated to T. This happens when T does not contain any GC'ed memory. The compiler can ensure the location in location = spawn f(...) is not read prematurely within a parallel section and so there is no need for the overhead of an indirection via FlowVar[T] to ensure correctness.

+
Note: +Currently exceptions are not propagated between spawn'ed tasks!
+

This feature is likely to be removed in the future as external packages can have better solutions.

+ +

Spawn statement

The spawn statement can be used to pass a task to the thread pool:

+

import std/threadpool
+
+proc processLine(line: string) =
+  discard "do some heavy lifting here"
+
+for x in lines("myinput.txt"):
+  spawn processLine(x)
+sync()

+

For reasons of type safety and implementation simplicity the expression that spawn takes is restricted:

+
  • It must be a call expression f(a, ...).
  • +
  • f must be gcsafe.
  • +
  • f must not have the calling convention closure.
  • +
  • f's parameters may not be of type var. This means one has to use raw ptr's for data passing reminding the programmer to be careful.
  • +
  • ref parameters are deeply copied, which is a subtle semantic change and can cause performance problems, but ensures memory safety. This deep copy is performed via system.deepCopy, so it can be overridden.
  • +
  • For safe data exchange between f and the caller, a global Channel needs to be used. However, since spawn can return a result, often no further communication is required.
  • +
+

spawn executes the passed expression on the thread pool and returns a data flow variable FlowVar[T] that can be read from. The reading with the ^ operator is blocking. However, one can use blockUntilAny to wait on multiple flow variables at the same time:

+

import std/threadpool, ...
+
+# wait until 2 out of 3 servers received the update:
+proc main =
+  var responses = newSeq[FlowVarBase](3)
+  for i in 0..2:
+    responses[i] = spawn tellServer(Update, "key", "value")
+  var index = blockUntilAny(responses)
+  assert index >= 0
+  responses.del(index)
+  discard blockUntilAny(responses)

+

Data flow variables ensure that no data races are possible. Due to technical limitations, not every type T can be used in a data flow variable: T has to be a ref, string, seq or of a type that doesn't contain any GC'd type. This restriction is not hard to work-around in practice.

+ +

Parallel statement

Example:

+

# Compute pi in an inefficient way
+import std/[strutils, math, threadpool]
+{.experimental: "parallel".}
+
+proc term(k: float): float = 4 * math.pow(-1, k) / (2*k + 1)
+
+proc pi(n: int): float =
+  var ch = newSeq[float](n + 1)
+  parallel:
+    for k in 0..ch.high:
+      ch[k] = spawn term(float(k))
+  for k in 0..ch.high:
+    result += ch[k]
+
+echo formatFloat(pi(5000))

+

The parallel statement is the preferred mechanism to introduce parallelism in a Nim program. Only a subset of the Nim language is valid within a parallel section. This subset is checked during semantic analysis to be free of data races. A sophisticated disjoint checker ensures that no data races are possible, even though shared memory is extensively supported!

+

The subset is in fact the full language with the following restrictions / changes:

+
  • spawn within a parallel section has special semantics.
  • +
  • Every location of the form a[i], a[i..j] and dest where dest is part of the pattern dest = spawn f(...) has to be provably disjoint. This is called the disjoint check.
  • +
  • Every other complex location loc that is used in a spawned proc (spawn f(loc)) has to be immutable for the duration of the parallel section. This is called the immutability check. Currently it is not specified what exactly "complex location" means. We need to make this an optimization!
  • +
  • Every array access has to be provably within bounds. This is called the bounds check.
  • +
  • Slices are optimized so that no copy is performed. This optimization is not yet performed for ordinary slices outside of a parallel section.
  • +
+ +

Strict definitions and out parameters

With experimental: "strictDefs" every local variable must be initialized explicitly before it can be used:

+

{.experimental: "strictDefs".}
+
+proc test =
+  var s: seq[string]
+  s.add "abc" # invalid!
+

+

Needs to be written as:

+

{.experimental: "strictDefs".}
+
+proc test =
+  var s: seq[string] = @[]
+  s.add "abc" # valid!
+

+

A control flow analysis is performed in order to prove that a variable has been written to before it is used. Thus the following is valid:

+

{.experimental: "strictDefs".}
+
+proc test(cond: bool) =
+  var s: seq[string]
+  if cond:
+    s = @["y"]
+  else:
+    s = @[]
+  s.add "abc" # valid!

+

In this example every path does set s to a value before it is used.

+

{.experimental: "strictDefs".}
+
+proc test(cond: bool) =
+  let s: seq[string]
+  if cond:
+    s = @["y"]
+  else:
+    s = @[]

+

With experimental: "strictDefs", let statements are allowed to not have an initial value, but every path should set s to a value before it is used.

+ +

out parameters

An out parameter is like a var parameter but it must be written to before it can be used:

+

proc myopen(f: out File; name: string): bool =
+  f = default(File)
+  result = open(f, name)

+

While it is usually the better style to use the return type in order to return results API and ABI considerations might make this infeasible. Like for var T Nim maps out T to a hidden pointer. For example POSIX's stat routine can be wrapped as:

+

proc stat*(a1: cstring, a2: out Stat): cint {.importc, header: "<sys/stat.h>".}

+

When the implementation of a routine with output parameters is analysed, the compiler checks that every path before the (implicit or explicit) return does set every output parameter:

+

proc p(x: out int; y: out string; cond: bool) =
+  x = 4
+  if cond:
+    y = "abc"
+  # error: not every path initializes 'y'

+ +

Out parameters and exception handling

The analysis should take exceptions into account (but currently does not):

+

proc p(x: out int; y: out string; cond: bool) =
+  x = canRaise(45)
+  y = "abc" # <-- error: not every path initializes 'y'

+

Once the implementation takes exceptions into account it is easy enough to use outParam = default(typeof(outParam)) in the beginning of the proc body.

+ +

Out parameters and inheritance

It is not valid to pass an lvalue of a supertype to an out T parameter:

+

type
+  Superclass = object of RootObj
+    a: int
+  Subclass = object of Superclass
+    s: string
+
+proc init(x: out Superclass) =
+  x = Superclass(a: 8)
+
+var v: Subclass
+init v
+use v.s # the 's' field was never initialized!

+

However, in the future this could be allowed and provide a better way to write object constructors that take inheritance into account.

+

Note: The implementation of "strict definitions" and "out parameters" is experimental but the concept is solid and it is expected that eventually this mode becomes the default in later versions.

+ +

Strict case objects

With experimental: "strictCaseObjects" every field access is checked to be valid at compile-time. The field is within a case section of an object.

+

{.experimental: "strictCaseObjects".}
+
+type
+  Foo = object
+    case b: bool
+    of false:
+      s: string
+    of true:
+      x: int
+
+var x = Foo(b: true, x: 4)
+case x.b
+of true:
+  echo x.x # valid
+of false:
+  echo "no"
+
+case x.b
+of false:
+  echo x.x # error: field access outside of valid case branch: x.x
+of true:
+  echo "no"
+

+

Note: The implementation of "strict case objects" is experimental but the concept is solid and it is expected that eventually this mode becomes the default in later versions.

+ +

Quirky routines

The default code generation strategy of exceptions under the ARC/ORC model is the so called --exceptions:goto implementation. This implementation inserts a check after every call that can potentially raise an exception. A typical instruction sequence for this on for a x86 64 bit machine looks like:

+

cmp DWORD PTR [rbx], 0
+je  .L1

+

This is a memory fetch followed by jump. (An ideal implementation would use the carry flag and a single instruction like jc .L1.)

+

This overhead might not be desired and depending on the semantics of the routine may not be required either. So it can be disabled via a .quirky annotation:

+

proc wontRaise(x: int) {.quirky.} =
+  if x != 0:
+    # because of `quirky` this will continue even if `write` raised an IO exception:
+    write x
+    wontRaise(x-1)
+
+wontRaise 10
+

+

If the used exception model is not --exceptions:goto then the quirky pragma has no effect and is ignored.

+

The quirky pragma can also be be pushed in order to affect a group of routines and whether the compiler supports the pragma can be checked with defined(nimHasQuirky):

+

when defined(nimHasQuirky):
+  {.push quirky: on.}
+
+proc doRaise() = raise newException(ValueError, "")
+
+proc f(): string = "abc"
+
+proc q(cond: bool) =
+  if cond:
+    doRaise()
+  echo f()
+
+q(true)
+
+when defined(nimHasQuirky):
+  {.pop.}

+

Warning: The quirky pragma only affects code generation, no check for validity is performed!

+ +

Threading under ARC/ORC

ARC/ORC supports a shared heap out of the box. This means that messages can be sent between threads without copies. However, without copying the data there is an inherent danger of data races. Data races are prevented at compile-time if it is enforced that only isolated subgraphs can be sent around.

+ +

Isolation

The standard library module isolation.nim provides a generic type Isolated[T] that captures the important notion that nothing else can reference the graph that is wrapped inside Isolated[T]. It is what a channel implementation should use in order to enforce the freedom of data races:

+

proc send*[T](c: var Channel[T]; msg: sink Isolated[T])
+proc recv*[T](c: var Channel[T]): T
+  ## Note: Returns T, not Isolated[T] for convenience.
+
+proc recvIso*[T](c: var Channel[T]): Isolated[T]
+  ## remembers the data is Isolated[T].

+

In order to create an Isolated graph one has to use either isolate or unsafeIsolate. unsafeIsolate is as its name says unsafe and no checking is performed. It should be considered to be as dangerous as a cast operation.

+

Construction must ensure that the invariant holds, namely that the wrapped T is free of external aliases into it. isolate ensures this invariant. It is inspired by Pony's recover construct:

+

func isolate(x: sink T): Isolated[T] {.magic: "Isolate".}

+

As you can see, this is a new builtin because the check it performs on x is non-trivial:

+

If T does not contain a ref or closure type, it is isolated. Else the syntactic structure of x is analyzed:

+
  • Literals like nil, 4, "abc" are isolated.
  • +
  • A local variable or a routine parameter is isolated if either of these conditions is true:
    1. Its type is annotated with the .sendable pragma. Note Isolated[T] is annotated as .sendable.
    2. +
    3. Its type contains the potentially dangerous ref and proc {.closure} types only in places that are protected via a .sendable container.
    4. +
    +
  • +
  • An array constructor [x...] is isolated if every element x is isolated.
  • +
  • An object constructor Obj(x...) is isolated if every element x is isolated.
  • +
  • An if or case expression is isolated if all possible values the expression may return are isolated.
  • +
  • A type conversion C(x) is isolated if x is isolated. Analogous for cast expressions.
  • +
  • A function call f(x...) is isolated if f is .noSideEffect and for every argument x:
    • x is isolated or
    • +
    • f's return type cannot alias x's type. This is checked via a form of alias analysis as explained in the next paragraph.
    • +
    +
  • +
+ +

Alias analysis

We start with an important, simple case that must be valid: Sending the result of parseJson to a channel. Since the signature is func parseJson(input: string): JsonNode it is easy to see that JsonNode can never simply be a view into input which is a string.

+

A different case is the identity function id, send id(myJsonGraph) must be invalid because we do not know how many aliases into myJsonGraph exist elsewhere.

+

In general type A can alias type T if:

+
  • A and T are the same types.
  • +
  • A is a distinct type derived from T.
  • +
  • A is a field inside T if T is a final object type.
  • +
  • T is an inheritable object type. (An inherited type could always contain a field: A).
  • +
  • T is a closure type. Reason: T's environment can contain a field of type A.
  • +
  • A is the element type of T if T is an array, sequence or pointer type.
  • +
+ +

Sendable pragma

A container type can be marked as .sendable. .sendable declares that the type encapsulates a ref type effectively so that a variable of this container type can be used in an isolate context:

+

type
+  Isolated*[T] {.sendable.} = object ## Isolated data can only be moved, not copied.
+    value: T
+
+proc `=copy`*[T](dest: var Isolated[T]; src: Isolated[T]) {.error.}
+
+proc `=sink`*[T](dest: var Isolated[T]; src: Isolated[T]) {.inline.} =
+  # delegate to value's sink operation
+  `=sink`(dest.value, src.value)
+
+proc `=destroy`*[T](dest: var Isolated[T]) {.inline.} =
+  # delegate to value's destroy operation
+  `=destroy`(dest.value)

+

The .sendable pragma itself is an experimenal, unchecked, unsafe annotation. It is currently only used by Isolated[T].

+ +

Virtual pragma

virtual is designed to extend or create virtual functions when targeting the cpp backend. When a proc is marked with virtual, it forward declares the proc header within the type's body.

+

Here's an example of how to use the virtual pragma:

+

proc newCpp*[T](): ptr T {.importcpp: "new '*0()".}
+type
+  Foo = object of RootObj
+  FooPtr = ptr Foo
+  Boo = object of Foo
+  BooPtr = ptr Boo
+
+proc salute(self: FooPtr) {.virtual.} =
+  echo "hello foo"
+
+proc salute(self: BooPtr) {.virtual.} =
+  echo "hello boo"
+
+let foo = newCpp[Foo]()
+let boo = newCpp[Boo]()
+let booAsFoo = cast[FooPtr](newCpp[Boo]())
+
+foo.salute() # prints hello foo
+boo.salute() # prints hello boo
+booAsFoo.salute() # prints hello boo
In this example, the salute function is virtual in both Foo and Boo types. This allows for polymorphism.

+

The virtual pragma also supports a special syntax to express Cpp constraints. Here's how it works:

+

$1 refers to the function name 'idx refers to the type of the argument at the position idx. Where idx = 1 is the this argument. #idx refers to the argument name.

+

The return type can be referred to as -> '0, but this is optional and often not needed.

+

{.emit:"""/*TYPESECTION*/
+#include <iostream>
+ class CppPrinter {
+ public:
+   
+   virtual void printConst(char* message) const {
+       std::cout << "Const Message: " << message << std::endl;
+   }
+   virtual void printConstRef(char* message, const int& flag) const {
+       std::cout << "Const Ref Message: " << message << std::endl;
+   }
+};
+""".}
+
+type
+ CppPrinter {.importcpp, inheritable.} = object
+ NimPrinter {.exportc.} = object of CppPrinter
+
+proc printConst(self: CppPrinter; message:cstring) {.importcpp.}
+CppPrinter().printConst(message)
+
+# override is optional.
+proc printConst(self: NimPrinter; message: cstring) {.virtual: "$1('2 #2) const override".} =
+ echo "NimPrinter: " & $message
+
+proc printConstRef(self: NimPrinter; message: cstring; flag:int32) {.virtual: "$1('2 #2, const '3& #3 ) const override".} =
+ echo "NimPrinterConstRef: " & $message
+
+NimPrinter().printConst(message)
+var val: int32 = 10
+NimPrinter().printConstRef(message, val)
+

+ +

Constructor pragma

The constructor pragma can be used in two ways: in conjunction with importcpp to import a C++ constructor, and to declare constructors that operate similarly to virtual.

+

Consider:

+

type Foo* = object
+  x: int32
+
+proc makeFoo(x: int32): Foo {.constructor.} =
+  result.x = x

+

It forward declares the constructor in the type definition. When the constructor has parameters, it also generates a default constructor. One can avoid this behaviour by using noDecl in a default constructor.

+

Like virtual, constructor also supports a syntax that allows to express C++ constraints.

+

For example:

+

{.emit:"""/*TYPESECTION*/
+struct CppClass {
+  int x;
+  int y;
+  CppClass(int inX, int inY) {
+    this->x = inX;
+    this->y = inY;
+  }
+  //CppClass() = default;
+};
+""".}
+
+type
+  CppClass* {.importcpp, inheritable.} = object
+    x: int32
+    y: int32
+  NimClass* = object of CppClass
+
+proc makeNimClass(x: int32): NimClass {.constructor:"NimClass('1 #1) : CppClass(0, #1)".} =
+  result.x = x
+
+# Optional: define the default constructor explicitly
+proc makeCppClass(): NimClass {.constructor: "NimClass() : CppClass(0, 0)".} =
+  result.x = 1

+

In the example above CppClass has a deleted default constructor. Notice how by using the constructor syntax, one can call the appropriate constructor.

+

Notice when calling a constructor in the section of a global variable initialization, it will be called before NimMain meaning Nim is not fully initialized.

+ +

Constructor Initializer

By default Nim initializes importcpp types with {}. This can be problematic when importing types with a deleted default constructor. In order to avoid this, one can specify default values for a constructor by specifying default values for the proc params in the constructor proc.

+

For example:

+

+{.emit: """/*TYPESECTION*/
+struct CppStruct {
+  CppStruct(int x, char* y): x(x), y(y){}
+  int x;
+  char* y;
+};
+""".}
+type
+  CppStruct {.importcpp, inheritable.} = object
+
+proc makeCppStruct(a: cint = 5, b:cstring = "hello"): CppStruct {.importcpp: "CppStruct(@)", constructor.}
+
+(proc (s: CppStruct) = echo "hello")(makeCppStruct())
+# If one removes a default value from the constructor and passes it to the call explicitly, the C++ compiler will complain.
+
Skip initializers in fields members

+
+

By using noInit in a type or field declaration, the compiler will skip the initializer. By doing so one can explicitly initialize those values in the constructor of the type owner.

+

For example:

+

+{.emit: """/*TYPESECTION*/
+  struct Foo {
+    Foo(int a){};
+  };
+  struct Boo {
+    Boo(int a){};
+  };
+  
+  """.}
+
+type
+  Foo {.importcpp.} = object
+  Boo {.importcpp, noInit.} = object
+  Test {.exportc.} = object
+    foo {.noInit.}: Foo
+    boo: Boo
+
+proc makeTest(): Test {.constructor: "Test() : foo(10), boo(1)".} =
+  discard
+
+proc main() =
+  var t = makeTest()
+
+main()
+

+

Will produce:

+

+struct Test {
+        Foo foo;
+        Boo boo;
+  N_LIB_PRIVATE N_NOCONV(, Test)(void);
+};
+

+

Notice that without noInit it would produce Foo foo {} and Boo boo {}

+ +

Member pragma

Like the constructor and virtual pragmas, the member pragma can be used to attach a procedure to a C++ type. It's more flexible than the virtual pragma in the sense that it accepts not only names but also operators and destructors.

+

For example:

+

proc print(s: cstring) {.importcpp: "printf(@)", header: "<stdio.h>".}
+
+type
+  Doo {.exportc.} = object
+    test: int
+
+proc memberProc(f: Doo) {.member.} =
+  echo $f.test
+
+proc destructor(f: Doo) {.member: "~'1()", used.} =
+  print "destructing\n"
+
+proc `==`(self, other: Doo): bool {.member: "operator==('2 const & #2) const -> '0".} =
+  self.test == other.test
+
+let doo = Doo(test: 2)
+doo.memberProc()
+echo doo == Doo(test: 1)
+

+

Will print:

+

2
+false
+destructing
+destructing

+

Notice how the C++ destructor is called automatically. Also notice the double implementation of == as an operator in Nim but also in C++. This is useful if you need the type to match some C++ concept or trait when interoping.

+

A side effect of being able to declare C++ operators, is that you can now also create a C++ functor to have seamless interop with C++ lambdas (syntactic sugar for functors).

+

For example:

+

type
+  NimFunctor = object
+    discard
+proc invoke(f: NimFunctor; n: int) {.member: "operator ()('2 #2)".} =
+  echo "FunctorSupport!"
+
+{.experimental: "callOperator".}
+proc `()`(f: NimFunctor; n:int) {.importcpp: "#(@)" .}
+NimFunctor()(1)
Notice we use the overload of () to have the same semantics in Nim, but on the importcpp we import the functor as a function. This allows to easy interop with functions that accepts for example a const operator in its signature.

+ +

Injected symbols in generic procs and templates

With the experimental option openSym, captured symbols in generic routine and template bodies may be replaced by symbols injected locally by templates/macros at instantiation time. bind may be used to keep the captured symbols over the injected ones regardless of enabling the options, but other methods like renaming the captured symbols should be used instead so that the code is not affected by context changes.

+

Since this change may affect runtime behavior, the experimental switch openSym needs to be enabled; and a warning is given in the case where an injected symbol would replace a captured symbol not bound by bind and the experimental switch isn't enabled.

+

const value = "captured"
+template foo(x: int, body: untyped): untyped =
+  let value {.inject.} = "injected"
+  body
+
+proc old[T](): string =
+  foo(123):
+    return value # warning: a new `value` has been injected, use `bind` or turn on `experimental:openSym`
+echo old[int]() # "captured"
+
+template oldTempl(): string =
+  block:
+    foo(123):
+      value # warning: a new `value` has been injected, use `bind` or turn on `experimental:openSym`
+echo oldTempl() # "captured"
+
+{.experimental: "openSym".}
+
+proc bar[T](): string =
+  foo(123):
+    return value
+assert bar[int]() == "injected" # previously it would be "captured"
+
+proc baz[T](): string =
+  bind value
+  foo(123):
+    return value
+assert baz[int]() == "captured"
+
+template barTempl(): string =
+  block:
+    foo(123):
+      value
+assert barTempl() == "injected" # previously it would be "captured"
+
+template bazTempl(): string =
+  bind value
+  block:
+    foo(123):
+      value
+assert bazTempl() == "captured"

+

This option also generates a new node kind nnkOpenSym which contains exactly 1 nnkSym node. In the future this might be merged with a slightly modified nnkOpenSymChoice node but macros that want to support the experimental feature should still handle nnkOpenSym, as the node kind would simply not be generated as opposed to being removed.

+

Another experimental switch genericsOpenSym exists that enables this behavior at instantiation time, meaning templates etc can enable it specifically when they are being called. However this does not generate nnkOpenSym nodes (unless the other switch is enabled) and so doesn't reflect the regular behavior of the switch.

+

const value = "captured"
+template foo(x: int, body: untyped): untyped =
+  let value {.inject.} = "injected"
+  {.push experimental: "genericsOpenSym".}
+  body
+  {.pop.}
+
+proc bar[T](): string =
+  foo(123):
+    return value
+echo bar[int]() # "injected"
+
+template barTempl(): string =
+  block:
+    var res: string
+    foo(123):
+      res = value
+    res
+assert barTempl() == "injected"

+ +

VTable for methods

Methods now support implementations based on a VTable by using --experimental:vtables. Note that the option needs to enabled globally. The virtual method table is stored in the type info of an object, which is an array of function pointers.

+

method foo(x: Base, ...) {.base.}
+method foo(x: Derived, ...) {.base.}

+

It roughly generates a dispatcher like

+

proc foo_dispatch(x: Base, ...) =
+  x.typeinfo.vtable[method_index](x, ...) # method_index is the index of the sorted order of a method

+

Methods are required to be in the same module where their type has been defined.

+

# types.nim
+type
+  Base* = ref object

+

import types
+
+method foo(x: Base) {.base.} = discard

+

It gives an error: method foo can be defined only in the same module with its type (Base).

+ +

asmSyntax pragma

The asmSyntax pragma is used to specify target inline assembler syntax in an asm statement.

+

It prevents compiling code with different of the target CC inline asm syntax, i.e. it will not allow gcc inline asm code to be compiled with vcc.

+

proc nothing() =
+  asm {.asmSyntax: "gcc".}"""
+    nop
+  """

+

The current C(C++) backend implementation cannot generate code for gcc and for vcc at the same time. For example, {.asmSyntax: "vcc".} with the ICC compiler will not generate code with intel asm syntax, even though ICC can use both gcc-like and vcc-like asm.

+ +

Type-bound overloads

With the experimental option --experimental:typeBoundOps, each "root" nominal type (namely object, enum, distinct, direct Foo = ref object types as well as their generic versions) can have operations attached to it. Exported top-level routines declared in the same scope as a nominal type with a parameter having a type directly deriving from that nominal type (i.e. with var/sink/typedesc modifiers or being in a generic constraint) are considered "attached" to the respective nominal type. This applies to every parameter regardless of placement.

+

When a call to a symbol is openly overloaded and overload matching starts, for all arguments in the call that have already undergone type checking, routines with the same name attached to the root nominal type (if it exists) of each given argument are added as a candidate to the overload match. This also happens as arguments gradually get typed after every match to an overload. This is so that the only overloads considered out of scope are attached to the types of the given arguments, and that matches to untyped or missing parameters are not influenced by outside overloads.

+

If no overloads with a given name are in scope, then overload matching will not begin, and so type-bound overloads are not considered for that name. Similarly, if the only overloads with a given name require a parameter to be untyped or missing, then type-bound overloads will not be considered for the argument in that position. Generally this means that a "base" overload with a compliant signature should be in scope so that type-bound overloads can be used.

+

In the case of ambiguity between distinct local/imported and type-bound symbols in overload matching, type-bound symbols are considered as a less specific scope than imports.

+

An example with the hash interface in the standard library is as follows:

+

# objs.nim
+import std/hashes
+
+type
+  Obj* = object
+    x*, y*: int
+    z*: string # to be ignored for equality
+
+proc `==`*(a, b: Obj): bool =
+  a.x == b.x and a.y == b.y
+
+proc hash*(a: Obj): Hash =
+  $!(hash(a.x) &! hash(a.y))
+
+# here both `==` and `hash` are attached to Obj
+# 1. they are both exported
+# 2. they are in the same scope as Obj
+# 3. they have parameters with types directly deriving from Obj
+# 4. Obj is nominal

+

# main.nim
+{.experimental: "typeBoundOps".}
+from objs import Obj # objs.hash, objs.`==` not imported
+import std/tables
+# tables use `hash`, only using the overloads in `std/hashes` and
+# the ones in instantiation scope (in this case, there are none)
+
+var t: Table[Obj, int]
+# because tables use `hash` and `==` in a compliant way,
+# the overloads bound to Obj are also considered, and in this case match best
+t[Obj(x: 3, y: 4, z: "debug")] = 34
+# if `hash` for all objects as in `std/hashes` was used, this would error:
+echo t[Obj(x: 3, y: 4, z: "ignored")] # 34

+

Another example, this time with $ and indirect imports:

+

# foo.nim
+type Foo* = object
+  x*, y*: int
+
+proc `$`*(f: Foo): string =
+  "Foo(" & $f.x & ", " & $f.y & ")"

+

# bar.nim
+import foo
+
+proc makeFoo*(x, y: int): Foo =
+  Foo(x: x, y: y)
+
+proc useFoo*(f: Foo) =
+  echo "used: ", f # directly calls `foo.$` from scope

+

# debugger.nim
+proc debug*[T](obj: T) =
+  echo "debugging: ", obj # calls generic `$`

+

# main.nim
+{.experimental: "typeBoundOps".}
+import bar, debugger # `foo` not imported, so `foo.$` not in scope
+
+let f = makeFoo(123, 456)
+useFoo(f) # used: Foo(123, 456)
+debug(f) # debugging: Foo(123, 456)

+

+ +
+
+ + +
+
+ + + + diff --git a/manual_experimental.idx b/manual_experimental.idx new file mode 100644 index 0000000000000..db2932fcda591 --- /dev/null +++ b/manual_experimental.idx @@ -0,0 +1,89 @@ +markupTitle Nim Experimental Features manual_experimental.html Nim Experimental Features 0 +heading About this document manual_experimental.html#about-this-document About this document 0 +heading Void type manual_experimental.html#void-type Void type 0 +heading Generic nimdefine pragma manual_experimental.html#generic-nimdefine-pragma Generic define pragma 0 +heading Top-down type inference manual_experimental.html#topminusdown-type-inference Top-down type inference 0 +heading Inferred generic parameters manual_experimental.html#topminusdown-type-inference-inferred-generic-parameters Inferred generic parameters 0 +heading Sequence literals manual_experimental.html#topminusdown-type-inference-sequence-literals Sequence literals 0 +heading Package level objects manual_experimental.html#package-level-objects Package level objects 0 +idx incomplete manual_experimental.html#incomplete_1 Package level objects 0 +heading Importing private symbols manual_experimental.html#importing-private-symbols Importing private symbols 0 +heading Code reordering manual_experimental.html#code-reordering Code reordering 0 +heading Special Operators manual_experimental.html#special-operators Special Operators 0 +heading dot operators manual_experimental.html#special-operators-dot-operators dot operators 0 +heading operator nim. manual_experimental.html#special-operators-operator-nimdot operator . 0 +heading operator nim.() manual_experimental.html#special-operators-operator-nimdot operator .() 0 +heading operator nim.= manual_experimental.html#special-operators-operator-nimdoteq operator .= 0 +heading Call operator manual_experimental.html#special-operators-call-operator Call operator 0 +heading Extended macro pragmas manual_experimental.html#extended-macro-pragmas Extended macro pragmas 0 +heading Symbols as template/macro calls (alias syntax) manual_experimental.html#symbols-as-templateslashmacro-calls-alias-syntax Symbols as template/macro calls (alias syntax) 0 +heading Not nil annotation manual_experimental.html#not-nil-annotation Not nil annotation 0 +heading Strict not nil checking manual_experimental.html#strict-not-nil-checking Strict not nil checking 0 +heading nil manual_experimental.html#strict-not-nil-checking-nil nil 0 +heading not nil manual_experimental.html#strict-not-nil-checking-not-nil not nil 0 +heading local turn on/off manual_experimental.html#strict-not-nil-checking-local-turn-onslashoff local turn on/off 0 +heading nilability state manual_experimental.html#strict-not-nil-checking-nilability-state nilability state 0 +heading type nilability manual_experimental.html#strict-not-nil-checking-type-nilability type nilability 0 +heading params rules manual_experimental.html#strict-not-nil-checking-params-rules params rules 0 +heading assignment rules manual_experimental.html#strict-not-nil-checking-assignment-rules assignment rules 0 +heading call args rules manual_experimental.html#strict-not-nil-checking-call-args-rules call args rules 0 +heading branches rules manual_experimental.html#strict-not-nil-checking-branches-rules branches rules 0 +heading compound expressions: field, index expressions manual_experimental.html#strict-not-nil-checking-compound-expressionscolon-field-index-expressions compound expressions: field, index expressions 0 +heading element tracking manual_experimental.html#strict-not-nil-checking-element-tracking element tracking 0 +heading unstructured control flow rules manual_experimental.html#strict-not-nil-checking-unstructured-control-flow-rules unstructured control flow rules 0 +heading aliasing manual_experimental.html#strict-not-nil-checking-aliasing aliasing 0 +heading warnings and errors manual_experimental.html#strict-not-nil-checking-warnings-and-errors warnings and errors 0 +heading Aliasing restrictions in parameter passing manual_experimental.html#aliasing-restrictions-in-parameter-passing Aliasing restrictions in parameter passing 0 +heading Strict funcs manual_experimental.html#strict-funcs Strict funcs 0 +heading View types manual_experimental.html#view-types View types 0 +heading Path expressions manual_experimental.html#view-types-path-expressions Path expressions 0 +heading Start of a borrow manual_experimental.html#view-types-start-of-a-borrow Start of a borrow 0 +heading End of a borrow manual_experimental.html#view-types-end-of-a-borrow End of a borrow 0 +heading Reborrows manual_experimental.html#view-types-reborrows Reborrows 0 +heading Algorithm manual_experimental.html#view-types-algorithm Algorithm 0 +heading Concepts manual_experimental.html#concepts Concepts 0 +heading Concept diagnostics manual_experimental.html#concepts-concept-diagnostics Concept diagnostics 0 +heading Generic concepts and type binding rules manual_experimental.html#concepts-generic-concepts-and-type-binding-rules Generic concepts and type binding rules 0 +heading Concept derived values manual_experimental.html#concepts-concept-derived-values Concept derived values 0 +heading Concept refinement manual_experimental.html#concepts-concept-refinement Concept refinement 0 +heading Dynamic arguments for bindSym manual_experimental.html#dynamic-arguments-for-bindsym Dynamic arguments for bindSym 0 +heading Term rewriting macros manual_experimental.html#term-rewriting-macros Term rewriting macros 0 +heading Parameter constraints manual_experimental.html#term-rewriting-macros-parameter-constraints Parameter constraints 0 +idx parameter constraint manual_experimental.html#parameter-constraint_1 Parameter constraints 0 +heading Pattern operators manual_experimental.html#term-rewriting-macros-pattern-operators Pattern operators 0 +heading The nim| operator manual_experimental.html#pattern-operators-the-nimbar-operator The | operator 0 +heading The nim{} operator manual_experimental.html#pattern-operators-the-nim-operator The {} operator 0 +heading The nim~ operator manual_experimental.html#pattern-operators-the-nimtilde-operator The ~ operator 0 +heading The nim* operator manual_experimental.html#pattern-operators-the-nimstar-operator The * operator 0 +heading The nim** operator manual_experimental.html#pattern-operators-the-nimstarstar-operator The ** operator 0 +heading Parameters manual_experimental.html#term-rewriting-macros-parameters Parameters 0 +heading noRewrite pragma manual_experimental.html#term-rewriting-macros-norewrite-pragma noRewrite pragma 0 +heading Example: Partial evaluation manual_experimental.html#term-rewriting-macros-examplecolon-partial-evaluation Example: Partial evaluation 0 +heading Example: Hoisting manual_experimental.html#term-rewriting-macros-examplecolon-hoisting Example: Hoisting 0 +heading AST based overloading manual_experimental.html#ast-based-overloading AST based overloading 0 +heading Parallel & Spawn manual_experimental.html#parallel-amp-spawn Parallel & Spawn 0 +idx Structured manual_experimental.html#structured_1 Parallel & Spawn 0 +idx Unstructured manual_experimental.html#unstructured_1 Parallel & Spawn 0 +heading Spawn statement manual_experimental.html#parallel-amp-spawn-spawn-statement Spawn statement 0 +idx spawn manual_experimental.html#spawn_1 Spawn statement 0 +idx data flow variable manual_experimental.html#data-flow-variable_1 Spawn statement 0 +heading Parallel statement manual_experimental.html#parallel-amp-spawn-parallel-statement Parallel statement 0 +idx disjoint checker manual_experimental.html#disjoint-checker_1 Parallel statement 0 +heading Strict definitions and nimout parameters manual_experimental.html#strict-definitions-and-nimout-parameters Strict definitions and out parameters 0 +heading nimout parameters manual_experimental.html#strict-definitions-and-nimout-parameters-nimout-parameters out parameters 0 +heading Out parameters and exception handling manual_experimental.html#strict-definitions-and-nimout-parameters-out-parameters-and-exception-handling Out parameters and exception handling 0 +heading Out parameters and inheritance manual_experimental.html#strict-definitions-and-nimout-parameters-out-parameters-and-inheritance Out parameters and inheritance 0 +heading Strict case objects manual_experimental.html#strict-case-objects Strict case objects 0 +heading Quirky routines manual_experimental.html#quirky-routines Quirky routines 0 +heading Threading under ARC/ORC manual_experimental.html#threading-under-arcslashorc Threading under ARC/ORC 0 +heading Isolation manual_experimental.html#threading-under-arcslashorc-isolation Isolation 0 +heading Alias analysis manual_experimental.html#threading-under-arcslashorc-alias-analysis Alias analysis 0 +heading Sendable pragma manual_experimental.html#threading-under-arcslashorc-sendable-pragma Sendable pragma 0 +heading Virtual pragma manual_experimental.html#virtual-pragma Virtual pragma 0 +heading Constructor pragma manual_experimental.html#constructor-pragma Constructor pragma 0 +heading Constructor Initializer manual_experimental.html#constructor-initializer Constructor Initializer 0 +heading Member pragma manual_experimental.html#member-pragma Member pragma 0 +heading Injected symbols in generic procs and templates manual_experimental.html#injected-symbols-in-generic-procs-and-templates Injected symbols in generic procs and templates 0 +heading VTable for methods manual_experimental.html#vtable-for-methods VTable for methods 0 +heading asmSyntax pragma manual_experimental.html#asmsyntax-pragma asmSyntax pragma 0 +heading Type-bound overloads manual_experimental.html#typeminusbound-overloads Type-bound overloads 0 diff --git a/manual_experimental_strictnotnil.html b/manual_experimental_strictnotnil.html new file mode 100644 index 0000000000000..23c2d0c3bf458 --- /dev/null +++ b/manual_experimental_strictnotnil.html @@ -0,0 +1,145 @@ + + + + + + + +doc/manual_experimental_strictnotnil + + + + + + + + + + + + + + + + +
+
+

doc/manual_experimental_strictnotnil

+ +

Strict not nil checking

Note: This feature is experimental, you need to enable it with

+

{.experimental: "strictNotNil".}

+

or

+

nim c --experimental:strictNotNil <program>

+

In the second case it would check builtin and imported modules as well.

+

It checks the nilability of ref-like types and makes dereferencing safer based on flow typing and not nil annotations.

+

Its implementation is different than the notnil one: defined under strictNotNil. Keep in mind the difference in option names, be careful with distinguishing them.

+

We check several kinds of types for nilability:

+
  • ref types
  • +
  • pointer types
  • +
  • proc types
  • +
  • cstrings
  • +
+ +

nil

The default kind of nilability types is the nilable kind: they can have the value nil. If you have a non-nilable type T, you can use T nil to get a nilable type for it.

+ +

not nil

You can annotate a type where nil isn't a valid value with not nil.

+

  type
+    NilableObject = ref object
+      a: int
+    Object = NilableObject not nil
+    
+    Proc = (proc (x, y: int))
+  
+  proc p(x: Object) =
+    echo x.a # ensured to dereference without an error
+  # compiler catches this:
+  p(nil)
+  # and also this:
+  var x: NilableObject
+  if x.isNil:
+    p(x)
+  else:
+    p(x) # ok

+

If a type can include nil as a valid value, dereferencing values of the type is checked by the compiler: if a value which might be nil is dereferenced, this produces a warning by default, you can turn this into an error using the compiler options --warningAsError:strictNotNil.

+

If a type is nilable, you should dereference its values only after a isNil or equivalent check.

+ +

local turn on/off

You can still turn off nil checking on function/module level by using a {.strictNotNil: off.} pragma.

+ +

nilability state

Currently, a nilable value can be Safe, MaybeNil or Nil : we use internally Parent and Unreachable but this is an implementation detail(a parent layer has the actual nilability).

+
  • Safe means it shouldn't be nil at that point: e.g. after assignment to a non-nil value or not a.isNil check
  • +
  • MaybeNil means it might be nil, but it might not be nil: e.g. an argument, a call argument or a value after an if and else.
  • +
  • Nil means it should be nil at that point; e.g. after an assignment to nil or a .isNil check.
  • +
  • Unreachable means it shouldn't be possible to access this in this branch: so we do generate a warning as well.
  • +
+

We show an error for each dereference ([], .field, [index] () etc.) which is of a tracked expression which is in MaybeNil or Nil state.

+ +

type nilability

Types are either nilable or non-nilable. When you pass a param or a default value, we use the type : for nilable types we return MaybeNil and for non-nilable Safe.

+ +

params rules

Param's nilability is detected based on type nilability. We use the type of the argument to detect the nilability.

+ +

assignment rules

Let's say we have left = right.

+

When we assign, we pass the right's nilability to the left's expression. There should be special handling of aliasing and compound expressions which we specify in their sections. (Assignment is a possible alias move or move out).

+ +

call args rules

When we call with arguments, we have two cases when we might change the nilability.

+

callByVar(a)

+

Here callByVar can re-assign a, so this might change a's nilability, so we change it to MaybeNil. This is also a possible aliasing move out (moving out of a current alias set).

+

call(a)

+

Here call can change a field or element of a, so if we have a dependant expression of a : e.g. a.field. Dependants become MaybeNil.

+ +

branches rules

Branches are the reason we do nil checking like this: with flow checking. Sources of branching are if, while, for, and, or, case, try and combinations with return, break, continue and raise

+

We create a new layer/"scope" for each branch where we map expressions to nilability. This happens when we "fork": usually on the beginning of a construct. When branches "join" we usually unify their expression maps or/and nilabilities.

+

Merging usually merges maps and alias sets: nilabilities are merged like this:

+

template union(l: Nilability, r: Nilability): Nilability =
+  ## unify two states
+  if l == r:
+    l
+  else:
+    MaybeNil

+

Special handling is for .isNil and == nil, also for not, and and or.

+

not reverses the nilability, and is similar to "forking" : the right expression is checked in the layer resulting from the left one and or is similar to "merging": the right and left expression should be both checked in the original layer.

+

isNil, == nil make expressions Nil. If there is a not or != nil, they make them Safe. We also reverse the nilability in the opposite branch: e.g. else.

+ +

compound expressions: field, index expressions

We want to track also field(dot) and index(bracket) expressions.

+

We track some of those compound expressions which might be nilable as dependants of their bases: a.field is changed if a is moved (re-assigned), similarly a[index] is dependent on a and a.field.field on a.field.

+

When we move the base, we update dependants to MaybeNil. Otherwise, we usually start with type nilability.

+

When we call args, we update the nilability of their dependants to MaybeNil as the calls usually can change them. We might need to check for strictFuncs pure funcs and not do that then.

+

For field expressions a.field, we calculate an integer value based on a hash of the tree and just accept equivalent trees as equivalent expressions.

+

For item expression a[index], we also calculate an integer value based on a hash of the tree and accept equivalent trees as equivalent expressions: for static values only. For now, we support only constant indices: we don't track expression with no-const indices. For those we just report a warning even if they are safe for now: one can use a local variable to workaround. For loops this might be annoying: so one should be able to turn off locally the warning using the {.warning[StrictNotNil]:off.}.

+

For bracket expressions, in the future we might count a[<any>] as the same general expression. This means we should the index but otherwise handle it the same for assign (maybe "aliasing" all the non-static elements) and differentiate only for static: e.g. a[0] and a[1].

+ +

element tracking

When we assign an object construction, we should track the fields as well:

+

var a = Nilable(field: Nilable()) # a : Safe, a.field: Safe

+

Usually we just track the result of an expression: probably this should apply for elements in other cases as well. Also related to tracking initialization of expressions/fields.

+ +

unstructured control flow rules

Unstructured control flow keywords as return, break, continue, raise mean that we jump from a branch out. This means that if there is code after the finishing of the branch, it would be run if one hasn't hit the direct parent branch of those: so it is similar to an else. In those cases we should use the reverse nilabilities for the local to the condition expressions. E.g.

+

for a in c:
+  if not a.isNil:
+    b()
+    break
+  code # here a: Nil , because if not, we would have breaked

+ +

aliasing

We support alias detection for local expressions.

+

We track sets of aliased expressions. We start with all nilable local expressions in separate sets. Assignments and other changes to nilability can move / move out expressions of sets.

+

move: Moving left to right means we remove left from its current set and unify it with the right's set. This means it stops being aliased with its previous aliases.

+

var left = b
+left = right # moving left to right

+

move out: Moving out left might remove it from the current set and ensure that it's in its own set as a single element. e.g.

+

var left = b
+left = nil # moving out

+ +

warnings and errors

We show an error for each dereference ([], .field, [index] () etc.) which is of a tracked expression which is in MaybeNil or Nil state.

+

We might also show a history of the transitions and the reasons for them that might change the nilability of the expression.

+ + + + +
+
+ + + + diff --git a/manual_experimental_strictnotnil.idx b/manual_experimental_strictnotnil.idx new file mode 100644 index 0000000000000..5942615bd58b4 --- /dev/null +++ b/manual_experimental_strictnotnil.idx @@ -0,0 +1,16 @@ +markupTitle manual_experimental_strictnotnil.md manual_experimental_strictnotnil.html manual_experimental_strictnotnil.md 0 +heading Strict not nil checking manual_experimental_strictnotnil.html#strict-not-nil-checking Strict not nil checking 0 +heading nil manual_experimental_strictnotnil.html#nil nil 0 +heading not nil manual_experimental_strictnotnil.html#not-nil not nil 0 +heading local turn on/off manual_experimental_strictnotnil.html#local-turn-onslashoff local turn on/off 0 +heading nilability state manual_experimental_strictnotnil.html#nilability-state nilability state 0 +heading type nilability manual_experimental_strictnotnil.html#type-nilability type nilability 0 +heading params rules manual_experimental_strictnotnil.html#params-rules params rules 0 +heading assignment rules manual_experimental_strictnotnil.html#assignment-rules assignment rules 0 +heading call args rules manual_experimental_strictnotnil.html#call-args-rules call args rules 0 +heading branches rules manual_experimental_strictnotnil.html#branches-rules branches rules 0 +heading compound expressions: field, index expressions manual_experimental_strictnotnil.html#compound-expressionscolon-field-index-expressions compound expressions: field, index expressions 0 +heading element tracking manual_experimental_strictnotnil.html#element-tracking element tracking 0 +heading unstructured control flow rules manual_experimental_strictnotnil.html#unstructured-control-flow-rules unstructured control flow rules 0 +heading aliasing manual_experimental_strictnotnil.html#aliasing aliasing 0 +heading warnings and errors manual_experimental_strictnotnil.html#warnings-and-errors warnings and errors 0 diff --git a/markdown_rst.html b/markdown_rst.html new file mode 100644 index 0000000000000..93b12f5fc287c --- /dev/null +++ b/markdown_rst.html @@ -0,0 +1,293 @@ + + + + + + + +Nim-flavored Markdown and reStructuredText + + + + + + + + + + + + + + + + +
+
+

Nim-flavored Markdown and reStructuredText

+
+ +
+ Source   +Edit   + +
+ +

+ +
Author:Andrey Makarov
Version:2.2.1

Both Markdown (md) and reStructuredText (RST) are markup languages whose goal is to typeset texts with complex structure, formatting and references using simple plaintext representation.

+ +

Command line usage

Usage (to convert Markdown into HTML):

+

nim md2html markdown_rst.md

+

Output:

+
You're reading it!
+

The md2tex command is invoked identically to md2html, but outputs a .tex file instead of .html.

+

These tools embedded into Nim compiler; the compiler can output the result to HTML [1] or Latex [2].

+
+
  commands nim doc for *.nim files and nim rst2html for *.rst files +
+
  commands nim doc2tex for *.nim and nim rst2tex for *.rst. +
+
+

Full list of supported commands:

+ + + + + + + + +
commandruns on...input formatoutput format
nim md2htmlstandalone md files.md.html HTML
nim md2texsamesame.tex LaTeX
nim rst2htmlstandalone rst files.rst.html HTML
nim rst2texsamesame.tex LaTeX
nim docdocumentation comments.nim.html HTML
nim doc2texsamesame.tex LaTeX
nim jsondocsamesame.json JSON
+

Basic markup

If you are new to Markdown/RST please consider reading the following:

+
  1. Markdown Basic Syntax
  2. +
  3. a long specification of Markdown: CommonMark Spec
  4. +
  5. a short quick introduction to RST
  6. +
  7. an RST reference: a comprehensive cheatsheet for RST
  8. +
  9. a more formal 50-page RST specification.
  10. +
+ +

Features

A large subset is implemented with some limitations and additional Nim-specific features.

+

Supported common RST/Markdown features:

+
  • body elements
    • sections
    • +
    • transitions
    • +
    • paragraphs
    • +
    • bullet lists using +, *, -
    • +
    • enumerated lists using arabic numerals or alphabet characters: 1. ... 2. ... or a. ... b. ... or A. ... B. ...
    • +
    • footnotes (including manually numbered, auto-numbered, auto-numbered with label, and auto-symbol footnotes) and citations
    • +
    • field lists
    • +
    • option lists
    • +
    • quoted literal blocks
    • +
    • line blocks
    • +
    • simple tables
    • +
    • directives (see official documentation in RST directives list):
      • image, figure for including images and videos
      • +
      • code
      • +
      • contents (table of contents), container, raw
      • +
      • include
      • +
      • admonitions: "attention", "caution", "danger", "error", "hint", "important", "note", "tip", "warning", "admonition"
      • +
      • substitution definitions: replace and image
      • +
      +
    • +
    • comments
    • +
    +
  • +
  • inline markup
    • emphasis, strong emphasis, inline literals, hyperlink references (including embedded URI), substitution references, standalone hyperlinks, internal links (inline and outline)
    • +
    • `interpreted text` with roles :literal:, :strong:, emphasis, :sub:/:subscript:, :sup:/:superscript: (see RST roles list for description).
    • +
    • inline internal targets
    • +
    +
  • +
+ +

RST mode only features

  • RST syntax for definition lists (that is additional indentation after a definition line)
  • +
  • indented literal blocks starting from ::
  • +
+ +

Markdown-specific features

  • Markdown tables
  • +
  • Markdown code blocks. For them the same additional arguments as for RST code blocks can be provided (e.g. test or number-lines) but with a one-line syntax like this:
    ```nim test number-lines=10
    +echo "ok"
    +```
    +
  • +
  • Markdown links [...](...)
  • +
  • Pandoc syntax for automatic links [...], see Referencing for description
  • +
  • Pandoc syntax for footnotes, including [^10] (manually numbered) and [^someName] (auto-numbered with a label)
  • +
  • Markdown literal blocks indented by 4 or more spaces
  • +
  • Markdown headlines
  • +
  • Markdown block quotes
  • +
  • Markdown syntax for definition lists
  • +
  • using 1 as auto-enumerator in enumerated lists like RST # (auto-enumerator 1 can not be used with # in the same list)
  • +
+ +

Additional Nim-specific features

  • referencing to definitions in external files, see Markup external referencing section
  • +
  • directives: code-block [3], title, index [3]
  • +
  • predefined roles
    • :nim: (default), :c: (C programming language), :python:, :yaml:, :java:, :cpp: (C++), :csharp (C#). That is every language that highlite supports. They turn on appropriate syntax highlighting in inline code.
      Note: +default role for Nim files is :nim:, for *.rst it's currently :literal:.
      +
    • +
    • generic command line highlighting roles:
      • :cmd: for commands and common shells syntax
      • +
      • :console: the same for interactive sessions (commands should be prepended by $)
      • +
      • :program: for executable names [3] (one can just use :cmd: on single word)
      • +
      • :option: for command line options [3]
      • +
      +
    • +
    • :tok:, a role for highlighting of programming language tokens
    • +
    +
  • +
  • triple emphasis (bold and italic) using ***
  • +
  • :idx: role for `interpreted text` to include the link to this text into an index (example: Nim index).
  • +
  • double slash // in option lists serves as a prefix for any option that starts from a word (without any leading symbols like -, --, /):
    //compile   compile the project
    +//doc       generate documentation
    +

    Here the dummy // will disappear, while options compile and doc will be left in the final document.

    +
  • +
  • emoji / smiley symbols
  • +
+
+
  similar but different from the directives of Python Sphinx directives and Sphinx roles extensions +
+
+
Note: +By default Nim has roSupportMarkdown and roSupportRawDirective turned on.
+
Warning: +Using Nim-specific features can cause other Markdown and RST implementations to fail on your document.
+ +

Referencing

To be able to copy and share links Nim generates anchors for all main document elements:

+
  • headlines (including document title)
  • +
  • footnotes
  • +
  • explicitly set anchors: RST internal cross-references and inline internal targets
  • +
  • Nim symbols (external referencing), see Nim DocGen Tools Guide for details.
  • +
+

But direct use of those anchors have 2 problems:

+
  1. the anchors are usually mangled (e.g. spaces substituted to minus signs, etc).
  2. +
  3. manual usage of anchors is not checked, so it's easy to get broken links inside your project if e.g. spelling has changed for a heading or you use a wrong relative path to your document.
  4. +
+

That's why Nim implementation has syntax for using original labels for referencing. Such referencing can be either local/internal or external:

+
  • Local referencing (inside any given file) is defined by RST standard or Pandoc Markdown User guide.
  • +
  • External (cross-document) referencing is a Nim-specific feature, though it's not really different from local referencing by its syntax.
  • +
+ +

Markup local referencing

There are 2 syntax option available for referencing to objects inside any given file, e.g. for headlines:

+
Markdown                  RST
+
+Some headline             Some headline
+=============             =============
+
+Ref. [Some headline]      Ref. `Some headline`_
+ +

Markup external referencing

The syntax is the same as for local referencing, but the anchors are saved in .idx files, so one needs to generate them beforehand, and they should be loaded by an .. importdoc:: directive. E.g. if we want to reference section "Some headline" in file1.md from file2.md, then file2.md may look like:

+

.. importdoc:: file1.md
+
+Ref. [Some headline]

+

nim md2html --index:only file1.md  # creates ``htmldocs/file1.idx``
+nim md2html file2.md               # creates ``htmldocs/file2.html``

+

To allow cross-references between any files in any order (especially, if circular references are present), it's strongly recommended to make a run for creating all the indexes first:

+

nim md2html --index:only file1.md  # creates ``htmldocs/file1.idx``
+nim md2html --index:only file2.md  # creates ``htmldocs/file2.idx``
+nim md2html file1.md               # creates ``htmldocs/file1.html``
+nim md2html file2.md               # creates ``htmldocs/file2.html``

+

and then one can freely reference any objects as if these 2 documents are actually 1 file.

+ +

Other

+

Idiosyncrasies

Currently we do not aim at 100% Markdown or RST compatibility in inline markup recognition rules because that would provide very little user value. This parser has 2 modes for inline markup:

+
  1. Markdown-like mode which is enabled by roPreferMarkdown option (turned on by default).
    Note: +RST features like directives are still turned on
    +
  2. +
  3. Compatibility mode which is RST rules.
  4. +
+
Note: +in both modes the parser interpretes text between single backticks (code) identically: backslash does not escape; the only exception: \ folowed by ` does escape so that we can always input a single backtick ` in inline code. However that makes impossible to input code with \ at the end in single backticks, one must use double backticks:
`\`   -- WRONG
+``\`` -- GOOD
+So single backticks can always be input: `\`` will turn to ` code
+
+
Attention: +We don't support some obviously poor design choices of Markdown (or RST).
  • no support for the rule of 2 spaces causing a line break in Markdown (use RST "line blocks" syntax for making line breaks)
  • +
  • interpretation of Markdown block quotes is also slightly different, e.g. case
    >>> foo
    +> bar
    +>>baz
    +

    is a single 3rd-level quote foo bar baz in original Markdown, while in Nim we naturally see it as 3rd-level quote foo + 1st level bar + 2nd level baz:

    +

    foo

    bar

    baz

    +
  • +
+
+ +

Limitations

  • no Unicode support in character width calculations
  • +
  • body elements
    • no roman numerals in enumerated lists
    • +
    • no doctest blocks
    • +
    • no grid tables
    • +
    • some directives are missing (check official RST directives list): parsed-literal, sidebar, topic, math, rubric, epigraph, highlights, pull-quote, compound, table, csv-table, list-table, section-numbering, header, footer, meta, class
      • no role directives and no custom interpreted text roles
      • +
      • some standard roles are not supported (check RST roles list)
      • +
      • no generic admonition support
      • +
      +
    • +
    +
  • +
  • inline markup
    • no simple-inline-markup
    • +
    • no embedded aliases
    • +
    +
  • +
+ +

Additional resources

  • See Nim DocGen Tools Guide for the details about nim doc command and idiosyncrasies of documentation markup in .nim files and Nim programming language projects.
  • +
  • See also documentation for rst module -- Nim RST/Markdown parser.
  • +
+

+ +
+
+ + +
+
+ + + + diff --git a/markdown_rst.idx b/markdown_rst.idx new file mode 100644 index 0000000000000..7629f5b659e2b --- /dev/null +++ b/markdown_rst.idx @@ -0,0 +1,16 @@ +markupTitle Nim-flavored Markdown and reStructuredText markdown_rst.html Nim-flavored Markdown and reStructuredText 0 +idx Markdown markdown_rst.html#markdown_1 Nim-flavored Markdown and reStructuredText 0 +idx reStructuredText markdown_rst.html#restructuredtext_1 Nim-flavored Markdown and reStructuredText 0 +heading Command line usage markdown_rst.html#command-line-usage Command line usage 0 +heading Basic markup markdown_rst.html#basic-markup Basic markup 0 +heading Features markdown_rst.html#basic-markup-features Features 0 +heading RST mode only features markdown_rst.html#basic-markup-rst-mode-only-features RST mode only features 0 +heading Markdown-specific features markdown_rst.html#basic-markup-markdownminusspecific-features Markdown-specific features 0 +heading Additional Nim-specific features markdown_rst.html#basic-markup-additional-nimminusspecific-features Additional Nim-specific features 0 +heading Referencing markdown_rst.html#referencing Referencing 0 +heading Markup local referencing markdown_rst.html#referencing-markup-local-referencing Markup local referencing 0 +heading Markup external referencing markdown_rst.html#referencing-markup-external-referencing Markup external referencing 0 +heading Other markdown_rst.html#other Other 0 +heading Idiosyncrasies markdown_rst.html#other-idiosyncrasies Idiosyncrasies 0 +heading Limitations markdown_rst.html#other-limitations Limitations 0 +heading Additional resources markdown_rst.html#other-additional-resources Additional resources 0 diff --git a/marshal.html b/marshal.html new file mode 100644 index 0000000000000..e49c46d2fee7a --- /dev/null +++ b/marshal.html @@ -0,0 +1,234 @@ + + + + + + + +std/marshal + + + + + + + + + + + + + + + + +
+
+

std/marshal

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module contains procs for serialization and deserialization of arbitrary Nim data structures. The serialization format uses JSON.

+

Restriction: For objects, their type is not serialized. This means essentially that it does not work if the object has some other runtime type than its compiletime type.

+ +

Basic usage

+

Example:

+
import std/marshal
+type
+  A = object of RootObj
+  B = object of A
+    f: int
+
+let a: ref A = new(B)
+assert $$a[] == "{}" # not "{f: 0}"
+
+# unmarshal
+let c = to[B]("""{"f": 2}""")
+assert typeof(c) is B
+assert c.f == 2
+
+# marshal
+assert $$c == """{"f": 2}"""
Note: The to and $$ operations are available at compile-time! +

See also

+

+ +
+

Procs

+
+
+
+
proc `$$`[T](x: sink T): string
+
+ +

Returns a string representation of x (serialization, marshalling).

+

Note: to serialize x to JSON use %x from the json module or jsonutils.toJson(x).

+ +

Example:

+
type
+  Foo = object
+    id: int
+    bar: string
+let x = Foo(id: 1, bar: "baz")
+## serialize:
+let y = $$x
+assert y == """{"id": 1, "bar": "baz"}"""
+ Source   +Edit   + +
+
+ +
+
+
+
proc load[T](s: Stream; data: var T)
+
+ + Loads data from the stream s. Raises IOError in case of an error. +

Example:

+
import std/streams
+
+var s = newStringStream("[1, 3, 5]")
+var a: array[3, int]
+load(s, a)
+assert a == [1, 3, 5]
+ Source   +Edit   + +
+
+ +
+
+
+
proc store[T](s: Stream; data: sink T)
+
+ + Stores data into the stream s. Raises IOError in case of an error. +

Example:

+
import std/streams
+
+var s = newStringStream("")
+var a = [1, 3, 5]
+store(s, a)
+s.setPosition(0)
+assert s.readAll() == "[1, 3, 5]"
+ Source   +Edit   + +
+
+ +
+
+
+
proc to[T](data: string): T
+
+ + Reads data and transforms it to a type T (deserialization, unmarshalling). +

Example:

+
type
+  Foo = object
+    id: int
+    bar: string
+let y = """{"id": 1, "bar": "baz"}"""
+assert typeof(y) is string
+## deserialize to type 'Foo':
+let z = y.to[:Foo]
+assert typeof(z) is Foo
+assert z.id == 1
+assert z.bar == "baz"
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/marshal.idx b/marshal.idx new file mode 100644 index 0000000000000..9ee9576dba848 --- /dev/null +++ b/marshal.idx @@ -0,0 +1,10 @@ +nimTitle marshal marshal.html module std/marshal 0 +nim load marshal.html#load,Stream,T proc load[T](s: Stream; data: var T) 282 +nim store marshal.html#store,Stream,sinkT proc store[T](s: Stream; data: sink T) 295 +nim `$$` marshal.html#$$,sinkT proc `$$`[T](x: sink T): string 317 +nim to marshal.html#to,string proc to[T](data: string): T 348 +idx serialization marshal.html#serialization_1 Module marshal 0 +idx deserialization marshal.html#deserialization_1 Module marshal 0 +idx JSON marshal.html#json_1 Module marshal 0 +heading Basic usage marshal.html#basic-usage Basic usage 0 +heading See also marshal.html#see-also See also 0 diff --git a/math.html b/math.html new file mode 100644 index 0000000000000..2f2ccb65350d0 --- /dev/null +++ b/math.html @@ -0,0 +1,2417 @@ + + + + + + + +std/math + + + + + + + + + + + + + + + + +
+
+

std/math

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Constructive mathematics is naturally typed. -- Simon Thompson

+

Basic math routines for Nim.

+

Note that the trigonometric functions naturally operate on radians. The helper functions degToRad and radToDeg provide conversion between radians and degrees.

+ +

Example:

+
import std/math
+from std/fenv import epsilon
+from std/random import rand
+
+proc generateGaussianNoise(mu: float = 0.0, sigma: float = 1.0): (float, float) =
+  # Generates values from a normal distribution.
+  # Translated from https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform#Implementation.
+  var u1: float
+  var u2: float
+  while true:
+    u1 = rand(1.0)
+    u2 = rand(1.0)
+    if u1 > epsilon(float): break
+  let mag = sigma * sqrt(-2 * ln(u1))
+  let z0 = mag * cos(2 * PI * u2) + mu
+  let z1 = mag * sin(2 * PI * u2) + mu
+  (z0, z1)
+
+echo generateGaussianNoise()
This module is available for the JavaScript target. +

See also

  • complex module for complex numbers and their mathematical operations
  • +
  • rationals module for rational numbers and their mathematical operations
  • +
  • fenv module for handling of floating-point rounding and exceptions (overflow, zero-divide, etc.)
  • +
  • random module for a fast and tiny random number generator
  • +
  • stats module for statistical analysis
  • +
  • strformat module for formatting floats for printing
  • +
  • system module for some very basic and trivial math operators (shr, shl, xor, clamp, etc.)
  • +
+this func uses bitwise comparisons from C compilers, which are not always available.

+ +
+

Types

+
+
+
FloatClass = enum
+  fcNormal,                 ## value is an ordinary nonzero floating point value
+  fcSubnormal,              ## value is a subnormal (a very small) floating point value
+  fcZero,                   ## value is zero
+  fcNegZero,                ## value is the negative zero
+  fcNan,                    ## value is Not a Number (NaN)
+  fcInf,                    ## value is positive infinity
+  fcNegInf                   ## value is negative infinity
+
+ + Describes the class a floating point value belongs to. This is the type that is returned by the classify func. + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
E = 2.718281828459045
+
+ + Euler's number. + Source   +Edit   + +
+
+
+
MaxFloat32Precision = 8
+
+ + Maximum number of meaningful digits after the decimal point for Nim's float32 type. + Source   +Edit   + +
+
+
+
MaxFloat64Precision = 16
+
+ + Maximum number of meaningful digits after the decimal point for Nim's float64 type. + Source   +Edit   + +
+
+
+
MaxFloatPrecision = 16
+
+ + Maximum number of meaningful digits after the decimal point for Nim's float type. + Source   +Edit   + +
+
+
+
MinFloatNormal = 2.225073858507201e-308
+
+ + Smallest normal number for Nim's float type (= 2^-1022). + Source   +Edit   + +
+
+
+
PI = 3.141592653589793
+
+ + The circle constant PI (Ludolph's number). + Source   +Edit   + +
+
+
+
TAU = 6.283185307179586
+
+ + The circle constant TAU (= 2 * PI). + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `^`[T: SomeNumber; U: SomeFloat](x: T; y: U): float
+
+ +

Computes x to the power of y.

+

Error handling follows the C++ specification even for the JS backend https://en.cppreference.com/w/cpp/numeric/math/pow

+

See also:

+ + +

Example:

+
doAssert almostEqual(5.5 ^ 2.2, 42.540042248725975)
+doAssert 1.0 ^ Inf == 1.0
+ Source   +Edit   + +
+
+
+
func `^`[T: SomeNumber](x: T; y: Natural): T
+
+ +

Computes x to the power of y.

+

The exponent y must be non-negative, use pow for negative exponents.

+

See also:

+ + +

Example:

+
doAssert -3 ^ 0 == 1
+doAssert -3 ^ 1 == -3
+doAssert -3 ^ 2 == 9
+ Source   +Edit   + +
+
+ +
+
+
+
func almostEqual[T: SomeFloat](x, y: T; unitsInLastPlace: Natural = 4): bool {.
+    inline.}
+
+ +

Checks if two float values are almost equal, using the machine epsilon.

+

unitsInLastPlace is the max number of units in the last place difference tolerated when comparing two numbers. The larger the value, the more error is allowed. A 0 value means that two numbers must be exactly the same to be considered equal.

+

The machine epsilon has to be scaled to the magnitude of the values used and multiplied by the desired precision in ULPs unless the difference is subnormal.

+ +

Example:

+
doAssert almostEqual(PI, 3.14159265358979)
+doAssert almostEqual(Inf, Inf)
+doAssert not almostEqual(NaN, NaN)
+ Source   +Edit   + +
+
+ +
+
+
+
func arccos(x: float32): float32 {.importc: "acosf", header: "<math.h>",
+                                   ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func arccos(x: float64): float64 {.importc: "acos", header: "<math.h>",
+                                   ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the arc cosine of x.

+

See also:

+ + +

Example:

+
doAssert almostEqual(radToDeg(arccos(0.0)), 90.0)
+doAssert almostEqual(radToDeg(arccos(1.0)), 0.0)
+ Source   +Edit   + +
+
+ +
+
+
+
func arccosh(x: float32): float32 {.importc: "acoshf", header: "<math.h>",
+                                    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func arccosh(x: float64): float64 {.importc: "acosh", header: "<math.h>",
+                                    ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the inverse hyperbolic cosine of x.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func arccot[T: float32 | float64](x: T): T
+
+ + Computes the inverse cotangent of x (arctan(1/x)). + Source   +Edit   + +
+
+ +
+
+
+
func arccoth[T: float32 | float64](x: T): T
+
+ + Computes the inverse hyperbolic cotangent of x (arctanh(1/x)). + Source   +Edit   + +
+
+ +
+
+
+
func arccsc[T: float32 | float64](x: T): T
+
+ + Computes the inverse cosecant of x (arcsin(1/x)). + Source   +Edit   + +
+
+ +
+
+
+
func arccsch[T: float32 | float64](x: T): T
+
+ + Computes the inverse hyperbolic cosecant of x (arcsinh(1/x)). + Source   +Edit   + +
+
+ +
+
+
+
func arcsec[T: float32 | float64](x: T): T
+
+ + Computes the inverse secant of x (arccos(1/x)). + Source   +Edit   + +
+
+ +
+
+
+
func arcsech[T: float32 | float64](x: T): T
+
+ + Computes the inverse hyperbolic secant of x (arccosh(1/x)). + Source   +Edit   + +
+
+ +
+
+
+
func arcsin(x: float32): float32 {.importc: "asinf", header: "<math.h>",
+                                   ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func arcsin(x: float64): float64 {.importc: "asin", header: "<math.h>",
+                                   ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the arc sine of x.

+

See also:

+ + +

Example:

+
doAssert almostEqual(radToDeg(arcsin(0.0)), 0.0)
+doAssert almostEqual(radToDeg(arcsin(1.0)), 90.0)
+ Source   +Edit   + +
+
+ +
+
+
+
func arcsinh(x: float32): float32 {.importc: "asinhf", header: "<math.h>",
+                                    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func arcsinh(x: float64): float64 {.importc: "asinh", header: "<math.h>",
+                                    ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the inverse hyperbolic sine of x.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func arctan(x: float32): float32 {.importc: "atanf", header: "<math.h>",
+                                   ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func arctan(x: float64): float64 {.importc: "atan", header: "<math.h>",
+                                   ...raises: [], tags: [], forbids: [].}
+
+ +

Calculate the arc tangent of x.

+

See also:

+ + +

Example:

+
doAssert almostEqual(arctan(1.0), 0.7853981633974483)
+doAssert almostEqual(radToDeg(arctan(1.0)), 45.0)
+ Source   +Edit   + +
+
+ +
+
+
+
func arctan2(y, x: float32): float32 {.importc: "atan2f", header: "<math.h>",
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func arctan2(y, x: float64): float64 {.importc: "atan2", header: "<math.h>",
+                                       ...raises: [], tags: [], forbids: [].}
+
+ +

Calculate the arc tangent of y/x.

+

It produces correct results even when the resulting angle is near PI/2 or -PI/2 (x near 0).

+

See also:

+ + +

Example:

+
doAssert almostEqual(arctan2(1.0, 0.0), PI / 2.0)
+doAssert almostEqual(radToDeg(arctan2(1.0, 0.0)), 90.0)
+ Source   +Edit   + +
+
+ +
+
+
+
func arctanh(x: float32): float32 {.importc: "atanhf", header: "<math.h>",
+                                    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func arctanh(x: float64): float64 {.importc: "atanh", header: "<math.h>",
+                                    ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the inverse hyperbolic tangent of x.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func binom(n, k: int): int {....raises: [], tags: [], forbids: [].}
+
+ + Computes the binomial coefficient. +

Example:

+
doAssert binom(6, 2) == 15
+doAssert binom(-6, 2) == 1
+doAssert binom(6, 0) == 1
+ Source   +Edit   + +
+
+ +
+
+
+
func cbrt(x: float32): float32 {.importc: "cbrtf", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func cbrt(x: float64): float64 {.importc: "cbrt", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the cube root of x.

+

See also:

+ + +

Example:

+
doAssert almostEqual(cbrt(8.0), 2.0)
+doAssert almostEqual(cbrt(2.197), 1.3)
+doAssert almostEqual(cbrt(-27.0), -3.0)
+ Source   +Edit   + +
+
+ +
+
+
+
func ceil(x: float32): float32 {.importc: "ceilf", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func ceil(x: float64): float64 {.importc: "ceil", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the ceiling function (i.e. the smallest integer not smaller than x).

+

See also:

+ + +

Example:

+
doAssert ceil(2.1)  == 3.0
+doAssert ceil(2.9)  == 3.0
+doAssert ceil(-2.1) == -2.0
+ Source   +Edit   + +
+
+ +
+
+
+
func ceilDiv[T: SomeInteger](x, y: T): T {.inline.}
+
+ +

Ceil division is conceptually defined as ceil(x / y).

+

Assumes x >= 0 and y > 0 (and x + y - 1 <= high(T) if T is SomeUnsignedInt).

+

This is different from the system.div operator, which works like trunc(x / y). That is, div rounds towards 0 and ceilDiv rounds up.

+

This function has the above input limitation, because that allows the compiler to generate faster code and it is rarely used with negative values or unsigned integers close to high(T)/2. If you need a ceilDiv that works with any input, see: https://github.com/demotomohiro/divmath.

+

See also:

+ + +

Example:

+
assert ceilDiv(12, 3) ==  4
+assert ceilDiv(13, 3) ==  5
+ Source   +Edit   + +
+
+ +
+
+
+
func clamp[T](val: T; bounds: Slice[T]): T {.inline.}
+
+ + Like system.clamp, but takes a slice, so you can easily clamp within a range. +

Example:

+
assert clamp(10, 1 .. 5) == 5
+assert clamp(1, 1 .. 3) == 1
+type A = enum a0, a1, a2, a3, a4, a5
+assert a1.clamp(a2..a4) == a2
+assert clamp((3, 0), (1, 0) .. (2, 9)) == (2, 9)
+doAssertRaises(AssertionDefect): discard clamp(1, 3..2) # invalid bounds
+ Source   +Edit   + +
+
+ +
+
+
+
func classify(x: float): FloatClass {....raises: [], tags: [], forbids: [].}
+
+ +

Classifies a floating point value.

+

Returns x's class as specified by the FloatClass enum.

+ +

Example:

+
doAssert classify(0.3) == fcNormal
+doAssert classify(0.0) == fcZero
+doAssert classify(0.3 / 0.0) == fcInf
+doAssert classify(-0.3 / 0.0) == fcNegInf
+doAssert classify(5.0e-324) == fcSubnormal
+ Source   +Edit   + +
+
+ +
+
+
+
func copySign[T: SomeFloat](x, y: T): T {.inline.}
+
+ + Returns a value with the magnitude of x and the sign of y; this works even if x or y are NaN, infinity or zero, all of which can carry a sign. +

Example:

+
doAssert copySign(10.0, 1.0) == 10.0
+doAssert copySign(10.0, -1.0) == -10.0
+doAssert copySign(-Inf, -0.0) == -Inf
+doAssert copySign(NaN, 1.0).isNaN
+doAssert copySign(1.0, copySign(NaN, -1.0)) == -1.0
+ Source   +Edit   + +
+
+ +
+
+
+
func cos(x: float32): float32 {.importc: "cosf", header: "<math.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func cos(x: float64): float64 {.importc: "cos", header: "<math.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ +

Computes the cosine of x.

+

See also:

+ + +

Example:

+
doAssert almostEqual(cos(2 * PI), 1.0)
+doAssert almostEqual(cos(degToRad(60.0)), 0.5)
+ Source   +Edit   + +
+
+ +
+
+
+
func cosh(x: float32): float32 {.importc: "coshf", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func cosh(x: float64): float64 {.importc: "cosh", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the hyperbolic cosine of x.

+

See also:

+ + +

Example:

+
doAssert almostEqual(cosh(0.0), 1.0)
+doAssert almostEqual(cosh(1.0), 1.543080634815244)
+ Source   +Edit   + +
+
+ +
+
+
+
func cot[T: float32 | float64](x: T): T
+
+ + Computes the cotangent of x (1/tan(x)). + Source   +Edit   + +
+
+ +
+
+
+
func coth[T: float32 | float64](x: T): T
+
+ + Computes the hyperbolic cotangent of x (1/tanh(x)). + Source   +Edit   + +
+
+ +
+
+
+
func csc[T: float32 | float64](x: T): T
+
+ + Computes the cosecant of x (1/sin(x)). + Source   +Edit   + +
+
+ +
+
+
+
func csch[T: float32 | float64](x: T): T
+
+ + Computes the hyperbolic cosecant of x (1/sinh(x)). + Source   +Edit   + +
+
+ +
+
+
+
func cumsum[T](x: var openArray[T])
+
+ +

Transforms x in-place (must be declared as var) into its cumulative (aka prefix) summation.

+

See also:

+ + +

Example:

+
var a = [1, 2, 3, 4]
+cumsum(a)
+doAssert a == @[1, 3, 6, 10]
+ Source   +Edit   + +
+
+ +
+
+
+
func cumsummed[T](x: openArray[T]): seq[T]
+
+ +

Returns the cumulative (aka prefix) summation of x.

+

If x is empty, @[] is returned.

+

See also:

+ + +

Example:

+
doAssert cumsummed([1, 2, 3, 4]) == @[1, 3, 6, 10]
+ Source   +Edit   + +
+
+ +
+
+
+
func degToRad[T: float32 | float64](d: T): T {.inline.}
+
+ +

Converts from degrees to radians.

+

See also:

+ + +

Example:

+
doAssert almostEqual(degToRad(180.0), PI)
+ Source   +Edit   + +
+
+ +
+
+
+
func divmod[T: SomeInteger](x, y: T): (T, T) {.inline.}
+
+ + Specialized instructions for computing both division and modulus. Return structure is: (quotient, remainder) +

Example:

+
doAssert divmod(5, 2) == (2, 1)
+doAssert divmod(5, -3) == (-1, 2)
+ Source   +Edit   + +
+
+ +
+
+
+
func erf(x: float32): float32 {.importc: "erff", header: "<math.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func erf(x: float64): float64 {.importc: "erf", header: "<math.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ +

Computes the error function for x.

+

Note: Not available for the JS backend.

+ + Source   +Edit   + +
+
+ +
+
+
+
func erfc(x: float32): float32 {.importc: "erfcf", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func erfc(x: float64): float64 {.importc: "erfc", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the complementary error function for x.

+

Note: Not available for the JS backend.

+ + Source   +Edit   + +
+
+ +
+
+
+
func euclDiv[T: SomeInteger](x, y: T): T
+
+ + Returns euclidean division of x by y. +

Example:

+
doAssert euclDiv(13, 3) == 4
+doAssert euclDiv(-13, 3) == -5
+doAssert euclDiv(13, -3) == -4
+doAssert euclDiv(-13, -3) == 5
+ Source   +Edit   + +
+
+ +
+
+
+
func euclMod[T: SomeNumber](x, y: T): T
+
+ + Returns euclidean modulo of x by y. euclMod(x, y) is non-negative. +

Example:

+
doAssert euclMod(13, 3) == 1
+doAssert euclMod(-13, 3) == 2
+doAssert euclMod(13, -3) == 1
+doAssert euclMod(-13, -3) == 2
+ Source   +Edit   + +
+
+ +
+
+
+
func exp(x: float32): float32 {.importc: "expf", header: "<math.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func exp(x: float64): float64 {.importc: "exp", header: "<math.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ +

Computes the exponential function of x (e^x).

+

See also:

+ + +

Example:

+
doAssert almostEqual(exp(1.0), E)
+doAssert almostEqual(ln(exp(4.0)), 4.0)
+doAssert almostEqual(exp(0.0), 1.0)
+ Source   +Edit   + +
+
+ +
+
+
+
func fac(n: int): int {....raises: [], tags: [], forbids: [].}
+
+ +

Computes the factorial of a non-negative integer n.

+

See also:

+ + +

Example:

+
doAssert fac(0) == 1
+doAssert fac(4) == 24
+doAssert fac(10) == 3628800
+ Source   +Edit   + +
+
+ +
+
+
+
func floor(x: float32): float32 {.importc: "floorf", header: "<math.h>",
+                                  ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func floor(x: float64): float64 {.importc: "floor", header: "<math.h>",
+                                  ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the floor function (i.e. the largest integer not greater than x).

+

See also:

+ + +

Example:

+
doAssert floor(2.1)  == 2.0
+doAssert floor(2.9)  == 2.0
+doAssert floor(-3.5) == -4.0
+ Source   +Edit   + +
+
+ +
+
+
+
func floorDiv[T: SomeInteger](x, y: T): T
+
+ +

Floor division is conceptually defined as floor(x / y).

+

This is different from the system.div operator, which is defined as trunc(x / y). That is, div rounds towards 0 and floorDiv rounds down.

+

See also:

+ + +

Example:

+
doAssert floorDiv( 13,  3) ==  4
+doAssert floorDiv(-13,  3) == -5
+doAssert floorDiv( 13, -3) == -5
+doAssert floorDiv(-13, -3) ==  4
+ Source   +Edit   + +
+
+ +
+
+
+
func floorMod[T: SomeNumber](x, y: T): T
+
+ +

Floor modulo is conceptually defined as x - (floorDiv(x, y) * y).

+

This func behaves the same as the % operator in Python.

+

See also:

+ + +

Example:

+
doAssert floorMod( 13,  3) ==  1
+doAssert floorMod(-13,  3) ==  2
+doAssert floorMod( 13, -3) == -2
+doAssert floorMod(-13, -3) == -1
+ Source   +Edit   + +
+
+ +
+
+
+
func frexp[T: float32 | float64](x: T): tuple[frac: T, exp: int] {.inline.}
+
+ + Splits x into a normalized fraction frac and an integral power of 2 exp, such that abs(frac) in 0.5..<1 and x == frac * 2 ^ exp, except for special cases shown below. +

Example:

+
doAssert frexp(8.0) == (0.5, 4)
+doAssert frexp(-8.0) == (-0.5, 4)
+doAssert frexp(0.0) == (0.0, 0)
+
+# special cases:
+when sizeof(int) == 8:
+  doAssert frexp(-0.0).frac.signbit # signbit preserved for +-0
+  doAssert frexp(Inf).frac == Inf # +- Inf preserved
+  doAssert frexp(NaN).frac.isNaN
+ Source   +Edit   + +
+
+
+
func frexp[T: float32 | float64](x: T; exponent: var int): T {.inline.}
+
+ + Overload of frexp that calls (result, exponent) = frexp(x). +

Example:

+
var x: int
+doAssert frexp(5.0, x) == 0.625
+doAssert x == 3
+ Source   +Edit   + +
+
+ +
+
+
+
func gamma(x: float32): float32 {.importc: "tgammaf", header: "<math.h>",
+                                  ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func gamma(x: float64): float64 {.importc: "tgamma", header: "<math.h>",
+                                  ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the gamma function for x.

+

Note: Not available for the JS backend.

+

See also:

+
  • lgamma func for the natural logarithm of the gamma function
  • +
+ +

Example:

+
doAssert almostEqual(gamma(1.0), 1.0)
+doAssert almostEqual(gamma(4.0), 6.0)
+doAssert almostEqual(gamma(11.0), 3628800.0)
+ Source   +Edit   + +
+
+ +
+
+
+
func gcd(x, y: SomeInteger): SomeInteger
+
+ +

Computes the greatest common (positive) divisor of x and y, using the binary GCD (aka Stein's) algorithm.

+

See also:

+ + +

Example:

+
doAssert gcd(12, 8) == 4
+doAssert gcd(17, 63) == 1
+ Source   +Edit   + +
+
+
+
func gcd[T](x, y: T): T
+
+ +

Computes the greatest common (positive) divisor of x and y.

+

Note that for floats, the result cannot always be interpreted as "greatest decimal z such that z*N == x and z*M == y where N and M are positive integers".

+

See also:

+ + +

Example:

+
doAssert gcd(13.5, 9.0) == 4.5
+ Source   +Edit   + +
+
+
+
func gcd[T](x: openArray[T]): T
+
+ +

Computes the greatest common (positive) divisor of the elements of x.

+

See also:

+
  • gcd func for a version with two arguments
  • +
+ +

Example:

+
doAssert gcd(@[13.5, 9.0]) == 4.5
+ Source   +Edit   + +
+
+ +
+
+
+
func hypot(x, y: float32): float32 {.importc: "hypotf", header: "<math.h>",
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func hypot(x, y: float64): float64 {.importc: "hypot", header: "<math.h>",
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + Computes the length of the hypotenuse of a right-angle triangle with x as its base and y as its height. Equivalent to sqrt(x*x + y*y). +

Example:

+
doAssert almostEqual(hypot(3.0, 4.0), 5.0)
+ Source   +Edit   + +
+
+ +
+
+
+
func isNaN(x: SomeFloat): bool {.inline.}
+
+ + Returns whether x is a NaN, more efficiently than via classify(x) == fcNan. Works even with --passc:-ffast-math. +

Example:

+
doAssert NaN.isNaN
+doAssert not Inf.isNaN
+doAssert not isNaN(3.1415926)
+ Source   +Edit   + +
+
+ +
+
+
+
func isPowerOfTwo(x: int): bool {....raises: [], tags: [], forbids: [].}
+
+ +

Returns true, if x is a power of two, false otherwise.

+

Zero and negative numbers are not a power of two.

+

See also:

+ + +

Example:

+
doAssert isPowerOfTwo(16)
+doAssert not isPowerOfTwo(5)
+doAssert not isPowerOfTwo(0)
+doAssert not isPowerOfTwo(-16)
+ Source   +Edit   + +
+
+ +
+
+
+
func lcm[T](x, y: T): T
+
+ +

Computes the least common multiple of x and y.

+

See also:

+ + +

Example:

+
doAssert lcm(24, 30) == 120
+doAssert lcm(13, 39) == 39
+ Source   +Edit   + +
+
+
+
func lcm[T](x: openArray[T]): T
+
+ +

Computes the least common multiple of the elements of x.

+

See also:

+
  • lcm func for a version with two arguments
  • +
+ +

Example:

+
doAssert lcm(@[24, 30]) == 120
+ Source   +Edit   + +
+
+ +
+
+
+
func lgamma(x: float32): float32 {.importc: "lgammaf", header: "<math.h>",
+                                   ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func lgamma(x: float64): float64 {.importc: "lgamma", header: "<math.h>",
+                                   ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the natural logarithm of the gamma function for x.

+

Note: Not available for the JS backend.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func ln(x: float32): float32 {.importc: "logf", header: "<math.h>", ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func ln(x: float64): float64 {.importc: "log", header: "<math.h>", ...raises: [],
+                               tags: [], forbids: [].}
+
+ +

Computes the natural logarithm of x.

+

See also:

+ + +

Example:

+
doAssert almostEqual(ln(exp(4.0)), 4.0)
+doAssert almostEqual(ln(1.0), 0.0)
+doAssert almostEqual(ln(0.0), -Inf)
+doAssert ln(-7.0).isNaN
+ Source   +Edit   + +
+
+ +
+
+
+
func log[T: SomeFloat](x, base: T): T
+
+ +

Computes the logarithm of x to base base.

+

See also:

+ + +

Example:

+
doAssert almostEqual(log(9.0, 3.0), 2.0)
+doAssert almostEqual(log(0.0, 2.0), -Inf)
+doAssert log(-7.0, 4.0).isNaN
+doAssert log(8.0, -2.0).isNaN
+ Source   +Edit   + +
+
+ +
+
+
+
func log2(x: float32): float32 {.importc: "log2f", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func log2(x: float64): float64 {.importc: "log2", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the binary logarithm (base 2) of x.

+

See also:

+ + +

Example:

+
doAssert almostEqual(log2(8.0), 3.0)
+doAssert almostEqual(log2(1.0), 0.0)
+doAssert almostEqual(log2(0.0), -Inf)
+doAssert log2(-2.0).isNaN
+ Source   +Edit   + +
+
+ +
+
+
+
func log10(x: float32): float32 {.importc: "log10f", header: "<math.h>",
+                                  ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func log10(x: float64): float64 {.importc: "log10", header: "<math.h>",
+                                  ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the common logarithm (base 10) of x.

+

See also:

+ + +

Example:

+
doAssert almostEqual(log10(100.0) , 2.0)
+doAssert almostEqual(log10(0.0), -Inf)
+doAssert log10(-100.0).isNaN
+ Source   +Edit   + +
+
+ +
+
+
+
func `mod`(x, y: float32): float32 {.importc: "fmodf", header: "<math.h>",
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `mod`(x, y: float64): float64 {.importc: "fmod", header: "<math.h>",
+                                     ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the modulo operation for float values (the remainder of x divided by y).

+

See also:

+ + +

Example:

+
doAssert  6.5 mod  2.5 ==  1.5
+doAssert -6.5 mod  2.5 == -1.5
+doAssert  6.5 mod -2.5 ==  1.5
+doAssert -6.5 mod -2.5 == -1.5
+ Source   +Edit   + +
+
+ +
+
+
+
func nextPowerOfTwo(x: int): int {....raises: [], tags: [], forbids: [].}
+
+ +

Returns x rounded up to the nearest power of two.

+

Zero and negative numbers get rounded up to 1.

+

See also:

+ + +

Example:

+
doAssert nextPowerOfTwo(16) == 16
+doAssert nextPowerOfTwo(5) == 8
+doAssert nextPowerOfTwo(0) == 1
+doAssert nextPowerOfTwo(-16) == 1
+ Source   +Edit   + +
+
+ +
+
+
+
func pow(x, y: float32): float32 {.importc: "powf", header: "<math.h>",
+                                   ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func pow(x, y: float64): float64 {.importc: "pow", header: "<math.h>",
+                                   ...raises: [], tags: [], forbids: [].}
+
+ +

Computes x raised to the power of y.

+

You may use the ^ func instead.

+

See also:

+ + +

Example:

+
doAssert almostEqual(pow(100, 1.5), 1000.0)
+doAssert almostEqual(pow(16.0, 0.5), 4.0)
+ Source   +Edit   + +
+
+ +
+
+
+
func prod[T](x: openArray[T]): T
+
+ +

Computes the product of the elements in x.

+

If x is empty, 1 is returned.

+

See also:

+ + +

Example:

+
doAssert prod([1, 2, 3, 4]) == 24
+doAssert prod([-4, 3, 5]) == -60
+ Source   +Edit   + +
+
+ +
+
+
+
func radToDeg[T: float32 | float64](d: T): T {.inline.}
+
+ +

Converts from radians to degrees.

+

See also:

+ + +

Example:

+
doAssert almostEqual(radToDeg(2 * PI), 360.0)
+ Source   +Edit   + +
+
+ +
+
+
+
func round(x: float32): float32 {.importc: "roundf", header: "<math.h>",
+                                  ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func round(x: float64): float64 {.importc: "round", header: "<math.h>",
+                                  ...raises: [], tags: [], forbids: [].}
+
+ +

Rounds a float to zero decimal places.

+

Used internally by the round func when the specified number of places is 0.

+

See also:

+ + +

Example:

+
doAssert round(3.4) == 3.0
+doAssert round(3.5) == 4.0
+doAssert round(4.5) == 5.0
+ Source   +Edit   + +
+
+
+
func round[T: float32 | float64](x: T; places: int): T
+
+ +

Decimal rounding on a binary floating point number.

+

This function is NOT reliable. Floating point numbers cannot hold non integer decimals precisely. If places is 0 (or omitted), round to the nearest integral value following normal mathematical rounding rules (e.g. round(54.5) -> 55.0). If places is greater than 0, round to the given number of decimal places, e.g. round(54.346, 2) -> 54.350000000000001421. If places is negative, round to the left of the decimal place, e.g. round(537.345, -1) -> 540.0.

+ +

Example:

+
doAssert round(PI, 2) == 3.14
+doAssert round(PI, 4) == 3.1416
+ Source   +Edit   + +
+
+ +
+
+
+
func sec[T: float32 | float64](x: T): T
+
+ + Computes the secant of x (1/cos(x)). + Source   +Edit   + +
+
+ +
+
+
+
func sech[T: float32 | float64](x: T): T
+
+ + Computes the hyperbolic secant of x (1/cosh(x)). + Source   +Edit   + +
+
+ +
+
+
+
func sgn[T: SomeNumber](x: T): int {.inline.}
+
+ +

Sign function.

+

Returns:

+
  • -1 for negative numbers and NegInf,
  • +
  • 1 for positive numbers and Inf,
  • +
  • 0 for positive zero, negative zero and NaN
  • +
+ +

Example:

+
doAssert sgn(5) == 1
+doAssert sgn(0) == 0
+doAssert sgn(-4.1) == -1
+ Source   +Edit   + +
+
+ +
+
+
+
proc signbit(x: SomeFloat): bool {.inline.}
+
+ + Returns true if x is negative, false otherwise. +

Example:

+
doAssert not signbit(0.0)
+doAssert signbit(-0.0)
+doAssert signbit(-0.1)
+doAssert not signbit(0.1)
+ Source   +Edit   + +
+
+ +
+
+
+
func sin(x: float32): float32 {.importc: "sinf", header: "<math.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func sin(x: float64): float64 {.importc: "sin", header: "<math.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ +

Computes the sine of x.

+

See also:

+ + +

Example:

+
doAssert almostEqual(sin(PI / 6), 0.5)
+doAssert almostEqual(sin(degToRad(90.0)), 1.0)
+ Source   +Edit   + +
+
+ +
+
+
+
func sinh(x: float32): float32 {.importc: "sinhf", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func sinh(x: float64): float64 {.importc: "sinh", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the hyperbolic sine of x.

+

See also:

+ + +

Example:

+
doAssert almostEqual(sinh(0.0), 0.0)
+doAssert almostEqual(sinh(1.0), 1.175201193643801)
+ Source   +Edit   + +
+
+ +
+
+
+
func splitDecimal[T: float32 | float64](x: T): tuple[intpart: T, floatpart: T]
+
+ +

Breaks x into an integer and a fractional part.

+

Returns a tuple containing intpart and floatpart, representing the integer part and the fractional part, respectively.

+

Both parts have the same sign as x. Analogous to the modf function in C.

+ +

Example:

+
doAssert splitDecimal(5.25) == (intpart: 5.0, floatpart: 0.25)
+doAssert splitDecimal(-2.73) == (intpart: -2.0, floatpart: -0.73)
+ Source   +Edit   + +
+
+ +
+
+
+
func sqrt(x: float32): float32 {.importc: "sqrtf", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func sqrt(x: float64): float64 {.importc: "sqrt", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the square root of x.

+

See also:

+ + +

Example:

+
doAssert almostEqual(sqrt(4.0), 2.0)
+doAssert almostEqual(sqrt(1.44), 1.2)
+ Source   +Edit   + +
+
+ +
+
+
+
func sum[T](x: openArray[T]): T
+
+ +

Computes the sum of the elements in x.

+

If x is empty, 0 is returned.

+

See also:

+ + +

Example:

+
doAssert sum([1, 2, 3, 4]) == 10
+doAssert sum([-4, 3, 5]) == 4
+ Source   +Edit   + +
+
+ +
+
+
+
func tan(x: float32): float32 {.importc: "tanf", header: "<math.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func tan(x: float64): float64 {.importc: "tan", header: "<math.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ +

Computes the tangent of x.

+

See also:

+ + +

Example:

+
doAssert almostEqual(tan(degToRad(45.0)), 1.0)
+doAssert almostEqual(tan(PI / 4), 1.0)
+ Source   +Edit   + +
+
+ +
+
+
+
func tanh(x: float32): float32 {.importc: "tanhf", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func tanh(x: float64): float64 {.importc: "tanh", header: "<math.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the hyperbolic tangent of x.

+

See also:

+ + +

Example:

+
doAssert almostEqual(tanh(0.0), 0.0)
+doAssert almostEqual(tanh(1.0), 0.7615941559557649)
+ Source   +Edit   + +
+
+ +
+
+
+
func trunc(x: float32): float32 {.importc: "truncf", header: "<math.h>",
+                                  ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func trunc(x: float64): float64 {.importc: "trunc", header: "<math.h>",
+                                  ...raises: [], tags: [], forbids: [].}
+
+ +

Truncates x to the decimal point.

+

See also:

+ + +

Example:

+
doAssert trunc(PI) == 3.0
+doAssert trunc(-1.85) == -1.0
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/math.idx b/math.idx new file mode 100644 index 0000000000000..cba03de59420d --- /dev/null +++ b/math.idx @@ -0,0 +1,158 @@ +nimTitle math math.html module std/math 0 +nim divmod math.html#divmod,T,T proc divmod[T: SomeInteger](x, y: T): (T, T) 98 +nim binom math.html#binom,int,int proc binom(n, k: int): int 117 +nim fac math.html#fac,int proc fac(n: int): int 135 +nim PI math.html#PI const PI 163 +nim TAU math.html#TAU const TAU 164 +nim E math.html#E const E 165 +nim MaxFloat64Precision math.html#MaxFloat64Precision const MaxFloat64Precision 167 +nim MaxFloat32Precision math.html#MaxFloat32Precision const MaxFloat32Precision 170 +nim MaxFloatPrecision math.html#MaxFloatPrecision const MaxFloatPrecision 173 +nim MinFloatNormal math.html#MinFloatNormal const MinFloatNormal 177 +nim fcNormal math.html#fcNormal FloatClass.fcNormal 182 +nim fcSubnormal math.html#fcSubnormal FloatClass.fcSubnormal 182 +nim fcZero math.html#fcZero FloatClass.fcZero 182 +nim fcNegZero math.html#fcNegZero FloatClass.fcNegZero 182 +nim fcNan math.html#fcNan FloatClass.fcNan 182 +nim fcInf math.html#fcInf FloatClass.fcInf 182 +nim fcNegInf math.html#fcNegInf FloatClass.fcNegInf 182 +nim FloatClass math.html#FloatClass enum FloatClass 182 +nim isNaN math.html#isNaN,SomeFloat proc isNaN(x: SomeFloat): bool 193 +nim signbit math.html#signbit,SomeFloat proc signbit(x: SomeFloat): bool 231 +nim copySign math.html#copySign,T,T proc copySign[T: SomeFloat](x, y: T): T 245 +nim classify math.html#classify,float proc classify(x: float): FloatClass 270 +nim almostEqual math.html#almostEqual,T,T,Natural proc almostEqual[T: SomeFloat](x, y: T; unitsInLastPlace: Natural = 4): bool 295 +nim isPowerOfTwo math.html#isPowerOfTwo,int proc isPowerOfTwo(x: int): bool 324 +nim nextPowerOfTwo math.html#nextPowerOfTwo,int proc nextPowerOfTwo(x: int): int 339 +nim sqrt math.html#sqrt,float32 proc sqrt(x: float32): float32 368 +nim sqrt math.html#sqrt,float64 proc sqrt(x: float64): float64 369 +nim cbrt math.html#cbrt,float32 proc cbrt(x: float32): float32 377 +nim cbrt math.html#cbrt,float64 proc cbrt(x: float64): float64 378 +nim ln math.html#ln,float32 proc ln(x: float32): float32 387 +nim ln math.html#ln,float64 proc ln(x: float64): float64 388 +nim log math.html#log,T,T proc log[T: SomeFloat](x, base: T): T 412 +nim log10 math.html#log10,float32 proc log10(x: float32): float32 428 +nim log10 math.html#log10,float64 proc log10(x: float64): float64 429 +nim exp math.html#exp,float32 proc exp(x: float32): float32 440 +nim exp math.html#exp,float64 proc exp(x: float64): float64 441 +nim sin math.html#sin,float32 proc sin(x: float32): float32 450 +nim sin math.html#sin,float64 proc sin(x: float64): float64 451 +nim cos math.html#cos,float32 proc cos(x: float32): float32 459 +nim cos math.html#cos,float64 proc cos(x: float64): float64 460 +nim tan math.html#tan,float32 proc tan(x: float32): float32 468 +nim tan math.html#tan,float64 proc tan(x: float64): float64 469 +nim sinh math.html#sinh,float32 proc sinh(x: float32): float32 477 +nim sinh math.html#sinh,float64 proc sinh(x: float64): float64 478 +nim cosh math.html#cosh,float32 proc cosh(x: float32): float32 486 +nim cosh math.html#cosh,float64 proc cosh(x: float64): float64 487 +nim tanh math.html#tanh,float32 proc tanh(x: float32): float32 495 +nim tanh math.html#tanh,float64 proc tanh(x: float64): float64 496 +nim arcsin math.html#arcsin,float32 proc arcsin(x: float32): float32 504 +nim arcsin math.html#arcsin,float64 proc arcsin(x: float64): float64 505 +nim arccos math.html#arccos,float32 proc arccos(x: float32): float32 513 +nim arccos math.html#arccos,float64 proc arccos(x: float64): float64 514 +nim arctan math.html#arctan,float32 proc arctan(x: float32): float32 522 +nim arctan math.html#arctan,float64 proc arctan(x: float64): float64 523 +nim arctan2 math.html#arctan2,float32,float32 proc arctan2(y, x: float32): float32 532 +nim arctan2 math.html#arctan2,float64,float64 proc arctan2(y, x: float64): float64 533 +nim arcsinh math.html#arcsinh,float32 proc arcsinh(x: float32): float32 544 +nim arcsinh math.html#arcsinh,float64 proc arcsinh(x: float64): float64 545 +nim arccosh math.html#arccosh,float32 proc arccosh(x: float32): float32 550 +nim arccosh math.html#arccosh,float64 proc arccosh(x: float64): float64 551 +nim arctanh math.html#arctanh,float32 proc arctanh(x: float32): float32 556 +nim arctanh math.html#arctanh,float64 proc arctanh(x: float64): float64 557 +nim cot math.html#cot,T proc cot[T: float32 | float64](x: T): T 590 +nim sec math.html#sec,T proc sec[T: float32 | float64](x: T): T 592 +nim csc math.html#csc,T proc csc[T: float32 | float64](x: T): T 594 +nim coth math.html#coth,T proc coth[T: float32 | float64](x: T): T 597 +nim sech math.html#sech,T proc sech[T: float32 | float64](x: T): T 599 +nim csch math.html#csch,T proc csch[T: float32 | float64](x: T): T 601 +nim arccot math.html#arccot,T proc arccot[T: float32 | float64](x: T): T 604 +nim arcsec math.html#arcsec,T proc arcsec[T: float32 | float64](x: T): T 606 +nim arccsc math.html#arccsc,T proc arccsc[T: float32 | float64](x: T): T 608 +nim arccoth math.html#arccoth,T proc arccoth[T: float32 | float64](x: T): T 611 +nim arcsech math.html#arcsech,T proc arcsech[T: float32 | float64](x: T): T 613 +nim arccsch math.html#arccsch,T proc arccsch[T: float32 | float64](x: T): T 615 +nim hypot math.html#hypot,float32,float32 proc hypot(x, y: float32): float32 621 +nim hypot math.html#hypot,float64,float64 proc hypot(x, y: float64): float64 622 +nim pow math.html#pow,float32,float32 proc pow(x, y: float32): float32 627 +nim pow math.html#pow,float64,float64 proc pow(x, y: float64): float64 628 +nim erf math.html#erf,float32 proc erf(x: float32): float32 644 +nim erf math.html#erf,float64 proc erf(x: float64): float64 645 +nim erfc math.html#erfc,float32 proc erfc(x: float32): float32 649 +nim erfc math.html#erfc,float64 proc erfc(x: float64): float64 650 +nim gamma math.html#gamma,float32 proc gamma(x: float32): float32 654 +nim gamma math.html#gamma,float64 proc gamma(x: float64): float64 655 +nim lgamma math.html#lgamma,float32 proc lgamma(x: float32): float32 666 +nim lgamma math.html#lgamma,float64 proc lgamma(x: float64): float64 667 +nim floor math.html#floor,float32 proc floor(x: float32): float32 675 +nim floor math.html#floor,float64 proc floor(x: float64): float64 676 +nim ceil math.html#ceil,float32 proc ceil(x: float32): float32 688 +nim ceil math.html#ceil,float64 proc ceil(x: float64): float64 689 +nim round math.html#round,float32 proc round(x: float32): float32 758 +nim round math.html#round,float64 proc round(x: float64): float64 759 +nim trunc math.html#trunc,float32 proc trunc(x: float32): float32 776 +nim trunc math.html#trunc,float64 proc trunc(x: float64): float64 777 +nim `mod` math.html#mod,float32,float32 proc `mod`(x, y: float32): float32 788 +nim `mod` math.html#mod,float64,float64 proc `mod`(x, y: float64): float64 789 +nim round math.html#round,T,int proc round[T: float32 | float64](x: T; places: int): T 840 +nim floorDiv math.html#floorDiv,T,T proc floorDiv[T: SomeInteger](x, y: T): T 860 +nim floorMod math.html#floorMod,T,T proc floorMod[T: SomeNumber](x, y: T): T 880 +nim euclDiv math.html#euclDiv,T,T proc euclDiv[T: SomeInteger](x, y: T): T 897 +nim euclMod math.html#euclMod,T,T proc euclMod[T: SomeNumber](x, y: T): T 912 +nim ceilDiv math.html#ceilDiv,T,T proc ceilDiv[T: SomeInteger](x, y: T): T 925 +nim frexp math.html#frexp,T proc frexp[T: float32 | float64](x: T): tuple[frac: T, exp: int] 977 +nim frexp math.html#frexp,T,int proc frexp[T: float32 | float64](x: T; exponent: var int): T 1019 +nim log2 math.html#log2,float32 proc log2(x: float32): float32 1047 +nim log2 math.html#log2,float64 proc log2(x: float64): float64 1048 +nim splitDecimal math.html#splitDecimal,T proc splitDecimal[T: float32 | float64](x: T): tuple[intpart: T, floatpart: T] 1061 +nim degToRad math.html#degToRad,T proc degToRad[T: float32 | float64](d: T): T 1081 +nim radToDeg math.html#radToDeg,T proc radToDeg[T: float32 | float64](d: T): T 1091 +nim sgn math.html#sgn,T proc sgn[T: SomeNumber](x: T): int 1101 +nim sum math.html#sum,openArray[T] proc sum[T](x: openArray[T]): T 1118 +nim prod math.html#prod,openArray[T] proc prod[T](x: openArray[T]): T 1133 +nim cumsummed math.html#cumsummed,openArray[T] proc cumsummed[T](x: openArray[T]): seq[T] 1148 +nim cumsum math.html#cumsum,openArray[T] proc cumsum[T](x: var openArray[T]) 1166 +nim `^` math.html#^,T,Natural proc `^`[T: SomeNumber](x: T; y: Natural): T 1181 +nim `^` math.html#^,T,U proc `^`[T: SomeNumber; U: SomeFloat](x: T; y: U): float 1217 +nim gcd math.html#gcd,T,T proc gcd[T](x, y: T): T 1255 +nim gcd math.html#gcd,SomeInteger,SomeInteger proc gcd(x, y: SomeInteger): SomeInteger 1276 +nim gcd math.html#gcd,openArray[T] proc gcd[T](x: openArray[T]): T 1310 +nim lcm math.html#lcm,T,T proc lcm[T](x, y: T): T 1322 +nim clamp math.html#clamp,T,Slice[T] proc clamp[T](val: T; bounds: Slice[T]): T 1333 +nim lcm math.html#lcm,openArray[T] proc lcm[T](x: openArray[T]): T 1345 +heading See also math.html#see-also See also 0 +nimgrp log2 math.html#log2-procs-all proc 1047 +nimgrp pow math.html#pow-procs-all proc 627 +nimgrp ceil math.html#ceil-procs-all proc 688 +nimgrp floor math.html#floor-procs-all proc 675 +nimgrp sinh math.html#sinh-procs-all proc 477 +nimgrp arctan2 math.html#arctan2-procs-all proc 532 +nimgrp gamma math.html#gamma-procs-all proc 654 +nimgrp round math.html#round-procs-all proc 758 +nimgrp arcsinh math.html#arcsinh-procs-all proc 544 +nimgrp cbrt math.html#cbrt-procs-all proc 377 +nimgrp mod math.html#mod-procs-all proc 788 +nimgrp tan math.html#tan-procs-all proc 468 +nimgrp sin math.html#sin-procs-all proc 450 +nimgrp gcd math.html#gcd-procs-all proc 1255 +nimgrp hypot math.html#hypot-procs-all proc 621 +nimgrp ln math.html#ln-procs-all proc 387 +nimgrp sqrt math.html#sqrt-procs-all proc 368 +nimgrp exp math.html#exp-procs-all proc 440 +nimgrp trunc math.html#trunc-procs-all proc 776 +nimgrp arctanh math.html#arctanh-procs-all proc 556 +nimgrp arcsin math.html#arcsin-procs-all proc 504 +nimgrp arctan math.html#arctan-procs-all proc 522 +nimgrp arccosh math.html#arccosh-procs-all proc 550 +nimgrp frexp math.html#frexp-procs-all proc 977 +nimgrp ^ math.html#^-procs-all proc 1181 +nimgrp arccos math.html#arccos-procs-all proc 513 +nimgrp erfc math.html#erfc-procs-all proc 649 +nimgrp erf math.html#erf-procs-all proc 644 +nimgrp log10 math.html#log10-procs-all proc 428 +nimgrp tanh math.html#tanh-procs-all proc 495 +nimgrp cos math.html#cos-procs-all proc 459 +nimgrp lcm math.html#lcm-procs-all proc 1322 +nimgrp lgamma math.html#lgamma-procs-all proc 666 +nimgrp cosh math.html#cosh-procs-all proc 486 diff --git a/md5.html b/md5.html new file mode 100644 index 0000000000000..c7b0054cde0e5 --- /dev/null +++ b/md5.html @@ -0,0 +1,268 @@ + + + + + + + +src/checksums/md5 + + + + + + + + + + + + + + + + +
+
+

src/checksums/md5

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

Note: +In order to use this module, run nimble install checksums.
+

Module for computing MD5 checksums.

+

Be aware that using MD5 for cryptographic purposes is strongly discouraged as it is no longer deemed secure enough even against consumer grade computational resources.

+

This module also works at compile time and in JavaScript.

+ +

See also

+

+
+

Types

+
+
+
MD5Context {.final.} = object
+
+ + + +
+
+
+
MD5Digest = array[0 .. 15, uint8]
+
+ + MD5 checksum of a string, obtained with the toMD5 proc. + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(d: MD5Digest): string {....raises: [], tags: [], forbids: [].}
+
+ + Converts a MD5Digest value into its string representation. + +
+
+ +
+
+
+
proc `==`(D1, D2: MD5Digest): bool {....raises: [], tags: [], forbids: [].}
+
+ + Checks if two MD5Digest values are identical. + +
+
+ +
+
+
+
proc getMD5(s: string): string {....raises: [], tags: [], forbids: [].}
+
+ +

Computes an MD5 value of s and returns its string representation.

+

See also:

+
  • toMD5 proc which returns the MD5Digest of a string
  • +
+ +

Example:

+
assert getMD5("abc") == "900150983cd24fb0d6963f7d28e17f72"
+ +
+
+ +
+
+
+
proc md5Final(c: var MD5Context; digest: var MD5Digest) {....raises: [], tags: [],
+    gcsafe, forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc md5Init(c: var MD5Context) {....raises: [], tags: [], gcsafe, forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc md5Update(c: var MD5Context; input: cstring; len: int) {....raises: [],
+    tags: [], gcsafe, forbids: [].}
+
+ +

Updates the MD5Context with the input data of length len.

+

If you use the toMD5 proc, there's no need to call this function explicitly.

+ + +
+
+
+
proc md5Update(c: var MD5Context; input: openArray[uint8]) {....raises: [],
+    tags: [], gcsafe, forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc toMD5(s: string): MD5Digest {....raises: [], tags: [], forbids: [].}
+
+ +

Computes the MD5Digest value for a string s.

+

See also:

+
  • getMD5 proc which returns a string representation of the MD5Digest
  • +
  • $ proc for converting MD5Digest to string
  • +
+ +

Example:

+
assert $toMD5("abc") == "900150983cd24fb0d6963f7d28e17f72"
+ +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/md5.idx b/md5.idx new file mode 100644 index 0000000000000..7aa4ff136dfa0 --- /dev/null +++ b/md5.idx @@ -0,0 +1,13 @@ +nimTitle md5 md5.html module src/checksums/md5 0 +nim MD5Digest md5.html#MD5Digest type MD5Digest 35 +nim MD5Context md5.html#MD5Context object MD5Context 38 +nim md5Init md5.html#md5Init,MD5Context proc md5Init(c: var MD5Context) 209 +nim md5Update md5.html#md5Update,MD5Context,openArray[uint8] proc md5Update(c: var MD5Context; input: openArray[uint8]) 210 +nim md5Final md5.html#md5Final,MD5Context,MD5Digest proc md5Final(c: var MD5Context; digest: var MD5Digest) 212 +nim md5Update md5.html#md5Update,MD5Context,cstring,int proc md5Update(c: var MD5Context; input: cstring; len: int) 214 +nim toMD5 md5.html#toMD5,string proc toMD5(s: string): MD5Digest 223 +nim `$` md5.html#$,MD5Digest proc `$`(d: MD5Digest): string 238 +nim getMD5 md5.html#getMD5,string proc getMD5(s: string): string 246 +nim `==` md5.html#==,MD5Digest,MD5Digest proc `==`(D1, D2: MD5Digest): bool 262 +nimgrp md5update md5.html#md5Update-procs-all proc 210 +heading See also md5.html#see-also See also 0 diff --git a/memfiles.html b/memfiles.html new file mode 100644 index 0000000000000..80d3b2884a948 --- /dev/null +++ b/memfiles.html @@ -0,0 +1,463 @@ + + + + + + + +std/memfiles + + + + + + + + + + + + + + + + +
+
+

std/memfiles

+
+ +
+ Source   +Edit   + +
+ +

+
Authors:Zahary Karadjov, Andreas Rumpf

This module provides support for memory mapped files (Posix's mmap) on the different operating systems.

+

It also provides some fast iterators over lines in text files (or other "line-like", variable length, delimited records).

+

+ +
+

Types

+
+
+
MemFile = object
+  mem*: pointer              ## a pointer to the memory mapped file. The pointer
+                             ## can be used directly to change the contents of the
+                             ## file, if it was opened with write access.
+  size*: int                 ## size of the memory mapped file
+  when defined(windows):
+    fHandle*: Handle ## **Caution**: Windows specific public field to allow
+                     ## even more low level trickery.
+    mapHandle*: Handle       ## **Caution**: Windows specific public field.
+    wasOpened*: bool         ## **Caution**: Windows specific public field.
+  else:
+    handle*: cint            ## **Caution**: Posix specific public field.
+    ## **Caution**: Platform specific private field.
+
+ + represents a memory mapped file + Source   +Edit   + +
+
+
+
MemMapFileStream = ref MemMapFileStreamObj
+
+ + a stream that encapsulates a MemFile + Source   +Edit   + +
+
+
+
MemMapFileStreamObj = object of Stream
+
+ + + Source   +Edit   + +
+
+
+
MemSlice = object
+  data*: pointer
+  size*: int
+
+ + represent slice of a MemFile for iteration over delimited lines/records + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(ms: MemSlice): string {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Return a Nim string built from a MemSlice. + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(x, y: MemSlice): bool {....raises: [], tags: [], forbids: [].}
+
+ + Compare a pair of MemSlice for strict equality. + Source   +Edit   + +
+
+ +
+
+
+
proc close(f: var MemFile) {....raises: [OSError], tags: [], forbids: [].}
+
+ + closes the memory mapped file f. All changes are written back to the file system, if f was opened with write access. + Source   +Edit   + +
+
+ +
+
+
+
proc flush(f: var MemFile; attempts: Natural = 3) {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ + Flushes f's buffer for the number of attempts equal to attempts. If were errors an exception OSError will be raised. + Source   +Edit   + +
+
+ +
+
+
+
proc mapMem(m: var MemFile; mode: FileMode = fmRead; mappedSize = -1;
+            offset = 0; mapFlags = cint(-1)): pointer {.
+    ...raises: [IOError, OSError], tags: [], forbids: [].}
+
+ +

returns a pointer to a mapped portion of MemFile m

+

mappedSize of -1 maps to the whole file, and offset must be multiples of the PAGE SIZE of your OS

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newMemMapFileStream(filename: string; mode: FileMode = fmRead;
+                         fileSize: int = -1): MemMapFileStream {.
+    ...raises: [IOError, OSError], tags: [], forbids: [].}
+
+ + creates a new stream from the file named filename with the mode mode. Raises ## OSError if the file cannot be opened. See the system module for a list of available FileMode enums. fileSize can only be set if the file does not exist and is opened with write access (e.g., with fmReadWrite). + Source   +Edit   + +
+
+ +
+
+
+
proc open(filename: string; mode: FileMode = fmRead; mappedSize = -1;
+          offset = 0; newFileSize = -1; allowRemap = false; mapFlags = cint(-1)): MemFile {.
+    ...raises: [IOError, OSError], tags: [], forbids: [].}
+
+ +

opens a memory mapped file. If this fails, OSError is raised.

+

newFileSize can only be set if the file does not exist and is opened with write access (e.g., with fmReadWrite).

+

mappedSize and offset can be used to map only a slice of the file.

+

offset must be multiples of the PAGE SIZE of your OS (usually 4K or 8K but is unique to your OS)

+

allowRemap only needs to be true if you want to call mapMem on the resulting MemFile; else file handles are not kept open.

+

mapFlags allows callers to override default choices for memory mapping flags with a bitwise mask of a variety of likely platform-specific flags which may be ignored or even cause open to fail if misspecified.

+

Example:

+

var
+  mm, mm_full, mm_half: MemFile
+
+mm = memfiles.open("/tmp/test.mmap", mode = fmWrite, newFileSize = 1024)    # Create a new file
+mm.close()
+
+# Read the whole file, would fail if newFileSize was set
+mm_full = memfiles.open("/tmp/test.mmap", mode = fmReadWrite, mappedSize = -1)
+
+# Read the first 512 bytes
+mm_half = memfiles.open("/tmp/test.mmap", mode = fmReadWrite, mappedSize = 512)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc resize(f: var MemFile; newFileSize: int) {....raises: [IOError, OSError],
+    tags: [], forbids: [].}
+
+ + Resize & re-map the file underlying an allowRemap MemFile. If the OS/FS supports it, file space is reserved to ensure room for new virtual pages. Caller should wait often enough for flush to finish to limit use of system RAM for write buffering, perhaps just prior to this call. Note: this assumes the entire file is mapped read-write at offset 0. Also, the value of .mem will probably change. + Source   +Edit   + +
+
+ +
+
+
+
proc unmapMem(f: var MemFile; p: pointer; size: int) {....raises: [OSError],
+    tags: [], forbids: [].}
+
+ +

unmaps the memory region (p, <p+size) of the mapped file f. All changes are written back to the file system, if f was opened with write access.

+

size must be of exactly the size that was requested via mapMem.

+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator lines(mfile: MemFile; buf: var string; delim = '\n'; eat = '\r'): string {.
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Replace contents of passed buffer with each new line, like readLine(File). delim, eat, and delimiting logic is exactly as for memSlices, but Nim strings are returned.

+

Example:

+

var buffer: string = ""
+for line in lines(memfiles.open("foo"), buffer):
+  echo line

+ + Source   +Edit   + +
+
+
+
iterator lines(mfile: MemFile; delim = '\n'; eat = '\r'): string {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Return each line in a file as a Nim string, like lines(File). delim, eat, and delimiting logic is exactly as for memSlices, but Nim strings are returned.

+

Example:

+

for line in lines(memfiles.open("foo")):
+  echo line

+ + Source   +Edit   + +
+
+ +
+
+
+
iterator memSlices(mfile: MemFile; delim = '\n'; eat = '\r'): MemSlice {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Iterates over [optional eat] delim-delimited slices in MemFile mfile.

+

Default parameters parse lines ending in either Unix(\l) or Windows(\r\l) style on on a line-by-line basis. I.e., not every line needs the same ending. Unlike readLine(File) & lines(File), archaic MacOS9 \r-delimited lines are not supported as a third option for each line. Such archaic MacOS9 files can be handled by passing delim='\r', eat='\0', though.

+

Delimiters are not part of the returned slice. A final, unterminated line or record is returned just like any other.

+

Non-default delimiters can be passed to allow iteration over other sorts of "line-like" variable length records. Pass eat='\0' to be strictly delim-delimited. (Eating an optional prefix equal to '\0' is not supported.)

+

This zero copy, memchr-limited interface is probably the fastest way to iterate over line-like records in a file. However, returned (data,size) objects are not Nim strings, bounds checked Nim arrays, or even terminated C strings. So, care is required to access the data (e.g., think C mem* functions, not str* functions).

+

Example:

+

var count = 0
+for slice in memSlices(memfiles.open("foo")):
+  if slice.size > 0 and cast[cstring](slice.data)[0] != '#':
+    inc(count)
+echo count

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/memfiles.idx b/memfiles.idx new file mode 100644 index 0000000000000..a48add4201ae9 --- /dev/null +++ b/memfiles.idx @@ -0,0 +1,20 @@ +nimTitle memfiles memfiles.html module std/memfiles 0 +nim MemFile memfiles.html#MemFile object MemFile 68 +nim mapMem memfiles.html#mapMem,MemFile,FileMode,int,int proc mapMem(m: var MemFile; mode: FileMode = fmRead; mappedSize = -1; offset = 0;\n mapFlags = cint(-1)): pointer 83 +nim unmapMem memfiles.html#unmapMem,MemFile,pointer,int proc unmapMem(f: var MemFile; p: pointer; size: int) 121 +nim open memfiles.html#open,string,FileMode,int,int,int proc open(filename: string; mode: FileMode = fmRead; mappedSize = -1; offset = 0;\n newFileSize = -1; allowRemap = false; mapFlags = cint(-1)): MemFile 134 +nim flush memfiles.html#flush,MemFile,Natural proc flush(f: var MemFile; attempts: Natural = 3) 294 +nim resize memfiles.html#resize,MemFile,int proc resize(f: var MemFile; newFileSize: int) 316 +nim close memfiles.html#close,MemFile proc close(f: var MemFile) 369 +nim MemSlice memfiles.html#MemSlice object MemSlice 404 +nim `==` memfiles.html#==,MemSlice,MemSlice proc `==`(x, y: MemSlice): bool 408 +nim `$` memfiles.html#$,MemSlice proc `$`(ms: MemSlice): string 412 +nim memSlices memfiles.html#memSlices.i,MemFile,char,char iterator memSlices(mfile: MemFile; delim = '\n'; eat = '\r'): MemSlice 417 +nim lines memfiles.html#lines.i,MemFile,string,char,char iterator lines(mfile: MemFile; buf: var string; delim = '\n'; eat = '\r'): string 469 +nim lines memfiles.html#lines.i,MemFile,char,char iterator lines(mfile: MemFile; delim = '\n'; eat = '\r'): string 489 +nim MemMapFileStream memfiles.html#MemMapFileStream type MemMapFileStream 506 +nim MemMapFileStreamObj memfiles.html#MemMapFileStreamObj object MemMapFileStreamObj 507 +nim newMemMapFileStream memfiles.html#newMemMapFileStream,string,FileMode,int proc newMemMapFileStream(filename: string; mode: FileMode = fmRead;\n fileSize: int = -1): MemMapFileStream 550 +idx memory mapped files memfiles.html#memory-mapped-files_1 Module memfiles 0 +idx mmap memfiles.html#mmap_1 Module memfiles 0 +nimgrp lines memfiles.html#lines-iterators-all iterator 469 diff --git a/mimetypes.html b/mimetypes.html new file mode 100644 index 0000000000000..a9d6d047f8254 --- /dev/null +++ b/mimetypes.html @@ -0,0 +1,1718 @@ + + + + + + + +std/mimetypes + + + + + + + + + + + + + + + + +
+
+

std/mimetypes

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a mimetypes database +

Example:

+
import std/mimetypes
+var m = newMimetypes()
+doAssert m.getMimetype("mp4") == "video/mp4"
+doAssert m.getExt("text/html") == "html"
+## Values can be uppercase too.
+doAssert m.getMimetype("MP4") == "video/mp4"
+doAssert m.getExt("TEXT/HTML") == "html"
+## If values are invalid then `default` is returned.
+doAssert m.getMimetype("INVALID") == "text/plain"
+doAssert m.getExt("INVALID/NONEXISTENT") == "txt"
+doAssert m.getMimetype("") == "text/plain"
+doAssert m.getExt("") == "txt"
+## Register new Mimetypes.
+m.register(ext = "fakext", mimetype = "text/fakelang")
+doAssert m.getMimetype("fakext") == "text/fakelang"
+doAssert m.getMimetype("FaKeXT") == "text/fakelang"

+ +
+

Types

+
+
+
MimeDB = object
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
mimes = [("ez", "application/andrew-inset"), ("aw", "application/applixware"),
+         ("atom", "application/atom+xml"),
+         ("atomcat", "application/atomcat+xml"),
+         ("atomsvc", "application/atomsvc+xml"),
+         ("ccxml", "application/ccxml+xml"),
+         ("cdmia", "application/cdmi-capability"),
+         ("cdmic", "application/cdmi-container"),
+         ("cdmid", "application/cdmi-domain"),
+         ("cdmio", "application/cdmi-object"),
+         ("cdmiq", "application/cdmi-queue"), ("cu", "application/cu-seeme"),
+         ("davmount", "application/davmount+xml"),
+         ("dbk", "application/docbook+xml"), ("dssc", "application/dssc+der"),
+         ("xdssc", "application/dssc+xml"), ("ecma", "application/ecmascript"),
+         ("emma", "application/emma+xml"), ("epub", "application/epub+zip"),
+         ("exi", "application/exi"), ("pfr", "application/font-tdpfr"),
+         ("gml", "application/gml+xml"), ("gpx", "application/gpx+xml"),
+         ("gxf", "application/gxf"), ("stk", "application/hyperstudio"),
+         ("ink", "application/inkml+xml"), ("inkml", "application/inkml+xml"),
+         ("ipfix", "application/ipfix"), ("jar", "application/java-archive"),
+         ("ser", "application/java-serialized-object"),
+         ("class", "application/java-vm"), ("json", "application/json"),
+         ("jsonml", "application/jsonml+json"),
+         ("lostxml", "application/lost+xml"),
+         ("hqx", "application/mac-binhex40"),
+         ("cpt", "application/mac-compactpro"),
+         ("mads", "application/mads+xml"), ("mrc", "application/marc"),
+         ("mrcx", "application/marcxml+xml"),
+         ("ma", "application/mathematica"), ("nb", "application/mathematica"),
+         ("mb", "application/mathematica"),
+         ("mathml", "application/mathml+xml"), ("mbox", "application/mbox"),
+         ("mscml", "application/mediaservercontrol+xml"),
+         ("metalink", "application/metalink+xml"),
+         ("meta4", "application/metalink4+xml"),
+         ("mets", "application/mets+xml"), ("mods", "application/mods+xml"),
+         ("m21", "application/mp21"), ("mp21", "application/mp21"),
+         ("mp4s", "application/mp4"), ("doc", "application/msword"),
+         ("dot", "application/msword"), ("mxf", "application/mxf"),
+         ("bin", "application/octet-stream"),
+         ("dms", "application/octet-stream"),
+         ("lrf", "application/octet-stream"),
+         ("mar", "application/octet-stream"),
+         ("so", "application/octet-stream"),
+         ("dist", "application/octet-stream"),
+         ("distz", "application/octet-stream"),
+         ("pkg", "application/octet-stream"),
+         ("bpk", "application/octet-stream"),
+         ("dump", "application/octet-stream"),
+         ("elc", "application/octet-stream"),
+         ("deploy", "application/octet-stream"), ("oda", "application/oda"),
+         ("opf", "application/oebps-package+xml"), ("ogx", "application/ogg"),
+         ("omdoc", "application/omdoc+xml"), ("onetoc", "application/onenote"),
+         ("onetoc2", "application/onenote"), ("onetmp", "application/onenote"),
+         ("onepkg", "application/onenote"), ("oxps", "application/oxps"),
+         ("xer", "application/patch-ops-error+xml"),
+         ("pdf", "application/pdf"), ("pgp", "application/pgp-encrypted"),
+         ("asc", "application/pgp-signature"),
+         ("sig", "application/pgp-signature"),
+         ("prf", "application/pics-rules"), ("p10", "application/pkcs10"),
+         ("p7m", "application/pkcs7-mime"), ("p7c", "application/pkcs7-mime"),
+         ("p7s", "application/pkcs7-signature"), ("p8", "application/pkcs8"),
+         ("ac", "application/pkix-attr-cert"),
+         ("cer", "application/pkix-cert"), ("crl", "application/pkix-crl"),
+         ("pkipath", "application/pkix-pkipath"),
+         ("pki", "application/pkixcmp"), ("pls", "application/pls+xml"),
+         ("ai", "application/postscript"), ("eps", "application/postscript"),
+         ("ps", "application/postscript"), ("cww", "application/prs.cww"),
+         ("pskcxml", "application/pskc+xml"), ("rdf", "application/rdf+xml"),
+         ("rif", "application/reginfo+xml"),
+         ("rnc", "application/relax-ng-compact-syntax"),
+         ("rl", "application/resource-lists+xml"),
+         ("rld", "application/resource-lists-diff+xml"),
+         ("rs", "application/rls-services+xml"),
+         ("gbr", "application/rpki-ghostbusters"),
+         ("mft", "application/rpki-manifest"), ("roa", "application/rpki-roa"),
+         ("rsd", "application/rsd+xml"), ("rss", "application/rss+xml"),
+         ("rtf", "application/rtf"), ("sbml", "application/sbml+xml"),
+         ("scq", "application/scvp-cv-request"),
+         ("scs", "application/scvp-cv-response"),
+         ("spq", "application/scvp-vp-request"),
+         ("spp", "application/scvp-vp-response"), ("sdp", "application/sdp"),
+         ("setpay", "application/set-payment-initiation"),
+         ("setreg", "application/set-registration-initiation"),
+         ("shf", "application/shf+xml"), ("smi", "application/smil+xml"),
+         ("smil", "application/smil+xml"), ("rq", "application/sparql-query"),
+         ("srx", "application/sparql-results+xml"),
+         ("gram", "application/srgs"), ("grxml", "application/srgs+xml"),
+         ("sru", "application/sru+xml"), ("ssdl", "application/ssdl+xml"),
+         ("ssml", "application/ssml+xml"), ("tei", "application/tei+xml"),
+         ("teicorpus", "application/tei+xml"),
+         ("tfi", "application/thraud+xml"),
+         ("tsd", "application/timestamped-data"),
+         ("plb", "application/vnd.3gpp.pic-bw-large"),
+         ("psb", "application/vnd.3gpp.pic-bw-small"),
+         ("pvb", "application/vnd.3gpp.pic-bw-var"),
+         ("tcap", "application/vnd.3gpp2.tcap"),
+         ("pwn", "application/vnd.3m.post-it-notes"),
+         ("aso", "application/vnd.accpac.simply.aso"),
+         ("imp", "application/vnd.accpac.simply.imp"),
+         ("acu", "application/vnd.acucobol"),
+         ("atc", "application/vnd.acucorp"),
+         ("acutc", "application/vnd.acucorp"), ("air",
+    "application/vnd.adobe.air-application-installer-package+zip"),
+         ("fcdt", "application/vnd.adobe.formscentral.fcdt"),
+         ("fxp", "application/vnd.adobe.fxp"),
+         ("fxpl", "application/vnd.adobe.fxp"),
+         ("xdp", "application/vnd.adobe.xdp+xml"),
+         ("xfdf", "application/vnd.adobe.xfdf"),
+         ("ahead", "application/vnd.ahead.space"),
+         ("azf", "application/vnd.airzip.filesecure.azf"),
+         ("azs", "application/vnd.airzip.filesecure.azs"),
+         ("azw", "application/vnd.amazon.ebook"),
+         ("acc", "application/vnd.americandynamics.acc"),
+         ("ami", "application/vnd.amiga.ami"),
+         ("apk", "application/vnd.android.package-archive"),
+         ("cii", "application/vnd.anser-web-certificate-issue-initiation"),
+         ("fti", "application/vnd.anser-web-funds-transfer-initiation"),
+         ("atx", "application/vnd.antix.game-component"),
+         ("mpkg", "application/vnd.apple.installer+xml"),
+         ("m3u8", "application/vnd.apple.mpegurl"),
+         ("swi", "application/vnd.aristanetworks.swi"),
+         ("iota", "application/vnd.astraea-software.iota"),
+         ("aep", "application/vnd.audiograph"),
+         ("mpm", "application/vnd.blueice.multipass"),
+         ("bmi", "application/vnd.bmi"),
+         ("rep", "application/vnd.businessobjects"),
+         ("cdxml", "application/vnd.chemdraw+xml"),
+         ("mmd", "application/vnd.chipnuts.karaoke-mmd"),
+         ("cdy", "application/vnd.cinderella"),
+         ("cla", "application/vnd.claymore"),
+         ("rp9", "application/vnd.cloanto.rp9"),
+         ("c4g", "application/vnd.clonk.c4group"),
+         ("c4d", "application/vnd.clonk.c4group"),
+         ("c4f", "application/vnd.clonk.c4group"),
+         ("c4p", "application/vnd.clonk.c4group"),
+         ("c4u", "application/vnd.clonk.c4group"),
+         ("c11amc", "application/vnd.cluetrust.cartomobile-config"),
+         ("c11amz", "application/vnd.cluetrust.cartomobile-config-pkg"),
+         ("csp", "application/vnd.commonspace"),
+         ("cdbcmsg", "application/vnd.contact.cmsg"),
+         ("cmc", "application/vnd.cosmocaller"),
+         ("clkx", "application/vnd.crick.clicker"),
+         ("clkk", "application/vnd.crick.clicker.keyboard"),
+         ("clkp", "application/vnd.crick.clicker.palette"),
+         ("clkt", "application/vnd.crick.clicker.template"),
+         ("clkw", "application/vnd.crick.clicker.wordbank"),
+         ("wbs", "application/vnd.criticaltools.wbs+xml"),
+         ("pml", "application/vnd.ctc-posml"),
+         ("ppd", "application/vnd.cups-ppd"),
+         ("car", "application/vnd.curl.car"),
+         ("pcurl", "application/vnd.curl.pcurl"),
+         ("dart", "application/vnd.dart"),
+         ("rdz", "application/vnd.data-vision.rdz"),
+         ("uvf", "application/vnd.dece.data"),
+         ("uvvf", "application/vnd.dece.data"),
+         ("uvd", "application/vnd.dece.data"),
+         ("uvvd", "application/vnd.dece.data"),
+         ("uvt", "application/vnd.dece.ttml+xml"),
+         ("uvvt", "application/vnd.dece.ttml+xml"),
+         ("uvx", "application/vnd.dece.unspecified"),
+         ("uvvx", "application/vnd.dece.unspecified"),
+         ("uvz", "application/vnd.dece.zip"),
+         ("uvvz", "application/vnd.dece.zip"),
+         ("fe_launch", "application/vnd.denovo.fcselayout-link"),
+         ("dna", "application/vnd.dna"), ("mlp", "application/vnd.dolby.mlp"),
+         ("dpg", "application/vnd.dpgraph"),
+         ("dfac", "application/vnd.dreamfactory"),
+         ("kpxx", "application/vnd.ds-keypoint"),
+         ("ait", "application/vnd.dvb.ait"),
+         ("svc", "application/vnd.dvb.service"),
+         ("geo", "application/vnd.dynageo"),
+         ("mag", "application/vnd.ecowin.chart"),
+         ("nml", "application/vnd.enliven"),
+         ("esf", "application/vnd.epson.esf"),
+         ("msf", "application/vnd.epson.msf"),
+         ("qam", "application/vnd.epson.quickanime"),
+         ("slt", "application/vnd.epson.salt"),
+         ("ssf", "application/vnd.epson.ssf"),
+         ("es3", "application/vnd.eszigno3+xml"),
+         ("et3", "application/vnd.eszigno3+xml"),
+         ("ez2", "application/vnd.ezpix-album"),
+         ("ez3", "application/vnd.ezpix-package"),
+         ("fdf", "application/vnd.fdf"),
+         ("mseed", "application/vnd.fdsn.mseed"),
+         ("seed", "application/vnd.fdsn.seed"),
+         ("dataless", "application/vnd.fdsn.seed"),
+         ("gph", "application/vnd.flographit"),
+         ("ftc", "application/vnd.fluxtime.clip"),
+         ("fm", "application/vnd.framemaker"),
+         ("frame", "application/vnd.framemaker"),
+         ("maker", "application/vnd.framemaker"),
+         ("book", "application/vnd.framemaker"),
+         ("fnc", "application/vnd.frogans.fnc"),
+         ("ltf", "application/vnd.frogans.ltf"),
+         ("fsc", "application/vnd.fsc.weblaunch"),
+         ("oas", "application/vnd.fujitsu.oasys"),
+         ("oa2", "application/vnd.fujitsu.oasys2"),
+         ("oa3", "application/vnd.fujitsu.oasys3"),
+         ("fg5", "application/vnd.fujitsu.oasysgp"),
+         ("bh2", "application/vnd.fujitsu.oasysprs"),
+         ("ddd", "application/vnd.fujixerox.ddd"),
+         ("xdw", "application/vnd.fujixerox.docuworks"),
+         ("xbd", "application/vnd.fujixerox.docuworks.binder"),
+         ("fzs", "application/vnd.fuzzysheet"),
+         ("txd", "application/vnd.genomatix.tuxedo"),
+         ("ggb", "application/vnd.geogebra.file"),
+         ("ggs", "application/vnd.geogebra.slides"),
+         ("ggt", "application/vnd.geogebra.tool"),
+         ("gex", "application/vnd.geometry-explorer"),
+         ("gre", "application/vnd.geometry-explorer"),
+         ("gxt", "application/vnd.geonext"),
+         ("g2w", "application/vnd.geoplan"),
+         ("g3w", "application/vnd.geospace"), ("gmx", "application/vnd.gmx"),
+         ("kml", "application/vnd.google-earth.kml+xml"),
+         ("kmz", "application/vnd.google-earth.kmz"),
+         ("gqf", "application/vnd.grafeq"), ("gqs", "application/vnd.grafeq"),
+         ("gac", "application/vnd.groove-account"),
+         ("ghf", "application/vnd.groove-help"),
+         ("gim", "application/vnd.groove-identity-message"),
+         ("grv", "application/vnd.groove-injector"),
+         ("gtm", "application/vnd.groove-tool-message"),
+         ("tpl", "application/vnd.groove-tool-template"),
+         ("vcg", "application/vnd.groove-vcard"),
+         ("hal", "application/vnd.hal+xml"),
+         ("zmm", "application/vnd.handheld-entertainment+xml"),
+         ("hbci", "application/vnd.hbci"),
+         ("les", "application/vnd.hhe.lesson-player"),
+         ("hpgl", "application/vnd.hp-hpgl"),
+         ("hpid", "application/vnd.hp-hpid"),
+         ("hps", "application/vnd.hp-hps"), ("jlt", "application/vnd.hp-jlyt"),
+         ("pcl", "application/vnd.hp-pcl"),
+         ("pclxl", "application/vnd.hp-pclxl"),
+         ("sfd-hdstx", "application/vnd.hydrostatix.sof-data"),
+         ("mpy", "application/vnd.ibm.minipay"),
+         ("afp", "application/vnd.ibm.modcap"),
+         ("listafp", "application/vnd.ibm.modcap"),
+         ("list3820", "application/vnd.ibm.modcap"),
+         ("irm", "application/vnd.ibm.rights-management"),
+         ("sc", "application/vnd.ibm.secure-container"),
+         ("icc", "application/vnd.iccprofile"),
+         ("icm", "application/vnd.iccprofile"),
+         ("igl", "application/vnd.igloader"),
+         ("ivp", "application/vnd.immervision-ivp"),
+         ("ivu", "application/vnd.immervision-ivu"),
+         ("igm", "application/vnd.insors.igm"),
+         ("xpw", "application/vnd.intercon.formnet"),
+         ("xpx", "application/vnd.intercon.formnet"),
+         ("i2g", "application/vnd.intergeo"),
+         ("qbo", "application/vnd.intu.qbo"),
+         ("qfx", "application/vnd.intu.qfx"),
+         ("rcprofile", "application/vnd.ipunplugged.rcprofile"),
+         ("irp", "application/vnd.irepository.package+xml"),
+         ("xpr", "application/vnd.is-xpr"),
+         ("fcs", "application/vnd.isac.fcs"), ("jam", "application/vnd.jam"),
+         ("rms", "application/vnd.jcp.javame.midlet-rms"),
+         ("jisp", "application/vnd.jisp"),
+         ("joda", "application/vnd.joost.joda-archive"),
+         ("ktz", "application/vnd.kahootz"),
+         ("ktr", "application/vnd.kahootz"),
+         ("karbon", "application/vnd.kde.karbon"),
+         ("chrt", "application/vnd.kde.kchart"),
+         ("kfo", "application/vnd.kde.kformula"),
+         ("flw", "application/vnd.kde.kivio"),
+         ("kon", "application/vnd.kde.kontour"),
+         ("kpr", "application/vnd.kde.kpresenter"),
+         ("kpt", "application/vnd.kde.kpresenter"),
+         ("ksp", "application/vnd.kde.kspread"),
+         ("kwd", "application/vnd.kde.kword"),
+         ("kwt", "application/vnd.kde.kword"),
+         ("htke", "application/vnd.kenameaapp"),
+         ("kia", "application/vnd.kidspiration"),
+         ("kne", "application/vnd.kinar"), ("knp", "application/vnd.kinar"),
+         ("skp", "application/vnd.koan"), ("skd", "application/vnd.koan"),
+         ("skt", "application/vnd.koan"), ("skm", "application/vnd.koan"),
+         ("sse", "application/vnd.kodak-descriptor"),
+         ("lasxml", "application/vnd.las.las+xml"),
+         ("lbd", "application/vnd.llamagraphics.life-balance.desktop"),
+         ("lbe", "application/vnd.llamagraphics.life-balance.exchange+xml"),
+         ("123", "application/vnd.lotus-1-2-3"),
+         ("apr", "application/vnd.lotus-approach"),
+         ("pre", "application/vnd.lotus-freelance"),
+         ("nsf", "application/vnd.lotus-notes"),
+         ("org", "application/vnd.lotus-organizer"),
+         ("scm", "application/vnd.lotus-screencam"),
+         ("lwp", "application/vnd.lotus-wordpro"),
+         ("portpkg", "application/vnd.macports.portpkg"),
+         ("mcd", "application/vnd.mcd"),
+         ("mc1", "application/vnd.medcalcdata"),
+         ("cdkey", "application/vnd.mediastation.cdkey"),
+         ("mwf", "application/vnd.mfer"), ("mfm", "application/vnd.mfmp"),
+         ("flo", "application/vnd.micrografx.flo"),
+         ("igx", "application/vnd.micrografx.igx"),
+         ("mif", "application/vnd.mif"), ("daf", "application/vnd.mobius.daf"),
+         ("dis", "application/vnd.mobius.dis"),
+         ("mbk", "application/vnd.mobius.mbk"),
+         ("mqy", "application/vnd.mobius.mqy"),
+         ("msl", "application/vnd.mobius.msl"),
+         ("plc", "application/vnd.mobius.plc"),
+         ("txf", "application/vnd.mobius.txf"),
+         ("mpn", "application/vnd.mophun.application"),
+         ("mpc", "application/vnd.mophun.certificate"),
+         ("xul", "application/vnd.mozilla.xul+xml"),
+         ("cil", "application/vnd.ms-artgalry"),
+         ("cab", "application/vnd.ms-cab-compressed"),
+         ("xls", "application/vnd.ms-excel"),
+         ("xlm", "application/vnd.ms-excel"),
+         ("xla", "application/vnd.ms-excel"),
+         ("xlc", "application/vnd.ms-excel"),
+         ("xlt", "application/vnd.ms-excel"),
+         ("xlw", "application/vnd.ms-excel"),
+         ("xlam", "application/vnd.ms-excel.addin.macroenabled.12"),
+         ("xlsb", "application/vnd.ms-excel.sheet.binary.macroenabled.12"),
+         ("xlsm", "application/vnd.ms-excel.sheet.macroenabled.12"),
+         ("xltm", "application/vnd.ms-excel.template.macroenabled.12"),
+         ("eot", "application/vnd.ms-fontobject"),
+         ("chm", "application/vnd.ms-htmlhelp"),
+         ("ims", "application/vnd.ms-ims"), ("lrm", "application/vnd.ms-lrm"),
+         ("thmx", "application/vnd.ms-officetheme"),
+         ("cat", "application/vnd.ms-pki.seccat"),
+         ("stl", "application/vnd.ms-pki.stl"),
+         ("ppt", "application/vnd.ms-powerpoint"),
+         ("pps", "application/vnd.ms-powerpoint"),
+         ("pot", "application/vnd.ms-powerpoint"),
+         ("ppam", "application/vnd.ms-powerpoint.addin.macroenabled.12"), (
+    "pptm", "application/vnd.ms-powerpoint.presentation.macroenabled.12"),
+         ("sldm", "application/vnd.ms-powerpoint.slide.macroenabled.12"),
+         ("ppsm", "application/vnd.ms-powerpoint.slideshow.macroenabled.12"),
+         ("potm", "application/vnd.ms-powerpoint.template.macroenabled.12"),
+         ("mpp", "application/vnd.ms-project"),
+         ("mpt", "application/vnd.ms-project"),
+         ("docm", "application/vnd.ms-word.document.macroenabled.12"),
+         ("dotm", "application/vnd.ms-word.template.macroenabled.12"),
+         ("wps", "application/vnd.ms-works"),
+         ("wks", "application/vnd.ms-works"),
+         ("wcm", "application/vnd.ms-works"),
+         ("wdb", "application/vnd.ms-works"),
+         ("wpl", "application/vnd.ms-wpl"),
+         ("xps", "application/vnd.ms-xpsdocument"),
+         ("mseq", "application/vnd.mseq"), ("mus", "application/vnd.musician"),
+         ("msty", "application/vnd.muvee.style"),
+         ("taglet", "application/vnd.mynfc"),
+         ("nlu", "application/vnd.neurolanguage.nlu"), ("nim", "text/nim"),
+         ("nimble", "text/nimble"), ("nimf", "text/nim"), ("nims", "text/nim"),
+         ("ntf", "application/vnd.nitf"), ("nitf", "application/vnd.nitf"),
+         ("nnd", "application/vnd.noblenet-directory"),
+         ("nns", "application/vnd.noblenet-sealer"),
+         ("nnw", "application/vnd.noblenet-web"),
+         ("ngdat", "application/vnd.nokia.n-gage.data"),
+         ("n-gage", "application/vnd.nokia.n-gage.symbian.install"),
+         ("rpst", "application/vnd.nokia.radio-preset"),
+         ("rpss", "application/vnd.nokia.radio-presets"),
+         ("edm", "application/vnd.novadigm.edm"),
+         ("edx", "application/vnd.novadigm.edx"),
+         ("ext", "application/vnd.novadigm.ext"),
+         ("odc", "application/vnd.oasis.opendocument.chart"),
+         ("otc", "application/vnd.oasis.opendocument.chart-template"),
+         ("odb", "application/vnd.oasis.opendocument.database"),
+         ("odf", "application/vnd.oasis.opendocument.formula"),
+         ("odft", "application/vnd.oasis.opendocument.formula-template"),
+         ("odg", "application/vnd.oasis.opendocument.graphics"),
+         ("otg", "application/vnd.oasis.opendocument.graphics-template"),
+         ("odi", "application/vnd.oasis.opendocument.image"),
+         ("oti", "application/vnd.oasis.opendocument.image-template"),
+         ("odp", "application/vnd.oasis.opendocument.presentation"),
+         ("otp", "application/vnd.oasis.opendocument.presentation-template"),
+         ("ods", "application/vnd.oasis.opendocument.spreadsheet"),
+         ("ots", "application/vnd.oasis.opendocument.spreadsheet-template"),
+         ("odt", "application/vnd.oasis.opendocument.text"),
+         ("odm", "application/vnd.oasis.opendocument.text-master"),
+         ("ott", "application/vnd.oasis.opendocument.text-template"),
+         ("oth", "application/vnd.oasis.opendocument.text-web"),
+         ("xo", "application/vnd.olpc-sugar"),
+         ("dd2", "application/vnd.oma.dd2+xml"),
+         ("oxt", "application/vnd.openofficeorg.extension"), ("pptx",
+    "application/vnd.openxmlformats-officedocument.presentationml.presentation"), (
+    "sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"), (
+    "ppsx",
+    "application/vnd.openxmlformats-officedocument.presentationml.slideshow"), (
+    "potx",
+    "application/vnd.openxmlformats-officedocument.presentationml.template"), (
+    "xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"), (
+    "xltx",
+    "application/vnd.openxmlformats-officedocument.spreadsheetml.template"), (
+    "docx",
+    "application/vnd.openxmlformats-officedocument.wordprocessingml.document"), (
+    "dotx",
+    "application/vnd.openxmlformats-officedocument.wordprocessingml.template"),
+         ("mgp", "application/vnd.osgeo.mapguide.package"),
+         ("dp", "application/vnd.osgi.dp"),
+         ("esa", "application/vnd.osgi.subsystem"),
+         ("pdb", "application/vnd.palm"), ("pqa", "application/vnd.palm"),
+         ("oprc", "application/vnd.palm"),
+         ("paw", "application/vnd.pawaafile"),
+         ("str", "application/vnd.pg.format"),
+         ("ei6", "application/vnd.pg.osasli"),
+         ("efif", "application/vnd.picsel"),
+         ("wg", "application/vnd.pmi.widget"),
+         ("plf", "application/vnd.pocketlearn"),
+         ("pbd", "application/vnd.powerbuilder6"),
+         ("box", "application/vnd.previewsystems.box"),
+         ("mgz", "application/vnd.proteus.magazine"),
+         ("qps", "application/vnd.publishare-delta-tree"),
+         ("ptid", "application/vnd.pvi.ptid1"),
+         ("qxd", "application/vnd.quark.quarkxpress"),
+         ("qxt", "application/vnd.quark.quarkxpress"),
+         ("qwd", "application/vnd.quark.quarkxpress"),
+         ("qwt", "application/vnd.quark.quarkxpress"),
+         ("qxl", "application/vnd.quark.quarkxpress"),
+         ("qxb", "application/vnd.quark.quarkxpress"),
+         ("bed", "application/vnd.realvnc.bed"),
+         ("mxl", "application/vnd.recordare.musicxml"),
+         ("musicxml", "application/vnd.recordare.musicxml+xml"),
+         ("cryptonote", "application/vnd.rig.cryptonote"),
+         ("cod", "application/vnd.rim.cod"),
+         ("rm", "application/vnd.rn-realmedia"),
+         ("rmvb", "application/vnd.rn-realmedia-vbr"),
+         ("link66", "application/vnd.route66.link66+xml"),
+         ("st", "application/vnd.sailingtracker.track"),
+         ("see", "application/vnd.seemail"), ("sema", "application/vnd.sema"),
+         ("semd", "application/vnd.semd"), ("semf", "application/vnd.semf"),
+         ("ifm", "application/vnd.shana.informed.formdata"),
+         ("itp", "application/vnd.shana.informed.formtemplate"),
+         ("iif", "application/vnd.shana.informed.interchange"),
+         ("ipk", "application/vnd.shana.informed.package"),
+         ("twd", "application/vnd.simtech-mindmapper"),
+         ("twds", "application/vnd.simtech-mindmapper"),
+         ("mmf", "application/vnd.smaf"),
+         ("teacher", "application/vnd.smart.teacher"),
+         ("sdkm", "application/vnd.solent.sdkm+xml"),
+         ("sdkd", "application/vnd.solent.sdkm+xml"),
+         ("dxp", "application/vnd.spotfire.dxp"),
+         ("sfs", "application/vnd.spotfire.sfs"),
+         ("sdc", "application/vnd.stardivision.calc"),
+         ("sda", "application/vnd.stardivision.draw"),
+         ("sdd", "application/vnd.stardivision.impress"),
+         ("smf", "application/vnd.stardivision.math"),
+         ("sdw", "application/vnd.stardivision.writer"),
+         ("vor", "application/vnd.stardivision.writer"),
+         ("sgl", "application/vnd.stardivision.writer-global"),
+         ("smzip", "application/vnd.stepmania.package"),
+         ("sm", "application/vnd.stepmania.stepchart"),
+         ("sxc", "application/vnd.sun.xml.calc"),
+         ("stc", "application/vnd.sun.xml.calc.template"),
+         ("sxd", "application/vnd.sun.xml.draw"),
+         ("std", "application/vnd.sun.xml.draw.template"),
+         ("sxi", "application/vnd.sun.xml.impress"),
+         ("sti", "application/vnd.sun.xml.impress.template"),
+         ("sxm", "application/vnd.sun.xml.math"),
+         ("sxw", "application/vnd.sun.xml.writer"),
+         ("sxg", "application/vnd.sun.xml.writer.global"),
+         ("stw", "application/vnd.sun.xml.writer.template"),
+         ("sus", "application/vnd.sus-calendar"),
+         ("susp", "application/vnd.sus-calendar"),
+         ("svd", "application/vnd.svd"),
+         ("sis", "application/vnd.symbian.install"),
+         ("sisx", "application/vnd.symbian.install"),
+         ("xsm", "application/vnd.syncml+xml"),
+         ("bdm", "application/vnd.syncml.dm+wbxml"),
+         ("xdm", "application/vnd.syncml.dm+xml"),
+         ("tao", "application/vnd.tao.intent-module-archive"),
+         ("pcap", "application/vnd.tcpdump.pcap"),
+         ("cap", "application/vnd.tcpdump.pcap"),
+         ("dmp", "application/vnd.tcpdump.pcap"),
+         ("tmo", "application/vnd.tmobile-livetv"),
+         ("tpt", "application/vnd.trid.tpt"),
+         ("mxs", "application/vnd.triscape.mxs"),
+         ("tra", "application/vnd.trueapp"), ("ufd", "application/vnd.ufdl"),
+         ("ufdl", "application/vnd.ufdl"),
+         ("utz", "application/vnd.uiq.theme"),
+         ("umj", "application/vnd.umajin"),
+         ("unityweb", "application/vnd.unity"),
+         ("uoml", "application/vnd.uoml+xml"), ("vcx", "application/vnd.vcx"),
+         ("vsd", "application/vnd.visio"), ("vst", "application/vnd.visio"),
+         ("vss", "application/vnd.visio"), ("vsw", "application/vnd.visio"),
+         ("vis", "application/vnd.visionary"), ("vsf", "application/vnd.vsf"),
+         ("wbxml", "application/vnd.wap.wbxml"),
+         ("wmlc", "application/vnd.wap.wmlc"),
+         ("wmlsc", "application/vnd.wap.wmlscriptc"),
+         ("wtb", "application/vnd.webturbo"),
+         ("nbp", "application/vnd.wolfram.player"),
+         ("wpd", "application/vnd.wordperfect"),
+         ("wqd", "application/vnd.wqd"), ("stf", "application/vnd.wt.stf"),
+         ("xar", "application/vnd.xara"), ("xfdl", "application/vnd.xfdl"),
+         ("hvd", "application/vnd.yamaha.hv-dic"),
+         ("hvs", "application/vnd.yamaha.hv-script"),
+         ("hvp", "application/vnd.yamaha.hv-voice"),
+         ("osf", "application/vnd.yamaha.openscoreformat"),
+         ("osfpvg", "application/vnd.yamaha.openscoreformat.osfpvg+xml"),
+         ("saf", "application/vnd.yamaha.smaf-audio"),
+         ("spf", "application/vnd.yamaha.smaf-phrase"),
+         ("cmp", "application/vnd.yellowriver-custom-menu"),
+         ("zir", "application/vnd.zul"), ("zirz", "application/vnd.zul"),
+         ("zaz", "application/vnd.zzazz.deck+xml"),
+         ("vxml", "application/voicexml+xml"), ("wasm", "application/wasm"),
+         ("wgt", "application/widget"), ("hlp", "application/winhlp"),
+         ("wsdl", "application/wsdl+xml"),
+         ("wspolicy", "application/wspolicy+xml"),
+         ("7z", "application/x-7z-compressed"),
+         ("abw", "application/x-abiword"),
+         ("ace", "application/x-ace-compressed"),
+         ("dmg", "application/x-apple-diskimage"),
+         ("aab", "application/x-authorware-bin"),
+         ("x32", "application/x-authorware-bin"),
+         ("u32", "application/x-authorware-bin"),
+         ("vox", "application/x-authorware-bin"),
+         ("aam", "application/x-authorware-map"),
+         ("aas", "application/x-authorware-seg"),
+         ("bcpio", "application/x-bcpio"),
+         ("torrent", "application/x-bittorrent"),
+         ("blb", "application/x-blorb"), ("blorb", "application/x-blorb"),
+         ("bz", "application/x-bzip"), ("bz2", "application/x-bzip2"),
+         ("boz", "application/x-bzip2"), ("cbr", "application/x-cbr"),
+         ("cba", "application/x-cbr"), ("cbt", "application/x-cbr"),
+         ("cbz", "application/x-cbr"), ("cb7", "application/x-cbr"),
+         ("vcd", "application/x-cdlink"),
+         ("cfs", "application/x-cfs-compressed"),
+         ("chat", "application/x-chat"), ("pgn", "application/x-chess-pgn"),
+         ("nsc", "application/x-conference"), ("cpio", "application/x-cpio"),
+         ("csh", "application/x-csh"), ("deb", "application/x-debian-package"),
+         ("udeb", "application/x-debian-package"),
+         ("dgc", "application/x-dgc-compressed"),
+         ("dir", "application/x-director"), ("dcr", "application/x-director"),
+         ("dxr", "application/x-director"), ("cst", "application/x-director"),
+         ("cct", "application/x-director"), ("cxt", "application/x-director"),
+         ("w3d", "application/x-director"), ("fgd", "application/x-director"),
+         ("swa", "application/x-director"), ("wad", "application/x-doom"),
+         ("ncx", "application/x-dtbncx+xml"),
+         ("dtb", "application/x-dtbook+xml"),
+         ("res", "application/x-dtbresource+xml"),
+         ("dvi", "application/x-dvi"), ("evy", "application/x-envoy"),
+         ("eva", "application/x-eva"), ("bdf", "application/x-font-bdf"),
+         ("gsf", "application/x-font-ghostscript"),
+         ("psf", "application/x-font-linux-psf"),
+         ("pcf", "application/x-font-pcf"), ("snf", "application/x-font-snf"),
+         ("pfa", "application/x-font-type1"),
+         ("pfb", "application/x-font-type1"),
+         ("pfm", "application/x-font-type1"),
+         ("afm", "application/x-font-type1"), ("arc", "application/x-freearc"),
+         ("spl", "application/x-futuresplash"),
+         ("gca", "application/x-gca-compressed"),
+         ("ulx", "application/x-glulx"),
+         ("gnumeric", "application/x-gnumeric"),
+         ("gramps", "application/x-gramps-xml"),
+         ("gtar", "application/x-gtar"), ("hdf", "application/x-hdf"),
+         ("install", "application/x-install-instructions"),
+         ("iso", "application/x-iso9660-image"),
+         ("jnlp", "application/x-java-jnlp-file"),
+         ("latex", "application/x-latex"),
+         ("lzh", "application/x-lzh-compressed"),
+         ("lha", "application/x-lzh-compressed"), ("mie", "application/x-mie"),
+         ("prc", "application/x-mobipocket-ebook"),
+         ("mobi", "application/x-mobipocket-ebook"),
+         ("application", "application/x-ms-application"),
+         ("lnk", "application/x-ms-shortcut"), ("wmd", "application/x-ms-wmd"),
+         ("wmz", "application/x-ms-wmz"), ("xbap", "application/x-ms-xbap"),
+         ("mdb", "application/x-msaccess"), ("obd", "application/x-msbinder"),
+         ("crd", "application/x-mscardfile"), ("clp", "application/x-msclip"),
+         ("exe", "application/x-msdownload"),
+         ("dll", "application/x-msdownload"),
+         ("com", "application/x-msdownload"),
+         ("bat", "application/x-msdownload"),
+         ("msi", "application/x-msdownload"),
+         ("mvb", "application/x-msmediaview"),
+         ("m13", "application/x-msmediaview"),
+         ("m14", "application/x-msmediaview"),
+         ("wmf", "application/x-msmetafile"),
+         ("wmz", "application/x-msmetafile"),
+         ("emf", "application/x-msmetafile"),
+         ("emz", "application/x-msmetafile"), ("mny", "application/x-msmoney"),
+         ("pub", "application/x-mspublisher"),
+         ("scd", "application/x-msschedule"),
+         ("trm", "application/x-msterminal"), ("wri", "application/x-mswrite"),
+         ("nc", "application/x-netcdf"), ("cdf", "application/x-netcdf"),
+         ("nzb", "application/x-nzb"), ("p12", "application/x-pkcs12"),
+         ("pfx", "application/x-pkcs12"),
+         ("p7b", "application/x-pkcs7-certificates"),
+         ("spc", "application/x-pkcs7-certificates"),
+         ("p7r", "application/x-pkcs7-certreqresp"),
+         ("rar", "application/x-rar-compressed"),
+         ("ris", "application/x-research-info-systems"),
+         ("sh", "application/x-sh"), ("shar", "application/x-shar"),
+         ("swf", "application/x-shockwave-flash"),
+         ("xap", "application/x-silverlight-app"),
+         ("sql", "application/x-sql"), ("sit", "application/x-stuffit"),
+         ("sitx", "application/x-stuffitx"), ("srt", "application/x-subrip"),
+         ("sv4cpio", "application/x-sv4cpio"),
+         ("sv4crc", "application/x-sv4crc"),
+         ("t3", "application/x-t3vm-image"), ("gam", "application/x-tads"),
+         ("tar", "application/x-tar"), ("tcl", "application/x-tcl"),
+         ("tex", "application/x-tex"), ("tfm", "application/x-tex-tfm"),
+         ("texinfo", "application/x-texinfo"),
+         ("texi", "application/x-texinfo"), ("obj", "application/x-tgif"),
+         ("ustar", "application/x-ustar"),
+         ("src", "application/x-wais-source"),
+         ("der", "application/x-x509-ca-cert"),
+         ("crt", "application/x-x509-ca-cert"), ("fig", "application/x-xfig"),
+         ("xlf", "application/x-xliff+xml"),
+         ("xpi", "application/x-xpinstall"), ("xz", "application/x-xz"),
+         ("z1", "application/x-zmachine"), ("z2", "application/x-zmachine"),
+         ("z3", "application/x-zmachine"), ("z4", "application/x-zmachine"),
+         ("z5", "application/x-zmachine"), ("z6", "application/x-zmachine"),
+         ("z7", "application/x-zmachine"), ("z8", "application/x-zmachine"),
+         ("xaml", "application/xaml+xml"),
+         ("xdf", "application/xcap-diff+xml"),
+         ("xenc", "application/xenc+xml"), ("xhtml", "application/xhtml+xml"),
+         ("xht", "application/xhtml+xml"), ("xml", "application/xml"),
+         ("xsl", "application/xml"), ("dtd", "application/xml-dtd"),
+         ("xop", "application/xop+xml"), ("xpl", "application/xproc+xml"),
+         ("xslt", "application/xslt+xml"), ("xspf", "application/xspf+xml"),
+         ("mxml", "application/xv+xml"), ("xhvml", "application/xv+xml"),
+         ("xvml", "application/xv+xml"), ("xvm", "application/xv+xml"),
+         ("yang", "application/yang"), ("yin", "application/yin+xml"),
+         ("zip", "application/zip"), ("adp", "audio/adpcm"),
+         ("au", "audio/basic"), ("snd", "audio/basic"), ("mid", "audio/midi"),
+         ("midi", "audio/midi"), ("kar", "audio/midi"), ("rmi", "audio/midi"),
+         ("m4a", "audio/mp4"), ("mp4a", "audio/mp4"), ("mpga", "audio/mpeg"),
+         ("mp2", "audio/mpeg"), ("mp2a", "audio/mpeg"), ("mp3", "audio/mpeg"),
+         ("m2a", "audio/mpeg"), ("m3a", "audio/mpeg"), ("oga", "audio/ogg"),
+         ("ogg", "audio/ogg"), ("spx", "audio/ogg"), ("opus", "audio/ogg"),
+         ("s3m", "audio/s3m"), ("sil", "audio/silk"),
+         ("uva", "audio/vnd.dece.audio"), ("uvva", "audio/vnd.dece.audio"),
+         ("eol", "audio/vnd.digital-winds"), ("dra", "audio/vnd.dra"),
+         ("dts", "audio/vnd.dts"), ("dtshd", "audio/vnd.dts.hd"),
+         ("lvp", "audio/vnd.lucent.voice"),
+         ("pya", "audio/vnd.ms-playready.media.pya"),
+         ("ecelp4800", "audio/vnd.nuera.ecelp4800"),
+         ("ecelp7470", "audio/vnd.nuera.ecelp7470"),
+         ("ecelp9600", "audio/vnd.nuera.ecelp9600"), ("rip", "audio/vnd.rip"),
+         ("weba", "audio/webm"), ("aac", "audio/x-aac"),
+         ("aif", "audio/x-aiff"), ("aiff", "audio/x-aiff"),
+         ("aifc", "audio/x-aiff"), ("caf", "audio/x-caf"),
+         ("flac", "audio/x-flac"), ("mka", "audio/x-matroska"),
+         ("m3u", "audio/x-mpegurl"), ("wax", "audio/x-ms-wax"),
+         ("wma", "audio/x-ms-wma"), ("ram", "audio/x-pn-realaudio"),
+         ("ra", "audio/x-pn-realaudio"),
+         ("rmp", "audio/x-pn-realaudio-plugin"), ("wav", "audio/x-wav"),
+         ("xm", "audio/xm"), ("cdx", "chemical/x-cdx"),
+         ("cif", "chemical/x-cif"), ("cmdf", "chemical/x-cmdf"),
+         ("cml", "chemical/x-cml"), ("csml", "chemical/x-csml"),
+         ("xyz", "chemical/x-xyz"), ("ttc", "font/collection"),
+         ("otf", "font/otf"), ("ttf", "font/ttf"), ("woff", "font/woff"),
+         ("woff2", "font/woff2"), ("bmp", "image/bmp"), ("cgm", "image/cgm"),
+         ("g3", "image/g3fax"), ("gif", "image/gif"), ("ief", "image/ief"),
+         ("jpeg", "image/jpeg"), ("jpg", "image/jpeg"), ("jpe", "image/jpeg"),
+         ("ktx", "image/ktx"), ("png", "image/png"),
+         ("btif", "image/prs.btif"), ("sgi", "image/sgi"),
+         ("svg", "image/svg+xml"), ("svgz", "image/svg+xml"),
+         ("tiff", "image/tiff"), ("tif", "image/tiff"),
+         ("psd", "image/vnd.adobe.photoshop"),
+         ("uvi", "image/vnd.dece.graphic"), ("uvvi", "image/vnd.dece.graphic"),
+         ("uvg", "image/vnd.dece.graphic"), ("uvvg", "image/vnd.dece.graphic"),
+         ("djvu", "image/vnd.djvu"), ("djv", "image/vnd.djvu"),
+         ("sub", "image/vnd.dvb.subtitle"), ("dwg", "image/vnd.dwg"),
+         ("dxf", "image/vnd.dxf"), ("fbs", "image/vnd.fastbidsheet"),
+         ("fpx", "image/vnd.fpx"), ("fst", "image/vnd.fst"),
+         ("mmr", "image/vnd.fujixerox.edmics-mmr"),
+         ("rlc", "image/vnd.fujixerox.edmics-rlc"),
+         ("mdi", "image/vnd.ms-modi"), ("wdp", "image/vnd.ms-photo"),
+         ("npx", "image/vnd.net-fpx"), ("wbmp", "image/vnd.wap.wbmp"),
+         ("xif", "image/vnd.xiff"), ("webp", "image/webp"),
+         ("3ds", "image/x-3ds"), ("ras", "image/x-cmu-raster"),
+         ("cmx", "image/x-cmx"), ("fh", "image/x-freehand"),
+         ("fhc", "image/x-freehand"), ("fh4", "image/x-freehand"),
+         ("fh5", "image/x-freehand"), ("fh7", "image/x-freehand"),
+         ("ico", "image/x-icon"), ("sid", "image/x-mrsid-image"),
+         ("pcx", "image/x-pcx"), ("pic", "image/x-pict"),
+         ("pct", "image/x-pict"), ("pnm", "image/x-portable-anymap"),
+         ("pbm", "image/x-portable-bitmap"),
+         ("pgm", "image/x-portable-graymap"),
+         ("ppm", "image/x-portable-pixmap"), ("rgb", "image/x-rgb"),
+         ("tga", "image/x-tga"), ("xbm", "image/x-xbitmap"),
+         ("xpm", "image/x-xpixmap"), ("xwd", "image/x-xwindowdump"),
+         ("eml", "message/rfc822"), ("mime", "message/rfc822"),
+         ("igs", "model/iges"), ("iges", "model/iges"), ("msh", "model/mesh"),
+         ("mesh", "model/mesh"), ("silo", "model/mesh"),
+         ("dae", "model/vnd.collada+xml"), ("dwf", "model/vnd.dwf"),
+         ("gdl", "model/vnd.gdl"), ("gtw", "model/vnd.gtw"),
+         ("mts", "model/vnd.mts"), ("vtu", "model/vnd.vtu"),
+         ("wrl", "model/vrml"), ("vrml", "model/vrml"),
+         ("x3db", "model/x3d+binary"), ("x3dbz", "model/x3d+binary"),
+         ("x3dv", "model/x3d+vrml"), ("x3dvz", "model/x3d+vrml"),
+         ("x3d", "model/x3d+xml"), ("x3dz", "model/x3d+xml"),
+         ("appcache", "text/cache-manifest"), ("ics", "text/calendar"),
+         ("ifb", "text/calendar"), ("css", "text/css"), ("csv", "text/csv"),
+         ("html", "text/html"), ("htm", "text/html"),
+         ("js", "text/javascript"), ("mjs", "text/javascript"),
+         ("n3", "text/n3"), ("txt", "text/plain"), ("text", "text/plain"),
+         ("conf", "text/plain"), ("def", "text/plain"), ("list", "text/plain"),
+         ("log", "text/plain"), ("in", "text/plain"),
+         ("dsc", "text/prs.lines.tag"), ("rtx", "text/richtext"),
+         ("sgml", "text/sgml"), ("sgm", "text/sgml"),
+         ("tsv", "text/tab-separated-values"), ("t", "text/troff"),
+         ("tr", "text/troff"), ("roff", "text/troff"), ("man", "text/troff"),
+         ("me", "text/troff"), ("ms", "text/troff"), ("ttl", "text/turtle"),
+         ("uri", "text/uri-list"), ("uris", "text/uri-list"),
+         ("urls", "text/uri-list"), ("vcard", "text/vcard"),
+         ("curl", "text/vnd.curl"), ("dcurl", "text/vnd.curl.dcurl"),
+         ("mcurl", "text/vnd.curl.mcurl"), ("scurl", "text/vnd.curl.scurl"),
+         ("sub", "text/vnd.dvb.subtitle"), ("fly", "text/vnd.fly"),
+         ("flx", "text/vnd.fmi.flexstor"), ("gv", "text/vnd.graphviz"),
+         ("3dml", "text/vnd.in3d.3dml"), ("spot", "text/vnd.in3d.spot"),
+         ("jad", "text/vnd.sun.j2me.app-descriptor"),
+         ("wml", "text/vnd.wap.wml"), ("wmls", "text/vnd.wap.wmlscript"),
+         ("s", "text/x-asm"), ("asm", "text/x-asm"), ("c", "text/x-c"),
+         ("cc", "text/x-c"), ("cxx", "text/x-c"), ("cpp", "text/x-c"),
+         ("h", "text/x-c"), ("hh", "text/x-c"), ("dic", "text/x-c"),
+         ("f", "text/x-fortran"), ("for", "text/x-fortran"),
+         ("f77", "text/x-fortran"), ("f90", "text/x-fortran"),
+         ("java", "text/x-java-source"), ("nfo", "text/x-nfo"),
+         ("opml", "text/x-opml"), ("p", "text/x-pascal"),
+         ("pas", "text/x-pascal"), ("etx", "text/x-setext"),
+         ("sfv", "text/x-sfv"), ("uu", "text/x-uuencode"),
+         ("vcs", "text/x-vcalendar"), ("vcf", "text/x-vcard"),
+         ("3gp", "video/3gpp"), ("3g2", "video/3gpp2"), ("h261", "video/h261"),
+         ("h263", "video/h263"), ("h264", "video/h264"),
+         ("jpgv", "video/jpeg"), ("jpm", "video/jpm"), ("jpgm", "video/jpm"),
+         ("mj2", "video/mj2"), ("mjp2", "video/mj2"), ("mp4", "video/mp4"),
+         ("mp4v", "video/mp4"), ("mpg4", "video/mp4"), ("mpeg", "video/mpeg"),
+         ("mpg", "video/mpeg"), ("mpe", "video/mpeg"), ("m1v", "video/mpeg"),
+         ("m2v", "video/mpeg"), ("ogv", "video/ogg"),
+         ("qt", "video/quicktime"), ("mov", "video/quicktime"),
+         ("uvh", "video/vnd.dece.hd"), ("uvvh", "video/vnd.dece.hd"),
+         ("uvm", "video/vnd.dece.mobile"), ("uvvm", "video/vnd.dece.mobile"),
+         ("uvp", "video/vnd.dece.pd"), ("uvvp", "video/vnd.dece.pd"),
+         ("uvs", "video/vnd.dece.sd"), ("uvvs", "video/vnd.dece.sd"),
+         ("uvv", "video/vnd.dece.video"), ("uvvv", "video/vnd.dece.video"),
+         ("dvb", "video/vnd.dvb.file"), ("fvt", "video/vnd.fvt"),
+         ("mxu", "video/vnd.mpegurl"), ("m4u", "video/vnd.mpegurl"),
+         ("pyv", "video/vnd.ms-playready.media.pyv"),
+         ("uvu", "video/vnd.uvvu.mp4"), ("uvvu", "video/vnd.uvvu.mp4"),
+         ("viv", "video/vnd.vivo"), ("webm", "video/webm"),
+         ("f4v", "video/x-f4v"), ("fli", "video/x-fli"),
+         ("flv", "video/x-flv"), ("m4v", "video/x-m4v"),
+         ("mkv", "video/x-matroska"), ("mk3d", "video/x-matroska"),
+         ("mks", "video/x-matroska"), ("mng", "video/x-mng"),
+         ("asf", "video/x-ms-asf"), ("asx", "video/x-ms-asf"),
+         ("vob", "video/x-ms-vob"), ("wm", "video/x-ms-wm"),
+         ("wmv", "video/x-ms-wmv"), ("wmx", "video/x-ms-wmx"),
+         ("wvx", "video/x-ms-wvx"), ("avi", "video/x-msvideo"),
+         ("movie", "video/x-sgi-movie"), ("smv", "video/x-smv"),
+         ("ice", "x-conference/x-cooltalk")]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func getExt(mimedb: MimeDB; mimetype: string; default = "txt"): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Gets extension which corresponds to mimetype. Returns default if mimetype could not be found. Extensions are returned without the leading dot. mimetype is lowercased before querying mimedb. + Source   +Edit   + +
+
+ +
+
+
+
func getMimetype(mimedb: MimeDB; ext: string; default = "text/plain"): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Gets mimetype which corresponds to ext. Returns default if ext could not be found. ext can start with an optional dot which is ignored. ext is lowercased before querying mimedb. + Source   +Edit   + +
+
+ +
+
+
+
func newMimetypes(): MimeDB {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new Mimetypes database. The database will contain the most common mimetypes. + Source   +Edit   + +
+
+ +
+
+
+
func register(mimedb: var MimeDB; ext: string; mimetype: string) {....raises: [],
+    tags: [], forbids: [].}
+
+ + Adds mimetype to the mimedb. mimetype and ext are lowercased before registering on mimedb. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/mimetypes.idx b/mimetypes.idx new file mode 100644 index 0000000000000..a718f08dd099a --- /dev/null +++ b/mimetypes.idx @@ -0,0 +1,7 @@ +nimTitle mimetypes mimetypes.html module std/mimetypes 0 +nim MimeDB mimetypes.html#MimeDB object MimeDB 37 +nim mimes mimetypes.html#mimes const mimes 40 +nim newMimetypes mimetypes.html#newMimetypes proc newMimetypes(): MimeDB 1037 +nim getMimetype mimetypes.html#getMimetype,MimeDB,string,string proc getMimetype(mimedb: MimeDB; ext: string; default = "text/plain"): string 1043 +nim getExt mimetypes.html#getExt,MimeDB,string,string proc getExt(mimedb: MimeDB; mimetype: string; default = "txt"): string 1054 +nim register mimetypes.html#register,MimeDB,string,string proc register(mimedb: var MimeDB; ext: string; mimetype: string) 1065 diff --git a/miscdollars.html b/miscdollars.html new file mode 100644 index 0000000000000..3f31594b271b3 --- /dev/null +++ b/miscdollars.html @@ -0,0 +1,137 @@ + + + + + + + +std/private/miscdollars + + + + + + + + + + + + + + + + +
+
+

std/private/miscdollars

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ digitsutils +
+
+
+

Templates

+
+
+
+
template toLocation(result: var string; file: string | cstring; line: int;
+                    col: int)
+
+ + avoids spurious allocations + Source   +Edit   + +
+
+ +
+
+
+
template tupleObjectDollar[T: tuple | object](result: var string; x: T)
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/miscdollars.idx b/miscdollars.idx new file mode 100644 index 0000000000000..76ba8e09685cf --- /dev/null +++ b/miscdollars.idx @@ -0,0 +1,3 @@ +nimTitle miscdollars miscdollars.html module std/private/miscdollars 0 +nim toLocation miscdollars.html#toLocation.t,string,,int,int template toLocation(result: var string; file: string | cstring; line: int; col: int) 3 +nim tupleObjectDollar miscdollars.html#tupleObjectDollar.t,string,T template tupleObjectDollar[T: tuple | object](result: var string; x: T) 18 diff --git a/mm.html b/mm.html new file mode 100644 index 0000000000000..a64b392821f09 --- /dev/null +++ b/mm.html @@ -0,0 +1,73 @@ + + + + + + + +Nim's Memory Management + + + + + + + + + + + + + + + + +
+
+

Nim's Memory Management

+ + +
Author:Andreas Rumpf
Version:2.2.1

"The road to hell is paved with good intentions."

+ +

Multi-paradigm Memory Management Strategies

Nim offers multiple different memory management strategies. To choose the memory management strategy use the --mm: switch.

+
Hint: +The recommended switch for newly written Nim code is `--mm:orc`.
+ +

ARC/ORC

ORC is the default memory management strategy. It is a memory management mode primarily based on reference counting. Reference cycles are handled by a cycle collection mechanism based on "trial deletion". Since algorithms based on "tracing" are not used, the runtime behavior is oblivious to the involved heap and stack sizes.

+

The reference counting operations (= "RC ops") do not use atomic instructions and do not have to -- instead entire subgraphs are moved between threads. The Nim compiler also aggressively optimizes away RC ops and exploits move semantics.

+

Nim performs a fair share of optimizations for ARC/ORC; you can inspect what it did to your time critical function via --expandArc:functionName. Likewise, you can inspect the whole module via --expandArc:fileName.

+

--mm:arc uses the same mechanism as --mm:orc, but it leaves out the cycle collector. Both ARC and ORC offer deterministic performance for hard realtime systems, but ARC can be easier to reason about for people coming from Ada/C++/C -- roughly speaking the memory for a variable is freed when it goes "out of scope".

+

We generally advise you to use the acyclic annotation in order to optimize away the cycle collector's overhead but --mm:orc also produces more machine code than --mm:arc, so if you're on a target where code size matters and you know that your code does not produce cycles, you can use --mm:arc. Notice that the default async implementation produces cycles and leaks memory with --mm:arc, in other words, for async you need to use --mm:orc.

+ +

Other MM modes

Note: +The refc GC is incremental, thread-local and not "stop-the-world".
+
--mm:refc
It's a deferred reference counting based garbage collector with a simple Mark&Sweep backup GC in order to collect cycles. Heaps are thread-local. This document contains further information.
+
--mm:markAndSweep
Simple Mark-And-Sweep based garbage collector. Heaps are thread-local.
+
--mm:boehm
Boehm based garbage collector, it offers a shared heap.
+
--mm:go
Go's garbage collector, useful for interoperability with Go. Offers a shared heap.
+
--mm:none
No memory management strategy nor a garbage collector. Allocated memory is simply never freed. You should use --mm:arc instead.
+

Here is a comparison of the different memory management modes:

+ + + + + + + + + +
Memory ManagementHeapReference CyclesStop-The-WorldAtomicValgrind compatibleCommand line switch
ORCSharedCycle CollectorNoNoYes--mm:orc
ARCSharedLeakNoNoYes--mm:arc
Atomic ARCSharedLeakNoYesYes--mm:atomicArc
RefCLocalCycle CollectorNoNoNo--mm:refc
Mark & SweepLocalCycle CollectorNoNoNo--mm:markAndSweep
BoehmSharedCycle CollectorYesNoNo--mm:boehm
GoSharedCycle CollectorYesNoNo--mm:go
NoneManualManualManualManualManual--mm:none

JavaScript's garbage collector is used for the JavaScript and NodeJS compilation targets. The NimScript target uses the memory management strategy built into the Nim compiler.

+ + + + +
+
+ + + + diff --git a/mm.idx b/mm.idx new file mode 100644 index 0000000000000..4ebb5aea84194 --- /dev/null +++ b/mm.idx @@ -0,0 +1,6 @@ +markupTitle Nim's Memory Management mm.html Nim's Memory Management 0 +heading Multi-paradigm Memory Management Strategies mm.html#multiminusparadigm-memory-management-strategies Multi-paradigm Memory Management Strategies 0 +heading ARC/ORC mm.html#arcslashorc ARC/ORC 0 +idx hard realtime mm.html#hard-realtime_1 ARC/ORC 0 +idx async mm.html#async_1 ARC/ORC 0 +heading Other MM modes mm.html#other-mm-modes Other MM modes 0 diff --git a/monotimes.html b/monotimes.html new file mode 100644 index 0000000000000..e988e701bac2c --- /dev/null +++ b/monotimes.html @@ -0,0 +1,322 @@ + + + + + + + +std/monotimes + + + + + + + + + + + + + + + + +
+
+

std/monotimes

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

The std/monotimes module implements monotonic timestamps. A monotonic timestamp represents the time that has passed since some system defined point in time. The monotonic timestamps are guaranteed not to decrease, meaning that that the following is guaranteed to work: +

Example:

+
import std/monotimes
+let a = getMonoTime()
+let b = getMonoTime()
+assert a <= b

This is not guaranteed for the times.Time type! This means that the MonoTime should be used when measuring durations of time with high precision.

+

However, since MonoTime represents the time that has passed since some unknown time origin, it cannot be converted to a human readable timestamp. If this is required, the times.Time type should be used instead.

+

The MonoTime type stores the timestamp in nanosecond resolution, but note that the actual supported time resolution differs for different systems.

+ +

See also

+

+
+

Imports

+
+ times, posix +
+
+
+

Types

+
+
+
MonoTime = object
+
+ + Represents a monotonic timestamp. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(t: MonoTime): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `+`(a: MonoTime; b: Duration): MonoTime {....raises: [], tags: [], forbids: [].}
+
+ + Increases a by b. + Source   +Edit   + +
+
+ +
+
+
+
proc `-`(a, b: MonoTime): Duration {....raises: [], tags: [], forbids: [].}
+
+ + Returns the difference between two MonoTime timestamps as a Duration. + Source   +Edit   + +
+
+
+
proc `-`(a: MonoTime; b: Duration): MonoTime {....raises: [], tags: [], forbids: [].}
+
+ + Reduces a by b. + Source   +Edit   + +
+
+ +
+
+
+
proc `<`(a, b: MonoTime): bool {....raises: [], tags: [], forbids: [].}
+
+ + Returns true if a happened before b. + Source   +Edit   + +
+
+ +
+
+
+
proc `<=`(a, b: MonoTime): bool {....raises: [], tags: [], forbids: [].}
+
+ + Returns true if a happened before b or if they happened simultaneous. + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(a, b: MonoTime): bool {....raises: [], tags: [], forbids: [].}
+
+ + Returns true if a and b happened simultaneous. + Source   +Edit   + +
+
+ +
+
+
+
proc getMonoTime(): MonoTime {....tags: [TimeEffect], raises: [], forbids: [].}
+
+ +

Returns the current MonoTime timestamp.

+

When compiled with the JS backend and executed in a browser, this proc calls window.performance.now(). See MDN for more information.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc high(typ: typedesc[MonoTime]): MonoTime
+
+ + Returns the highest representable MonoTime. + Source   +Edit   + +
+
+ +
+
+
+
proc low(typ: typedesc[MonoTime]): MonoTime
+
+ + Returns the lowest representable MonoTime. + Source   +Edit   + +
+
+ +
+
+
+
proc ticks(t: MonoTime): int64 {....raises: [], tags: [], forbids: [].}
+
+ + Returns the raw ticks value from a MonoTime. This value always uses nanosecond time resolution. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/monotimes.idx b/monotimes.idx new file mode 100644 index 0000000000000..4b090c05cff37 --- /dev/null +++ b/monotimes.idx @@ -0,0 +1,15 @@ +nimTitle monotimes monotimes.html module std/monotimes 0 +nim MonoTime monotimes.html#MonoTime object MonoTime 42 +nim getMonoTime monotimes.html#getMonoTime proc getMonoTime(): MonoTime 89 +nim ticks monotimes.html#ticks,MonoTime proc ticks(t: MonoTime): int64 122 +nim `$` monotimes.html#$,MonoTime proc `$`(t: MonoTime): string 127 +nim `-` monotimes.html#-,MonoTime,MonoTime proc `-`(a, b: MonoTime): Duration 130 +nim `+` monotimes.html#+,MonoTime,Duration proc `+`(a: MonoTime; b: Duration): MonoTime 134 +nim `-` monotimes.html#-,MonoTime,Duration proc `-`(a: MonoTime; b: Duration): MonoTime 138 +nim `<` monotimes.html#<,MonoTime,MonoTime proc `<`(a, b: MonoTime): bool 142 +nim `<=` monotimes.html#<=,MonoTime,MonoTime proc `<=`(a, b: MonoTime): bool 146 +nim `==` monotimes.html#==,MonoTime,MonoTime proc `==`(a, b: MonoTime): bool 150 +nim high monotimes.html#high,typedesc[MonoTime] proc high(typ: typedesc[MonoTime]): MonoTime 154 +nim low monotimes.html#low,typedesc[MonoTime] proc low(typ: typedesc[MonoTime]): MonoTime 158 +heading See also monotimes.html#see-also See also 0 +nimgrp - monotimes.html#--procs-all proc 130 diff --git a/mysql.html b/mysql.html new file mode 100644 index 0000000000000..a433aaec89d03 --- /dev/null +++ b/mysql.html @@ -0,0 +1,5684 @@ + + + + + + + +src/db_connector/mysql + + + + + + + + + + + + + + + + +
+
+

src/db_connector/mysql

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

+
+

Types

+
+
+
BIND = St_mysql_bind
+
+ + + +
+
+
+
Character_set {.final.} = object
+  number*: cuint
+  state*: cuint
+  csname*: cstring
+  name*: cstring
+  comment*: cstring
+  dir*: cstring
+  mbminlen*: cuint
+  mbmaxlen*: cuint
+
+ + + +
+
+
+
CHARSET_INFO = Charset_info_st
+
+ + + +
+
+
+
Charset_info_st {.final.} = object
+  number*: cuint
+  primary_number*: cuint
+  binary_number*: cuint
+  state*: cuint
+  csname*: cstring
+  name*: cstring
+  comment*: cstring
+  tailoring*: cstring
+  ftype*: cstring
+  to_lower*: cstring
+  to_upper*: cstring
+  sort_order*: cstring
+  contractions*: ptr int16
+  sort_order_big*: ptr ptr int16
+  tab_to_uni*: ptr int16
+  tab_from_uni*: pointer
+  state_map*: cstring
+  ident_map*: cstring
+  strxfrm_multiply*: cuint
+  mbminlen*: cuint
+  mbmaxlen*: cuint
+  min_sort_char*: int16
+  max_sort_char*: int16
+  escape_with_backslash_is_dangerous*: my_bool
+  cset*: pointer
+  coll*: pointer
+
+ + + +
+
+
+
cuint = cint
+
+ + + +
+
+
+
DATA = St_mysql_data
+
+ + + +
+
+ +
+
Enum_cursor_type = enum
+  CURSOR_TYPE_NO_CURSOR = 0, CURSOR_TYPE_READ_ONLY = 1,
+  CURSOR_TYPE_FOR_UPDATE = 2, CURSOR_TYPE_SCROLLABLE = 4
+
+ + + +
+
+
+
Enum_field_types = enum
+  TYPE_DECIMAL, TYPE_TINY, TYPE_SHORT, TYPE_LONG, TYPE_FLOAT, TYPE_DOUBLE,
+  TYPE_NULL, TYPE_TIMESTAMP, TYPE_LONGLONG, TYPE_INT24, TYPE_DATE, TYPE_TIME,
+  TYPE_DATETIME, TYPE_YEAR, TYPE_NEWDATE, TYPE_VARCHAR, TYPE_BIT,
+  TYPE_NEWDECIMAL = 246, TYPE_ENUM = 247, TYPE_SET = 248, TYPE_TINY_BLOB = 249,
+  TYPE_MEDIUM_BLOB = 250, TYPE_LONG_BLOB = 251, TYPE_BLOB = 252,
+  TYPE_VAR_STRING = 253, TYPE_STRING = 254, TYPE_GEOMETRY = 255
+
+ + + +
+
+
+
Enum_mysql_set_option = enum
+  OPTION_MULTI_STATEMENTS_ON, OPTION_MULTI_STATEMENTS_OFF
+
+ + + +
+
+
+
Enum_mysql_stmt_state = enum
+  STMT_INIT_DONE = 1, STMT_PREPARE_DONE, STMT_EXECUTE_DONE, STMT_FETCH_DONE
+
+ + + +
+
+
+
Enum_server_command = enum
+  COM_SLEEP, COM_QUIT, COM_INIT_DB, COM_QUERY, COM_FIELD_LIST, COM_CREATE_DB,
+  COM_DROP_DB, COM_REFRESH, COM_SHUTDOWN, COM_STATISTICS, COM_PROCESS_INFO,
+  COM_CONNECT, COM_PROCESS_KILL, COM_DEBUG, COM_PING, COM_TIME,
+  COM_DELAYED_INSERT, COM_CHANGE_USER, COM_BINLOG_DUMP, COM_TABLE_DUMP,
+  COM_CONNECT_OUT, COM_REGISTER_SLAVE, COM_STMT_PREPARE, COM_STMT_EXECUTE,
+  COM_STMT_SEND_LONG_DATA, COM_STMT_CLOSE, COM_STMT_RESET, COM_SET_OPTION,
+  COM_STMT_FETCH, COM_END
+
+ + + +
+
+
+
Enum_shutdown_level = enum
+  SHUTDOWN_DEFAULT = 0, SHUTDOWN_WAIT_CONNECTIONS = 1,
+  SHUTDOWN_WAIT_TRANSACTIONS = 2, SHUTDOWN_WAIT_UPDATES = 8,
+  SHUTDOWN_WAIT_ALL_BUFFERS = 16, SHUTDOWN_WAIT_CRITICAL_BUFFERS = 17,
+  KILL_QUERY = 254, KILL_CONNECTION = 255
+
+ + + +
+
+
+
Enum_stmt_attr_type = enum
+  STMT_ATTR_UPDATE_MAX_LENGTH, STMT_ATTR_CURSOR_TYPE, STMT_ATTR_PREFETCH_ROWS
+
+ + + +
+
+
+
FIELD = St_mysql_field
+
+ + + +
+
+
+
FIELD_OFFSET = cuint
+
+ + + +
+
+
+
gptr = cstring
+
+ + + +
+
+
+
Item_result = enum
+  STRING_RESULT, REAL_RESULT, INT_RESULT, ROW_RESULT, DECIMAL_RESULT
+
+ + + +
+
+
+
MANAGER = St_mysql_manager
+
+ + + +
+
+
+
MEM_ROOT = St_mem_root
+
+ + + +
+
+
+
METHODS = St_mysql_methods
+
+ + + +
+
+
+
my_bool = bool
+
+ + + +
+
+ +
+
my_socket = cint
+
+ + + +
+
+
+
my_ulonglong = int64
+
+ + + +
+
+
+
MySQL = St_mysql
+
+ + + +
+
+
+
NET = St_net
+
+ + + +
+
+
+
Option = enum
+  OPT_CONNECT_TIMEOUT, OPT_COMPRESS, OPT_NAMED_PIPE, INIT_COMMAND,
+  READ_DEFAULT_FILE, READ_DEFAULT_GROUP, SET_CHARSET_DIR, SET_CHARSET_NAME,
+  OPT_LOCAL_INFILE, OPT_PROTOCOL, SHARED_MEMORY_BASE_NAME, OPT_READ_TIMEOUT,
+  OPT_WRITE_TIMEOUT, OPT_USE_RESULT, OPT_USE_REMOTE_CONNECTION,
+  OPT_USE_EMBEDDED_CONNECTION, OPT_GUESS_CONNECTION, SET_CLIENT_IP, SECURE_AUTH,
+  REPORT_DATA_TRUNCATION, OPT_RECONNECT
+
+ + + +
+
+ +
+
PBIND = ptr BIND
+
+ + + +
+
+
+
Pcharacter_set = ptr Character_set
+
+ + + +
+
+
+
Pcharset_info_st = ptr Charset_info_st
+
+ + + +
+
+
+
PDATA = ptr DATA
+
+ + + +
+
+
+
PFIELD = ptr FIELD
+
+ + + +
+
+
+
PFIELD_OFFSET = ptr FIELD_OFFSET
+
+ + + +
+
+
+
Pgptr = ptr gptr
+
+ + + +
+
+
+
PItem_result = ptr Item_result
+
+ + + +
+
+
+
PMANAGER = ptr MANAGER
+
+ + + +
+
+
+
PMEM_ROOT = ptr MEM_ROOT
+
+ + + +
+
+
+
PMETHODS = ptr METHODS
+
+ + + +
+
+
+
Pmy_bool = ptr my_bool
+
+ + + +
+
+
+
PMY_CHARSET_INFO = ptr MY_CHARSET_INFO
+
+ + + +
+
+
+
Pmy_socket = ptr my_socket
+
+ + + +
+
+
+
Pmy_ulonglong = ptr my_ulonglong
+
+ + + +
+
+
+
PMySQL = ptr MySQL
+
+ + + +
+
+
+
PNET = ptr NET
+
+ + + +
+
+
+
PPARAMETERS = ptr PARAMETERS
+
+ + + +
+
+
+
PPByte = pointer
+
+ + + +
+
+
+
Prand_struct = ptr Rand_struct
+
+ + + +
+
+
+
PRES = ptr RES
+
+ + + +
+
+
+
Protocol_type = enum
+  PROTOCOL_DEFAULT, PROTOCOL_TCP, PROTOCOL_SOCKET, PROTOCOL_PIPE,
+  PROTOCOL_MEMORY
+
+ + + +
+
+
+
PROW = ptr ROW
+
+ + + +
+
+
+
PROW_OFFSET = ptr ROW_OFFSET
+
+ + + +
+
+
+
PROWS = ptr ROWS
+
+ + + +
+
+
+
Psockaddr = ptr Sockaddr
+
+ + + +
+
+
+
Pst_dynamic_array = ptr St_dynamic_array
+
+ + + +
+
+
+
Pst_mem_root = ptr St_mem_root
+
+ + + +
+
+
+
Pst_mysql = ptr St_mysql
+
+ + + +
+
+
+
Pst_mysql_bind = ptr St_mysql_bind
+
+ + + +
+
+
+
Pst_mysql_data = ptr St_mysql_data
+
+ + + +
+
+
+
Pst_mysql_field = ptr St_mysql_field
+
+ + + +
+
+
+
Pst_mysql_manager = ptr St_mysql_manager
+
+ + + +
+
+
+
Pst_mysql_methods = ptr St_mysql_methods
+
+ + + +
+
+
+
Pst_mysql_options = ptr St_mysql_options
+
+ + + +
+
+ +
+
Pst_mysql_res = ptr St_mysql_res
+
+ + + +
+
+
+
Pst_mysql_rows = ptr St_mysql_rows
+
+ + + +
+
+
+
Pst_mysql_stmt = ptr St_mysql_stmt
+
+ + + +
+
+
+
Pst_net = ptr St_net
+
+ + + +
+
+
+
Pst_udf_args = ptr St_udf_args
+
+ + + +
+
+
+
Pst_udf_init = ptr St_udf_init
+
+ + + +
+
+
+
Pst_used_mem = ptr St_used_mem
+
+ + + +
+
+
+
PSTMT = ptr STMT
+
+ + + +
+
+
+
PUDF_ARGS = ptr UDF_ARGS
+
+ + + +
+
+
+
PUDF_INIT = ptr UDF_INIT
+
+ + + +
+
+
+
PUSED_MEM = ptr USED_MEM
+
+ + + +
+
+
+
PVIO = pointer
+
+ + + +
+
+
+
Rand_struct {.final.} = object
+  seed1*: int
+  seed2*: int
+  max_value*: int
+  max_value_dbl*: cdouble
+
+ + + +
+
+
+
RES = St_mysql_res
+
+ + + +
+
+
+
ROW = cstringArray
+
+ + + +
+
+
+
ROW_OFFSET = ROWS
+
+ + + +
+
+
+
ROWS = St_mysql_rows
+
+ + + +
+
+
+
Rpl_type = enum
+  RPL_MASTER, RPL_SLAVE, RPL_ADMIN
+
+ + + +
+
+
+
Sockaddr {.final.} = object
+
+ + + +
+
+
+
St_dynamic_array {.final.} = object
+  buffer*: cstring
+  elements*: cuint
+  max_element*: cuint
+  alloc_increment*: cuint
+  size_of_element*: cuint
+
+ + + +
+
+
+
St_mem_root {.final.} = object
+  free*: PUSED_MEM
+  used*: PUSED_MEM
+  pre_alloc*: PUSED_MEM
+  min_malloc*: cuint
+  block_size*: cuint
+  block_num*: cuint
+  first_block_usage*: cuint
+  error_handler*: proc () {.cdecl.}
+
+ + + +
+
+
+
St_mysql {.final.} = object
+  net*: NET
+  connector_fd*: gptr
+  host*: cstring
+  user*: cstring
+  passwd*: cstring
+  unix_socket*: cstring
+  server_version*: cstring
+  host_info*: cstring
+  info*: cstring
+  db*: cstring
+  charset*: Pcharset_info_st
+  fields*: PFIELD
+  field_alloc*: MEM_ROOT
+  affected_rows*: my_ulonglong
+  insert_id*: my_ulonglong
+  extra_info*: my_ulonglong
+  thread_id*: int
+  packet_length*: int
+  port*: cuint
+  client_flag*: int
+  server_capabilities*: int
+  protocol_version*: cuint
+  field_count*: cuint
+  server_status*: cuint
+  server_language*: cuint
+  warning_count*: cuint
+  options*: St_mysql_options
+  status*: Status
+  free_me*: my_bool
+  reconnect*: my_bool
+  scramble*: array[0 .. 21 - 1, char]
+  rpl_pivot*: my_bool
+  master*: Pst_mysql
+  next_slave*: Pst_mysql
+  last_used_slave*: Pst_mysql
+  last_used_con*: Pst_mysql
+  stmts*: pointer
+  methods*: Pst_mysql_methods
+  thd*: pointer
+  unbuffered_fetch_owner*: Pmy_bool
+
+ + + +
+
+
+
St_mysql_bind {.final.} = object
+  len*: int
+  is_null*: Pmy_bool
+  buffer*: pointer
+  error*: Pmy_bool
+  buffer_type*: Enum_field_types
+  buffer_length*: int
+  row_ptr*: ptr byte
+  offset*: int
+  length_value*: int
+  param_number*: cuint
+  pack_length*: cuint
+  error_value*: my_bool
+  is_unsigned*: my_bool
+  long_data_used*: my_bool
+  is_null_value*: my_bool
+  store_param_func*: proc (net: PNET; param: Pst_mysql_bind) {.cdecl.}
+  fetch_result*: proc (para1: Pst_mysql_bind; para2: PFIELD; row: PPByte)
+  skip_result*: proc (para1: Pst_mysql_bind; para2: PFIELD; row: PPByte)
+
+ + + +
+
+
+
St_mysql_data {.final.} = object
+  rows*: my_ulonglong
+  fields*: cuint
+  data*: PROWS
+  alloc*: MEM_ROOT
+  prev_ptr*: ptr PROWS
+
+ + + +
+
+
+
St_mysql_field {.final.} = object
+  name*: cstring
+  org_name*: cstring
+  table*: cstring
+  org_table*: cstring
+  db*: cstring
+  catalog*: cstring
+  def*: cstring
+  len*: int
+  max_length*: int
+  name_length*: cuint
+  org_name_length*: cuint
+  table_length*: cuint
+  org_table_length*: cuint
+  db_length*: cuint
+  catalog_length*: cuint
+  def_length*: cuint
+  flags*: cuint
+  decimals*: cuint
+  charsetnr*: cuint
+  ftype*: Enum_field_types
+  extension*: pointer
+
+ + + +
+
+
+
St_mysql_manager {.final.} = object
+  net*: NET
+  host*: cstring
+  user*: cstring
+  passwd*: cstring
+  port*: cuint
+  free_me*: my_bool
+  eof*: my_bool
+  cmd_status*: cint
+  last_errno*: cint
+  net_buf*: cstring
+  net_buf_pos*: cstring
+  net_data_end*: cstring
+  net_buf_size*: cint
+  last_error*: array[0 .. 256 - 1, char]
+
+ + + +
+
+
+
St_mysql_methods {.final.} = object
+  read_query_result*: proc (MySQL: PMySQL): my_bool {.cdecl.}
+  advanced_command*: proc (MySQL: PMySQL; command: Enum_server_command;
+                           header: cstring; header_length: int; arg: cstring;
+                           arg_length: int; skip_check: my_bool): my_bool
+  read_rows*: proc (MySQL: PMySQL; fields: PFIELD; fields_count: cuint): PDATA
+  use_result*: proc (MySQL: PMySQL): PRES
+  fetch_lengths*: proc (fto: ptr int; column: ROW; field_count: cuint)
+  flush_use_result*: proc (MySQL: PMySQL)
+  list_fields*: proc (MySQL: PMySQL): PFIELD
+  read_prepare_result*: proc (MySQL: PMySQL; stmt: PSTMT): my_bool
+  stmt_execute*: proc (stmt: PSTMT): cint
+  read_binary_rows*: proc (stmt: PSTMT): cint
+  unbuffered_fetch*: proc (MySQL: PMySQL; row: cstringArray): cint
+  free_embedded_thd*: proc (MySQL: PMySQL)
+  read_statistics*: proc (MySQL: PMySQL): cstring
+  next_result*: proc (MySQL: PMySQL): my_bool
+  read_change_user_result*: proc (MySQL: PMySQL; buff: cstring; passwd: cstring): cint
+  read_rowsfrom_cursor*: proc (stmt: PSTMT): cint
+
+ + + +
+
+
+
St_mysql_options {.final.} = object
+  connect_timeout*: cuint
+  read_timeout*: cuint
+  write_timeout*: cuint
+  port*: cuint
+  protocol*: cuint
+  client_flag*: int
+  host*: cstring
+  user*: cstring
+  password*: cstring
+  unix_socket*: cstring
+  db*: cstring
+  init_commands*: Pst_dynamic_array
+  my_cnf_file*: cstring
+  my_cnf_group*: cstring
+  charset_dir*: cstring
+  charset_name*: cstring
+  ssl_key*: cstring
+  ssl_cert*: cstring
+  ssl_ca*: cstring
+  ssl_capath*: cstring
+  ssl_cipher*: cstring
+  shared_memory_base_name*: cstring
+  max_allowed_packet*: int
+  use_ssl*: my_bool
+  compress*: my_bool
+  named_pipe*: my_bool
+  rpl_probe*: my_bool
+  rpl_parse*: my_bool
+  no_master_reads*: my_bool
+  separate_thread*: my_bool
+  methods_to_use*: Option
+  client_ip*: cstring
+  secure_auth*: my_bool
+  report_data_truncation*: my_bool
+  local_infile_init*: proc (para1: var pointer; para2: cstring; para3: pointer): cint {.
+      cdecl.}
+  local_infile_read*: proc (para1: pointer; para2: cstring; para3: cuint): cint
+  local_infile_end*: proc (para1: pointer)
+  local_infile_error*: proc (para1: pointer; para2: cstring; para3: cuint): cint
+  local_infile_userdata*: pointer
+
+ + + +
+
+
+
St_mysql_parameters {.final.} = object
+  p_max_allowed_packet*: ptr int
+  p_net_buffer_length*: ptr int
+
+ + + +
+
+
+
St_mysql_res {.final.} = object
+  row_count*: my_ulonglong
+  fields*: PFIELD
+  data*: PDATA
+  data_cursor*: PROWS
+  lengths*: ptr int
+  handle*: PMySQL
+  field_alloc*: MEM_ROOT
+  field_count*: cuint
+  current_field*: cuint
+  row*: ROW
+  current_row*: ROW
+  eof*: my_bool
+  unbuffered_fetch_cancelled*: my_bool
+  methods*: Pst_mysql_methods
+
+ + + +
+
+
+
St_mysql_rows {.final.} = object
+  next*: Pst_mysql_rows
+  data*: ROW
+  len*: int
+
+ + + +
+
+
+
St_mysql_stmt {.final.} = object
+  mem_root*: MEM_ROOT
+  mysql*: PMySQL
+  params*: PBIND
+  fields*: PFIELD
+  result*: DATA
+  data_cursor*: PROWS
+  affected_rows*: my_ulonglong
+  insert_id*: my_ulonglong
+  read_row_func*: proc (stmt: Pst_mysql_stmt; row: PPByte): cint {.cdecl.}
+  stmt_id*: int
+  flags*: int
+  prefetch_rows*: int
+  server_status*: cuint
+  last_errno*: cuint
+  param_count*: cuint
+  field_count*: cuint
+  state*: Enum_mysql_stmt_state
+  last_error*: array[0 .. 200 - 1, char]
+  sqlstate*: array[0 .. 6 - 1, char]
+  send_types_to_server*: my_bool
+  bind_param_done*: my_bool
+  bind_result_done*: char
+  unbuffered_fetch_cancelled*: my_bool
+  update_max_length*: my_bool
+
+ + + +
+
+
+
St_net {.final.} = object
+  vio*: PVIO
+  buff*: cstring
+  buff_end*: cstring
+  write_pos*: cstring
+  read_pos*: cstring
+  fd*: my_socket
+  max_packet*: int
+  max_packet_size*: int
+  pkt_nr*: cuint
+  compress_pkt_nr*: cuint
+  write_timeout*: cuint
+  read_timeout*: cuint
+  retry_count*: cuint
+  fcntl*: cint
+  compress*: my_bool
+  remain_in_buf*: int
+  len*: int
+  buf_length*: int
+  where_b*: int
+  return_status*: ptr cint
+  reading_or_writing*: char
+  save_char*: cchar
+  no_send_ok*: my_bool
+  no_send_eof*: my_bool
+  no_send_error*: my_bool
+  last_error*: array[0 .. 200 - 1, char]
+  sqlstate*: array[0 .. 6 - 1, char]
+  last_errno*: cuint
+  error*: char
+  query_cache_query*: gptr
+  report_error*: my_bool
+  return_errno*: my_bool
+
+ + + +
+
+
+
St_udf_args {.final.} = object
+  arg_count*: cuint
+  arg_type*: PItem_result
+  args*: cstringArray
+  lengths*: ptr int
+  maybe_null*: cstring
+  attributes*: cstringArray
+  attribute_lengths*: ptr int
+
+ + + +
+
+
+
St_udf_init {.final.} = object
+  maybe_null*: my_bool
+  decimals*: cuint
+  max_length*: int
+  theptr*: cstring
+  const_item*: my_bool
+
+ + + +
+
+
+
St_used_mem {.final.} = object
+  next*: Pst_used_mem
+  left*: cuint
+  size*: cuint
+
+ + + +
+
+
+
Status = enum
+  STATUS_READY, STATUS_GET_RESULT, STATUS_USE_RESULT
+
+ + + +
+
+
+
STMT = St_mysql_stmt
+
+ + + +
+
+
+
UDF_ARGS = St_udf_args
+
+ + + +
+
+
+
UDF_INIT = St_udf_init
+
+ + + +
+
+
+
USED_MEM = St_used_mem
+
+ + + +
+
+ +
+
+
+

Consts

+
+
+
ALLOC_MAX_BLOCK_TO_DROP = 4096
+
+ + + +
+
+ +
+
AUTO_INCREMENT_FLAG = 512
+
+ + + +
+
+
+
BINARY_FLAG = 128
+
+ + + +
+
+
+
BINCMP_FLAG = 131072
+
+ + + +
+
+
+
BLOB_FLAG = 16
+
+ + + +
+
+
+
CLIENT_COMPRESS = 32
+
+ + + +
+
+
+
CLIENT_CONNECT_WITH_DB = 8
+
+ + + +
+
+
+
CLIENT_FOUND_ROWS = 2
+
+ + + +
+
+
+
CLIENT_IGNORE_SIGPIPE = 4096
+
+ + + +
+
+
+
CLIENT_IGNORE_SPACE = 256
+
+ + + +
+
+
+
CLIENT_INTERACTIVE = 1024
+
+ + + +
+
+
+
CLIENT_LOCAL_FILES = 128
+
+ + + +
+
+
+
CLIENT_LONG_FLAG = 4
+
+ + + +
+
+
+
CLIENT_LONG_PASSWORD = 1
+
+ + + +
+
+
+
CLIENT_MULTI_QUERIES = 65536
+
+ + + +
+
+
+
CLIENT_MULTI_RESULTS = 131072
+
+ + + +
+
+
+
CLIENT_MULTI_STATEMENTS = 65536
+
+ + + +
+
+
+
CLIENT_NET_READ_TIMEOUT = 31536000
+
+ + + +
+
+
+
CLIENT_NET_WRITE_TIMEOUT = 31536000
+
+ + + +
+
+
+
CLIENT_NO_SCHEMA = 16
+
+ + + +
+
+
+
CLIENT_ODBC = 64
+
+ + + +
+
+
+
CLIENT_PROTOCOL_41 = 512
+
+ + + +
+
+
+
CLIENT_REMEMBER_OPTIONS: int = 2147483648
+
+ + + +
+
+
+
CLIENT_RESERVED = 16384
+
+ + + +
+
+
+
CLIENT_SECURE_CONNECTION = 32768
+
+ + + +
+
+
+
CLIENT_SSL = 2048
+
+ + + +
+
+
+
CLIENT_TRANSACTIONS = 8192
+
+ + + +
+
+
+
COMP_HEADER_SIZE = 3
+
+ + + +
+
+
+
COUNT_ERROR = -1'i64
+
+ + + +
+
+
+
DATA_TRUNCATED = 101
+
+ + + +
+
+
+
ENUM_FLAG = 256
+
+ + + +
+
+
+
ERRMSG_SIZE = 200
+
+ + + +
+
+
+
FIELD_TYPE_BIT = TYPE_BIT
+
+ + + +
+
+
+
FIELD_TYPE_BLOB = TYPE_BLOB
+
+ + + +
+
+
+
FIELD_TYPE_CHAR = TYPE_TINY
+
+ + + +
+
+
+
FIELD_TYPE_DATE = TYPE_DATE
+
+ + + +
+
+
+
FIELD_TYPE_DATETIME = TYPE_DATETIME
+
+ + + +
+
+
+
FIELD_TYPE_DECIMAL = TYPE_DECIMAL
+
+ + + +
+
+
+
FIELD_TYPE_DOUBLE = TYPE_DOUBLE
+
+ + + +
+
+
+
FIELD_TYPE_ENUM = TYPE_ENUM
+
+ + + +
+
+
+
FIELD_TYPE_FLOAT = TYPE_FLOAT
+
+ + + +
+
+
+
FIELD_TYPE_GEOMETRY = TYPE_GEOMETRY
+
+ + + +
+
+
+
FIELD_TYPE_INT24 = TYPE_INT24
+
+ + + +
+
+
+
FIELD_TYPE_INTERVAL = TYPE_ENUM
+
+ + + +
+
+
+
FIELD_TYPE_LONG = TYPE_LONG
+
+ + + +
+
+
+
FIELD_TYPE_LONG_BLOB = TYPE_LONG_BLOB
+
+ + + +
+
+
+
FIELD_TYPE_LONGLONG = TYPE_LONGLONG
+
+ + + +
+
+
+
FIELD_TYPE_MEDIUM_BLOB = TYPE_MEDIUM_BLOB
+
+ + + +
+
+
+
FIELD_TYPE_NEWDATE = TYPE_NEWDATE
+
+ + + +
+
+
+
FIELD_TYPE_NEWDECIMAL = TYPE_NEWDECIMAL
+
+ + + +
+
+
+
FIELD_TYPE_NULL = TYPE_NULL
+
+ + + +
+
+
+
FIELD_TYPE_SET = TYPE_SET
+
+ + + +
+
+
+
FIELD_TYPE_SHORT = TYPE_SHORT
+
+ + + +
+
+
+
FIELD_TYPE_STRING = TYPE_STRING
+
+ + + +
+
+
+
FIELD_TYPE_TIME = TYPE_TIME
+
+ + + +
+
+
+
FIELD_TYPE_TIMESTAMP = TYPE_TIMESTAMP
+
+ + + +
+
+
+
FIELD_TYPE_TINY = TYPE_TINY
+
+ + + +
+
+
+
FIELD_TYPE_TINY_BLOB = TYPE_TINY_BLOB
+
+ + + +
+
+
+
FIELD_TYPE_VAR_STRING = TYPE_VAR_STRING
+
+ + + +
+
+
+
FIELD_TYPE_YEAR = TYPE_YEAR
+
+ + + +
+
+
+
GROUP_FLAG = 32768
+
+ + + +
+
+
+
HOSTNAME_LENGTH = 60
+
+ + + +
+
+
+
LOCAL_HOST = "localhost"
+
+ + + +
+
+
+
LOCAL_HOST_NAMEDPIPE = '.'
+
+ + + +
+
+
+
LOCAL_INFILE_ERROR_LEN = 512
+
+ + + +
+
+
+
LONG_DATA_HEADER = 6
+
+ + + +
+
+
+
MANAGER_ACCESS = 401
+
+ + + +
+
+
+
MANAGER_CLIENT_ERR = 450
+
+ + + +
+
+
+
MANAGER_INFO = 250
+
+ + + +
+
+
+
MANAGER_INTERNAL_ERR = 500
+
+ + + +
+
+
+
MANAGER_OK = 200
+
+ + + +
+
+
+
MAX_BIGINT_WIDTH = 20
+
+ + + +
+
+
+
MAX_BLOB_WIDTH = 8192
+
+ + + +
+
+
+
MAX_CHAR_WIDTH = 255
+
+ + + +
+
+
+
MAX_INT_WIDTH = 10
+
+ + + +
+
+
+
MAX_MEDIUMINT_WIDTH = 8
+
+ + + +
+
+
+
MAX_MYSQL_MANAGER_ERR = 256
+
+ + + +
+
+
+
MAX_MYSQL_MANAGER_MSG = 256
+
+ + + +
+
+
+
MAX_SMALLINT_WIDTH = 5
+
+ + + +
+
+
+
MAX_TINYINT_WIDTH = 3
+
+ + + +
+
+
+
MULTIPLE_KEY_FLAG = 8
+
+ + + +
+
+
+
NAME_LEN = 64
+
+ + + +
+
+
+
NAMEDPIPE = "MySQL"
+
+ + + +
+
+
+
NET_HEADER_SIZE = 4
+
+ + + +
+
+
+
NET_READ_TIMEOUT = 30
+
+ + + +
+
+
+
NET_WAIT_TIMEOUT = 28800
+
+ + + +
+
+
+
NET_WRITE_TIMEOUT = 60
+
+ + + +
+
+
+
NO_DATA = 100
+
+ + + +
+
+
+
NO_DEFAULT_VALUE_FLAG = 4096
+
+ + + +
+
+
+
NOT_NULL_FLAG = 1
+
+ + + +
+
+
+
NULL_LENGTH: int = -1
+
+ + + +
+
+
+
NUM_FLAG = 32768
+
+ + + +
+
+
+
ONLY_KILL_QUERY = 1
+
+ + + +
+
+
+
packet_error = -1
+
+ + + +
+
+
+
PART_KEY_FLAG = 16384
+
+ + + +
+
+
+
PRI_KEY_FLAG = 2
+
+ + + +
+
+
+
REFRESH_DES_KEY_FILE = 0x00040000
+
+ + + +
+
+
+
REFRESH_FAST = 32768
+
+ + + +
+
+
+
REFRESH_GRANT = 1
+
+ + + +
+
+
+
REFRESH_HOSTS = 8
+
+ + + +
+
+
+
REFRESH_LOG = 2
+
+ + + +
+
+
+
REFRESH_MASTER = 128
+
+ + + +
+
+
+
REFRESH_QUERY_CACHE = 65536
+
+ + + +
+
+
+
REFRESH_QUERY_CACHE_FREE = 0x00020000
+
+ + + +
+
+
+
REFRESH_READ_LOCK = 16384
+
+ + + +
+
+
+
REFRESH_SLAVE = 64
+
+ + + +
+
+
+
REFRESH_STATUS = 16
+
+ + + +
+
+
+
REFRESH_TABLES = 4
+
+ + + +
+
+
+
REFRESH_THREADS = 32
+
+ + + +
+
+
+
REFRESH_USER_RESOURCES = 0x00080000
+
+ + + +
+
+
+
SCRAMBLE_LENGTH = 20
+
+ + + +
+
+
+
SCRAMBLE_LENGTH_323 = 8
+
+ + + +
+
+
+
SCRAMBLED_PASSWORD_CHAR_LENGTH = 41
+
+ + + +
+
+ +
+
SERVER_MORE_RESULTS_EXISTS = 8
+
+ + + +
+
+ +
+
SERVER_QUERY_NO_INDEX_USED = 32
+
+ + + +
+
+
+
SERVER_STATUS_AUTOCOMMIT = 2
+
+ + + +
+
+
+
SERVER_STATUS_CURSOR_EXISTS = 64
+
+ + + +
+
+
+
SERVER_STATUS_DB_DROPPED = 256
+
+ + + +
+
+
+
SERVER_STATUS_IN_TRANS = 1
+
+ + + +
+
+
+
SERVER_STATUS_LAST_ROW_SENT = 128
+
+ + + +
+
+
+
SERVER_STATUS_MORE_RESULTS = 4
+
+ + + +
+
+ +
+
SERVER_VERSION_LENGTH = 60
+
+ + + +
+
+
+
SERVICENAME = "MySQL"
+
+ + + +
+
+
+
SET_FLAG = 2048
+
+ + + +
+
+
+
SHUTDOWN_KILLABLE_CONNECT = '\x01'
+
+ + + +
+
+
+
SHUTDOWN_KILLABLE_LOCK_TABLE = '\x04'
+
+ + + +
+
+
+
SHUTDOWN_KILLABLE_TRANS = '\x02'
+
+ + + +
+
+
+
SHUTDOWN_KILLABLE_UPDATE = '\b'
+
+ + + +
+
+
+
SQLSTATE_LENGTH = 5
+
+ + + +
+
+
+
STMT_HEADER = 4
+
+ + + +
+
+
+
TIMESTAMP_FLAG = 1024
+
+ + + +
+
+
+
UNIQUE_FLAG = 65536
+
+ + + +
+
+
+
UNIQUE_KEY_FLAG = 4
+
+ + + +
+
+
+
UNSIGNED_FLAG = 32
+
+ + + +
+
+
+
USERNAME_LENGTH = 16
+
+ + + +
+
+
+
ZEROFILL_FLAG = 64
+
+ + + +
+
+ +
+
+
+

Procs

+
+
+
+
proc add_slave(MySQL: PMySQL; host: cstring; port: cuint; user: cstring;
+               passwd: cstring): cint {.stdcall, dynlib: lib,
+                                        importc: "mysql_add_slave", ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc affected_rows(MySQL: PMySQL): my_ulonglong {.stdcall, dynlib: lib,
+    importc: "mysql_affected_rows", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc autocommit(MySQL: PMySQL; auto_mode: my_bool): my_bool {.stdcall,
+    dynlib: lib, importc: "mysql_autocommit", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc change_user(MySQL: PMySQL; user: cstring; passwd: cstring; db: cstring): my_bool {.
+    stdcall, dynlib: lib, importc: "mysql_change_user", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc character_set_name(MySQL: PMySQL): cstring {.stdcall, dynlib: lib,
+    importc: "mysql_character_set_name", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc check_scramble(reply: cstring; message: cstring; hash_stage2: pointer): my_bool {.
+    cdecl, dynlib: lib, importc: "check_scramble", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc check_scramble_323(para1: cstring; message: cstring; salt: int): my_bool {.
+    cdecl, dynlib: lib, importc: "check_scramble_323", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc close(sock: PMySQL) {.stdcall, dynlib: lib, importc: "mysql_close",
+                           ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc commit(MySQL: PMySQL): my_bool {.stdcall, dynlib: lib,
+                                      importc: "mysql_commit", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc create_random_string(fto: cstring; len: cuint; rand_st: Prand_struct) {.
+    cdecl, dynlib: lib, importc: "create_random_string", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc data_seek(result: PRES; offset: my_ulonglong) {.stdcall, dynlib: lib,
+    importc: "mysql_data_seek", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc debug(debug: cstring) {.stdcall, dynlib: lib, importc: "mysql_debug",
+                             ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc disable_reads_from_master(MySQL: PMySQL) {.stdcall, dynlib: lib,
+    importc: "mysql_disable_reads_from_master", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc disable_rpl_parse(MySQL: PMySQL) {.stdcall, dynlib: lib,
+                                        importc: "mysql_disable_rpl_parse",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc dump_debug_info(MySQL: PMySQL): cint {.stdcall, dynlib: lib,
+    importc: "mysql_dump_debug_info", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc embedded(): my_bool {.stdcall, dynlib: lib, importc: "mysql_embedded",
+                           ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc enable_reads_from_master(MySQL: PMySQL) {.stdcall, dynlib: lib,
+    importc: "mysql_enable_reads_from_master", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc enable_rpl_parse(MySQL: PMySQL) {.stdcall, dynlib: lib,
+                                       importc: "mysql_enable_rpl_parse",
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc eof(res: PRES): my_bool {.stdcall, dynlib: lib, importc: "mysql_eof",
+                               ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc errno(MySQL: PMySQL): cuint {.stdcall, dynlib: lib, importc: "mysql_errno",
+                                   ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc errno_to_sqlstate(errno: cuint): cstring {.cdecl, dynlib: lib,
+    importc: "mysql_errno_to_sqlstate", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc error(MySQL: PMySQL): cstring {.stdcall, dynlib: lib,
+                                     importc: "mysql_error", ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc escape_string(fto: cstring; from: cstring; from_length: int): int {.
+    stdcall, dynlib: lib, importc: "mysql_escape_string", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc fetch_field(result: PRES): PFIELD {.stdcall, dynlib: lib,
+    importc: "mysql_fetch_field", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc fetch_field_direct(res: PRES; fieldnr: cuint): PFIELD {.stdcall,
+    dynlib: lib, importc: "mysql_fetch_field_direct", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc fetch_fields(res: PRES): PFIELD {.stdcall, dynlib: lib,
+                                       importc: "mysql_fetch_fields",
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc fetch_lengths(result: PRES): ptr int {.stdcall, dynlib: lib,
+    importc: "mysql_fetch_lengths", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc fetch_row(result: PRES): ROW {.stdcall, dynlib: lib,
+                                    importc: "mysql_fetch_row", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc field_count(MySQL: PMySQL): cuint {.stdcall, dynlib: lib,
+    importc: "mysql_field_count", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc field_seek(result: PRES; offset: FIELD_OFFSET): FIELD_OFFSET {.stdcall,
+    dynlib: lib, importc: "mysql_field_seek", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc field_tell(res: PRES): FIELD_OFFSET {.stdcall, dynlib: lib,
+    importc: "mysql_field_tell", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc free_result(result: PRES) {.stdcall, dynlib: lib,
+                                 importc: "mysql_free_result", ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc get_character_set_info(MySQL: PMySQL; charset: PMY_CHARSET_INFO) {.stdcall,
+    dynlib: lib, importc: "mysql_get_character_set_info", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc get_client_info(): cstring {.stdcall, dynlib: lib,
+                                  importc: "mysql_get_client_info", ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc get_client_version(): int {.stdcall, dynlib: lib,
+                                 importc: "mysql_get_client_version",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc get_host_info(MySQL: PMySQL): cstring {.stdcall, dynlib: lib,
+    importc: "mysql_get_host_info", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc get_parameters(): PPARAMETERS {.stdcall, dynlib: lib,
+                                     importc: "mysql_get_parameters",
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc get_proto_info(MySQL: PMySQL): cuint {.stdcall, dynlib: lib,
+    importc: "mysql_get_proto_info", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc get_salt_from_password(res: pointer; password: cstring) {.cdecl,
+    dynlib: lib, importc: "get_salt_from_password", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc get_salt_from_password_323(res: ptr int; password: cstring) {.cdecl,
+    dynlib: lib, importc: "get_salt_from_password_323", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc get_server_info(MySQL: PMySQL): cstring {.stdcall, dynlib: lib,
+    importc: "mysql_get_server_info", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc get_server_version(MySQL: PMySQL): int {.stdcall, dynlib: lib,
+    importc: "mysql_get_server_version", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc get_tty_password(opt_message: cstring): cstring {.cdecl, dynlib: lib,
+    importc: "get_tty_password", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc hash_password(fto: int; password: cstring; password_len: cuint) {.cdecl,
+    dynlib: lib, importc: "hash_password", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc hex_string(fto: cstring; from: cstring; from_length: int): int {.stdcall,
+    dynlib: lib, importc: "mysql_hex_string", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc info(MySQL: PMySQL): cstring {.stdcall, dynlib: lib, importc: "mysql_info",
+                                    ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc init(MySQL: PMySQL): PMySQL {.stdcall, dynlib: lib, importc: "mysql_init",
+                                   ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc insert_id(MySQL: PMySQL): my_ulonglong {.stdcall, dynlib: lib,
+    importc: "mysql_insert_id", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc INTERNAL_NUM_FIELD(f: Pst_mysql_field): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc IS_BLOB(n: int32): bool {....raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc IS_NOT_NULL(n: int32): bool {....raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc IS_NUM(t: Enum_field_types): bool {....raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc IS_NUM_FIELD(f: Pst_mysql_field): bool {....raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc IS_PRI_KEY(n: int32): bool {....raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc kill(MySQL: PMySQL; pid: int): cint {.stdcall, dynlib: lib,
+    importc: "mysql_kill", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc library_end() {.cdecl, dynlib: lib, importc: "mysql_server_end",
+                     ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc library_init(argc: cint; argv: cstringArray; groups: cstringArray): cint {.
+    cdecl, dynlib: lib, importc: "mysql_server_init", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc list_dbs(MySQL: PMySQL; wild: cstring): PRES {.stdcall, dynlib: lib,
+    importc: "mysql_list_dbs", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc list_fields(MySQL: PMySQL; table: cstring; wild: cstring): PRES {.stdcall,
+    dynlib: lib, importc: "mysql_list_fields", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc list_processes(MySQL: PMySQL): PRES {.stdcall, dynlib: lib,
+    importc: "mysql_list_processes", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc list_tables(MySQL: PMySQL; wild: cstring): PRES {.stdcall, dynlib: lib,
+    importc: "mysql_list_tables", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc load_defaults(conf_file: cstring; groups: cstringArray; argc: ptr cint;
+                   argv: ptr cstringArray): cint {.cdecl, dynlib: lib,
+    importc: "load_defaults", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc make_password_from_salt(fto: cstring; hash_stage2: pointer) {.cdecl,
+    dynlib: lib, importc: "make_password_from_salt", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc make_password_from_salt_323(fto: cstring; salt: ptr int) {.cdecl,
+    dynlib: lib, importc: "make_password_from_salt_323", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc make_scrambled_password(fto: cstring; password: cstring) {.cdecl,
+    dynlib: lib, importc: "make_scrambled_password", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc make_scrambled_password_323(fto: cstring; password: cstring) {.cdecl,
+    dynlib: lib, importc: "make_scrambled_password_323", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc manager_close(con: PMANAGER) {.stdcall, dynlib: lib,
+                                    importc: "mysql_manager_close", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc manager_command(con: PMANAGER; cmd: cstring; cmd_len: cint): cint {.
+    stdcall, dynlib: lib, importc: "mysql_manager_command", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc manager_connect(con: PMANAGER; host: cstring; user: cstring;
+                     passwd: cstring; port: cuint): PMANAGER {.stdcall,
+    dynlib: lib, importc: "mysql_manager_connect", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc manager_fetch_line(con: PMANAGER; res_buf: cstring; res_buf_size: cint): cint {.
+    stdcall, dynlib: lib, importc: "mysql_manager_fetch_line", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc manager_init(con: PMANAGER): PMANAGER {.stdcall, dynlib: lib,
+    importc: "mysql_manager_init", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc master_query(MySQL: PMySQL; q: cstring; len: int): my_bool {.stdcall,
+    dynlib: lib, importc: "mysql_master_query", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc master_send_query(MySQL: PMySQL; q: cstring; len: int): my_bool {.stdcall,
+    dynlib: lib, importc: "mysql_master_send_query", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc modify_defaults_file(file_location: cstring; option: cstring;
+                          option_value: cstring; section_name: cstring;
+                          remove_option: cint): cint {.cdecl, dynlib: lib,
+    importc: "load_defaults", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc more_results(MySQL: PMySQL): my_bool {.stdcall, dynlib: lib,
+    importc: "mysql_more_results", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc my_connect(s: my_socket; name: Psockaddr; namelen: cuint; timeout: cuint): cint {.
+    cdecl, dynlib: lib, importc: "my_connect", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc my_init(): my_bool {.cdecl, dynlib: lib, importc: "my_init", ...raises: [],
+                          tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc my_net_init(net: PNET; vio: PVIO): my_bool {.cdecl, dynlib: lib,
+    importc: "my_net_init", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc my_net_local_init(net: PNET) {.cdecl, dynlib: lib,
+                                    importc: "my_net_local_init", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc my_net_read(net: PNET): int {.cdecl, dynlib: lib, importc: "my_net_read",
+                                   ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc my_net_write(net: PNET; packet: cstring; length: int): my_bool {.cdecl,
+    dynlib: lib, importc: "my_net_write", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc my_rnd(para1: Prand_struct): cdouble {.cdecl, dynlib: lib,
+    importc: "my_rnd", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc my_thread_end() {.cdecl, dynlib: lib, importc: "my_thread_end", ...raises: [],
+                       tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc my_thread_init(): my_bool {.cdecl, dynlib: lib, importc: "my_thread_init",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc myodbc_remove_escape(MySQL: PMySQL; name: cstring) {.stdcall, dynlib: lib,
+    importc: "myodbc_remove_escape", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc net_clear(net: PNET) {.cdecl, dynlib: lib, importc: "net_clear",
+                            ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc net_end(net: PNET) {.cdecl, dynlib: lib, importc: "net_end", ...raises: [],
+                          tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc net_flush(net: PNET): my_bool {.cdecl, dynlib: lib, importc: "net_flush",
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc net_real_write(net: PNET; packet: cstring; length: int): cint {.cdecl,
+    dynlib: lib, importc: "net_real_write", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc net_realloc(net: PNET; len: int): my_bool {.cdecl, dynlib: lib,
+    importc: "net_realloc", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc net_safe_read(MySQL: PMySQL): cuint {.cdecl, dynlib: lib,
+    importc: "net_safe_read", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc net_write_command(net: PNET; command: char; header: cstring; head_len: int;
+                       packet: cstring; length: int): my_bool {.cdecl,
+    dynlib: lib, importc: "net_write_command", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc next_result(MySQL: PMySQL): cint {.stdcall, dynlib: lib,
+                                        importc: "mysql_next_result",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc num_fields(res: PRES): cuint {.stdcall, dynlib: lib,
+                                    importc: "mysql_num_fields", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc num_rows(res: PRES): my_ulonglong {.stdcall, dynlib: lib,
+    importc: "mysql_num_rows", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc octet2hex(fto: cstring; str: cstring; length: cuint): cstring {.cdecl,
+    dynlib: lib, importc: "octet2hex", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc options(MySQL: PMySQL; option: Option; arg: cstring): cint {.stdcall,
+    dynlib: lib, importc: "mysql_options", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc ping(MySQL: PMySQL): cint {.stdcall, dynlib: lib, importc: "mysql_ping",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc query(MySQL: PMySQL; q: cstring): cint {.stdcall, dynlib: lib,
+    importc: "mysql_query", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc randominit(para1: Prand_struct; seed1: int; seed2: int) {.cdecl,
+    dynlib: lib, importc: "randominit", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc read_query_result(MySQL: PMySQL): my_bool {.stdcall, dynlib: lib,
+    importc: "mysql_read_query_result", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc reads_from_master_enabled(MySQL: PMySQL): my_bool {.stdcall, dynlib: lib,
+    importc: "mysql_reads_from_master_enabled", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc real_connect(MySQL: PMySQL; host: cstring; user: cstring; passwd: cstring;
+                  db: cstring; port: cuint; unix_socket: cstring;
+                  clientflag: int): PMySQL {.stdcall, dynlib: lib,
+    importc: "mysql_real_connect", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc real_escape_string(MySQL: PMySQL; fto: cstring; from: cstring; len: int): int {.
+    stdcall, dynlib: lib, importc: "mysql_real_escape_string", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc real_query(MySQL: PMySQL; q: cstring; len: int): cint {.stdcall,
+    dynlib: lib, importc: "mysql_real_query", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc refresh(sql: PMySQL; refresh_options: cuint): cint {.stdcall, dynlib: lib,
+    importc: "mysql_refresh", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc reload(x: PMySQL): cint {....raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc rollback(MySQL: PMySQL): my_bool {.stdcall, dynlib: lib,
+                                        importc: "mysql_rollback", ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc row_seek(result: PRES; offset: ROW_OFFSET): ROW_OFFSET {.stdcall,
+    dynlib: lib, importc: "mysql_row_seek", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc row_tell(res: PRES): ROW_OFFSET {.stdcall, dynlib: lib,
+                                       importc: "mysql_row_tell", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc rpl_parse_enabled(MySQL: PMySQL): cint {.stdcall, dynlib: lib,
+    importc: "mysql_rpl_parse_enabled", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc rpl_probe(MySQL: PMySQL): my_bool {.stdcall, dynlib: lib,
+    importc: "mysql_rpl_probe", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc rpl_query_type(q: cstring; length: cint): Rpl_type {.stdcall, dynlib: lib,
+    importc: "mysql_rpl_query_type", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc scramble(fto: cstring; message: cstring; password: cstring) {.cdecl,
+    dynlib: lib, importc: "scramble", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc scramble_323(fto: cstring; message: cstring; password: cstring) {.cdecl,
+    dynlib: lib, importc: "scramble_323", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc select_db(MySQL: PMySQL; db: cstring): cint {.stdcall, dynlib: lib,
+    importc: "mysql_select_db", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc send_query(MySQL: PMySQL; q: cstring; len: int): cint {.stdcall,
+    dynlib: lib, importc: "mysql_send_query", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc server_end() {.cdecl, dynlib: lib, importc: "mysql_server_end", ...raises: [],
+                    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc server_init(argc: cint; argv: cstringArray; groups: cstringArray): cint {.
+    cdecl, dynlib: lib, importc: "mysql_server_init", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc set_character_set(MySQL: PMySQL; csname: cstring): int32 {.stdcall,
+    dynlib: lib, importc: "mysql_set_character_set", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc set_local_infile_default(MySQL: PMySQL) {.cdecl, dynlib: lib,
+    importc: "mysql_set_local_infile_default", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc set_master(MySQL: PMySQL; host: cstring; port: cuint; user: cstring;
+                passwd: cstring): cint {.stdcall, dynlib: lib,
+    importc: "mysql_set_master", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc set_server_option(MySQL: PMySQL; option: Enum_mysql_set_option): cint {.
+    stdcall, dynlib: lib, importc: "mysql_set_server_option", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc shutdown(MySQL: PMySQL; shutdown_level: Enum_shutdown_level): cint {.
+    stdcall, dynlib: lib, importc: "mysql_shutdown", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc slave_query(MySQL: PMySQL; q: cstring; len: int): my_bool {.stdcall,
+    dynlib: lib, importc: "mysql_slave_query", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc slave_send_query(MySQL: PMySQL; q: cstring; len: int): my_bool {.stdcall,
+    dynlib: lib, importc: "mysql_slave_send_query", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc sqlstate(MySQL: PMySQL): cstring {.stdcall, dynlib: lib,
+                                        importc: "mysql_sqlstate", ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc ssl_set(MySQL: PMySQL; key: cstring; cert: cstring; ca: cstring;
+             capath: cstring; cipher: cstring): my_bool {.stdcall, dynlib: lib,
+    importc: "mysql_ssl_set", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stat(MySQL: PMySQL): cstring {.stdcall, dynlib: lib, importc: "mysql_stat",
+                                    ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_affected_rows(stmt: PSTMT): my_ulonglong {.stdcall, dynlib: lib,
+    importc: "mysql_stmt_affected_rows", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_attr_get(stmt: PSTMT; attr_type: Enum_stmt_attr_type; attr: pointer): my_bool {.
+    stdcall, dynlib: lib, importc: "mysql_stmt_attr_get", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_attr_set(stmt: PSTMT; attr_type: Enum_stmt_attr_type; attr: pointer): my_bool {.
+    stdcall, dynlib: lib, importc: "mysql_stmt_attr_set", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_bind_param(stmt: PSTMT; bnd: PBIND): my_bool {.stdcall, dynlib: lib,
+    importc: "mysql_stmt_bind_param", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_bind_result(stmt: PSTMT; bnd: PBIND): my_bool {.stdcall, dynlib: lib,
+    importc: "mysql_stmt_bind_result", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_close(stmt: PSTMT): my_bool {.stdcall, dynlib: lib,
+                                        importc: "mysql_stmt_close", ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_data_seek(stmt: PSTMT; offset: my_ulonglong) {.stdcall, dynlib: lib,
+    importc: "mysql_stmt_data_seek", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_errno(stmt: PSTMT): cuint {.stdcall, dynlib: lib,
+                                      importc: "mysql_stmt_errno", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_error(stmt: PSTMT): cstring {.stdcall, dynlib: lib,
+                                        importc: "mysql_stmt_error", ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_execute(stmt: PSTMT): cint {.stdcall, dynlib: lib,
+                                       importc: "mysql_stmt_execute",
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_fetch(stmt: PSTMT): cint {.stdcall, dynlib: lib,
+                                     importc: "mysql_stmt_fetch", ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_fetch_column(stmt: PSTMT; bind: PBIND; column: cuint; offset: int): cint {.
+    stdcall, dynlib: lib, importc: "mysql_stmt_fetch_column", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_field_count(stmt: PSTMT): cuint {.stdcall, dynlib: lib,
+    importc: "mysql_stmt_field_count", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_free_result(stmt: PSTMT): my_bool {.stdcall, dynlib: lib,
+    importc: "mysql_stmt_free_result", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_init(MySQL: PMySQL): PSTMT {.stdcall, dynlib: lib,
+                                       importc: "mysql_stmt_init", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_insert_id(stmt: PSTMT): my_ulonglong {.stdcall, dynlib: lib,
+    importc: "mysql_stmt_insert_id", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_num_rows(stmt: PSTMT): my_ulonglong {.stdcall, dynlib: lib,
+    importc: "mysql_stmt_num_rows", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_param_count(stmt: PSTMT): int {.stdcall, dynlib: lib,
+    importc: "mysql_stmt_param_count", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_param_metadata(stmt: PSTMT): PRES {.stdcall, dynlib: lib,
+    importc: "mysql_stmt_param_metadata", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_prepare(stmt: PSTMT; query: cstring; len: int): cint {.stdcall,
+    dynlib: lib, importc: "mysql_stmt_prepare", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_reset(stmt: PSTMT): my_bool {.stdcall, dynlib: lib,
+                                        importc: "mysql_stmt_reset", ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_result_metadata(stmt: PSTMT): PRES {.stdcall, dynlib: lib,
+    importc: "mysql_stmt_result_metadata", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_row_seek(stmt: PSTMT; offset: ROW_OFFSET): ROW_OFFSET {.stdcall,
+    dynlib: lib, importc: "mysql_stmt_row_seek", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_row_tell(stmt: PSTMT): ROW_OFFSET {.stdcall, dynlib: lib,
+    importc: "mysql_stmt_row_tell", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_send_long_data(stmt: PSTMT; param_number: cuint; data: cstring;
+                         len: int): my_bool {.stdcall, dynlib: lib,
+    importc: "mysql_stmt_send_long_data", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_sqlstate(stmt: PSTMT): cstring {.stdcall, dynlib: lib,
+    importc: "mysql_stmt_sqlstate", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc stmt_store_result(stmt: PSTMT): cint {.stdcall, dynlib: lib,
+    importc: "mysql_stmt_store_result", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc store_result(MySQL: PMySQL): PRES {.stdcall, dynlib: lib,
+    importc: "mysql_store_result", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc thread_end() {.stdcall, dynlib: lib, importc: "mysql_thread_end",
+                    ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc thread_id(MySQL: PMySQL): int {.stdcall, dynlib: lib,
+                                     importc: "mysql_thread_id", ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc thread_init(): my_bool {.stdcall, dynlib: lib,
+                              importc: "mysql_thread_init", ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc thread_safe(): cuint {.stdcall, dynlib: lib, importc: "mysql_thread_safe",
+                            ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc use_result(MySQL: PMySQL): PRES {.stdcall, dynlib: lib,
+                                       importc: "mysql_use_result", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc warning_count(MySQL: PMySQL): cuint {.stdcall, dynlib: lib,
+    importc: "mysql_warning_count", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/nativesockets.html b/nativesockets.html new file mode 100644 index 0000000000000..512544ec1d5a0 --- /dev/null +++ b/nativesockets.html @@ -0,0 +1,1009 @@ + + + + + + + +std/nativesockets + + + + + + + + + + + + + + + + +
+
+

std/nativesockets

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a low-level cross-platform sockets interface. Look at the net module for the higher-level version.

+ +
+

Types

+
+
+
Domain = enum
+  AF_UNSPEC = 0, ## unspecified domain (can be detected automatically by
+                  ## some procedures, such as getaddrinfo)
+  AF_UNIX = 1,              ## for local socket (using a file). Unsupported on Windows.
+  AF_INET = 2,              ## for network protocol IPv4 or
+  AF_INET6 = 10
+
+ + +domain, which specifies the protocol family of the created socket. Other domains than those that are listed here are unsupported. + Source   +Edit   + +
+
+
+
Hostent = object
+  name*: string
+  aliases*: seq[string]
+  addrtype*: Domain
+  length*: int
+  addrList*: seq[string]
+
+ + information about a given host + Source   +Edit   + +
+
+
+
Port = distinct uint16
+
+ + port type + Source   +Edit   + +
+
+
+
Protocol = enum
+  IPPROTO_TCP = 6,          ## Transmission control protocol.
+  IPPROTO_UDP = 17,         ## User datagram protocol.
+  IPPROTO_IP,               ## Internet protocol.
+  IPPROTO_IPV6,             ## Internet Protocol Version 6.
+  IPPROTO_RAW,              ## Raw IP Packets Protocol. Unsupported on Windows.
+  IPPROTO_ICMP,             ## Internet Control message protocol.
+  IPPROTO_ICMPV6             ## Internet Control message protocol for IPv6.
+
+ + third argument to socket proc + Source   +Edit   + +
+
+
+
Servent = object
+  name*: string
+  aliases*: seq[string]
+  port*: Port
+  proto*: string
+
+ + information about a service + Source   +Edit   + +
+
+
+
SockType = enum
+  SOCK_STREAM = 1,          ## reliable stream-oriented service or Stream Sockets
+  SOCK_DGRAM = 2,           ## datagram service or Datagram Sockets
+  SOCK_RAW = 3,             ## raw protocols atop the network layer.
+  SOCK_SEQPACKET = 5         ## reliable sequenced packet service
+
+ + second argument to socket proc + Source   +Edit   + +
+
+ +
+
+
+

Lets

+
+
+
osInvalidSocket = INVALID_SOCKET
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
FIONBIO = -2147195266'i32
+
+ + + Source   +Edit   + +
+
+
+
IOC_IN = -2147483648
+
+ + + Source   +Edit   + +
+
+
+
IOCPARM_MASK = 127
+
+ + + Source   +Edit   + +
+
+
+
IPPROTO_NONE = IPPROTO_IP
+
+ + Use this if your socket type requires a protocol value of zero (e.g. Unix sockets). + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(p: Port): string {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + Returns the port number as a string + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(a, b: Port): bool {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + == for ports. + Source   +Edit   + +
+
+ +
+
+
+
proc accept(fd: SocketHandle; inheritable = defined(nimInheritHandles)): (
+    SocketHandle, string) {....raises: [], tags: [], forbids: [].}
+
+ +

Accepts a new client connection.

+

inheritable decides if the resulting SocketHandle can be inherited by child processes.

+

Returns (osInvalidSocket, "") if an error occurred.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc bindAddr(socket: SocketHandle; name: ptr SockAddr; namelen: SockLen): cint {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc close(socket: SocketHandle) {....raises: [], tags: [], forbids: [].}
+
+ + Closes a socket. + Source   +Edit   + +
+
+ +
+
+
+
proc createNativeSocket(domain: cint; sockType: cint; protocol: cint;
+                        inheritable: bool = defined(nimInheritHandles)): SocketHandle {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new socket; returns osInvalidSocket if an error occurs.

+

inheritable decides if the resulting SocketHandle can be inherited by child processes.

+

Use this overload if one of the enums specified above does not contain what you need.

+ + Source   +Edit   + +
+
+
+
proc createNativeSocket(domain: Domain = AF_INET;
+                        sockType: SockType = SOCK_STREAM;
+                        protocol: Protocol = IPPROTO_TCP;
+                        inheritable: bool = defined(nimInheritHandles)): SocketHandle {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new socket; returns osInvalidSocket if an error occurs.

+

inheritable decides if the resulting SocketHandle can be inherited by child processes.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getAddrInfo(address: string; port: Port; domain: Domain = AF_INET;
+                 sockType: SockType = SOCK_STREAM;
+                 protocol: Protocol = IPPROTO_TCP): ptr AddrInfo {.
+    ...raises: [OSError], tags: [], forbids: [].}
+
+ +
Warning: +The resulting ptr AddrInfo must be freed using freeAddrInfo!
+ + Source   +Edit   + +
+
+ +
+
+
+
proc getAddrString(sockAddr: ptr SockAddr): string {.
+    ...raises: [Exception, OSError, IOError], tags: [], forbids: [].}
+
+ + Returns the string representation of address within sockAddr + Source   +Edit   + +
+
+
+
proc getAddrString(sockAddr: ptr SockAddr; strAddress: var string) {.
+    ...raises: [Exception, OSError, IOError], tags: [], forbids: [].}
+
+ +

Stores in strAddress the string representation of the address inside sockAddr

+

Note

+
  • strAddress must be initialized to 46 in length.
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
proc getHostByAddr(ip: string): Hostent {....tags: [ReadIOEffect],
+    raises: [OSError, IOError, Exception], forbids: [].}
+
+ + This function will lookup the hostname of an IP Address. + Source   +Edit   + +
+
+ +
+
+
+
proc getHostByName(name: string): Hostent {....tags: [ReadIOEffect],
+    raises: [OSError], forbids: [].}
+
+ + This function will lookup the IP address of a hostname. + Source   +Edit   + +
+
+ +
+
+
+
proc getHostname(): string {....tags: [ReadIOEffect], raises: [OSError],
+                             forbids: [].}
+
+ + Returns the local hostname (not the FQDN) + Source   +Edit   + +
+
+ +
+
+
+
proc getLocalAddr(socket: SocketHandle; domain: Domain): (string, Port) {.
+    ...raises: [OSError, Exception], tags: [], forbids: [].}
+
+ +

Returns the socket's local address and port number.

+

Similar to POSIX's getsockname.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getPeerAddr(socket: SocketHandle; domain: Domain): (string, Port) {.
+    ...raises: [OSError, Exception], tags: [], forbids: [].}
+
+ +

Returns the socket's peer address and port number.

+

Similar to POSIX's getpeername

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getProtoByName(name: string): int {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ + Returns a protocol code from the database that matches the protocol name. + Source   +Edit   + +
+
+ +
+
+
+
proc getServByName(name, proto: string): Servent {....tags: [ReadIOEffect],
+    raises: [OSError], forbids: [].}
+
+ +

Searches the database from the beginning and finds the first entry for which the service name specified by name matches the s_name member and the protocol name specified by proto matches the s_proto member.

+

On posix this will search through the /etc/services file.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getServByPort(port: Port; proto: string): Servent {....tags: [ReadIOEffect],
+    raises: [OSError], forbids: [].}
+
+ +

Searches the database from the beginning and finds the first entry for which the port specified by port matches the s_port member and the protocol name specified by proto matches the s_proto member.

+

On posix this will search through the /etc/services file.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getSockDomain(socket: SocketHandle): Domain {....raises: [OSError, IOError],
+    tags: [], forbids: [].}
+
+ + Returns the socket's domain (AF_INET or AF_INET6). + Source   +Edit   + +
+
+ +
+
+
+
proc getSockName(socket: SocketHandle): Port {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ + Returns the socket's associated port number. + Source   +Edit   + +
+
+ +
+
+
+
proc getSockOptInt(socket: SocketHandle; level, optname: int): int {.
+    ...tags: [ReadIOEffect], raises: [OSError], forbids: [].}
+
+ + getsockopt for integer options. + Source   +Edit   + +
+
+ +
+
+
+
proc ioctlsocket(s: SocketHandle; cmd: clong; argptr: ptr clong): cint {.
+    stdcall, importc: "ioctlsocket", dynlib: "ws2_32.dll", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc listen(socket: SocketHandle; backlog = SOMAXCONN): cint {.
+    ...tags: [ReadIOEffect], raises: [], forbids: [].}
+
+ + Marks socket as accepting connections. Backlog specifies the maximum length of the queue of pending connections. + Source   +Edit   + +
+
+ +
+
+
+
proc ntohl(x: uint32): uint32 {....raises: [], tags: [], forbids: [].}
+
+ + Converts 32-bit unsigned integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation. + Source   +Edit   + +
+
+ +
+
+
+
proc ntohs(x: uint16): uint16 {....raises: [], tags: [], forbids: [].}
+
+ + Converts 16-bit unsigned integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation. + Source   +Edit   + +
+
+ +
+
+
+
proc selectRead(readfds: var seq[SocketHandle]; timeout = 500): int {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

When a socket in readfds is ready to be read from then a non-zero value will be returned specifying the count of the sockets which can be read from. The sockets which cannot be read from will also be removed from readfds.

+

timeout is specified in milliseconds and -1 can be specified for an unlimited time.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc selectWrite(writefds: var seq[SocketHandle]; timeout = 500): int {.
+    ...tags: [ReadIOEffect], raises: [], forbids: [].}
+
+ +

When a socket in writefds is ready to be written to then a non-zero value will be returned specifying the count of the sockets which can be written to. The sockets which cannot be written to will also be removed from writefds.

+

timeout is specified in milliseconds and -1 can be specified for an unlimited time.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc setBlocking(s: SocketHandle; blocking: bool) {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ +

Sets blocking mode on socket.

+

Raises OSError on error.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc setInheritable(s: SocketHandle; inheritable: bool): bool {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Set whether a socket is inheritable by child processes. Returns true on success.

+

This function is not implemented on all platform, test for availability with declared() <system.html#declared,untyped>.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc setSockOptInt(socket: SocketHandle; level, optname, optval: int) {.
+    ...tags: [WriteIOEffect], raises: [OSError], forbids: [].}
+
+ + setsockopt for integer options. + Source   +Edit   + +
+
+ +
+
+
+
proc toInt(domain: Domain): cint {....raises: [], tags: [], forbids: [].}
+
+ + Converts the Domain enum to a platform-dependent cint. + Source   +Edit   + +
+
+
+
proc toInt(p: Protocol): cint {....raises: [], tags: [], forbids: [].}
+
+ + Converts the Protocol enum to a platform-dependent cint. + Source   +Edit   + +
+
+
+
proc toInt(typ: SockType): cint {....raises: [], tags: [], forbids: [].}
+
+ + Converts the SockType enum to a platform-dependent cint. + Source   +Edit   + +
+
+ +
+
+
+
proc toKnownDomain(family: cint): Option[Domain] {....raises: [], tags: [],
+    forbids: [].}
+
+ + Converts the platform-dependent cint to the Domain or none(), if the cint is not known. + Source   +Edit   + +
+
+ +
+
+
+
proc toSockType(protocol: Protocol): SockType {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template htonl(x: uint32): untyped
+
+ + Converts 32-bit unsigned integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation. + Source   +Edit   + +
+
+ +
+
+
+
template htons(x: uint16): untyped
+
+ + Converts 16-bit unsigned integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/nativesockets.idx b/nativesockets.idx new file mode 100644 index 0000000000000..f74c8f3a2cf46 --- /dev/null +++ b/nativesockets.idx @@ -0,0 +1,69 @@ +nimTitle nativesockets nativesockets.html module std/nativesockets 0 +nim Port nativesockets.html#Port type Port 60 +nim AF_UNSPEC nativesockets.html#AF_UNSPEC Domain.AF_UNSPEC 62 +nim AF_UNIX nativesockets.html#AF_UNIX Domain.AF_UNIX 62 +nim AF_INET nativesockets.html#AF_INET Domain.AF_INET 62 +nim AF_INET6 nativesockets.html#AF_INET6 Domain.AF_INET6 62 +nim Domain nativesockets.html#Domain enum Domain 62 +nim SOCK_STREAM nativesockets.html#SOCK_STREAM SockType.SOCK_STREAM 72 +nim SOCK_DGRAM nativesockets.html#SOCK_DGRAM SockType.SOCK_DGRAM 72 +nim SOCK_RAW nativesockets.html#SOCK_RAW SockType.SOCK_RAW 72 +nim SOCK_SEQPACKET nativesockets.html#SOCK_SEQPACKET SockType.SOCK_SEQPACKET 72 +nim SockType nativesockets.html#SockType enum SockType 72 +nim IPPROTO_TCP nativesockets.html#IPPROTO_TCP Protocol.IPPROTO_TCP 78 +nim IPPROTO_UDP nativesockets.html#IPPROTO_UDP Protocol.IPPROTO_UDP 78 +nim IPPROTO_IP nativesockets.html#IPPROTO_IP Protocol.IPPROTO_IP 78 +nim IPPROTO_IPV6 nativesockets.html#IPPROTO_IPV6 Protocol.IPPROTO_IPV6 78 +nim IPPROTO_RAW nativesockets.html#IPPROTO_RAW Protocol.IPPROTO_RAW 78 +nim IPPROTO_ICMP nativesockets.html#IPPROTO_ICMP Protocol.IPPROTO_ICMP 78 +nim IPPROTO_ICMPV6 nativesockets.html#IPPROTO_ICMPV6 Protocol.IPPROTO_ICMPV6 78 +nim Protocol nativesockets.html#Protocol enum Protocol 78 +nim Servent nativesockets.html#Servent object Servent 87 +nim Hostent nativesockets.html#Hostent object Hostent 93 +nim IPPROTO_NONE nativesockets.html#IPPROTO_NONE const IPPROTO_NONE 100 +nim osInvalidSocket nativesockets.html#osInvalidSocket let osInvalidSocket 104 +nim IOCPARM_MASK nativesockets.html#IOCPARM_MASK const IOCPARM_MASK 107 +nim IOC_IN nativesockets.html#IOC_IN const IOC_IN 108 +nim FIONBIO nativesockets.html#FIONBIO const FIONBIO 109 +nim ioctlsocket nativesockets.html#ioctlsocket,SocketHandle,clong,ptr.clong proc ioctlsocket(s: SocketHandle; cmd: clong; argptr: ptr clong): cint 114 +nim `==` nativesockets.html#==,Port,Port proc `==`(a, b: Port): bool 124 +nim `$` nativesockets.html#$,Port proc `$`(p: Port): string 127 +nim toInt nativesockets.html#toInt,Domain proc toInt(domain: Domain): cint 130 +nim toInt nativesockets.html#toInt,SockType proc toInt(typ: SockType): cint 133 +nim toInt nativesockets.html#toInt,Protocol proc toInt(p: Protocol): cint 136 +nim toKnownDomain nativesockets.html#toKnownDomain,cint proc toKnownDomain(family: cint): Option[Domain] 177 +nim toSockType nativesockets.html#toSockType,Protocol proc toSockType(protocol: Protocol): SockType 205 +nim getProtoByName nativesockets.html#getProtoByName,string proc getProtoByName(name: string): int 214 +nim close nativesockets.html#close,SocketHandle proc close(socket: SocketHandle) 226 +nim setInheritable nativesockets.html#setInheritable,SocketHandle,bool proc setInheritable(s: SocketHandle; inheritable: bool): bool 236 +nim createNativeSocket nativesockets.html#createNativeSocket,cint,cint,cint,bool proc createNativeSocket(domain: cint; sockType: cint; protocol: cint;\n inheritable: bool = defined(nimInheritHandles)): SocketHandle 244 +nim createNativeSocket nativesockets.html#createNativeSocket,Domain,SockType,Protocol,bool proc createNativeSocket(domain: Domain = AF_INET; sockType: SockType = SOCK_STREAM;\n protocol: Protocol = IPPROTO_TCP;\n inheritable: bool = defined(nimInheritHandles)): SocketHandle 264 +nim bindAddr nativesockets.html#bindAddr,SocketHandle,ptr.SockAddr,SockLen proc bindAddr(socket: SocketHandle; name: ptr SockAddr; namelen: SockLen): cint 274 +nim listen nativesockets.html#listen,SocketHandle proc listen(socket: SocketHandle; backlog = SOMAXCONN): cint 278 +nim getAddrInfo nativesockets.html#getAddrInfo,string,Port,Domain,SockType,Protocol proc getAddrInfo(address: string; port: Port; domain: Domain = AF_INET;\n sockType: SockType = SOCK_STREAM; protocol: Protocol = IPPROTO_TCP): ptr AddrInfo 288 +nim ntohl nativesockets.html#ntohl,uint32 proc ntohl(x: uint32): uint32 315 +nim ntohs nativesockets.html#ntohs,uint16 proc ntohs(x: uint16): uint16 325 +nim htonl nativesockets.html#htonl.t,uint32 template htonl(x: uint32): untyped 332 +nim htons nativesockets.html#htons.t,uint16 template htons(x: uint16): untyped 338 +nim getSockDomain nativesockets.html#getSockDomain,SocketHandle proc getSockDomain(socket: SocketHandle): Domain 344 +nim getServByName nativesockets.html#getServByName,string,string proc getServByName(name, proto: string): Servent 358 +nim getServByPort nativesockets.html#getServByPort,Port,string proc getServByPort(port: Port; proto: string): Servent 374 +nim getHostByAddr nativesockets.html#getHostByAddr,string proc getHostByAddr(ip: string): Hostent 390 +nim getHostByName nativesockets.html#getHostByName,string proc getHostByName(name: string): Hostent 461 +nim getHostname nativesockets.html#getHostname proc getHostname(): string 490 +nim getAddrString nativesockets.html#getAddrString,ptr.SockAddr proc getAddrString(sockAddr: ptr SockAddr): string 506 +nim getAddrString nativesockets.html#getAddrString,ptr.SockAddr,string proc getAddrString(sockAddr: ptr SockAddr; strAddress: var string) 532 +nim getSockName nativesockets.html#getSockName,SocketHandle proc getSockName(socket: SocketHandle): Port 574 +nim getLocalAddr nativesockets.html#getLocalAddr,SocketHandle,Domain proc getLocalAddr(socket: SocketHandle; domain: Domain): (string, Port) 589 +nim getPeerAddr nativesockets.html#getPeerAddr,SocketHandle,Domain proc getPeerAddr(socket: SocketHandle; domain: Domain): (string, Port) 626 +nim getSockOptInt nativesockets.html#getSockOptInt,SocketHandle,int,int proc getSockOptInt(socket: SocketHandle; level, optname: int): int 735 +nim setSockOptInt nativesockets.html#setSockOptInt,SocketHandle,int,int,int proc setSockOptInt(socket: SocketHandle; level, optname, optval: int) 745 +nim setBlocking nativesockets.html#setBlocking,SocketHandle,bool proc setBlocking(s: SocketHandle; blocking: bool) 753 +nim selectRead nativesockets.html#selectRead,seq[SocketHandle],int proc selectRead(readfds: var seq[SocketHandle]; timeout = 500): int 797 +nim selectWrite nativesockets.html#selectWrite,seq[SocketHandle],int proc selectWrite(writefds: var seq[SocketHandle]; timeout = 500): int 818 +nim accept nativesockets.html#accept,SocketHandle proc accept(fd: SocketHandle; inheritable = defined(nimInheritHandles)): (\n SocketHandle, string) 840 +idx getpeername nativesockets.html#getpeername_1 Module nativesockets 0 +idx getsockname nativesockets.html#getsockname_1 Module nativesockets 0 +nimgrp createnativesocket nativesockets.html#createNativeSocket-procs-all proc 244 +nimgrp toint nativesockets.html#toInt-procs-all proc 130 +nimgrp getaddrstring nativesockets.html#getAddrString-procs-all proc 506 diff --git a/nep1.html b/nep1.html new file mode 100644 index 0000000000000..26c19c41fa3d4 --- /dev/null +++ b/nep1.html @@ -0,0 +1,273 @@ + + + + + + + +Standard Library Style Guide + + + + + + + + + + + + + + + + +
+
+

Standard Library Style Guide

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + + +
+
+ Source   +Edit   + +
+ +

+ +
Author:Clay Sweetser, Dominik Picheta
Version:2.2.1
+

Introduction

Although Nim supports a variety of code and formatting styles, it is nevertheless beneficial that certain community efforts, such as the standard library, should follow a consistent set of style guidelines when suitable. This enhancement proposal aims to list a series of guidelines that the standard library should follow.

+

Note that there can be exceptions to these rules. Nim being as flexible as it is, there will be parts of this style guide that don't make sense in certain contexts. Furthermore, just as Python's style guide changes over time, this style guide will too.

+

These rules will only be enforced for contributions to the Nim codebase and official projects, such as the Nim compiler, the standard library, and the various official tools such as C2Nim.

+

Style Guidelines

+

Spacing and Whitespace Conventions

  • Lines should be no longer than 80 characters. Limiting the amount of information present on each line makes for more readable code - the reader has smaller chunks to process.
  • +
  • Two spaces should be used for indentation of blocks; tabstops are not allowed (the compiler enforces this). Using spaces means that the appearance of code is more consistent across editors. Unlike spaces, tabstop width varies across editors, and not all editors provide means of changing this width.
  • +
  • Although use of whitespace for stylistic reasons other than the ones endorsed by this guide are allowed, careful thought should be put into such practices. Not all editors support automatic alignment of code sections, and re-aligning long sections of code by hand can quickly become tedious.

    +

    # This is bad, as the next time someone comes
    +# to edit this code block, they
    +# must re-align all the assignments again:
    +type
    +  WordBool*    = int16
    +  CalType*     = int
    +  ... # 5 lines later
    +  CalId*       = int
    +  LongLong*    = int64
    +  LongLongPtr* = ptr LongLong

    +
  • +
+ +

Naming Conventions

  • Type identifiers should be in PascalCase. All other identifiers should be in camelCase with the exception of constants which may use PascalCase but are not required to.

    +

    # Constants can start with either a lower case or upper case letter.
    +const aConstant = 42
    +const FooBar = 4.2
    +
    +var aVariable = "Meep" # Variables must start with a lowercase letter.
    +
    +# Types must start with an uppercase letter.
    +type
    +  FooBar = object

    +

    For constants coming from a C/C++ wrapper, ALL_UPPERCASE are allowed, but ugly. (Why shout CONSTANT? Constants do no harm, variables do!)

    +
  • +
  • When naming types that come in value, pointer, and reference varieties, use a regular name for the variety that is to be used the most, and add a "Obj", "Ref", or "Ptr" suffix for the other varieties. If there is no single variety that will be used the most, add the suffixes to the pointer variants only. The same applies to C/C++ wrappers.

    +

    type
    +  Handle = object # Will be used most often
    +    fd: int64
    +  HandleRef = ref Handle # Will be used less often

    +
  • +
  • Exception and Error types should have the "Error" or "Defect" suffix.

    +

    type
    +  ValueError = object of CatchableError
    +  AssertionDefect = object of Defect
    +  Foo = object of Exception # bad style, try to inherit CatchableError or Defect

    +
  • +
  • Unless marked with the {.pure.} pragma, members of enums should have an identifying prefix, such as an abbreviation of the enum's name.

    +

    type
    +  PathComponent = enum
    +    pcDir
    +    pcLinkToDir
    +    pcFile
    +    pcLinkToFile

    +
  • +
  • Non-pure enum values should use camelCase whereas pure enum values should use PascalCase.

    +

    type
    +  PathComponent {.pure.} = enum
    +    Dir
    +    LinkToDir
    +    File
    +    LinkToFile

    +
  • +
  • In the age of HTTP, HTML, FTP, TCP, IP, UTF, WWW it is foolish to pretend these are somewhat special words requiring all uppercase. Instead treat them as what they are: Real words. So it's parseUrl rather than parseURL, checkHttpHeader instead of checkHTTPHeader etc.
  • +
  • Operations like mitems or mpairs (or the now deprecated mget) that allow a mutating view into some data structure should start with an m.
  • +
  • When both in-place mutation and 'returns transformed copy' are available the latter is a past participle of the former:
    • reverse and reversed in algorithm
    • +
    • sort and sorted
    • +
    • rotate and rotated
    • +
    +
  • +
  • When the 'returns transformed copy' version already exists like strutils.replace an in-place version should get an -In suffix (replaceIn for this example).
  • +
  • Use subjectVerb, not verbSubject, e.g.: fileExists, not existsFile.
  • +
+

The stdlib API is designed to be easy to use and consistent. Ease of use is measured by the number of calls to achieve a concrete high level action. The ultimate goal is that the programmer can guess a name.

+

The library uses a simple naming scheme that makes use of common abbreviations to keep the names short but meaningful.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
English wordTo useNotes
initializeinitFooinitializes a value type Foo
newnewFooinitializes a reference type Foo via new or a value type Foo with reference semantics.
this or selfselffor method like procs, e.g.: proc fun(self: Foo, a: int) rationale: self is more unique in English than this, and foo would not be DRY.
findfindshould return the position where something was found; for a bool result use contains
containscontainsoften short for find() >= 0
appendadduse add instead of append
comparecmpshould return an int with the < 0 == 0 or > 0 semantics; for a bool result use sameXYZ
putput, []=consider overloading []= for put
getget, []consider overloading [] for get; consider to not use get as a prefix: len instead of getLen
lengthlenalso used for number of elements
sizesize, lensize should refer to a byte size
capacitycap
memorymemimplies a low-level operation
itemsitemsdefault iterator over a collection
pairspairsiterator over (key, value) pairs
deletedelete, deldel is supposed to be faster than delete, because it does not keep the order; delete keeps the order
removedelete, delinconsistent right now
includeincl
excludeexcl
commandcmd
executeexec
environmentenv
variablevar
valuevalue, val val is preferred, inconsistent right now
executableexe
directorydir
pathpathpath is the string "/usr/bin" (for example), dir is the content of "/usr/bin"; inconsistent right now
extensionext
separatorsep
columncol, column col is preferred, inconsistent right now
applicationapp
configurationcfg
messagemsg
argumentarg
objectobj
parameterparam
operatoropr
procedureproc
functionfunc
coordinatecoord
rectanglerect
pointpoint
symbolsym
literallit
stringstr
identifierident
indentationindent
+

Coding Conventions

  • The return statement should ideally be used when its control-flow properties are required. Use a procedure's implicit result variable whenever possible. This improves readability.

    +

    proc repeat(text: string, x: int): string =
    +  result = ""
    +  
    +  for i in 0..x:
    +    result.add($i)

    +
  • +
  • Use a proc when possible, only using the more powerful facilities of macros, templates, iterators, and converters when necessary.
  • +
  • Use the let statement (not the var statement) when declaring variables that do not change within their scope. Using the let statement ensures that variables remain immutable, and gives those who read the code a better idea of the code's purpose.
  • +
+ +

Conventions for multi-line statements and expressions

  • Tuples which are longer than one line should indent their parameters.

    +

    type
    +  LongTupleA = tuple[
    +    wordyTupleMemberOne: int, wordyTupleMemberTwo: string,
    +    wordyTupleMemberThree: float]

    +
  • +
  • Similarly, any procedure and procedure type declarations that are longer than one line should do the same thing. Double indent may be used to distinguish them from the body that follows - this applies to all constructs with a body (if, while, etc).

    +

    type
    +  EventCallback = proc(
    +    timeReceived: Time, errorCode: int, event: Event,
    +    output: var string)
    +
    +proc lotsOfArguments(
    +    argOne: string, argTwo: int, argThree: float,
    +    argFour: proc(), argFive: bool, argSix: int
    +): GenericType[int, string] {.heyLookALongPragma.} =
    +  discard

    +
  • +
  • Multi-line procedure calls should continue indented (like multi-line procedure declarations).

    +

    startProcess(
    +  nimExecutable, currentDirectory, compilerArguments
    +  environment, processOptions)

    +
  • +
+

Previous versions of this guide advocated vertical alignment along the opening brace / parenthesis - both styles are permissible with a preference for the current style in new code.

+ +

Miscellaneous

  • Use a..b instead of a .. b, except when b contains an operator, for example a .. -3. Likewise with a..<b, a..^b and other operators starting with ...
  • +
  • Use std prefix for standard library modules, namely use std/os for single module and use std/[os, sysrand, posix] for multiple modules.
  • +
  • Prefer multiline triple quote literals to start with a newline; it's semantically identical (it's a feature of triple quote literals) but clearer because it aligns with the next line:

    +

    use this:

    +

    let a = """
    +foo
    +bar
    +"""

    +

    instead of:

    +

    let a = """foo
    +bar
    +"""

    +
  • +
  • A getter API for a private field foo should preferably be named foo, not getFoo. A getter-like API should preferably be named getFoo, not foo if:
    • the API has side effects
    • +
    • or the cost is not O(1)
    • +
    +

    For in between cases, there is no clear guideline.

    +
  • +
  • Likewise with a setter API, replacing foo with foo= and getFoo with setFoo in the above text.
  • +
+

+ +
+
+ + +
+
+ + + + diff --git a/nep1.idx b/nep1.idx new file mode 100644 index 0000000000000..038b41a1ac666 --- /dev/null +++ b/nep1.idx @@ -0,0 +1,8 @@ +markupTitle Standard Library Style Guide nep1.html Standard Library Style Guide 0 +heading Introduction nep1.html#introduction Introduction 0 +heading Style Guidelines nep1.html#introduction-style-guidelines Style Guidelines 0 +heading Spacing and Whitespace Conventions nep1.html#style-guidelines-spacing-and-whitespace-conventions Spacing and Whitespace Conventions 0 +heading Naming Conventions nep1.html#style-guidelines-naming-conventions Naming Conventions 0 +heading Coding Conventions nep1.html#style-guidelines-coding-conventions Coding Conventions 0 +heading Conventions for multi-line statements and expressions nep1.html#style-guidelines-conventions-for-multiminusline-statements-and-expressions Conventions for multi-line statements and expressions 0 +heading Miscellaneous nep1.html#style-guidelines-miscellaneous Miscellaneous 0 diff --git a/net.html b/net.html new file mode 100644 index 0000000000000..c81719c2ee3fc --- /dev/null +++ b/net.html @@ -0,0 +1,1825 @@ + + + + + + + +std/net + + + + + + + + + + + + + + + + +
+
+

std/net

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a high-level cross-platform sockets interface. The procedures implemented in this module are primarily for blocking sockets. For asynchronous non-blocking sockets use the asyncnet module together with the asyncdispatch module.

+

The first thing you will always need to do in order to start using sockets, is to create a new instance of the Socket type using the newSocket procedure.

+ +

SSL

In order to use the SSL procedures defined in this module, you will need to compile your application with the -d:ssl flag. See the newContext procedure for additional details.

+ +

SSL on Windows

On Windows the SSL library checks for valid certificates. It uses the cacert.pem file for this purpose which was extracted from https://curl.se/ca/cacert.pem. Besides the OpenSSL DLLs (e.g. libssl-1_1-x64.dll, libcrypto-1_1-x64.dll) you also need to ship cacert.pem with your .exe file.

+ +

Examples

+

Connecting to a server

After you create a socket with the newSocket procedure, you can easily connect it to a server running at a known hostname (or IP address) and port. To do so over TCP, use the example below.

+ +

Example: cmd: -r:off

+
import std/net
+let socket = newSocket()
+socket.connect("google.com", Port(80))
For SSL, use the following example: +

Example: cmd: -r:off -d:ssl

+
import std/net
+let socket = newSocket()
+let ctx = newContext()
+wrapSocket(ctx, socket)
+socket.connect("google.com", Port(443))
UDP is a connectionless protocol, so UDP sockets don't have to explicitly call the connect procedure. They can simply start sending data immediately. +

Example: cmd: -r:off

+
import std/net
+let socket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
+socket.sendTo("192.168.0.1", Port(27960), "status\n")
+

Example: cmd: -r:off

+
import std/net
+let socket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
+let ip = parseIpAddress("192.168.0.1")
+doAssert socket.sendTo(ip, Port(27960), "status\c\l") == 8
+

Creating a server

After you create a socket with the newSocket procedure, you can create a TCP server by calling the bindAddr and listen procedures.

+ +

Example: cmd: -r:off

+
import std/net
+let socket = newSocket()
+socket.bindAddr(Port(1234))
+socket.listen()
+
+# You can then begin accepting connections using the `accept` procedure.
+var client: Socket
+var address = ""
+while true:
+  socket.acceptAddr(client, address)
+  echo "Client connected from: ", address

+ +
+

Types

+
+
+
Certificate = string
+
+ + DER encoded certificate + Source   +Edit   + +
+
+
+
IpAddress = object
+  case family*: IpAddressFamily ## the type of the IP address (IPv4 or IPv6)
+  of IpAddressFamily.IPv6:
+    address_v6*: array[0 .. 15, uint8] ## Contains the IP address in bytes in
+                                       ## case of IPv6
+  of IpAddressFamily.IPv4:
+    address_v4*: array[0 .. 3, uint8] ## Contains the IP address in bytes in
+                                      ## case of IPv4
+
+ + stores an arbitrary IP address + Source   +Edit   + +
+
+
+
IpAddressFamily {.pure.} = enum
+  IPv6,                     ## IPv6 address
+  IPv4                       ## IPv4 address
+
+ + Describes the type of an IP address + Source   +Edit   + +
+
+
+
ReadLineResult = enum
+  ReadFullLine, ReadPartialLine, ReadDisconnected, ReadNone
+
+ + result for readLineAsync + Source   +Edit   + +
+
+
+
SOBool = enum
+  OptAcceptConn, OptBroadcast, OptDebug, OptDontRoute, OptKeepAlive,
+  OptOOBInline, OptReuseAddr, OptReusePort, OptNoDelay
+
+ + Boolean socket options. + Source   +Edit   + +
+
+
+
Socket = ref SocketImpl
+
+ + + Source   +Edit   + +
+
+
+
SocketFlag {.pure.} = enum
+  Peek, SafeDisconn          ## Ensures disconnection exceptions (ECONNRESET, EPIPE etc) are not thrown.
+
+ + + Source   +Edit   + +
+
+
+
SocketImpl = object
+  when defineSsl:
+  ## stores the last error on this socket
+
+ + socket type + Source   +Edit   + +
+
+
+
SslAcceptResult = enum
+  AcceptNoClient = 0, AcceptNoHandshake, AcceptSuccess
+
+ + + Source   +Edit   + +
+
+
+
SslClientGetPskFunc = proc (hint: string): tuple[identity: string, psk: string]
+
+ + + Source   +Edit   + +
+
+
+
SslContext = ref object
+  context*: SslCtx
+
+ + + Source   +Edit   + +
+
+
+
SslCVerifyMode = enum
+  CVerifyNone, CVerifyPeer, CVerifyPeerUseEnvVars
+
+ + + Source   +Edit   + +
+
+
+
SslError = object of CatchableError
+
+ + + Source   +Edit   + +
+
+
+
SslHandshakeType = enum
+  handshakeAsClient, handshakeAsServer
+
+ + + Source   +Edit   + +
+
+
+
SslProtVersion = enum
+  protSSLv2, protSSLv3, protTLSv1, protSSLv23
+
+ + + Source   +Edit   + +
+
+
+
SslServerGetPskFunc = proc (identity: string): string
+
+ + + Source   +Edit   + +
+
+
+
TimeoutError = object of CatchableError
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
BufferSize: int = 4000
+
+ + size of a buffered socket's buffer + Source   +Edit   + +
+
+
+
MaxLineLength = 1000000
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(address: IpAddress): string {....raises: [], tags: [], forbids: [].}
+
+ + Converts an IpAddress into the textual representation + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(lhs, rhs: IpAddress): bool {....raises: [], tags: [], forbids: [].}
+
+ + Compares two IpAddresses for Equality. Returns true if the addresses are equal + Source   +Edit   + +
+
+ +
+
+
+
proc accept(server: Socket; client: var owned(Socket); flags = {SafeDisconn};
+            inheritable = defined(nimInheritHandles)) {....tags: [ReadIOEffect],
+    raises: [OSError, IOError, SslError], forbids: [].}
+
+ +

Equivalent to acceptAddr but doesn't return the address, only the socket.

+

The SocketHandle associated with the resulting client will not be inheritable by child processes by default. This can be changed via the inheritable parameter.

+

The accept call may result in an error if the connecting socket disconnects during the duration of the accept. If the SafeDisconn flag is specified then this error will not be raised and instead accept will be called again.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc acceptAddr(server: Socket; client: var owned(Socket); address: var string;
+                flags = {SafeDisconn}; inheritable = defined(nimInheritHandles)) {.
+    ...tags: [ReadIOEffect], gcsafe, raises: [OSError, IOError, SslError],
+    forbids: [].}
+
+ +

Blocks until a connection is being made from a client. When a connection is made sets client to the client socket and address to the address of the connecting client. This function will raise OSError if an error occurs.

+

The resulting client will inherit any properties of the server socket. For example: whether the socket is buffered or not.

+

The SocketHandle associated with the resulting client will not be inheritable by child processes by default. This can be changed via the inheritable parameter.

+

The accept call may result in an error if the connecting socket disconnects during the duration of the accept. If the SafeDisconn flag is specified then this error will not be raised and instead accept will be called again.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc bindAddr(socket: Socket; port = Port(0); address = "") {.
+    ...tags: [ReadIOEffect], raises: [ValueError, OSError], forbids: [].}
+
+ +

Binds address:port to the socket.

+

If address is "" then ADDR_ANY will be bound.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc bindUnix(socket: Socket; path: string) {....raises: [], tags: [], forbids: [].}
+
+ + Binds Unix socket to path. This only works on Unix-style systems: Mac OS X, BSD and Linux + Source   +Edit   + +
+
+ +
+
+
+
proc clientGetPskFunc(ctx: SslContext): SslClientGetPskFunc {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clientGetPskFunc=(ctx: SslContext; fun: SslClientGetPskFunc) {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Sets function that returns the client identity and the PSK based on identity hint from the server.

+

Only used in PSK ciphersuites.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc close(socket: Socket; flags = {SafeDisconn}) {.
+    ...raises: [LibraryError, Exception, OSError, SslError, OSError],
+    tags: [RootEffect], forbids: [].}
+
+ +

Closes a socket.

+

If socket is an SSL/TLS socket, this proc will also send a closure notification to the peer. If SafeDisconn is in flags, failure to do so due to disconnections will be ignored. This is generally safe in practice. See here for more details.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc connect(socket: Socket; address: string; port = Port(0)) {.
+    ...tags: [ReadIOEffect, RootEffect], raises: [OSError, SslError], forbids: [].}
+
+ +

Connects socket to address:port. Address can be an IP address or a host name. If address is a host name, this function will try each IP of that host name. htons is already performed on port so you must not do it.

+

If socket is an SSL socket a handshake will be automatically performed.

+ + Source   +Edit   + +
+
+
+
proc connect(socket: Socket; address: string; port = Port(0); timeout: int) {.
+    ...tags: [ReadIOEffect, WriteIOEffect, RootEffect],
+    raises: [OSError, TimeoutError], forbids: [].}
+
+ +

Connects to server as specified by address on port specified by port.

+

The timeout parameter specifies the time in milliseconds to allow for the connection to the server to be made.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc connectUnix(socket: Socket; path: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Connects to Unix socket on path. This only works on Unix-style systems: Mac OS X, BSD and Linux + Source   +Edit   + +
+
+ +
+
+
+
proc destroyContext(ctx: SslContext) {....raises: [SslError], tags: [], forbids: [].}
+
+ + Free memory referenced by SslContext. + Source   +Edit   + +
+
+ +
+
+
+
proc dial(address: string; port: Port; protocol = IPPROTO_TCP; buffered = true): owned(
+    Socket) {....tags: [ReadIOEffect, WriteIOEffect], raises: [OSError, IOError],
+              forbids: [].}
+
+ + Establishes connection to the specified address:port pair via the specified protocol. The procedure iterates through possible resolutions of the address until it succeeds, meaning that it seamlessly works with both IPv4 and IPv6. Returns Socket ready to send or receive data. + Source   +Edit   + +
+
+ +
+
+
+
proc fromSockAddr(sa: Sockaddr_storage | SockAddr | Sockaddr_in | Sockaddr_in6;
+                  sl: SockLen; address: var IpAddress; port: var Port) {.inline.}
+
+ + Converts SockAddr and SockLen to IpAddress and Port. Raises ObjectConversionDefect in case of invalid sa and sl arguments. + Source   +Edit   + +
+
+ +
+
+
+
proc getExtraData(ctx: SslContext; index: int): RootRef {....raises: [SslError],
+    tags: [], forbids: [].}
+
+ + Retrieves arbitrary data stored inside SslContext. + Source   +Edit   + +
+
+ +
+
+
+
proc getFd(socket: Socket): SocketHandle {....raises: [], tags: [], forbids: [].}
+
+ + Returns the socket's file descriptor + Source   +Edit   + +
+
+ +
+
+
+
proc getLocalAddr(socket: Socket): (string, Port) {.
+    ...raises: [OSError, Exception], tags: [], forbids: [].}
+
+ +

Get the socket's local address and port number.

+

This is high-level interface for getsockname.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getPeerAddr(socket: Socket): (string, Port) {....raises: [OSError, Exception],
+    tags: [], forbids: [].}
+
+ +

Get the socket's peer address and port number.

+

This is high-level interface for getpeername.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getPeerCertificates(socket: Socket): seq[Certificate] {.
+    ...raises: [Exception], tags: [], forbids: [].}
+
+ + Returns the certificate chain received by the peer we are connected to through the given socket. The handshake must have been completed and the certificate chain must have been verified successfully or else an empty sequence is returned. The chain is ordered from leaf certificate to root certificate. + Source   +Edit   + +
+
+
+
proc getPeerCertificates(sslHandle: SslPtr): seq[Certificate] {.
+    ...raises: [Exception], tags: [], forbids: [].}
+
+ + Returns the certificate chain received by the peer we are connected to through the OpenSSL connection represented by sslHandle. The handshake must have been completed and the certificate chain must have been verified successfully or else an empty sequence is returned. The chain is ordered from leaf certificate to root certificate. + Source   +Edit   + +
+
+ +
+
+
+
proc getPrimaryIPAddr(dest = parseIpAddress("8.8.8.8")): IpAddress {.
+    ...raises: [OSError, OSError, SslError, ValueError, Exception, LibraryError],
+    tags: [ReadIOEffect, RootEffect], forbids: [].}
+
+ +

Finds the local IP address, usually assigned to eth0 on LAN or wlan0 on WiFi, used to reach an external address. Useful to run local services.

+

No traffic is sent.

+

Supports IPv4 and v6. Raises OSError if external networking is not set up.

+ +

Example: cmd: -r:off

+
echo getPrimaryIPAddr() # "192.168.1.2"
+ Source   +Edit   + +
+
+ +
+
+
+
proc getPskIdentity(socket: Socket): string {....raises: [], tags: [], forbids: [].}
+
+ + Gets the PSK identity provided by the client. + Source   +Edit   + +
+
+ +
+
+
+
proc getSocketError(socket: Socket): OSErrorCode {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ + Checks osLastError for a valid error. If it has been reset it uses the last error stored in the socket object. + Source   +Edit   + +
+
+ +
+
+
+
proc getSockOpt(socket: Socket; opt: SOBool; level = SOL_SOCKET): bool {.
+    ...tags: [ReadIOEffect], raises: [OSError], forbids: [].}
+
+ + Retrieves option opt as a boolean value. + Source   +Edit   + +
+
+ +
+
+
+
proc gotHandshake(socket: Socket): bool {....raises: [SslError], tags: [],
+    forbids: [].}
+
+ +

Determines whether a handshake has occurred between a client (socket) and the server that socket is connected to.

+

Throws SslError if socket is not an SSL socket.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc hasDataBuffered(s: Socket): bool {....raises: [], tags: [], forbids: [].}
+
+ + Determines whether a socket has data buffered. + Source   +Edit   + +
+
+ +
+
+
+
proc IPv4_any(): IpAddress {....raises: [], tags: [], forbids: [].}
+
+ + Returns the IPv4 any address, which can be used to listen on all available network adapters + Source   +Edit   + +
+
+ +
+
+
+
proc IPv4_broadcast(): IpAddress {....raises: [], tags: [], forbids: [].}
+
+ + Returns the IPv4 broadcast address (255.255.255.255) + Source   +Edit   + +
+
+ +
+
+
+
proc IPv4_loopback(): IpAddress {....raises: [], tags: [], forbids: [].}
+
+ + Returns the IPv4 loopback address (127.0.0.1) + Source   +Edit   + +
+
+ +
+
+
+
proc IPv6_any(): IpAddress {....raises: [], tags: [], forbids: [].}
+
+ + Returns the IPv6 any address (::0), which can be used to listen on all available network adapters + Source   +Edit   + +
+
+ +
+
+
+
proc IPv6_loopback(): IpAddress {....raises: [], tags: [], forbids: [].}
+
+ + Returns the IPv6 loopback address (::1) + Source   +Edit   + +
+
+ +
+
+
+
proc isDisconnectionError(flags: set[SocketFlag]; lastError: OSErrorCode): bool {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Determines whether lastError is a disconnection error. Only does this if flags contains SafeDisconn. + Source   +Edit   + +
+
+ +
+
+
+
proc isIpAddress(addressStr: string): bool {....tags: [], raises: [], forbids: [].}
+
+ + Checks if a string is an IP address Returns true if it is, false otherwise + Source   +Edit   + +
+
+ +
+
+
+
proc isSsl(socket: Socket): bool {....raises: [], tags: [], forbids: [].}
+
+ + Determines whether socket is a SSL socket. + Source   +Edit   + +
+
+ +
+
+
+
proc listen(socket: Socket; backlog = SOMAXCONN) {....tags: [ReadIOEffect],
+    raises: [OSError], forbids: [].}
+
+ +

Marks socket as accepting connections. Backlog specifies the maximum length of the queue of pending connections.

+

Raises an OSError error upon failure.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newContext(protVersion = protSSLv23; verifyMode = CVerifyPeer;
+                certFile = ""; keyFile = ""; cipherList = CiphersIntermediate;
+                caDir = ""; caFile = ""; ciphersuites = CiphersModern): SslContext {.
+    ...raises: [LibraryError, SslError, Exception, IOError],
+    tags: [RootEffect, ReadDirEffect, ReadEnvEffect], forbids: [].}
+
+ +

Creates an SSL context.

+

Protocol version is currently ignored by default and TLS is used. With -d:openssl10, only SSLv23 and TLSv1 may be used.

+

There are three options for verify mode: CVerifyNone: certificates are not verified; CVerifyPeer: certificates are verified; CVerifyPeerUseEnvVars: certificates are verified and the optional environment variables SSL_CERT_FILE and SSL_CERT_DIR are also used to locate certificates

+

The nimDisableCertificateValidation define overrides verifyMode and disables certificate verification globally!

+

CA certificates will be loaded, in the following order, from:

+
  • caFile, caDir, parameters, if set
  • +
  • if verifyMode is set to CVerifyPeerUseEnvVars, the SSL_CERT_FILE and SSL_CERT_DIR environment variables are used
  • +
  • a set of files and directories from the ssl_certs file.
  • +
+

The last two parameters specify the certificate file path and the key file path, a server socket will most likely not work without these.

+

Certificates can be generated using the following command:

+
  • openssl req -x509 -nodes -days 365 -newkey rsa:4096 -keyout mykey.pem -out mycert.pem
  • +
+

or using ECDSA:

+
  • openssl ecparam -out mykey.pem -name secp256k1 -genkey
  • +
  • openssl req -new -key mykey.pem -x509 -nodes -days 365 -out mycert.pem
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
proc newSocket(domain, sockType, protocol: cint; buffered = true;
+               inheritable = defined(nimInheritHandles)): owned(Socket) {.
+    ...raises: [OSError], tags: [], forbids: [].}
+
+ +

Creates a new socket.

+

The SocketHandle associated with the resulting Socket will not be inheritable by child processes by default. This can be changed via the inheritable parameter.

+

If an error occurs OSError will be raised.

+ + Source   +Edit   + +
+
+
+
proc newSocket(domain: Domain = AF_INET; sockType: SockType = SOCK_STREAM;
+               protocol: Protocol = IPPROTO_TCP; buffered = true;
+               inheritable = defined(nimInheritHandles)): owned(Socket) {.
+    ...raises: [OSError], tags: [], forbids: [].}
+
+ +

Creates a new socket.

+

The SocketHandle associated with the resulting Socket will not be inheritable by child processes by default. This can be changed via the inheritable parameter.

+

If an error occurs OSError will be raised.

+ + Source   +Edit   + +
+
+
+
proc newSocket(fd: SocketHandle; domain: Domain = AF_INET;
+               sockType: SockType = SOCK_STREAM;
+               protocol: Protocol = IPPROTO_TCP; buffered = true): owned(Socket) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Creates a new socket as specified by the params. + Source   +Edit   + +
+
+ +
+
+
+
proc parseIpAddress(addressStr: string): IpAddress {....raises: [ValueError],
+    tags: [], forbids: [].}
+
+ +

Parses an IP address

+

Raises ValueError on error.

+

For IPv4 addresses, only the strict form as defined in RFC 6943 is considered valid, see https://datatracker.ietf.org/doc/html/rfc6943#section-3.1.1.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc pskIdentityHint=(ctx: SslContext; hint: string) {....raises: [SslError],
+    tags: [], forbids: [].}
+
+ +

Sets the identity hint passed to server.

+

Only used in PSK ciphersuites.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc raiseSSLError(s = "") {....raises: [SslError], tags: [], forbids: [].}
+
+ + Raises a new SSL error. + Source   +Edit   + +
+
+ +
+
+
+
proc readLine(socket: Socket; line: var string; timeout = -1;
+              flags = {SafeDisconn}; maxLength = MaxLineLength) {.
+    ...tags: [ReadIOEffect, TimeEffect], raises: [TimeoutError, OSError, SslError],
+    forbids: [].}
+
+ +

Reads a line of data from socket.

+

If a full line is read \r\L is not added to line, however if solely \r\L is read then line will be set to it.

+

If the socket is disconnected, line will be set to "".

+

An OSError exception will be raised in the case of a socket error.

+

A timeout can be specified in milliseconds, if data is not received within the specified time a TimeoutError exception will be raised.

+

The maxLength parameter determines the maximum amount of characters that can be read. The result is truncated after that.

+
Warning: +Only the SafeDisconn flag is currently supported.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc recv(socket: Socket; data: pointer; size: int): int {....tags: [ReadIOEffect],
+    raises: [], forbids: [].}
+
+ +

Receives data from a socket.

+

Note: This is a low-level function, you may be interested in the higher level versions of this function which are also named recv.

+ + Source   +Edit   + +
+
+
+
proc recv(socket: Socket; data: pointer; size: int; timeout: int): int {.
+    ...tags: [ReadIOEffect, TimeEffect], raises: [TimeoutError, OSError],
+    forbids: [].}
+
+ + overload with a timeout parameter in milliseconds. + Source   +Edit   + +
+
+
+
proc recv(socket: Socket; data: var string; size: int; timeout = -1;
+          flags = {SafeDisconn}): int {....raises: [TimeoutError, OSError, SslError],
+                                        tags: [ReadIOEffect, TimeEffect],
+                                        forbids: [].}
+
+ +

Higher-level version of recv.

+

Reads up to size bytes from socket into data.

+

For buffered sockets this function will attempt to read all the requested data. It will read this data in BufferSize chunks.

+

For unbuffered sockets this function makes no effort to read all the data requested. It will return as much data as the operating system gives it.

+

When 0 is returned the socket's connection has been closed.

+

This function will throw an OSError exception when an error occurs. A value lower than 0 is never returned.

+

A timeout may be specified in milliseconds, if enough data is not received within the time specified a TimeoutError exception will be raised.

+
Warning: +Only the SafeDisconn flag is currently supported.
+ + Source   +Edit   + +
+
+
+
proc recv(socket: Socket; size: int; timeout = -1; flags = {SafeDisconn}): string {.
+    inline, ...raises: [TimeoutError, OSError, SslError],
+    tags: [ReadIOEffect, TimeEffect], forbids: [].}
+
+ +

Higher-level version of recv which returns a string.

+

Reads up to size bytes from socket into the result.

+

For buffered sockets this function will attempt to read all the requested data. It will read this data in BufferSize chunks.

+

For unbuffered sockets this function makes no effort to read all the data requested. It will return as much data as the operating system gives it.

+

When "" is returned the socket's connection has been closed.

+

This function will throw an OSError exception when an error occurs.

+

A timeout may be specified in milliseconds, if enough data is not received within the time specified a TimeoutError exception will be raised.

+
Warning: +Only the SafeDisconn flag is currently supported.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc recvFrom[T: string | IpAddress](socket: Socket; data: var string;
+                                     length: int; address: var T;
+                                     port: var Port; flags = 0'i32): int {.
+    ...tags: [ReadIOEffect].}
+
+ +

Receives data from socket. This function should normally be used with connection-less sockets (UDP sockets). The source address of the data packet is stored in the address argument as either a string or an IpAddress.

+

If an error occurs an OSError exception will be raised. Otherwise the return value will be the length of data received.

+
Warning: +This function does not yet have a buffered implementation, so when socket is buffered the non-buffered implementation will be used. Therefore if socket contains something in its buffer this function will make no effort to return it.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc recvLine(socket: Socket; timeout = -1; flags = {SafeDisconn};
+              maxLength = MaxLineLength): string {.
+    ...raises: [TimeoutError, OSError, SslError], tags: [ReadIOEffect, TimeEffect],
+    forbids: [].}
+
+ +

Reads a line of data from socket.

+

If a full line is read \r\L is not added to the result, however if solely \r\L is read then the result will be set to it.

+

If the socket is disconnected, the result will be set to "".

+

An OSError exception will be raised in the case of a socket error.

+

A timeout can be specified in milliseconds, if data is not received within the specified time a TimeoutError exception will be raised.

+

The maxLength parameter determines the maximum amount of characters that can be read. The result is truncated after that.

+
Warning: +Only the SafeDisconn flag is currently supported.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc send(socket: Socket; data: pointer; size: int): int {.
+    ...tags: [WriteIOEffect], raises: [], forbids: [].}
+
+ +

Sends data to a socket.

+

Note: This is a low-level version of send. You likely should use the version below.

+ + Source   +Edit   + +
+
+
+
proc send(socket: Socket; data: string; flags = {SafeDisconn}; maxRetries = 100) {.
+    ...tags: [WriteIOEffect], raises: [SslError, OSError], forbids: [].}
+
+ + Sends data to a socket. Will try to send all the data by handling interrupts and incomplete writes up to maxRetries. + Source   +Edit   + +
+
+ +
+
+
+
proc sendTo(socket: Socket; address: IpAddress; port: Port; data: string;
+            flags = 0'i32): int {.discardable, ...tags: [WriteIOEffect],
+                                  raises: [OSError], forbids: [].}
+
+ +

This proc sends data to the specified IpAddress and returns the number of bytes written.

+

Generally for use with connection-less (UDP) sockets.

+

If an error occurs an OSError exception will be raised.

+

This is the high-level version of the above sendTo function.

+ + Source   +Edit   + +
+
+
+
proc sendTo(socket: Socket; address: string; port: Port; data: pointer;
+            size: int; af: Domain = AF_INET; flags = 0'i32) {.
+    ...tags: [WriteIOEffect], raises: [OSError], forbids: [].}
+
+ +

This proc sends data to the specified address, which may be an IP address or a hostname, if a hostname is specified this function will try each IP of that hostname. This function should normally be used with connection-less sockets (UDP sockets).

+

If an error occurs an OSError exception will be raised.

+

Note: You may wish to use the high-level version of this function which is defined below.

+

Note: This proc is not available for SSL sockets.

+ + Source   +Edit   + +
+
+
+
proc sendTo(socket: Socket; address: string; port: Port; data: string) {.
+    ...tags: [WriteIOEffect], raises: [OSError], forbids: [].}
+
+ +

This proc sends data to the specified address, which may be an IP address or a hostname, if a hostname is specified this function will try each IP of that hostname.

+

Generally for use with connection-less (UDP) sockets.

+

If an error occurs an OSError exception will be raised.

+

This is the high-level version of the above sendTo function.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc serverGetPskFunc(ctx: SslContext): SslServerGetPskFunc {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc serverGetPskFunc=(ctx: SslContext; fun: SslServerGetPskFunc) {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Sets function that returns PSK based on the client identity.

+

Only used in PSK ciphersuites.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc sessionIdContext=(ctx: SslContext; sidCtx: string) {....raises: [SslError],
+    tags: [], forbids: [].}
+
+ +

Sets the session id context in which a session can be reused. Used for permitting clients to reuse a session id instead of doing a new handshake.

+

TLS clients might attempt to resume a session using the session id context, thus it must be set if verifyMode is set to CVerifyPeer or CVerifyPeerUseEnvVars, otherwise the connection will fail and SslError will be raised if resumption occurs.

+
  • Only useful if set server-side.
  • +
  • Should be unique per-application to prevent clients from malfunctioning.
  • +
  • sidCtx must be at most 32 characters in length.
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
proc setExtraData(ctx: SslContext; index: int; data: RootRef) {.
+    ...raises: [SslError], tags: [], forbids: [].}
+
+ + Stores arbitrary data inside SslContext. The unique index should be retrieved using getSslContextExtraDataIndex. + Source   +Edit   + +
+
+ +
+
+
+
proc setSockOpt(socket: Socket; opt: SOBool; value: bool; level = SOL_SOCKET) {.
+    ...tags: [WriteIOEffect], raises: [OSError], forbids: [].}
+
+ + Sets option opt to a boolean value specified by value. +

Example: cmd: -r:off

+
let socket = newSocket()
+socket.setSockOpt(OptReusePort, true)
+socket.setSockOpt(OptNoDelay, true, level = IPPROTO_TCP.cint)
+ Source   +Edit   + +
+
+ +
+
+
+
proc skip(socket: Socket; size: int; timeout = -1) {.
+    ...raises: [TimeoutError, OSError], tags: [TimeEffect, ReadIOEffect],
+    forbids: [].}
+
+ +

Skips size amount of bytes.

+

An optional timeout can be specified in milliseconds, if skipping the bytes takes longer than specified a TimeoutError exception will be raised.

+

Returns the number of skipped bytes.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc socketError(socket: Socket; err: int = -1; async = false;
+                 lastError = -1.OSErrorCode; flags: set[SocketFlag] = {}) {.
+    ...gcsafe, raises: [SslError, OSError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sslHandle(self: Socket): SslPtr {....raises: [], tags: [], forbids: [].}
+
+ + Retrieve the ssl pointer of socket. Useful for interfacing with openssl. + Source   +Edit   + +
+
+ +
+
+
+
proc toCInt(opt: SOBool): cint {....raises: [], tags: [], forbids: [].}
+
+ + Converts a SOBool into its Socket Option cint representation. + Source   +Edit   + +
+
+ +
+
+
+
proc toOSFlags(socketFlags: set[SocketFlag]): cint {....raises: [], tags: [],
+    forbids: [].}
+
+ + Converts the flags into the underlying OS representation. + Source   +Edit   + +
+
+ +
+
+
+
proc toSockAddr(address: IpAddress; port: Port; sa: var Sockaddr_storage;
+                sl: var SockLen) {....raises: [], tags: [], forbids: [].}
+
+ + Converts IpAddress and Port to SockAddr and SockLen + Source   +Edit   + +
+
+ +
+
+
+
proc trySend(socket: Socket; data: string): bool {....tags: [WriteIOEffect],
+    raises: [], forbids: [].}
+
+ + Safe alternative to send. Does not raise an OSError when an error occurs, and instead returns false on failure. + Source   +Edit   + +
+
+ +
+
+
+
proc wrapConnectedSocket(ctx: SslContext; socket: Socket;
+                         handshake: SslHandshakeType; hostname: string = "") {.
+    ...raises: [SslError, Exception], tags: [RootEffect], forbids: [].}
+
+ +

Wraps a connected socket in an SSL context. This function effectively turns socket into an SSL socket. hostname should be specified so that the client knows which hostname the server certificate should be validated against.

+

This should be called on a connected socket, and will perform an SSL handshake immediately.

+

FIXME: Disclaimer: This code is not well tested, may be very unsafe and prone to security vulnerabilities.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc wrapSocket(ctx: SslContext; socket: Socket) {....raises: [SslError], tags: [],
+    forbids: [].}
+
+ +

Wraps a socket in an SSL context. This function effectively turns socket into an SSL socket.

+

This must be called on an unconnected socket; an SSL session will be started when the socket is connected.

+

FIXME: Disclaimer: This code is not well tested, may be very unsafe and prone to security vulnerabilities.

+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template `&=`(socket: Socket; data: typed)
+
+ + an alias for 'send'. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/net.idx b/net.idx new file mode 100644 index 0000000000000..cdfebc2dd9ac9 --- /dev/null +++ b/net.idx @@ -0,0 +1,128 @@ +nimTitle net net.html module std/net 0 +nim Certificate net.html#Certificate type Certificate 119 +nim SslError net.html#SslError object SslError 121 +nim CVerifyNone net.html#CVerifyNone SslCVerifyMode.CVerifyNone 123 +nim CVerifyPeer net.html#CVerifyPeer SslCVerifyMode.CVerifyPeer 123 +nim CVerifyPeerUseEnvVars net.html#CVerifyPeerUseEnvVars SslCVerifyMode.CVerifyPeerUseEnvVars 123 +nim SslCVerifyMode net.html#SslCVerifyMode enum SslCVerifyMode 123 +nim protSSLv2 net.html#protSSLv2 SslProtVersion.protSSLv2 126 +nim protSSLv3 net.html#protSSLv3 SslProtVersion.protSSLv3 126 +nim protTLSv1 net.html#protTLSv1 SslProtVersion.protTLSv1 126 +nim protSSLv23 net.html#protSSLv23 SslProtVersion.protSSLv23 126 +nim SslProtVersion net.html#SslProtVersion enum SslProtVersion 126 +nim SslContext net.html#SslContext type SslContext 129 +nim AcceptNoClient net.html#AcceptNoClient SslAcceptResult.AcceptNoClient 134 +nim AcceptNoHandshake net.html#AcceptNoHandshake SslAcceptResult.AcceptNoHandshake 134 +nim AcceptSuccess net.html#AcceptSuccess SslAcceptResult.AcceptSuccess 134 +nim SslAcceptResult net.html#SslAcceptResult enum SslAcceptResult 134 +nim handshakeAsClient net.html#handshakeAsClient SslHandshakeType.handshakeAsClient 137 +nim handshakeAsServer net.html#handshakeAsServer SslHandshakeType.handshakeAsServer 137 +nim SslHandshakeType net.html#SslHandshakeType enum SslHandshakeType 137 +nim SslClientGetPskFunc net.html#SslClientGetPskFunc type SslClientGetPskFunc 140 +nim SslServerGetPskFunc net.html#SslServerGetPskFunc type SslServerGetPskFunc 142 +nim BufferSize net.html#BufferSize const BufferSize 153 +nim MaxLineLength net.html#MaxLineLength const MaxLineLength 154 +nim SocketImpl net.html#SocketImpl object SocketImpl 157 +nim Socket net.html#Socket type Socket 176 +nim OptAcceptConn net.html#OptAcceptConn SOBool.OptAcceptConn 178 +nim OptBroadcast net.html#OptBroadcast SOBool.OptBroadcast 178 +nim OptDebug net.html#OptDebug SOBool.OptDebug 178 +nim OptDontRoute net.html#OptDontRoute SOBool.OptDontRoute 178 +nim OptKeepAlive net.html#OptKeepAlive SOBool.OptKeepAlive 178 +nim OptOOBInline net.html#OptOOBInline SOBool.OptOOBInline 178 +nim OptReuseAddr net.html#OptReuseAddr SOBool.OptReuseAddr 178 +nim OptReusePort net.html#OptReusePort SOBool.OptReusePort 178 +nim OptNoDelay net.html#OptNoDelay SOBool.OptNoDelay 178 +nim SOBool net.html#SOBool enum SOBool 178 +nim ReadFullLine net.html#ReadFullLine ReadLineResult.ReadFullLine 182 +nim ReadPartialLine net.html#ReadPartialLine ReadLineResult.ReadPartialLine 182 +nim ReadDisconnected net.html#ReadDisconnected ReadLineResult.ReadDisconnected 182 +nim ReadNone net.html#ReadNone ReadLineResult.ReadNone 182 +nim ReadLineResult net.html#ReadLineResult enum ReadLineResult 182 +nim TimeoutError net.html#TimeoutError object TimeoutError 185 +nim SocketFlag net.html#SocketFlag enum SocketFlag 187 +nim IpAddressFamily net.html#IpAddressFamily enum IpAddressFamily 195 +nim IpAddress net.html#IpAddress object IpAddress 199 +nim socketError net.html#socketError,Socket,int,set[SocketFlag] proc socketError(socket: Socket; err: int = -1; async = false;\n lastError = -1.OSErrorCode; flags: set[SocketFlag] = {}) 234 +nim isDisconnectionError net.html#isDisconnectionError,set[SocketFlag],OSErrorCode proc isDisconnectionError(flags: set[SocketFlag]; lastError: OSErrorCode): bool 238 +nim toOSFlags net.html#toOSFlags,set[SocketFlag] proc toOSFlags(socketFlags: set[SocketFlag]): cint 256 +nim newSocket net.html#newSocket,SocketHandle,Domain,SockType,Protocol proc newSocket(fd: SocketHandle; domain: Domain = AF_INET;\n sockType: SockType = SOCK_STREAM; protocol: Protocol = IPPROTO_TCP;\n buffered = true): owned(Socket) 264 +nim newSocket net.html#newSocket,cint,cint,cint proc newSocket(domain, sockType, protocol: cint; buffered = true;\n inheritable = defined(nimInheritHandles)): owned(Socket) 282 +nim newSocket net.html#newSocket,Domain,SockType,Protocol proc newSocket(domain: Domain = AF_INET; sockType: SockType = SOCK_STREAM;\n protocol: Protocol = IPPROTO_TCP; buffered = true;\n inheritable = defined(nimInheritHandles)): owned(Socket) 297 +nim parseIpAddress net.html#parseIpAddress,string proc parseIpAddress(addressStr: string): IpAddress 481 +nim isIpAddress net.html#isIpAddress,string proc isIpAddress(addressStr: string): bool 496 +nim toSockAddr net.html#toSockAddr,IpAddress,Port,Sockaddr_storage,SockLen proc toSockAddr(address: IpAddress; port: Port; sa: var Sockaddr_storage;\n sl: var SockLen) 505 +nim fromSockAddr net.html#fromSockAddr,,SockLen,IpAddress,Port proc fromSockAddr(sa: Sockaddr_storage | SockAddr | Sockaddr_in | Sockaddr_in6;\n sl: SockLen; address: var IpAddress; port: var Port) 543 +nim sslHandle net.html#sslHandle,Socket proc sslHandle(self: Socket): SslPtr 558 +nim raiseSSLError net.html#raiseSSLError,string proc raiseSSLError(s = "") 563 +nim getExtraData net.html#getExtraData,SslContext,int proc getExtraData(ctx: SslContext; index: int): RootRef 579 +nim setExtraData net.html#setExtraData,SslContext,int,RootRef proc setExtraData(ctx: SslContext; index: int; data: RootRef) 588 +nim newContext net.html#newContext,string,string,string,string proc newContext(protVersion = protSSLv23; verifyMode = CVerifyPeer; certFile = "";\n keyFile = ""; cipherList = CiphersIntermediate; caDir = "";\n caFile = ""; ciphersuites = CiphersModern): SslContext 623 +nim destroyContext net.html#destroyContext,SslContext proc destroyContext(ctx: SslContext) 738 +nim pskIdentityHint= net.html#pskIdentityHint=,SslContext,string proc pskIdentityHint=(ctx: SslContext; hint: string) 748 +nim clientGetPskFunc net.html#clientGetPskFunc,SslContext proc clientGetPskFunc(ctx: SslContext): SslClientGetPskFunc 755 +nim clientGetPskFunc= net.html#clientGetPskFunc=,SslContext,SslClientGetPskFunc proc clientGetPskFunc=(ctx: SslContext; fun: SslClientGetPskFunc) 773 +nim serverGetPskFunc net.html#serverGetPskFunc,SslContext proc serverGetPskFunc(ctx: SslContext): SslServerGetPskFunc 782 +nim serverGetPskFunc= net.html#serverGetPskFunc=,SslContext,SslServerGetPskFunc proc serverGetPskFunc=(ctx: SslContext; fun: SslServerGetPskFunc) 795 +nim getPskIdentity net.html#getPskIdentity,Socket proc getPskIdentity(socket: Socket): string 803 +nim wrapSocket net.html#wrapSocket,SslContext,Socket proc wrapSocket(ctx: SslContext; socket: Socket) 808 +nim wrapConnectedSocket net.html#wrapConnectedSocket,SslContext,Socket,SslHandshakeType,string proc wrapConnectedSocket(ctx: SslContext; socket: Socket;\n handshake: SslHandshakeType; hostname: string = "") 855 +nim getPeerCertificates net.html#getPeerCertificates,SslPtr proc getPeerCertificates(sslHandle: SslPtr): seq[Certificate] 888 +nim getPeerCertificates net.html#getPeerCertificates,Socket proc getPeerCertificates(socket: Socket): seq[Certificate] 907 +nim sessionIdContext= net.html#sessionIdContext=,SslContext,string proc sessionIdContext=(ctx: SslContext; sidCtx: string) 918 +nim getSocketError net.html#getSocketError,Socket proc getSocketError(socket: Socket): OSErrorCode 934 +nim listen net.html#listen,Socket proc listen(socket: Socket; backlog = SOMAXCONN) 1008 +nim bindAddr net.html#bindAddr,Socket,string proc bindAddr(socket: Socket; port = Port(0); address = "") 1017 +nim acceptAddr net.html#acceptAddr,Socket,,string proc acceptAddr(server: Socket; client: var owned(Socket); address: var string;\n flags = {SafeDisconn}; inheritable = defined(nimInheritHandles)) 1039 +nim accept net.html#accept,Socket, proc accept(server: Socket; client: var owned(Socket); flags = {SafeDisconn};\n inheritable = defined(nimInheritHandles)) 1138 +nim close net.html#close,Socket proc close(socket: Socket; flags = {SafeDisconn}) 1214 +nim toCInt net.html#toCInt,SOBool proc toCInt(opt: SOBool): cint 1275 +nim getSockOpt net.html#getSockOpt,Socket,SOBool proc getSockOpt(socket: Socket; opt: SOBool; level = SOL_SOCKET): bool 1288 +nim getLocalAddr net.html#getLocalAddr,Socket proc getLocalAddr(socket: Socket): (string, Port) 1294 +nim getPeerAddr net.html#getPeerAddr,Socket proc getPeerAddr(socket: Socket): (string, Port) 1301 +nim setSockOpt net.html#setSockOpt,Socket,SOBool,bool proc setSockOpt(socket: Socket; opt: SOBool; value: bool; level = SOL_SOCKET) 1307 +nim connectUnix net.html#connectUnix,Socket,string proc connectUnix(socket: Socket; path: string) 1318 +nim bindUnix net.html#bindUnix,Socket,string proc bindUnix(socket: Socket; path: string) 1327 +nim gotHandshake net.html#gotHandshake,Socket proc gotHandshake(socket: Socket): bool 1337 +nim hasDataBuffered net.html#hasDataBuffered,Socket proc hasDataBuffered(s: Socket): bool 1347 +nim recv net.html#recv,Socket,pointer,int proc recv(socket: Socket; data: pointer; size: int): int 1396 +nim recv net.html#recv,Socket,pointer,int,int proc recv(socket: Socket; data: pointer; size: int; timeout: int): int 1478 +nim recv net.html#recv,Socket,string,int,int proc recv(socket: Socket; data: var string; size: int; timeout = -1;\n flags = {SafeDisconn}): int 1496 +nim recv net.html#recv,Socket,int,int proc recv(socket: Socket; size: int; timeout = -1; flags = {SafeDisconn}): string 1531 +nim readLine net.html#readLine,Socket,string,int proc readLine(socket: Socket; line: var string; timeout = -1; flags = {SafeDisconn};\n maxLength = MaxLineLength) 1576 +nim recvLine net.html#recvLine,Socket,int proc recvLine(socket: Socket; timeout = -1; flags = {SafeDisconn};\n maxLength = MaxLineLength): string 1633 +nim recvFrom net.html#recvFrom,Socket,string,int,T,Port,int32 proc recvFrom[T: string | IpAddress](socket: Socket; data: var string; length: int;\n address: var T; port: var Port; flags = 0'i32): int 1656 +nim skip net.html#skip,Socket,int,int proc skip(socket: Socket; size: int; timeout = -1) 1704 +nim send net.html#send,Socket,pointer,int proc send(socket: Socket; data: pointer; size: int): int 1719 +nim send net.html#send,Socket,string,int proc send(socket: Socket; data: string; flags = {SafeDisconn}; maxRetries = 100) 1738 +nim `&=` net.html#&=.t,Socket,typed template `&=`(socket: Socket; data: typed) 1770 +nim trySend net.html#trySend,Socket,string proc trySend(socket: Socket; data: string): bool 1774 +nim sendTo net.html#sendTo,Socket,string,Port,pointer,int,Domain,int32 proc sendTo(socket: Socket; address: string; port: Port; data: pointer; size: int;\n af: Domain = AF_INET; flags = 0'i32) 1779 +nim sendTo net.html#sendTo,Socket,string,Port,string proc sendTo(socket: Socket; address: string; port: Port; data: string) 1814 +nim sendTo net.html#sendTo,Socket,IpAddress,Port,string,int32 proc sendTo(socket: Socket; address: IpAddress; port: Port; data: string;\n flags = 0'i32): int 1827 +nim isSsl net.html#isSsl,Socket proc isSsl(socket: Socket): bool 1852 +nim getFd net.html#getFd,Socket proc getFd(socket: Socket): SocketHandle 1859 +nim IPv4_any net.html#IPv4_any proc IPv4_any(): IpAddress 1875 +nim IPv4_loopback net.html#IPv4_loopback proc IPv4_loopback(): IpAddress 1882 +nim IPv4_broadcast net.html#IPv4_broadcast proc IPv4_broadcast(): IpAddress 1888 +nim IPv6_any net.html#IPv6_any proc IPv6_any(): IpAddress 1894 +nim IPv6_loopback net.html#IPv6_loopback proc IPv6_loopback(): IpAddress 1901 +nim `==` net.html#==,IpAddress,IpAddress proc `==`(lhs, rhs: IpAddress): bool 1910 +nim `$` net.html#$,IpAddress proc `$`(address: IpAddress): string 1921 +nim dial net.html#dial,string,Port proc dial(address: string; port: Port; protocol = IPPROTO_TCP; buffered = true): owned(\n Socket) 1989 +nim connect net.html#connect,Socket,string proc connect(socket: Socket; address: string; port = Port(0)) 2049 +nim connect net.html#connect,Socket,string,int proc connect(socket: Socket; address: string; port = Port(0); timeout: int) 2124 +nim getPrimaryIPAddr net.html#getPrimaryIPAddr proc getPrimaryIPAddr(dest = parseIpAddress("8.8.8.8")): IpAddress 2156 +heading SSL net.html#ssl SSL 0 +heading SSL on Windows net.html#ssl-on-windows SSL on Windows 0 +heading Examples net.html#examples Examples 0 +heading Connecting to a server net.html#examples-connecting-to-a-server Connecting to a server 0 +heading Creating a server net.html#examples-creating-a-server Creating a server 0 +idx getsockname net.html#getsockname_1 Creating a server 0 +idx getpeername net.html#getpeername_1 Creating a server 0 +nimgrp getpeercertificates net.html#getPeerCertificates-procs-all proc 888 +nimgrp sendto net.html#sendTo-procs-all proc 1779 +nimgrp connect net.html#connect-procs-all proc 2049 +nimgrp recv net.html#recv-procs-all proc 1396 +nimgrp send net.html#send-procs-all proc 1719 +nimgrp newsocket net.html#newSocket-procs-all proc 264 diff --git a/nimc.html b/nimc.html new file mode 100644 index 0000000000000..642fc7cd0b3b8 --- /dev/null +++ b/nimc.html @@ -0,0 +1,572 @@ + + + + + + + +Nim Compiler User Guide + + + + + + + + + + + + + + + + +
+
+

Nim Compiler User Guide

+
+ +
+ Source   +Edit   + +
+ +

+ +
Author:Andreas Rumpf
Version:2.2.1

"Look at you, hacker. A pathetic creature of meat and bone, panting and sweating as you run through my corridors. How can you challenge a perfect, immortal machine?"

+ +

Introduction

This document describes the usage of the Nim compiler on the different supported platforms. It is not a definition of the Nim programming language (which is covered in the manual).

+

Nim is free software; it is licensed under the MIT License.

+ +

Compiler Usage

+

Command-line switches

All options that take a PATH or DIR argument are subject to path substitution:

+
  • $nim: The global nim prefix path
  • +
  • $lib: The stdlib path
  • +
  • $home and ~: The user's home path
  • +
  • $config: The directory of the module currently being compiled
  • +
  • $projectname: The project file's name without file extension
  • +
  • $projectpath and $projectdir: The project file's path
  • +
  • $nimcache: The nimcache path
  • +
+

Basic command-line switches are:

+

Usage:

+
nim command [options] [projectfile] [arguments]
+

Command:

+
compile, c
compile project with default code generator (C)
+
r
compile to $nimcache/projname, run with arguments using backend specified by --backend (default: c)
+
doc
generate the documentation for inputfile for backend specified by --backend (default: c)
+

Arguments: arguments are passed to the program being run (if --run option is selected)

+

Options:

+
-p, --path:PATH
add path to search paths
+
-d, --define:SYMBOL(:VAL)
define a conditional symbol (Optionally: Define the value for that symbol, see: "compile time define pragmas")
+
-u, --undef:SYMBOL
undefine a conditional symbol
+
-f, --forceBuild:on|off
force rebuilding of all modules
+
--stackTrace:on|off
turn stack tracing on|off
+
--lineTrace:on|off
turn line tracing on|off
+
--threads:on|off
turn support for multi-threading on|off
+
-x, --checks:on|off
turn all runtime checks on|off
+
-a, --assertions:on|off
turn assertions on|off
+
--opt:none|speed|size
optimize not at all or for speed|size Note: use -d:release for a release build!
+
--debugger:native
use native debugger (gdb)
+
--app:console|gui|lib|staticlib
generate a console app|GUI app|DLL|static library
+
-r, --run
run the compiled program with given arguments
+
--eval:cmd
evaluate nim code directly; e.g.: nim --eval:"echo 1" defaults to e (nimscript) but customizable: nim r --eval:'for a in stdin.lines: echo a'
+
--fullhelp
show all command line switches
+
-h, --help
show this help
+
-v, --version
show detailed version information
+

Note, single letter options that take an argument require a colon. E.g. -p:PATH.

+
+

Advanced command-line switches are:

+Advanced commands:
compileToC, cc
compile project with C code generator
+
compileToCpp, cpp
compile project to C++ code
+
compileToOC, objc
compile project to Objective C code
+
js
compile project to Javascript
+
e
run a Nimscript file
+
md2html
convert a Markdown file to HTML use --docCmd:skip to skip compiling snippets
+
rst2html
convert a reStructuredText file to HTML use --docCmd:skip to skip compiling snippets
+
md2tex
convert a Markdown file to LaTeX
+
rst2tex
convert a reStructuredText file to LaTeX
+
doc2tex
extract the documentation to a LaTeX file
+
jsondoc
extract the documentation to a json file
+
ctags
create a tags file
+
buildIndex
build an index for the whole documentation
+
genDepend
generate a DOT file containing the module dependency graph
+
dump
dump all defined conditionals and search paths see also: --dump.format:json (useful with: | jq)
+
check
checks the project for syntax and semantics (can be combined with --defusages)
+

Runtime checks (see -x):

+
--objChecks:on|off
turn obj conversion checks on|off
+
--fieldChecks:on|off
turn case variant field checks on|off
+
--rangeChecks:on|off
turn range checks on|off
+
--boundChecks:on|off
turn bound checks on|off
+
--overflowChecks:on|off
turn int over-/underflow checks on|off
+
--floatChecks:on|off
turn all floating point (NaN/Inf) checks on|off
+
--nanChecks:on|off
turn NaN checks on|off
+
--infChecks:on|off
turn Inf checks on|off
+

Advanced options:

+
--defusages:FILE,LINE,COL
find the definition and all usages of a symbol
+
-o:FILE, --out:FILE
set the output filename
+
--outdir:DIR
set the path where the output file will be written
+
--usenimcache
will use outdir=$$nimcache, whichever it resolves to after all options have been processed
+
--stdout:on|off
output to stdout
+
--colors:on|off
turn compiler messages coloring on|off
+
--filenames:abs|canonical|legacyRelProj
customize how filenames are rendered in compiler messages, defaults to abs (absolute)
+
--processing:dots|filenames|off
show files as they're being processed by nim compiler
+
--unitsep:on|off
use the ASCII unit separator (31) between error messages, useful for IDE-like tooling
+
--declaredLocs:on|off
show declaration locations in messages
+
--spellSuggest:num
show at most num >= 0 spelling suggestions on typos. if num is not specified (or auto), return an implementation defined set of suggestions.
+
--hints:on|off|list.
on|off enables or disables hints. list reports which hints are selected.
+
--hint:X:on|off
turn specific hint X on|off. hint:X means hint:X:on, as with similar flags. all is the set of all hints (only all:off is supported).
+
--hintAsError:X:on|off
turn specific hint X into an error on|off
+
-w:on|off|list, --warnings:on|off|list
on|off enables or disables warnings. list reports which warnings are selected.
+
--warning:X:on|off
turn specific warning X on|off. warning:X means warning:X:on, as with similar flags. all is the set of all warning (only all:off is supported).
+
--warningAsError:X:on|off
turn specific warning X into an error on|off
+
--styleCheck:off|hint|error
produce hints or errors for Nim identifiers that do not adhere to Nim's official style guide https://nim-lang.org/docs/nep1.html
+
--styleCheck:usages
only enforce consistent spellings of identifiers, do not enforce the style on declarations
+
--showAllMismatches:on|off
show all mismatching candidates in overloading resolution
+
--lib:PATH
set the system library path
+
--import:PATH
add an automatically imported module see also patchFile in nimscript which offers more flexibility.
+
--include:PATH
add an automatically included module
+
--nimcache:PATH
+
-c, --compileOnly:on|off
compile Nim files only; do not assemble or link
+
--noLinking:on|off
compile Nim and generated files but do not link
+
--noMain:on|off
do not generate a main procedure
+
--genScript:on|off
generate a compile script (in the 'nimcache' subdirectory named 'compile_$$project$$scriptext'), and a '.deps' file containing the dependencies; implies --compileOnly
+
--os:SYMBOL
set the target operating system (cross-compilation)
+
--cpu:SYMBOL
set the target processor (cross-compilation)
+
--debuginfo:on|off
enables debug information
+
-t, --passC:OPTION
pass an option to the C compiler
+
-l, --passL:OPTION
pass an option to the linker
+
--cc:SYMBOL
specify the C compiler
+
--cincludes:DIR
modify the C compiler header search path
+
--clibdir:DIR
modify the linker library search path
+
--clib:LIBNAME
link an additional C library (you should omit platform-specific extensions)
+
--project
document the whole project (doc)
+
--docRoot:path
nim doc --docRoot:/foo --project --outdir:docs /foo/sub/main.nim generates: docs/sub/main.html if path == @pkg, will use nimble file enclosing dir if path == @path, will use first matching dir in --path if path == @default (the default and most useful), will use best match among @pkg,@path. if these are nonexistent, will use project path
+
-b, --backend:c|cpp|js|objc
sets backend to use with commands like nim doc or nim r
+
--docCmd:cmd
if cmd == skip, skips runnableExamples else, runs runnableExamples with given options, e.g.: --docCmd:"-d:foo --threads:on"
+
--docSeeSrcUrl:url
activate 'see source' for doc command (see doc.item.seesrc in config/nimdoc.cfg)
+
--docInternal
also generate documentation for non-exported symbols
+
--lineDir:on|off
generation of #line directive on|off
+
--embedsrc:on|off
embeds the original source code as comments in the generated output
+
--tlsEmulation:on|off
turn thread local storage emulation on|off
+
--implicitStatic:on|off
turn implicit compile time evaluation on|off
+
--trmacros:on|off
turn term rewriting macros on|off
+
--multimethods:on|off
turn multi-methods on|off
+
--hotCodeReloading:on|off
turn support for hot code reloading on|off
+
--excessiveStackTrace:on|off
stack traces use full file paths
+
--stackTraceMsgs:on|off
enable user defined stack frame msgs via setFrameMsg
+
--skipCfg:on|off
do not read the nim installation's configuration file
+
--skipUserCfg:on|off
do not read the user's configuration file
+
--skipParentCfg:on|off
do not read the parent dirs' configuration files
+
--skipProjCfg:on|off
do not read the project's configuration file
+
--mm:orc|arc|refc|markAndSweep|boehm|go|none|regions
select which memory management to use; default is 'orc'
+
--exceptions:setjmp|cpp|goto|quirky
select the exception handling implementation
+
--index:on|off|only
docgen: turn index file generation on|off (only means not generate output files like HTML)
+
--noImportdoc:on|off
turn loading documentation .idx files on|off
+
--putenv:key=value
set an environment variable
+
--NimblePath:PATH
add a path for Nimble support
+
--noNimblePath
deactivate the Nimble path
+
--clearNimblePath
empty the list of Nimble package search paths
+
--cppCompileToNamespace:namespace
use the provided namespace for the generated C++ code, if no namespace is provided "Nim" will be used
+
--nimMainPrefix:prefix
use {prefix}NimMain instead of NimMain in the produced C/C++ code
+
--expandMacro:MACRO
dump every generated AST from MACRO
+
--expandArc:PROCNAME
show how PROCNAME looks like after diverse optimizations before the final backend phase (mostly ARC/ORC specific)
+
--excludePath:PATH
exclude a path from the list of search paths
+
--dynlibOverride:SYMBOL
marks SYMBOL so that dynlib:SYMBOL has no effect and can be statically linked instead; symbol matching is fuzzy so that --dynlibOverride:lua matches dynlib: "liblua.so.3"
+
--dynlibOverrideAll
disables the effects of the dynlib pragma
+
--listCmd
list the compilation commands; can be combined with --hint:exec:on and --hint:link:on
+
--asm
produce assembler code
+
--parallelBuild:0|1|...
perform a parallel build value = number of processors (0 for auto-detect)
+
--incremental:on|off
only recompile the changed modules (experimental!)
+
--verbosity:0|1|2|3
set Nim's verbosity level (1 is default)
+
--errorMax:N
stop compilation after N errors; 0 means unlimited
+
--maxLoopIterationsVM:N
set max iterations for all VM loops
+
--experimental:$1
enable experimental language feature
+
--legacy:$2
enable obsolete/legacy language feature
+
--benchmarkVM:on|off
turn benchmarking of VM code with cpuTime() on|off
+
--profileVM:on|off
turn compile time VM profiler on|off
+
--panics:on|off
turn panics into process terminations (default: off)
+
--deepcopy:on|off
enable 'system.deepCopy' for --mm:arc|orc
+
--jsbigint64:on|off
toggle the use of BigInt for 64-bit integers for the JavaScript backend (default: on)
+
--nimBasePattern:nimbase.h
allows to specify a custom pattern for nimbase.h
+
+

List of warnings

Each warning can be activated individually with --warning:NAME:on|off or in a push pragma with {.warning[NAME]:on|off.}.

+ + + + + + + + + + + + + +
NameDescription
CannotOpenFileSome file not essential for the compiler's working could not be opened.
OctalEscapeThe code contains an unsupported octal sequence.
DeprecatedThe code uses a deprecated symbol.
ConfigDeprecatedThe project makes use of a deprecated config file.
SmallLshouldNotBeUsedThe letter 'l' should not be used as an identifier.
EachIdentIsTupleThe code contains a confusing var declaration.
CStringConvWarn about dangerous implicit conversions to cstring.
EnumConvWarn about conversions from enum to enum.
AnyEnumConvWarn about any conversions to an enum type.
HoleEnumConvWarn about conversion to an enum with holes. These conversions are unsafe.
ResultUsedWarn about the usage of the built-in result variable.
UserSome user-defined warning.
+

List of hints

Each hint can be activated individually with --hint:NAME:on|off or in a push pragma with {.hint[NAME]:on|off.}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameDescription
CCShows when the C compiler is called.
CodeBegin
CodeEnd
CondTrue
ConfA config file was loaded.
ConvToBaseNotNeeded
ConvFromXtoItselfNotNeeded
Dependency
ExecProgram is executed.
ExprAlwaysX
ExtendedContext
GCStatsDumps statistics about the Garbage Collector.
GlobalVarShows global variables declarations.
LinkLinking phase.
Name
PathSearch paths modifications.
Pattern
Performance
ProcessingArtifact being compiled.
QuitCalled
SourceThe source line that triggered a diagnostic message.
StackTrace
Success, SuccessXSuccessful compilation of a library or a binary.
User
UserRaw
XDeclaredButNotUsedUnused symbols in the code.
+

Verbosity levels

+ + + + +
LevelDescription
0Minimal output level for the compiler.
1Displays compilation of all the compiled files, including those imported by other modules or through the compile pragma. This is the default level.
2Displays compilation statistics, enumerates the dynamic libraries that will be loaded by the final binary, and dumps to standard output the result of applying a filter to the source code if any filter was used during compilation.
3In addition to the previous levels dumps a debug stack trace for compiler developers.
+

Compile-time symbols

Through the -d:x or --define:x switch you can define compile-time symbols for conditional compilation. The defined switches can be checked in source code with the when statement and defined proc. The typical use of this switch is to enable builds in release mode (-d:release) where optimizations are enabled for better performance. Another common use is the -d:ssl switch to activate SSL sockets.

+

Additionally, you may pass a value along with the symbol: -d:x=y which may be used in conjunction with the compile-time define pragmas to override symbols during build time.

+

Compile-time symbols are completely case insensitive and underscores are ignored too. --define:FOO and --define:foo are identical.

+

Compile-time symbols starting with the nim prefix are reserved for the implementation and should not be used elsewhere.

+ + + + + +
NameDescription
nimStdSetjmpUse the standard setjmp()/longjmp() library functions for setjmp-based exceptions. This is the default on most platforms.
nimSigSetjmpUse sigsetjmp()/siglongjmp() for setjmp-based exceptions.
nimRawSetjmpUse _setjmp()/_longjmp() on POSIX and _setjmp()/longjmp() on Windows, for setjmp-based exceptions. It's the default on BSDs and BSD-like platforms, where it's significantly faster than the standard functions.
nimBuiltinSetjmpUse __builtin_setjmp()/__builtin_longjmp() for setjmp-based exceptions. This will not work if an exception is being thrown and caught inside the same procedure. Useful for benchmarking.
+

Configuration files

Note: The project file name is the name of the .nim file that is passed as a command-line argument to the compiler.

+

The nim executable processes configuration files in the following directories (in this order; later files overwrite previous settings):

+
  1. $nim/config/nim.cfg, /etc/nim/nim.cfg (UNIX) or <Nim's installation directory>\config\nim.cfg (Windows). This file can be skipped with the --skipCfg command line option.
  2. +
  3. If environment variable XDG_CONFIG_HOME is defined, $XDG_CONFIG_HOME/nim/nim.cfg or ~/.config/nim/nim.cfg (POSIX) or %APPDATA%/nim/nim.cfg (Windows). This file can be skipped with the --skipUserCfg command line option.
  4. +
  5. $parentDir/nim.cfg where $parentDir stands for any parent directory of the project file's path. These files can be skipped with the --skipParentCfg command-line option.
  6. +
  7. $projectDir/nim.cfg where $projectDir stands for the project file's path. This file can be skipped with the --skipProjCfg command-line option.
  8. +
  9. A project can also have a project-specific configuration file named $project.nim.cfg that resides in the same directory as $project.nim. This file can be skipped with the --skipProjCfg command-line option.
  10. +
+

Command-line settings have priority over configuration file settings.

+

The default build of a project is a debug build. To compile a release build define the release symbol:

+

nim c -d:release myproject.nim

+

To compile a dangerous release build define the danger symbol:

+

nim c -d:danger myproject.nim

+ +

Search path handling

Nim has the concept of a global search path (PATH) that is queried to determine where to find imported modules or include files. If multiple files are found an ambiguity error is produced.

+

nim dump shows the contents of the PATH.

+

However before the PATH is used the current directory is checked for the file's existence. So if PATH contains $lib and $lib/bar and the directory structure looks like this:

+
$lib/x.nim
+$lib/bar/x.nim
+foo/x.nim
+foo/main.nim
+other.nim
+

And main imports x, foo/x is imported. If other imports x then both $lib/x.nim and $lib/bar/x.nim match but $lib/x.nim is used as it is the first match.

+ +

Generated C code directory

The generated files that Nim produces all go into a subdirectory called nimcache. Its full path is

+
  • $XDG_CACHE_HOME/nim/$projectname(_r|_d) or ~/.cache/nim/$projectname(_r|_d) on Posix
  • +
  • $HOME\nimcache\$projectname(_r|_d) on Windows.
  • +
+

The _r suffix is used for release builds, _d is for debug builds.

+

This makes it easy to delete all generated files.

+

The --nimcache compiler switch can be used to to change the nimcache directory.

+

However, the generated C code is not platform-independent. C code generated for Linux does not compile on Windows, for instance. The comment on top of the C file lists the OS, CPU, and CC the file has been compiled for.

+ +

Compiler Selection

To change the compiler from the default compiler (at the command line):

+

nim c --cc:llvm_gcc --compile_only myfile.nim

+

This uses the configuration defined in config\nim.cfg for llvm_gcc.

+

If nimcache already contains compiled code from a different compiler for the same project, add the -f flag to force all files to be recompiled.

+

The default compiler is defined at the top of config\nim.cfg. Changing this setting affects the compiler used by koch to (re)build Nim.

+

To use the CC environment variable, use nim c --cc:env myfile.nim. To use the CXX environment variable, use nim cpp --cc:env myfile.nim. --cc:env is available since Nim version 1.4.

+ +

Cross-compilation

To cross compile, use for example:

+

nim c --cpu:i386 --os:linux --compileOnly --genScript myproject.nim

+

Then move the C code and the compile script compile_myproject.sh to your Linux i386 machine and run the script.

+

Another way is to make Nim invoke a cross compiler toolchain:

+

nim c --cpu:arm --os:linux myproject.nim

+

For cross compilation, the compiler invokes a C compiler named like $cpu.$os.$cc (for example arm.linux.gcc) with options defined in $cpu.$os.$cc.options.always. The configuration system is used to provide meaningful defaults. For example, for Linux on a 32-bit ARM CPU, your configuration file should contain something like:

+
arm.linux.gcc.path = "/usr/bin"
+arm.linux.gcc.exe = "arm-linux-gcc"
+arm.linux.gcc.linkerexe = "arm-linux-gcc"
+arm.linux.gcc.options.always = "-w -fmax-errors=3"
+ +

Cross-compilation for Windows

To cross-compile for Windows from Linux or macOS using the MinGW-w64 toolchain:

+

nim c -d:mingw myproject.nim
+# `nim r` also works, running the binary via `wine` or `wine64`:
+nim r -d:mingw --eval:'import os; echo "a" / "b"'

+

Use --cpu:i386 or --cpu:amd64 to switch the CPU architecture.

+

The MinGW-w64 toolchain can be installed as follows:

+

apt install mingw-w64   # Ubuntu
+yum install mingw32-gcc
+yum install mingw64-gcc # CentOS - requires EPEL
+brew install mingw-w64  # OSX

+ +

Cross-compilation for Android

There are two ways to compile for Android: terminal programs (Termux) and with the NDK (Android Native Development Kit).

+

The first one is to treat Android as a simple Linux and use Termux to connect and run the Nim compiler directly on android as if it was Linux. These programs are console-only programs that can't be distributed in the Play Store.

+

Use regular nim c inside termux to make Android terminal programs.

+

Normal Android apps are written in Java, to use Nim inside an Android app you need a small Java stub that calls out to a native library written in Nim using the NDK. You can also use native-activity to have the Java stub be auto-generated for you.

+

Use nim c -c --cpu:arm --os:android -d:androidNDK --noMain:on to generate the C source files you need to include in your Android Studio project. Add the generated C files to CMake build script in your Android project. Then do the final compile with Android Studio which uses Gradle to call CMake to compile the project.

+

Because Nim is part of a library it can't have its own C-style main() so you would need to define your own android_main and init the Java environment, or use a library like SDL2 or GLFM to do it. After the Android stuff is done, it's very important to call NimMain() in order to initialize Nim's garbage collector and to run the top level statements of your program.

+

proc NimMain() {.importc.}
+proc glfmMain*(display: ptr GLFMDisplay) {.exportc.} =
+  NimMain() # initialize garbage collector memory, types and stack

+

The name NimMain can be influenced via the --nimMainPrefix:prefix switch. Use --nimMainPrefix:MyLib and the function to call is named MyLibNimMain.

+ +

Cross-compilation for iOS

To cross-compile for iOS you need to be on a macOS computer and use XCode. Normal languages for iOS development are Swift and Objective C. Both of these use LLVM and can be compiled into object files linked together with C, C++ or Objective C code produced by Nim.

+

Use nim c -c --os:ios --noMain:on to generate C files and include them in your XCode project. Then you can use XCode to compile, link, package and sign everything.

+

Because Nim is part of a library it can't have its own C-style main() so you would need to define main that calls autoreleasepool and UIApplicationMain to do it, or use a library like SDL2 or GLFM. After the iOS setup is done, it's very important to call NimMain() to initialize Nim's garbage collector and to run the top-level statements of your program.

+

proc NimMain() {.importc.}
+proc glfmMain*(display: ptr GLFMDisplay) {.exportc.} =
+  NimMain() # initialize garbage collector memory, types and stack

+

Note: XCode's "make clean" gets confused about the generated nim.c files, so you need to clean those files manually to do a clean build.

+

The name NimMain can be influenced via the --nimMainPrefix:prefix switch. Use --nimMainPrefix:MyLib and the function to call is named MyLibNimMain.

+ +

Cross-compilation for Nintendo Switch

Simply add --os:nintendoswitch to your usual nim c or nim cpp command and set the passC and passL command line switches to something like:

+

nim c ... --d:nimAllocPagesViaMalloc --mm:orc --passC="-I$DEVKITPRO/libnx/include" ...
+--passL="-specs=$DEVKITPRO/libnx/switch.specs -L$DEVKITPRO/libnx/lib -lnx"

+

or setup a nim.cfg file like so:

+
#nim.cfg
+--mm:orc
+--d:nimAllocPagesViaMalloc
+--define:nimInheritHandles
+--passC="-I$DEVKITPRO/libnx/include"
+--passL="-specs=$DEVKITPRO/libnx/switch.specs -L$DEVKITPRO/libnx/lib -lnx"
+

The devkitPro setup must be the same as the default with their new installer here for Mac/Linux or here for Windows.

+

For example, with the above-mentioned config:

+

nim c --os:nintendoswitch switchhomebrew.nim

+

This will generate a file called switchhomebrew.elf which can then be turned into an nro file with the elf2nro tool in the devkitPro release. Examples can be found at the nim-libnx github repo.

+

There are a few things that don't work because the devkitPro libraries don't support them. They are:

+
  1. Waiting for a subprocess to finish. A subprocess can be started, but right now it can't be waited on, which sort of makes subprocesses a bit hard to use
  2. +
  3. Dynamic calls. Switch OS (Horizon) doesn't support dynamic libraries, so dlopen/dlclose are not available.
  4. +
  5. mqueue. Sadly there are no mqueue headers.
  6. +
  7. ucontext. No headers for these either. No coroutines for now :(
  8. +
  9. nl_types. No headers for this.
  10. +
  11. As mmap is not supported, the nimAllocPagesViaMalloc option has to be used.
  12. +
+ +

GPU Compilation

Compiling for GPU computation can be achieved with --cc:nvcc for CUDA with nvcc, or with --cc:hipcc for AMD GPUs with HIP. Both compilers require building for C++ with nim cpp.

+

Here's a very simple CUDA kernel example using emit, which can be compiled with nim cpp --cc:nvcc --define:"useMalloc" hello_kernel.nim assuming you have the CUDA toolkit installed.

+

{.emit: """
+__global__ void add(int a, int b) {
+  int c;
+  c = a + b;
+}
+""".}
+
+proc main() =
+  {.emit: """
+  add<<<1,1>>>(2,7);
+  """.}
+
+main()

+ +

DLL generation

Note: The same rules apply to lib*.so shared object files on UNIX. For better readability only the DLL version is described here.

+

Nim supports the generation of DLLs. However, there must be only one instance of the GC per process/address space. This instance is contained in nimrtl.dll. This means that every generated Nim DLL depends on nimrtl.dll. To generate the "nimrtl.dll" file, use the command:

+

nim c -d:release lib/nimrtl.nim

+

To link against nimrtl.dll use the command:

+

nim c -d:useNimRtl myprog.nim

+ +

Additional compilation switches

The standard library supports a growing number of useX conditional defines affecting how some features are implemented. This section tries to give a complete list.

+ + + + + + + + + + + + + + + + + + + + +
DefineEffect
releaseTurns on the optimizer. More aggressive optimizations are possible, e.g.: --passC:-ffast-math (but see issue #10305)
dangerTurns off all runtime checks and turns on the optimizer.
useForkMakes osproc use fork instead of posix_spawn.
useNimRtlCompile and link against nimrtl.dll.
useMallocMakes Nim use C's malloc instead of Nim's own memory manager, albeit prefixing each allocation with its size to support clearing memory on reallocation. This only works with --mm:none, --mm:arc and --mm:orc.
useRealtimeGCEnables support of Nim's GC for soft realtime systems. See the documentation of the refc for further information.
logGCEnable GC logging to stdout.
nodejsThe JS target is actually node.js.
sslEnables OpenSSL support for the sockets module.
memProfilerEnables memory profiling for the native GC.
uClibcUse uClibc instead of libc. (Relevant for Unix-like OSes)
checkAbiWhen using types from C headers, add checks that compare what's in the Nim file with what's in the C header. This may become enabled by default in the future.
tempDirThis symbol takes a string as its value, like --define:tempDir:/some/temp/path to override the temporary directory returned by os.getTempDir(). The value should end with a directory separator character. (Relevant for the Android platform)
useShPathThis symbol takes a string as its value, like --define:useShPath:/opt/sh/bin/sh to override the path for the sh binary, in cases where it is not located in the default location /bin/sh.
noSignalHandlerDisable the crash handler from system.nim.
globalSymbolsLoad all {.dynlib.} libraries with the RTLD_GLOBAL flag on Posix systems to resolve symbols in subsequently loaded libraries.
ltoEnable link-time optimization in the backend compiler and linker.
lto_incrementalEnable link-time optimization and additionally enable incremental linking for compilers that support it. Currently only clang and vcc.
stripStrip debug symbols added by the backend compiler from the executable.
+

Additional Features

This section describes Nim's additional features that are not listed in the Nim manual. Some of the features here only make sense for the C code generator and are subject to change.

+ +

LineDir option

The --lineDir option can be turned on or off. If turned on the generated C code contains #line directives. This may be helpful for debugging with GDB.

+ +

StackTrace option

If the --stackTrace option is turned on, the generated C contains code to ensure that proper stack traces are given if the program crashes or some uncaught exception is raised.

+ +

LineTrace option

The --lineTrace option implies the stackTrace option. If turned on, the generated C contains code to ensure that proper stack traces with line number information are given if the program crashes or an uncaught exception is raised.

+ +

DynlibOverride

By default Nim's dynlib pragma causes the compiler to generate GetProcAddress (or their Unix counterparts) calls to bind to a DLL. With the dynlibOverride command line switch this can be prevented and then via --passL the static library can be linked against. For instance, to link statically against Lua this command might work on Linux:

+

nim c --dynlibOverride:lua --passL:liblua.lib program.nim

+ +

Backend language options

The typical compiler usage involves using the compile or c command to transform a .nim file into one or more .c files which are then compiled with the platform's C compiler into a static binary. However, there are other commands to compile to C++, Objective-C, or JavaScript. More details can be read in the Nim Backend Integration document.

+ +

Nim documentation tools

Nim provides the doc command to generate HTML documentation from .nim source files. Only exported symbols will appear in the output. For more details see the docgen documentation.

+ +

Nim idetools integration

Nim provides language integration with external IDEs through the idetools command. See the documentation of idetools for further information.

+ +

Nim for embedded systems

While the default Nim configuration is targeted for optimal performance on modern PC hardware and operating systems with ample memory, it is very well possible to run Nim code and a good part of the Nim standard libraries on small embedded microprocessors with only a few kilobytes of memory.

+

A good start is to use the any operating target together with the malloc memory allocator and the arc garbage collector. For example:

+

nim c --os:any --mm:arc -d:useMalloc [...] x.nim

+
  • --mm:arc will enable the reference counting memory management instead of the default garbage collector. This enables Nim to use heap memory which is required for strings and seqs, for example.
  • +
  • The --os:any target makes sure Nim does not depend on any specific operating system primitives. Your platform should support only some basic ANSI C library stdlib and stdio functions which should be available on almost any platform.
  • +
  • The -d:useMalloc option configures Nim to use only the standard C memory manage primitives malloc(), free(), realloc().
  • +
+

If your platform does not provide these functions it should be trivial to provide an implementation for them and link these to your program.

+

For targets with very restricted memory, it might be beneficial to pass some additional flags to both the Nim compiler and the C compiler and/or linker to optimize the build for size. For example, the following flags can be used when targeting a gcc compiler:

+

--opt:size -d:lto -d:strip

+

The --opt:size flag instructs Nim to optimize code generation for small size (with the help of the C compiler), the -d:lto flags enable link-time optimization in the compiler and linker, the -d:strip strips debug symbols.

+

Check the Cross-compilation section for instructions on how to compile the program for your target.

+ +

nimAllocPagesViaMalloc

Nim's default allocator is based on TLSF, this algorithm was designed for embedded devices. This allocator gets blocks/pages of memory via a currently undocumented osalloc API which usually uses POSIX's mmap call. On many environments mmap is not available but C's malloc is. You can use the nimAllocPagesViaMalloc define to use malloc instead of mmap. nimAllocPagesViaMalloc is currently only supported with --mm:arc or --mm:orc. (Since version 1.6)

+ +

nimPage256 / nimPage512 / nimPage1k

Adjust the page size for Nim's GC allocator. This enables using nimAllocPagesViaMalloc on devices with less RAM. The default page size requires too much RAM to work.

+

Recommended settings:

+
  • < 32 kB of RAM use nimPage256
  • +
  • < 512 kB of RAM use nimPage512
  • +
  • < 2 MB of RAM use nimPage1k
  • +
+

Initial testing hasn't shown much difference between 512B or 1kB page sizes in terms of performance or latency. Using nimPages256 will limit the total amount of allocatable RAM.

+ +

nimMemAlignTiny

Sets MemAlign to 4 bytes which reduces the memory alignment to better match some embedded devices.

+ +

Thread stack size

Nim's thread API provides a simple wrapper around more advanced RTOS task features. Customizing the stack size and stack guard size can be done by setting -d:nimThreadStackSize=16384 or -d:nimThreadStackGuard=32.

+

Currently only Zephyr, NuttX and FreeRTOS support these configurations.

+ +

Nim for realtime systems

See the --mm:arc or --mm:orc memory management settings in MM for further information.

+ +

Signal handling in Nim

The Nim programming language has no concept of Posix's signal handling mechanisms. However, the standard library offers some rudimentary support for signal handling, in particular, segmentation faults are turned into fatal errors that produce a stack trace. This can be disabled with the -d:noSignalHandler switch.

+ +

Optimizing for Nim

Nim has no separate optimizer, but the C code that is produced is very efficient. Most C compilers have excellent optimizers, so usually it is not needed to optimize one's code. Nim has been designed to encourage efficient code: The most readable code in Nim is often the most efficient too.

+

However, sometimes one has to optimize. Do it in the following order:

+
  1. switch off the embedded debugger (it is slow!)
  2. +
  3. turn on the optimizer and turn off runtime checks
  4. +
  5. profile your code to find where the bottlenecks are
  6. +
  7. try to find a better algorithm
  8. +
  9. do low-level optimizations
  10. +
+

This section can only help you with the last item.

+ +

Optimizing string handling

String assignments are sometimes expensive in Nim: They are required to copy the whole string. However, the compiler is often smart enough to not copy strings. Due to the argument passing semantics, strings are never copied when passed to subroutines. The compiler does not copy strings that are a result of a procedure call, because the callee returns a new string anyway. Thus it is efficient to do:

+

var s = procA() # assignment will not copy the string; procA allocates a new
+                # string already

+

However, it is not efficient to do:

+

var s = varA    # assignment has to copy the whole string into a new buffer!

+

For let symbols a copy is not always necessary:

+

let s = varA    # may only copy a pointer if it safe to do so

+

The compiler optimizes string case statements: A hashing scheme is used for them if several different string constants are used. So code like this is reasonably efficient:

+

case normalize(k.key)
+of "name": c.name = v
+of "displayname": c.displayName = v
+of "version": c.version = v
+of "os": c.oses = split(v, {';'})
+of "cpu": c.cpus = split(v, {';'})
+of "authors": c.authors = split(v, {';'})
+of "description": c.description = v
+of "app":
+  case normalize(v)
+  of "console": c.app = appConsole
+  of "gui": c.app = appGUI
+  else: quit(errorStr(p, "expected: console or gui"))
+of "license": c.license = UnixToNativePath(k.value)
+else: quit(errorStr(p, "unknown variable: " & k.key))

+

+ +
+
+ + +
+
+ + + + diff --git a/nimc.idx b/nimc.idx new file mode 100644 index 0000000000000..99b8601db95c0 --- /dev/null +++ b/nimc.idx @@ -0,0 +1,42 @@ +markupTitle Nim Compiler User Guide nimc.html Nim Compiler User Guide 0 +heading Introduction nimc.html#introduction Introduction 0 +heading Compiler Usage nimc.html#compiler-usage Compiler Usage 0 +heading Command-line switches nimc.html#compiler-usage-commandminusline-switches Command-line switches 0 +heading List of warnings nimc.html#compiler-usage-list-of-warnings List of warnings 0 +heading List of hints nimc.html#compiler-usage-list-of-hints List of hints 0 +heading Verbosity levels nimc.html#compiler-usage-verbosity-levels Verbosity levels 0 +heading Compile-time symbols nimc.html#compiler-usage-compileminustime-symbols Compile-time symbols 0 +heading Configuration files nimc.html#compiler-usage-configuration-files Configuration files 0 +idx debug build nimc.html#debug-build_1 Configuration files 0 +idx release build nimc.html#release-build_1 Configuration files 0 +idx dangerous release build nimc.html#dangerous-release-build_1 Configuration files 0 +heading Search path handling nimc.html#compiler-usage-search-path-handling Search path handling 0 +heading Generated C code directory nimc.html#compiler-usage-generated-c-code-directory Generated C code directory 0 +heading Compiler Selection nimc.html#compiler-selection Compiler Selection 0 +heading Cross-compilation nimc.html#crossminuscompilation Cross-compilation 0 +heading Cross-compilation for Windows nimc.html#crossminuscompilation-for-windows Cross-compilation for Windows 0 +heading Cross-compilation for Android nimc.html#crossminuscompilation-for-android Cross-compilation for Android 0 +heading Cross-compilation for iOS nimc.html#crossminuscompilation-for-ios Cross-compilation for iOS 0 +heading Cross-compilation for Nintendo Switch nimc.html#crossminuscompilation-for-nintendo-switch Cross-compilation for Nintendo Switch 0 +heading GPU Compilation nimc.html#gpu-compilation GPU Compilation 0 +heading DLL generation nimc.html#dll-generation DLL generation 0 +heading Additional compilation switches nimc.html#additional-compilation-switches Additional compilation switches 0 +idx malloc nimc.html#malloc_1 Additional compilation switches 0 +heading Additional Features nimc.html#additional-features Additional Features 0 +heading LineDir option nimc.html#additional-features-linedir-option LineDir option 0 +heading StackTrace option nimc.html#additional-features-stacktrace-option StackTrace option 0 +heading LineTrace option nimc.html#additional-features-linetrace-option LineTrace option 0 +heading DynlibOverride nimc.html#dynliboverride DynlibOverride 0 +heading Backend language options nimc.html#backend-language-options Backend language options 0 +heading Nim documentation tools nimc.html#nim-documentation-tools Nim documentation tools 0 +idx doc nimc.html#doc_1 Nim documentation tools 0 +heading Nim idetools integration nimc.html#nim-idetools-integration Nim idetools integration 0 +heading Nim for embedded systems nimc.html#nim-for-embedded-systems Nim for embedded systems 0 +heading nimAllocPagesViaMalloc nimc.html#nim-for-embedded-systems-nimallocpagesviamalloc nimAllocPagesViaMalloc 0 +heading nimPage256 / nimPage512 / nimPage1k nimc.html#nimpage256-slash-nimpage512-slash-nimpage1k nimPage256 / nimPage512 / nimPage1k 0 +heading nimMemAlignTiny nimc.html#nimmemaligntiny nimMemAlignTiny 0 +heading Thread stack size nimc.html#thread-stack-size Thread stack size 0 +heading Nim for realtime systems nimc.html#nim-for-realtime-systems Nim for realtime systems 0 +heading Signal handling in Nim nimc.html#signal-handling-in-nim Signal handling in Nim 0 +heading Optimizing for Nim nimc.html#optimizing-for-nim Optimizing for Nim 0 +heading Optimizing string handling nimc.html#optimizing-for-nim-optimizing-string-handling Optimizing string handling 0 diff --git a/nimcache/runnableExamples/asyncjs_examples_1.nim b/nimcache/runnableExamples/asyncjs_examples_1.nim new file mode 100644 index 0000000000000..eab66993f9d57 --- /dev/null +++ b/nimcache/runnableExamples/asyncjs_examples_1.nim @@ -0,0 +1,36 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/asyncjs.nim(205, 21) +rdoccmd: -r:off +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/asyncjs.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/asyncjs.nim", 205, 21).}: + from std/sugar import `=>` + + proc fn(n: int): Future[int] {.async.} = + if n >= 7: raise newException(ValueError, "foobar: " & $n) + else: result = n * 2 + + proc asyncFact(n: int): Future[int] {.async.} = + if n > 0: result = n * await asyncFact(n-1) + else: result = 1 + + proc main() {.async.} = + block: # then + assert asyncFact(3).await == 3*2 + assert asyncFact(3).then(asyncFact).await == 6*5*4*3*2 + let x1 = await fn(3) + assert x1 == 3 * 2 + let x2 = await fn(4) + .then((a: int) => a.float) + .then((a: float) => $a) + assert x2 == "8.0" + + block: # then with `onReject` callback + var witness = 1 + await fn(6).then((a: int) => (witness = 2), (r: Error) => (witness = 3)) + assert witness == 2 + await fn(7).then((a: int) => (witness = 2), (r: Error) => (witness = 3)) + assert witness == 3 + diff --git a/nimcache/runnableExamples/asyncjs_examples_2.nim b/nimcache/runnableExamples/asyncjs_examples_2.nim new file mode 100644 index 0000000000000..94fdf01670250 --- /dev/null +++ b/nimcache/runnableExamples/asyncjs_examples_2.nim @@ -0,0 +1,25 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/asyncjs.nim(251, 21) +rdoccmd: -r:off +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/asyncjs.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/asyncjs.nim", 251, 21).}: + from std/sugar import `=>` + from std/strutils import contains + + proc fn(n: int): Future[int] {.async.} = + if n >= 7: raise newException(ValueError, "foobar: " & $n) + else: result = n * 2 + + proc main() {.async.} = + var reason: Error + await fn(6).catch((r: Error) => (reason = r)) # note: `()` are needed, `=> reason = r` would not work + assert reason == nil + await fn(7).catch((r: Error) => (reason = r)) + assert reason != nil + assert "foobar: 7" in $reason.message + + discard main() + diff --git a/nimcache/runnableExamples/asyncjs_group0_examples.js b/nimcache/runnableExamples/asyncjs_group0_examples.js new file mode 100644 index 0000000000000..e12b3741bae40 --- /dev/null +++ b/nimcache/runnableExamples/asyncjs_group0_examples.js @@ -0,0 +1,1221 @@ +/* Generated by the Nim Compiler v2.2.1 */ +var framePtr = null; +var excHandler = 0; +var lastJSError = null; +var NTI134217745 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555173 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217746 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217749 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217751 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554435 = {size: 0,kind: 31,base: null,node: null,finalizer: null}; +var NTI33555836 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI33555175 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554449 = {size: 0,kind: 28,base: null,node: null,finalizer: null}; +var NTI33555174 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33555171 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555172 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217741 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217743 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555167 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555177 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554450 = {size: 0,kind: 29,base: null,node: null,finalizer: null}; +var NTI671088769 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI671088768 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI973078612 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NNI671088769 = {kind: 2, len: 2, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "message", len: 0, typ: NTI33554450, name: "message", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}]}; +NTI671088769.node = NNI671088769; +var NNI33555177 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555177.node = NNI33555177; +var NNI33555167 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555167.node = NNI33555167; +NTI33555177.base = NTI33555167; +NTI671088769.base = NTI33555177; +NTI671088768.base = NTI671088769; +var NNI973078612 = {kind: 1, offset: "reason0", len: 0, typ: NTI671088768, name: "reason0", sons: null}; +NTI973078612.node = NNI973078612; +NTI973078612.base = NTI33555167; +var NNI134217743 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217743.node = NNI134217743; +var NNI134217741 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217741.node = NNI134217741; +var NNI33555172 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555172.node = NNI33555172; +NTI33555174.base = NTI33555171; +NTI33555175.base = NTI33555171; +var NNI33555171 = {kind: 2, len: 5, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "parent", len: 0, typ: NTI33555174, name: "parent", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}, +{kind: 1, offset: "message", len: 0, typ: NTI33554449, name: "msg", sons: null}, +{kind: 1, offset: "trace", len: 0, typ: NTI33554449, name: "trace", sons: null}, +{kind: 1, offset: "up", len: 0, typ: NTI33555175, name: "up", sons: null}]}; +NTI33555171.node = NNI33555171; +NTI33555171.base = NTI33555167; +NTI33555172.base = NTI33555171; +NTI134217741.base = NTI33555172; +NTI134217743.base = NTI134217741; +var NNI33555836 = {kind: 2, len: 3, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "Field0", len: 0, typ: NTI33554450, name: "Field0", sons: null}, +{kind: 1, offset: "Field1", len: 0, typ: NTI33554435, name: "Field1", sons: null}, +{kind: 1, offset: "Field2", len: 0, typ: NTI33554450, name: "Field2", sons: null}]}; +NTI33555836.node = NNI33555836; +var NNI134217751 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217751.node = NNI134217751; +NTI134217751.base = NTI33555172; +var NNI134217749 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217749.node = NNI134217749; +NTI134217749.base = NTI33555172; +var NNI134217746 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217746.node = NNI134217746; +var NNI33555173 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555173.node = NNI33555173; +NTI33555173.base = NTI33555171; +NTI134217746.base = NTI33555173; +var NNI134217745 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217745.node = NNI134217745; +NTI134217745.base = NTI33555172; + +function mnewString(len_p0) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; i++) {result[i] = 0;} + return result; + + + +} + +function arrayConstr(len_p0, value_p1, typ_p2) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; ++i) result[i] = nimCopy(null, value_p1, typ_p2); + return result; + + + +} + +function setConstr() { + var result = {}; + for (var i = 0; i < arguments.length; ++i) { + var x = arguments[i]; + if (typeof(x) == "object") { + for (var j = x[0]; j <= x[1]; ++j) { + result[j] = true; + } + } else { + result[x] = true; + } + } + return result; + + + +} +var ConstSet1 = setConstr(17, 16, 4, 18, 27, 19, 23, 22, 21); + +function nimCopy(dest_p0, src_p1, ti_p2) { + var result_33557321 = null; + + switch (ti_p2.kind) { + case 21: + case 22: + case 23: + case 5: + if (!(isFatPointer__system_u2869(ti_p2))) { + result_33557321 = src_p1; + } + else { + result_33557321 = [src_p1[0], src_p1[1]]; + } + + break; + case 19: + if (dest_p0 === null || dest_p0 === undefined) { + dest_p0 = {}; + } + else { + for (var key in dest_p0) { delete dest_p0[key]; } + } + for (var key in src_p1) { dest_p0[key] = src_p1[key]; } + result_33557321 = dest_p0; + + break; + case 18: + case 17: + if (!((ti_p2.base == null))) { + result_33557321 = nimCopy(dest_p0, src_p1, ti_p2.base); + } + else { + if ((ti_p2.kind == 17)) { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {m_type: ti_p2} : dest_p0; + } + else { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {} : dest_p0; + } + } + nimCopyAux(result_33557321, src_p1, ti_p2.node); + break; + case 4: + case 16: + if(ArrayBuffer.isView(src_p1)) { + if(dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new src_p1.constructor(src_p1); + } else { + dest_p0.set(src_p1, 0); + } + result_33557321 = dest_p0; + } else { + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + } + + break; + case 24: + case 27: + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + + break; + case 28: + if (src_p1 !== null) { + result_33557321 = src_p1.slice(0); + } + + break; + default: + result_33557321 = src_p1; + break; + } + + return result_33557321; + +} + +function cstrToNimstr(c_p0) { + var ln = c_p0.length; + var result = new Array(ln); + var r = 0; + for (var i = 0; i < ln; ++i) { + var ch = c_p0.charCodeAt(i); + + if (ch < 128) { + result[r] = ch; + } + else { + if (ch < 2048) { + result[r] = (ch >> 6) | 192; + } + else { + if (ch < 55296 || ch >= 57344) { + result[r] = (ch >> 12) | 224; + } + else { + ++i; + ch = 65536 + (((ch & 1023) << 10) | (c_p0.charCodeAt(i) & 1023)); + result[r] = (ch >> 18) | 240; + ++r; + result[r] = ((ch >> 12) & 63) | 128; + } + ++r; + result[r] = ((ch >> 6) & 63) | 128; + } + ++r; + result[r] = (ch & 63) | 128; + } + ++r; + } + return result; + + + +} + +function toJSStr(s_p0) { + var result_33556910 = null; + + var res_33556964 = newSeq__system_u2507((s_p0).length); + var i_33556965 = 0; + var j_33556966 = 0; + Label1: { + Label2: while (true) { + if (!(i_33556965 < (s_p0).length)) break Label2; + var c_33556967 = s_p0[i_33556965]; + if ((c_33556967 < 128)) { + res_33556964[j_33556966] = String.fromCharCode(c_33556967); + i_33556965 += 1; + } + else { + var helper_33556993 = newSeq__system_u2507(0); + Label3: { + Label4: while (true) { + if (!true) break Label4; + var code_33556994 = c_33556967.toString(16); + if ((((code_33556994) == null ? 0 : (code_33556994).length) == 1)) { + helper_33556993.push("%0");; + } + else { + helper_33556993.push("%");; + } + + helper_33556993.push(code_33556994);; + i_33556965 += 1; + if ((((s_p0).length <= i_33556965) || (s_p0[i_33556965] < 128))) { + break Label3; + } + + c_33556967 = s_p0[i_33556965]; + } + }; +++excHandler; + try { + res_33556964[j_33556966] = decodeURIComponent(helper_33556993.join("")); +--excHandler; +} catch (EXCEPTION) { + var prevJSError = lastJSError; + lastJSError = EXCEPTION; + --excHandler; + res_33556964[j_33556966] = helper_33556993.join(""); + lastJSError = prevJSError; + } finally { + } + } + + j_33556966 += 1; + } + }; + if (res_33556964.length < j_33556966) { for (var i = res_33556964.length ; i < j_33556966 ; ++i) res_33556964.push(null); } + else { res_33556964.length = j_33556966; }; + result_33556910 = res_33556964.join(""); + + return result_33556910; + +} + +function raiseException(e_p0, ename_p1) { + e_p0.name = ename_p1; + if ((excHandler == 0)) { + unhandledException(e_p0); + } + + e_p0.trace = nimCopy(null, rawWriteStackTrace__system_u2180(), NTI33554449); + throw e_p0; + + +} + +function addInt(a_p0, b_p1) { + var result = a_p0 + b_p1; + checkOverflowInt(result); + return result; + + + +} + +function chckRange(i_p0, a_p1, b_p2) { + var result_33557361 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557361 = i_p0; + break BeforeRet; + } + else { + raiseRangeError(); + } + + }; + + return result_33557361; + +} + +function chckIndx(i_p0, a_p1, b_p2) { + var result_33557356 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557356 = i_p0; + break BeforeRet; + } + else { + raiseIndexError(i_p0, a_p1, b_p2); + } + + }; + + return result_33557356; + +} + +function mulInt(a_p0, b_p1) { + var result = a_p0 * b_p1; + checkOverflowInt(result); + return result; + + + +} + +function makeNimstrLit(c_p0) { + var result = []; + for (var i = 0; i < c_p0.length; ++i) { + result[i] = c_p0.charCodeAt(i); + } + return result; + + + +} + +function subInt(a_p0, b_p1) { + var result = a_p0 - b_p1; + checkOverflowInt(result); + return result; + + + +} +var F = {procname: "module macros", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/core/macros.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module macros", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/core/macros.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module hashes", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/hashes.nim", line: 0}; +framePtr = F; +F.line = 218; +F.filename = "hashes.nim"; +var objectID_738197682 = [0]; +framePtr = F.prev; +var F = {procname: "module hashes", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/hashes.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops_utils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/bitops_utils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops_utils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/bitops_utils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module countbits_impl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/countbits_impl.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module countbits_impl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/countbits_impl.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/bitops.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/bitops.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module fenv", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/fenv.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module fenv", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/fenv.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module math", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/math.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module math", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/math.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module algorithm", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/algorithm.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module algorithm", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/algorithm.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module outparams", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/outparams.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module outparams", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/outparams.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module tables", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/collections/tables.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module tables", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/collections/tables.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsffi", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsffi.nim", line: 0}; +framePtr = F; +F.line = 45; +F.filename = "jsffi.nim"; +F.line = 46; +framePtr = F.prev; +var F = {procname: "module jsffi", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsffi.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module asyncjs", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/asyncjs.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module asyncjs", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/asyncjs.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module underscored_calls", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/underscored_calls.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module underscored_calls", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/underscored_calls.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module sugar", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/sugar.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module sugar", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/sugar.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module asyncjs_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/asyncjs_examples_1.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module asyncjs_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/asyncjs_examples_1.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module parseutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/parseutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module parseutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/parseutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module typetraits", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/typetraits.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module typetraits", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/typetraits.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module enumutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/enumutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module enumutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/enumutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module strbasics", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/strbasics.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module strbasics", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/strbasics.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module unicode", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/unicode.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module unicode", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/unicode.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module strimpl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/strimpl.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module strimpl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/strimpl.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module strutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/strutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module strutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/strutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function catch__asyncjs95examples952_u55(future_p0, onReject_p1) { + var result_973078587 = null; + + var F = {procname: "catch.catch", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/asyncjs.nim", line: 0}; + framePtr = F; + F.line = 269; + F.filename = "asyncjs.nim"; + result_973078587 = future_p0.catch(onReject_p1); + framePtr = F.prev; + + return result_973078587; + +} + +function add__system_u1942(x_p0, x_p0_Idx, y_p1) { + if (x_p0[x_p0_Idx] === null) { x_p0[x_p0_Idx] = []; } + var off = x_p0[x_p0_Idx].length; + x_p0[x_p0_Idx].length += y_p1.length; + for (var i = 0; i < y_p1.length; ++i) { + x_p0[x_p0_Idx][off+i] = y_p1.charCodeAt(i); + } + + + +} + +function isFatPointer__system_u2869(ti_p0) { + var result_33557303 = false; + + BeforeRet: { + result_33557303 = !((ConstSet1[ti_p0.base.kind] != undefined)); + break BeforeRet; + }; + + return result_33557303; + +} + +function nimCopyAux(dest_p0, src_p1, n_p2) { + switch (n_p2.kind) { + case 0: + break; + case 1: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + + break; + case 2: + for (var i = 0; i < n_p2.sons.length; i++) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i]); + } + + break; + case 3: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + for (var i = 0; i < n_p2.sons.length; ++i) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i][1]); + } + + break; + } + + +} + +function auxWriteStackTrace__system_u2084(f_p0) { + var result_33556518 = [[]]; + + var it_33556526 = f_p0; + var i_33556527 = 0; + var total_33556528 = 0; + var tempFrames_33556529 = arrayConstr(64, {Field0: null, Field1: 0, Field2: null}, NTI33555836); + Label1: { + Label2: while (true) { + if (!(!((it_33556526 == null)) && (i_33556527 <= 63))) break Label2; + tempFrames_33556529[i_33556527].Field0 = it_33556526.procname; + tempFrames_33556529[i_33556527].Field1 = it_33556526.line; + tempFrames_33556529[i_33556527].Field2 = it_33556526.filename; + i_33556527 += 1; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + Label3: { + Label4: while (true) { + if (!!((it_33556526 == null))) break Label4; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + result_33556518[0] = nimCopy(null, [], NTI33554449); + if (!((total_33556528 == i_33556527))) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + result_33556518[0].push.apply(result_33556518[0], HEX24__systemZdollars_u8((total_33556528 - i_33556527)));; + result_33556518[0].push.apply(result_33556518[0], [32,99,97,108,108,115,32,111,109,105,116,116,101,100,41,32,46,46,46,10]);; + } + + Label5: { + var j_33556562 = 0; + var colontmp__973078688 = 0; + colontmp__973078688 = (i_33556527 - 1); + var res_973078690 = colontmp__973078688; + Label6: { + Label7: while (true) { + if (!(0 <= res_973078690)) break Label7; + j_33556562 = res_973078690; + result_33556518[0].push.apply(result_33556518[0], cstrToNimstr(tempFrames_33556529[j_33556562].Field2));; + if ((0 < tempFrames_33556529[j_33556562].Field1)) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, tempFrames_33556529[j_33556562].Field1); + if (false) { + result_33556518[0].push.apply(result_33556518[0], [44,32]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, 0); + } + + result_33556518[0].push.apply(result_33556518[0], [41]);; + } + + result_33556518[0].push.apply(result_33556518[0], [32,97,116,32]);; + add__system_u1942(result_33556518, 0, tempFrames_33556529[j_33556562].Field0); + result_33556518[0].push.apply(result_33556518[0], [10]);; + res_973078690 -= 1; + } + }; + }; + + return result_33556518[0]; + +} + +function rawWriteStackTrace__system_u2180() { + var result_33556613 = []; + + if (!((framePtr == null))) { + result_33556613 = nimCopy(null, ([84,114,97,99,101,98,97,99,107,32,40,109,111,115,116,32,114,101,99,101,110,116,32,99,97,108,108,32,108,97,115,116,41,10]).concat(auxWriteStackTrace__system_u2084(framePtr)), NTI33554449); + } + else { + result_33556613 = nimCopy(null, [78,111,32,115,116,97,99,107,32,116,114,97,99,101,98,97,99,107,32,97,118,97,105,108,97,98,108,101,10], NTI33554449); + } + + + return result_33556613; + +} + +function newSeq__system_u2507(len_p0) { + var result_33556943 = []; + + var F = {procname: "newSeq.newSeq", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system.nim", line: 0}; + framePtr = F; + F.line = 653; + F.filename = "system.nim"; + result_33556943 = new Array(len_p0); for (var i = 0 ; i < len_p0 ; ++i) { result_33556943[i] = null; } framePtr = F.prev; + + return result_33556943; + +} + +function unhandledException(e_p0) { + var buf_33556658 = [[]]; + if (!(((e_p0.message).length == 0))) { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32]);; + buf_33556658[0].push.apply(buf_33556658[0], e_p0.message);; + } + else { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110]);; + } + + buf_33556658[0].push.apply(buf_33556658[0], [32,91]);; + add__system_u1942(buf_33556658, 0, e_p0.name); + buf_33556658[0].push.apply(buf_33556658[0], [93,10]);; + buf_33556658[0].push.apply(buf_33556658[0], rawWriteStackTrace__system_u2180());; + var cbuf_33556659 = toJSStr(buf_33556658[0]); + framePtr = null; + if (typeof(Error) !== "undefined") { + throw new Error(cbuf_33556659); + } + else { + throw cbuf_33556659; + } + + + +} + +function raiseOverflow() { + raiseException({message: [111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119], parent: null, m_type: NTI134217743, name: null, trace: [], up: null}, "OverflowDefect"); + + +} + +function checkOverflowInt(a_p0) { + if (a_p0 > 2147483647 || a_p0 < -2147483648) raiseOverflow(); + + + +} + +function raiseRangeError() { + raiseException({message: [118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101], parent: null, m_type: NTI134217751, name: null, trace: [], up: null}, "RangeDefect"); + + +} + +function raiseIndexError(i_p0, a_p1, b_p2) { + var Temporary1; + + if ((b_p2 < a_p1)) { + Temporary1 = [105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]; + } + else { + Temporary1 = ([105,110,100,101,120,32]).concat(HEX24__systemZdollars_u8(i_p0),[32,110,111,116,32,105,110,32],HEX24__systemZdollars_u8(a_p1),[32,46,46,32],HEX24__systemZdollars_u8(b_p2)); + } + + raiseException({message: nimCopy(null, Temporary1, NTI33554449), parent: null, m_type: NTI134217749, name: null, trace: [], up: null}, "IndexDefect"); + + +} + +function addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, start_p2, n_p3) { + var Temporary1; + + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 44; + F.filename = "digitsutils.nim"; + var old_301990096 = (result_p0[result_p0_Idx]).length; + F.line = 45; + if (result_p0[result_p0_Idx].length < (Temporary1 = chckRange(addInt(old_301990096, n_p3), 0, 2147483647), Temporary1)) { for (var i = result_p0[result_p0_Idx].length; i < Temporary1; ++i) result_p0[result_p0_Idx].push(0); } + else {result_p0[result_p0_Idx].length = Temporary1; }; + Label2: { + F.line = 47; + var iHEX60gensym4_301990110 = 0; + F.line = 128; + F.filename = "iterators_1.nim"; + var i_973078683 = 0; + Label3: { + F.line = 129; + Label4: while (true) { + if (!(i_973078683 < n_p3)) break Label4; + F.line = 50; + F.filename = "digitsutils.nim"; + iHEX60gensym4_301990110 = i_973078683; + F.line = 47; + result_p0[result_p0_Idx][chckIndx(addInt(old_301990096, iHEX60gensym4_301990110), 0, (result_p0[result_p0_Idx]).length - 1)] = x_p1.charCodeAt(chckIndx(addInt(start_p2, iHEX60gensym4_301990110), 0, (x_p1).length - 1)); + F.line = 131; + F.filename = "iterators_1.nim"; + i_973078683 = addInt(i_973078683, 1); + } + }; + }; + framePtr = F.prev; + + +} + +function addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 56; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, 0, ((x_p1) == null ? 0 : (x_p1).length)); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 112; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, ((x_p1) + "")); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u241(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 116; + F.filename = "digitsutils.nim"; + addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, BigInt(x_p1)); + framePtr = F.prev; + + +} + +function HEX24__systemZdollars_u8(x_p0) { + var result_369098762 = [[]]; + + var F = {procname: "dollars.$", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/dollars.nim", line: 0}; + framePtr = F; + F.line = 18; + F.filename = "dollars.nim"; + addInt__stdZprivateZdigitsutils_u241(result_369098762, 0, x_p0); + framePtr = F.prev; + + return result_369098762[0]; + +} +async function fn__asyncjs95examples952_u8(n_p0) { + var result_973078539 = null; + + var F = {procname: "asyncjs_examples_2.fn", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/asyncjs_examples_2.nim", line: 0}; + framePtr = F; + if ((7 <= n_p0)) { + F.line = 251; + F.filename = "asyncjs.nim"; + raiseException({message: ([102,111,111,98,97,114,58,32]).concat(HEX24__systemZdollars_u8(n_p0)), parent: null, m_type: NTI134217746, name: null, trace: [], up: null}, "ValueError"); + } + else { + F.line = 251; + result_973078539 = mulInt(n_p0, 2); + } + + framePtr = F.prev; + + return result_973078539; + +} + +function HEX3Aanonymous__asyncjs95examples952_u36(r_p0) { + var F = {procname: "main.:anonymous", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/asyncjs_examples_2.nim", line: 0}; + framePtr = F; + F.line = 251; + F.filename = "asyncjs.nim"; + this.reason0 = r_p0; + framePtr = F.prev; + + +} + +function sysFatal__stdZassertions_u44(message_p1) { + var F = {procname: "sysFatal.sysFatal", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/fatal.nim", line: 0}; + framePtr = F; + F.line = 53; + F.filename = "fatal.nim"; + raiseException({message: nimCopy(null, message_p1, NTI33554449), m_type: NTI134217745, parent: null, name: null, trace: [], up: null}, "AssertionDefect"); + framePtr = F.prev; + + +} + +function raiseAssert__stdZassertions_u42(msg_p0) { + var F = {procname: "assertions.raiseAssert", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 36; + F.filename = "assertions.nim"; + sysFatal__stdZassertions_u44(msg_p0); + framePtr = F.prev; + + +} + +function failedAssertImpl__stdZassertions_u84(msg_p0) { + var F = {procname: "assertions.failedAssertImpl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 41; + F.filename = "assertions.nim"; + raiseAssert__stdZassertions_u42(msg_p0); + framePtr = F.prev; + + +} + +function HEX3Aanonymous__asyncjs95examples952_u74(r_p0) { + var F = {procname: "main.:anonymous", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/asyncjs_examples_2.nim", line: 0}; + framePtr = F; + F.line = 251; + F.filename = "asyncjs.nim"; + this.reason0 = r_p0; + framePtr = F.prev; + + +} + +function nsuFindChar(s_p0, sub_p1, start_p2, last_p3) { + var Temporary1; + + var result_989857446 = 0; + + var F = {procname: "strutils.find", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/strutils.nim", line: 0}; + framePtr = F; + BeforeRet: { + F.line = 1968; + F.filename = "strutils.nim"; + result_989857446 = (-1); + F.line = 1969; + if ((last_p3 < 0)) { + Temporary1 = (s_p0).length - 1; + } + else { + Temporary1 = last_p3; + } + + var last_989857447 = Temporary1; + Label2: { + F.line = 1972; + var iHEX60gensym174_989857461 = 0; + F.line = 81; + F.filename = "iterators_1.nim"; + var colontmp__973078699 = 0; + F.line = 1972; + F.filename = "strutils.nim"; + colontmp__973078699 = start_p2; + F.line = 96; + F.filename = "iterators_1.nim"; + var res_973078700 = colontmp__973078699; + Label3: { + F.line = 97; + Label4: while (true) { + if (!(res_973078700 <= last_989857447)) break Label4; + F.line = 1986; + F.filename = "strutils.nim"; + iHEX60gensym174_989857461 = res_973078700; + if ((s_p0[chckIndx(iHEX60gensym174_989857461, 0, (s_p0).length - 1)] == sub_p1)) { + F.line = 1974; + result_989857446 = iHEX60gensym174_989857461; + break BeforeRet; + } + + F.line = 102; + F.filename = "iterators_1.nim"; + res_973078700 = addInt(res_973078700, 1); + } + }; + }; + }; + framePtr = F.prev; + + return result_989857446; + +} + +function nsuFindStrA(a_p0, s_p1, sub_p2, start_p3, last_p4) { + var Temporary1; + + var result_989857425 = 0; + + var F = {procname: "strutils.find", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/strutils.nim", line: 0}; + framePtr = F; + BeforeRet: { + F.line = 1928; + F.filename = "strutils.nim"; + if ((last_p4 < 0)) { + Temporary1 = (s_p1).length - 1; + } + else { + Temporary1 = last_p4; + } + + var last_989857426 = Temporary1; + F.line = 1929; + var subLast_989857427 = subInt((sub_p2).length, 1); + if ((subLast_989857427 == (-1))) { + F.line = 1934; + result_989857425 = start_p3; + break BeforeRet; + } + + F.line = 1938; + result_989857425 = (-1); + F.line = 1939; + var skip_989857428 = start_p3; + Label2: { + F.line = 1941; + Label3: while (true) { + if (!(subLast_989857427 <= subInt(last_989857426, skip_989857428))) break Label3; + F.line = 1942; + var i_989857429 = subLast_989857427; + Label4: { + F.line = 1943; + Label5: while (true) { + if (!(s_p1[chckIndx(addInt(skip_989857428, i_989857429), 0, (s_p1).length - 1)] == sub_p2[chckIndx(i_989857429, 0, (sub_p2).length - 1)])) break Label5; + if ((i_989857429 == 0)) { + F.line = 1945; + result_989857425 = skip_989857428; + break BeforeRet; + } + + F.line = 1946; + i_989857429 = subInt(i_989857429, 1); + } + }; + F.line = 1947; + skip_989857428 = addInt(skip_989857428, a_p0[chckIndx(s_p1[chckIndx(addInt(skip_989857428, subLast_989857427), 0, (s_p1).length - 1)], 0, (a_p0).length - 1)]); + } + }; + }; + framePtr = F.prev; + + return result_989857425; + +} + +function fill__pureZstrutils_u1621(a_p0, value_p1) { + var F = {procname: "fill.fill", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/algorithm.nim", line: 0}; + framePtr = F; + F.line = 72; + F.filename = "algorithm.nim"; + var xHEX60gensym170_989857374 = 0; + Label1: { + F.line = 98; + Label2: while (true) { + if (!(xHEX60gensym170_989857374 <= (a_p0).length - 1)) break Label2; + F.line = 98; + a_p0[chckIndx(xHEX60gensym170_989857374, 0, (a_p0).length - 1)] = value_p1; + F.line = 75; + xHEX60gensym170_989857374 = addInt(xHEX60gensym170_989857374, 1); + } + }; + framePtr = F.prev; + + +} + +function nsuInitSkipTable(a_p0, sub_p1) { + var F = {procname: "strutils.initSkipTable", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/strutils.nim", line: 0}; + framePtr = F; + F.line = 1901; + F.filename = "strutils.nim"; + var m_989857364 = (sub_p1).length; + F.line = 1902; + fill__pureZstrutils_u1621(a_p0, m_989857364); + Label1: { + F.line = 1904; + var i_989857384 = 0; + F.line = 126; + F.filename = "iterators_1.nim"; + var colontmp__973078705 = 0; + F.line = 1904; + F.filename = "strutils.nim"; + colontmp__973078705 = subInt(m_989857364, 1); + F.line = 128; + F.filename = "iterators_1.nim"; + var i_973078706 = 0; + Label2: { + F.line = 129; + Label3: while (true) { + if (!(i_973078706 < colontmp__973078705)) break Label3; + F.line = 1904; + F.filename = "strutils.nim"; + i_989857384 = i_973078706; + F.line = 1905; + a_p0[chckIndx(sub_p1[chckIndx(i_989857384, 0, (sub_p1).length - 1)], 0, (a_p0).length - 1)] = subInt(subInt(m_989857364, 1), i_989857384); + F.line = 131; + F.filename = "iterators_1.nim"; + i_973078706 = addInt(i_973078706, 1); + } + }; + }; + framePtr = F.prev; + + +} + +function nsuInitNewSkipTable(sub_p0) { + var result_989857418 = [new Int32Array(256)]; + + var F = {procname: "strutils.initSkipTable", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/strutils.nim", line: 0}; + framePtr = F; + F.line = 1914; + F.filename = "strutils.nim"; + nsuInitSkipTable(result_989857418[0], sub_p0); + framePtr = F.prev; + + return result_989857418[0]; + +} + +function nsuFindStr(s_p0, sub_p1, start_p2, last_p3) { + var result_989857483 = 0; + + var F = {procname: "strutils.find", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/strutils.nim", line: 0}; + framePtr = F; + BeforeRet: { + if ((subInt((s_p0).length, start_p2) < (sub_p1).length)) { + F.line = 2026; + F.filename = "strutils.nim"; + result_989857483 = (-1); + break BeforeRet; + } + + if (((sub_p1).length == 1)) { + F.line = 2027; + result_989857483 = nsuFindChar(s_p0, sub_p1[chckIndx(0, 0, (sub_p1).length - 1)], start_p2, last_p3); + break BeforeRet; + } + + F.line = 2030; + result_989857483 = nsuFindStrA(nsuInitNewSkipTable(sub_p1), s_p0, sub_p1, start_p2, last_p3); + }; + framePtr = F.prev; + + return result_989857483; + +} + +function contains__pureZstrutils_u1877(s_p0, sub_p1) { + var result_989857624 = false; + + var F = {procname: "strutils.contains", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/strutils.nim", line: 0}; + framePtr = F; + BeforeRet: { + F.line = 2184; + F.filename = "strutils.nim"; + result_989857624 = (0 <= nsuFindStr(s_p0, sub_p1, 0, (-1))); + break BeforeRet; + }; + framePtr = F.prev; + + return result_989857624; + +} +async function main__asyncjs95examples952_u26() { + var Temporary1; + var Temporary2; + + var result_973078556 = null; + + var F = {procname: "asyncjs_examples_2.main", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/asyncjs_examples_2.nim", line: 0}; + framePtr = F; + BeforeRet: { + F.line = 251; + F.filename = "asyncjs.nim"; + var HEX3Aenv_973078631 = null; + F.line = 251; + HEX3Aenv_973078631 = {m_type: NTI973078612, reason0: null}; + HEX3Aenv_973078631.reason0 = null; + F.line = 251; + Temporary1 = HEX3Aanonymous__asyncjs95examples952_u36.bind(HEX3Aenv_973078631); Temporary1.ClP_0 = HEX3Aanonymous__asyncjs95examples952_u36; Temporary1.ClE_0 = HEX3Aenv_973078631; + (await catch__asyncjs95examples952_u55(fn__asyncjs95examples952_u8(6), Temporary1)); + if (!((HEX3Aenv_973078631.reason0 == null))) { + F.line = 251; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/asyncjs_examples_2.nim(19, 5) `reason == nil` ")); + } + + F.line = 251; + Temporary2 = HEX3Aanonymous__asyncjs95examples952_u74.bind(HEX3Aenv_973078631); Temporary2.ClP_0 = HEX3Aanonymous__asyncjs95examples952_u74; Temporary2.ClE_0 = HEX3Aenv_973078631; + (await catch__asyncjs95examples952_u55(fn__asyncjs95examples952_u8(7), Temporary2)); + if (!(!((HEX3Aenv_973078631.reason0 == null)))) { + F.line = 251; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/asyncjs_examples_2.nim(21, 5) `reason != nil` ")); + } + + if (!(contains__pureZstrutils_u1877(cstrToNimstr(HEX3Aenv_973078631.reason0.message), [102,111,111,98,97,114,58,32,55]))) { + F.line = 251; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/asyncjs_examples_2.nim(22, 5) `\"foobar: 7\" in $reason.message` ")); + } + + F.line = 251; + result_973078556 = undefined; + break BeforeRet; + }; + framePtr = F.prev; + + return result_973078556; + +} +var F = {procname: "module asyncjs_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/asyncjs_examples_2.nim", line: 0}; +framePtr = F; +F.line = 251; +F.filename = "asyncjs.nim"; +(main__asyncjs95examples952_u26()); +framePtr = F.prev; +var F = {procname: "module asyncjs_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/asyncjs_examples_2.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module asyncjs_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/asyncjs_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module asyncjs_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/asyncjs_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; diff --git a/nimcache/runnableExamples/asyncjs_group0_examples.nim b/nimcache/runnableExamples/asyncjs_group0_examples.nim new file mode 100644 index 0000000000000..73a8bf5c8bb33 --- /dev/null +++ b/nimcache/runnableExamples/asyncjs_group0_examples.nim @@ -0,0 +1,5 @@ +# autogenerated by docgen +# source: /home/runner/work/Nim/Nim/lib/js/asyncjs.nim +# rdoccmd: -r:off +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/asyncjs_examples_1.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/asyncjs_examples_2.nim" diff --git a/nimcache/runnableExamples/dom_examples_1.nim b/nimcache/runnableExamples/dom_examples_1.nim new file mode 100644 index 0000000000000..02dea7b3d8ef7 --- /dev/null +++ b/nimcache/runnableExamples/dom_examples_1.nim @@ -0,0 +1,11 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/dom.nim(18, 17) +rdoccmd: -b:js -r:off +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/dom.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/dom.nim", 18, 17).}: + proc example(e: Event) = echo "Document is ready" + document.addEventListener("DOMContentLoaded", example) # You can also use "load" event. + diff --git a/nimcache/runnableExamples/dom_examples_2.nim b/nimcache/runnableExamples/dom_examples_2.nim new file mode 100644 index 0000000000000..7c5802d4a2fc8 --- /dev/null +++ b/nimcache/runnableExamples/dom_examples_2.nim @@ -0,0 +1,12 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/dom.nim(22, 17) +rdoccmd: -b:js -r:off +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/dom.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/dom.nim", 22, 17).}: + proc example() = echo "5 seconds after document ready" + proc domReady(e: Event) = discard setTimeout(example, 5_000) # Document is ready. + document.addEventListener("DOMContentLoaded", domReady) + diff --git a/nimcache/runnableExamples/dom_examples_3.nim b/nimcache/runnableExamples/dom_examples_3.nim new file mode 100644 index 0000000000000..b3f2f4281a383 --- /dev/null +++ b/nimcache/runnableExamples/dom_examples_3.nim @@ -0,0 +1,11 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/dom.nim(30, 17) +rdoccmd: -b:js -r:off +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/dom.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/dom.nim", 30, 17).}: + proc example(e: Event) = echo "Document is unloaded" + document.addEventListener("unload", example) # You can also use "beforeunload". + diff --git a/nimcache/runnableExamples/dom_examples_4.nim b/nimcache/runnableExamples/dom_examples_4.nim new file mode 100644 index 0000000000000..753dbeed23367 --- /dev/null +++ b/nimcache/runnableExamples/dom_examples_4.nim @@ -0,0 +1,11 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/dom.nim(37, 17) +rdoccmd: -b:js -r:off +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/dom.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/dom.nim", 37, 17).}: + proc example() = window.location.reload() + discard setTimeout(example, 5_000) + diff --git a/nimcache/runnableExamples/dom_group0_examples.js b/nimcache/runnableExamples/dom_group0_examples.js new file mode 100644 index 0000000000000..2e2d3c333a59e --- /dev/null +++ b/nimcache/runnableExamples/dom_group0_examples.js @@ -0,0 +1,843 @@ +/* Generated by the Nim Compiler v2.2.1 */ +var framePtr = null; +var excHandler = 0; +var lastJSError = null; +var NTI671088829 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088826 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088825 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI671088705 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI671088828 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI671088706 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI671088775 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI671088664 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI671088764 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI671088776 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI671088665 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI671088763 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI671088762 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI671088781 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI671088669 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI671088761 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI671088760 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI671088777 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI671088666 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI671088759 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI671088733 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088732 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088731 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088730 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088729 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088728 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088727 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088726 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088725 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088724 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088723 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088722 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088721 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088720 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088719 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088718 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088717 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088716 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088715 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088714 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088713 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088712 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088711 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088710 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI671088709 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI671088782 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI671088670 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI671088657 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI671088655 = {size: 0, kind: 14, base: null, node: null, finalizer: null}; +var NTI671088757 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI671088756 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI671088656 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI671088755 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI671088754 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI671088767 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI671088778 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI671088667 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI671088766 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI33554435 = {size: 0,kind: 31,base: null,node: null,finalizer: null}; +var NTI671088780 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI671088779 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI671088668 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554466 = {size: 0,kind: 1,base: null,node: null,finalizer: null}; +var NTI33555167 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI671088751 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI671088654 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554450 = {size: 0,kind: 29,base: null,node: null,finalizer: null}; +var NTI671088765 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI671088658 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI671088758 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NNI671088751 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI671088751.node = NNI671088751; +var NNI33555167 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555167.node = NNI33555167; +NTI671088751.base = NTI33555167; +NTI671088654.base = NTI671088751; +NTI671088780.base = NTI671088658; +var NNI671088779 = {kind: 2, len: 10, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "acceptCharset", len: 0, typ: NTI33554450, name: "acceptCharset", sons: null}, +{kind: 1, offset: "action", len: 0, typ: NTI33554450, name: "action", sons: null}, +{kind: 1, offset: "autocomplete", len: 0, typ: NTI33554450, name: "autocomplete", sons: null}, +{kind: 1, offset: "elements", len: 0, typ: NTI671088780, name: "elements", sons: null}, +{kind: 1, offset: "encoding", len: 0, typ: NTI33554450, name: "encoding", sons: null}, +{kind: 1, offset: "enctype", len: 0, typ: NTI33554450, name: "enctype", sons: null}, +{kind: 1, offset: "length", len: 0, typ: NTI33554435, name: "length", sons: null}, +{kind: 1, offset: "method", len: 0, typ: NTI33554450, name: "method", sons: null}, +{kind: 1, offset: "noValidate", len: 0, typ: NTI33554466, name: "noValidate", sons: null}, +{kind: 1, offset: "target", len: 0, typ: NTI33554450, name: "target", sons: null}]}; +NTI671088779.node = NNI671088779; +NTI671088779.base = NTI671088765; +NTI671088668.base = NTI671088779; +var NNI671088778 = {kind: 2, len: 5, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "defaultSelected", len: 0, typ: NTI33554466, name: "defaultSelected", sons: null}, +{kind: 1, offset: "selected", len: 0, typ: NTI33554466, name: "selected", sons: null}, +{kind: 1, offset: "selectedIndex", len: 0, typ: NTI33554435, name: "selectedIndex", sons: null}, +{kind: 1, offset: "text", len: 0, typ: NTI33554450, name: "text", sons: null}, +{kind: 1, offset: "value", len: 0, typ: NTI33554450, name: "value", sons: null}]}; +NTI671088778.node = NNI671088778; +NTI671088778.base = NTI671088765; +NTI671088667.base = NTI671088778; +NTI671088766.base = NTI671088667; +NTI671088767.base = NTI671088667; +var NNI671088765 = {kind: 2, len: 20, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "className", len: 0, typ: NTI33554450, name: "className", sons: null}, +{kind: 1, offset: "classList", len: 0, typ: NTI671088654, name: "classList", sons: null}, +{kind: 1, offset: "checked", len: 0, typ: NTI33554466, name: "checked", sons: null}, +{kind: 1, offset: "defaultChecked", len: 0, typ: NTI33554466, name: "defaultChecked", sons: null}, +{kind: 1, offset: "defaultValue", len: 0, typ: NTI33554450, name: "defaultValue", sons: null}, +{kind: 1, offset: "disabled", len: 0, typ: NTI33554466, name: "disabled", sons: null}, +{kind: 1, offset: "form", len: 0, typ: NTI671088668, name: "form", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}, +{kind: 1, offset: "readOnly", len: 0, typ: NTI33554466, name: "readOnly", sons: null}, +{kind: 1, offset: "options", len: 0, typ: NTI671088766, name: "options", sons: null}, +{kind: 1, offset: "selectedOptions", len: 0, typ: NTI671088767, name: "selectedOptions", sons: null}, +{kind: 1, offset: "clientWidth", len: 0, typ: NTI33554435, name: "clientWidth", sons: null}, +{kind: 1, offset: "clientHeight", len: 0, typ: NTI33554435, name: "clientHeight", sons: null}, +{kind: 1, offset: "contentEditable", len: 0, typ: NTI33554450, name: "contentEditable", sons: null}, +{kind: 1, offset: "isContentEditable", len: 0, typ: NTI33554466, name: "isContentEditable", sons: null}, +{kind: 1, offset: "dir", len: 0, typ: NTI33554450, name: "dir", sons: null}, +{kind: 1, offset: "offsetHeight", len: 0, typ: NTI33554435, name: "offsetHeight", sons: null}, +{kind: 1, offset: "offsetWidth", len: 0, typ: NTI33554435, name: "offsetWidth", sons: null}, +{kind: 1, offset: "offsetLeft", len: 0, typ: NTI33554435, name: "offsetLeft", sons: null}, +{kind: 1, offset: "offsetTop", len: 0, typ: NTI33554435, name: "offsetTop", sons: null}]}; +NTI671088765.node = NNI671088765; +NTI671088656.base = NTI671088754; +NTI671088755.base = NTI671088656; +NTI671088756.base = NTI671088656; +NTI671088757.base = NTI671088656; +var NNI671088655 = {kind: 2, offset: 0, typ: null, name: null, len: 12, sons: {"1": {kind: 1, offset: 1, typ: NTI671088655, name: "ElementNode", len: 0, sons: null}, +"2": {kind: 1, offset: 2, typ: NTI671088655, name: "AttributeNode", len: 0, sons: null}, +"3": {kind: 1, offset: 3, typ: NTI671088655, name: "TextNode", len: 0, sons: null}, +"4": {kind: 1, offset: 4, typ: NTI671088655, name: "CDATANode", len: 0, sons: null}, +"5": {kind: 1, offset: 5, typ: NTI671088655, name: "EntityRefNode", len: 0, sons: null}, +"6": {kind: 1, offset: 6, typ: NTI671088655, name: "EntityNode", len: 0, sons: null}, +"7": {kind: 1, offset: 7, typ: NTI671088655, name: "ProcessingInstructionNode", len: 0, sons: null}, +"8": {kind: 1, offset: 8, typ: NTI671088655, name: "CommentNode", len: 0, sons: null}, +"9": {kind: 1, offset: 9, typ: NTI671088655, name: "DocumentNode", len: 0, sons: null}, +"10": {kind: 1, offset: 10, typ: NTI671088655, name: "DocumentTypeNode", len: 0, sons: null}, +"11": {kind: 1, offset: 11, typ: NTI671088655, name: "DocumentFragmentNode", len: 0, sons: null}, +"12": {kind: 1, offset: 12, typ: NTI671088655, name: "NotationNode", len: 0, sons: null}}}; +NTI671088655.node = NNI671088655; +NTI671088657.base = NTI671088758; +var NNI671088782 = {kind: 2, len: 368, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "alignContent", len: 0, typ: NTI33554450, name: "alignContent", sons: null}, +{kind: 1, offset: "alignItems", len: 0, typ: NTI33554450, name: "alignItems", sons: null}, +{kind: 1, offset: "alignSelf", len: 0, typ: NTI33554450, name: "alignSelf", sons: null}, +{kind: 1, offset: "all", len: 0, typ: NTI33554450, name: "all", sons: null}, +{kind: 1, offset: "animation", len: 0, typ: NTI33554450, name: "animation", sons: null}, +{kind: 1, offset: "animationDelay", len: 0, typ: NTI33554450, name: "animationDelay", sons: null}, +{kind: 1, offset: "animationDirection", len: 0, typ: NTI33554450, name: "animationDirection", sons: null}, +{kind: 1, offset: "animationDuration", len: 0, typ: NTI33554450, name: "animationDuration", sons: null}, +{kind: 1, offset: "animationFillMode", len: 0, typ: NTI33554450, name: "animationFillMode", sons: null}, +{kind: 1, offset: "animationIterationCount", len: 0, typ: NTI33554450, name: "animationIterationCount", sons: null}, +{kind: 1, offset: "animationName", len: 0, typ: NTI33554450, name: "animationName", sons: null}, +{kind: 1, offset: "animationPlayState", len: 0, typ: NTI33554450, name: "animationPlayState", sons: null}, +{kind: 1, offset: "animationTimingFunction", len: 0, typ: NTI33554450, name: "animationTimingFunction", sons: null}, +{kind: 1, offset: "backdropFilter", len: 0, typ: NTI33554450, name: "backdropFilter", sons: null}, +{kind: 1, offset: "backfaceVisibility", len: 0, typ: NTI33554450, name: "backfaceVisibility", sons: null}, +{kind: 1, offset: "background", len: 0, typ: NTI33554450, name: "background", sons: null}, +{kind: 1, offset: "backgroundAttachment", len: 0, typ: NTI33554450, name: "backgroundAttachment", sons: null}, +{kind: 1, offset: "backgroundBlendMode", len: 0, typ: NTI33554450, name: "backgroundBlendMode", sons: null}, +{kind: 1, offset: "backgroundClip", len: 0, typ: NTI33554450, name: "backgroundClip", sons: null}, +{kind: 1, offset: "backgroundColor", len: 0, typ: NTI33554450, name: "backgroundColor", sons: null}, +{kind: 1, offset: "backgroundImage", len: 0, typ: NTI33554450, name: "backgroundImage", sons: null}, +{kind: 1, offset: "backgroundOrigin", len: 0, typ: NTI33554450, name: "backgroundOrigin", sons: null}, +{kind: 1, offset: "backgroundPosition", len: 0, typ: NTI33554450, name: "backgroundPosition", sons: null}, +{kind: 1, offset: "backgroundRepeat", len: 0, typ: NTI33554450, name: "backgroundRepeat", sons: null}, +{kind: 1, offset: "backgroundSize", len: 0, typ: NTI33554450, name: "backgroundSize", sons: null}, +{kind: 1, offset: "blockSize", len: 0, typ: NTI33554450, name: "blockSize", sons: null}, +{kind: 1, offset: "border", len: 0, typ: NTI33554450, name: "border", sons: null}, +{kind: 1, offset: "borderBlock", len: 0, typ: NTI33554450, name: "borderBlock", sons: null}, +{kind: 1, offset: "borderBlockColor", len: 0, typ: NTI33554450, name: "borderBlockColor", sons: null}, +{kind: 1, offset: "borderBlockEnd", len: 0, typ: NTI33554450, name: "borderBlockEnd", sons: null}, +{kind: 1, offset: "borderBlockEndColor", len: 0, typ: NTI33554450, name: "borderBlockEndColor", sons: null}, +{kind: 1, offset: "borderBlockEndStyle", len: 0, typ: NTI33554450, name: "borderBlockEndStyle", sons: null}, +{kind: 1, offset: "borderBlockEndWidth", len: 0, typ: NTI33554450, name: "borderBlockEndWidth", sons: null}, +{kind: 1, offset: "borderBlockStart", len: 0, typ: NTI33554450, name: "borderBlockStart", sons: null}, +{kind: 1, offset: "borderBlockStartColor", len: 0, typ: NTI33554450, name: "borderBlockStartColor", sons: null}, +{kind: 1, offset: "borderBlockStartStyle", len: 0, typ: NTI33554450, name: "borderBlockStartStyle", sons: null}, +{kind: 1, offset: "borderBlockStartWidth", len: 0, typ: NTI33554450, name: "borderBlockStartWidth", sons: null}, +{kind: 1, offset: "borderBlockStyle", len: 0, typ: NTI33554450, name: "borderBlockStyle", sons: null}, +{kind: 1, offset: "borderBlockWidth", len: 0, typ: NTI33554450, name: "borderBlockWidth", sons: null}, +{kind: 1, offset: "borderBottom", len: 0, typ: NTI33554450, name: "borderBottom", sons: null}, +{kind: 1, offset: "borderBottomColor", len: 0, typ: NTI33554450, name: "borderBottomColor", sons: null}, +{kind: 1, offset: "borderBottomLeftRadius", len: 0, typ: NTI33554450, name: "borderBottomLeftRadius", sons: null}, +{kind: 1, offset: "borderBottomRightRadius", len: 0, typ: NTI33554450, name: "borderBottomRightRadius", sons: null}, +{kind: 1, offset: "borderBottomStyle", len: 0, typ: NTI33554450, name: "borderBottomStyle", sons: null}, +{kind: 1, offset: "borderBottomWidth", len: 0, typ: NTI33554450, name: "borderBottomWidth", sons: null}, +{kind: 1, offset: "borderCollapse", len: 0, typ: NTI33554450, name: "borderCollapse", sons: null}, +{kind: 1, offset: "borderColor", len: 0, typ: NTI33554450, name: "borderColor", sons: null}, +{kind: 1, offset: "borderEndEndRadius", len: 0, typ: NTI33554450, name: "borderEndEndRadius", sons: null}, +{kind: 1, offset: "borderEndStartRadius", len: 0, typ: NTI33554450, name: "borderEndStartRadius", sons: null}, +{kind: 1, offset: "borderImage", len: 0, typ: NTI33554450, name: "borderImage", sons: null}, +{kind: 1, offset: "borderImageOutset", len: 0, typ: NTI33554450, name: "borderImageOutset", sons: null}, +{kind: 1, offset: "borderImageRepeat", len: 0, typ: NTI33554450, name: "borderImageRepeat", sons: null}, +{kind: 1, offset: "borderImageSlice", len: 0, typ: NTI33554450, name: "borderImageSlice", sons: null}, +{kind: 1, offset: "borderImageSource", len: 0, typ: NTI33554450, name: "borderImageSource", sons: null}, +{kind: 1, offset: "borderImageWidth", len: 0, typ: NTI33554450, name: "borderImageWidth", sons: null}, +{kind: 1, offset: "borderInline", len: 0, typ: NTI33554450, name: "borderInline", sons: null}, +{kind: 1, offset: "borderInlineColor", len: 0, typ: NTI33554450, name: "borderInlineColor", sons: null}, +{kind: 1, offset: "borderInlineEnd", len: 0, typ: NTI33554450, name: "borderInlineEnd", sons: null}, +{kind: 1, offset: "borderInlineEndColor", len: 0, typ: NTI33554450, name: "borderInlineEndColor", sons: null}, +{kind: 1, offset: "borderInlineEndStyle", len: 0, typ: NTI33554450, name: "borderInlineEndStyle", sons: null}, +{kind: 1, offset: "borderInlineEndWidth", len: 0, typ: NTI33554450, name: "borderInlineEndWidth", sons: null}, +{kind: 1, offset: "borderInlineStart", len: 0, typ: NTI33554450, name: "borderInlineStart", sons: null}, +{kind: 1, offset: "borderInlineStartColor", len: 0, typ: NTI33554450, name: "borderInlineStartColor", sons: null}, +{kind: 1, offset: "borderInlineStartStyle", len: 0, typ: NTI33554450, name: "borderInlineStartStyle", sons: null}, +{kind: 1, offset: "borderInlineStartWidth", len: 0, typ: NTI33554450, name: "borderInlineStartWidth", sons: null}, +{kind: 1, offset: "borderInlineStyle", len: 0, typ: NTI33554450, name: "borderInlineStyle", sons: null}, +{kind: 1, offset: "borderInlineWidth", len: 0, typ: NTI33554450, name: "borderInlineWidth", sons: null}, +{kind: 1, offset: "borderLeft", len: 0, typ: NTI33554450, name: "borderLeft", sons: null}, +{kind: 1, offset: "borderLeftColor", len: 0, typ: NTI33554450, name: "borderLeftColor", sons: null}, +{kind: 1, offset: "borderLeftStyle", len: 0, typ: NTI33554450, name: "borderLeftStyle", sons: null}, +{kind: 1, offset: "borderLeftWidth", len: 0, typ: NTI33554450, name: "borderLeftWidth", sons: null}, +{kind: 1, offset: "borderRadius", len: 0, typ: NTI33554450, name: "borderRadius", sons: null}, +{kind: 1, offset: "borderRight", len: 0, typ: NTI33554450, name: "borderRight", sons: null}, +{kind: 1, offset: "borderRightColor", len: 0, typ: NTI33554450, name: "borderRightColor", sons: null}, +{kind: 1, offset: "borderRightStyle", len: 0, typ: NTI33554450, name: "borderRightStyle", sons: null}, +{kind: 1, offset: "borderRightWidth", len: 0, typ: NTI33554450, name: "borderRightWidth", sons: null}, +{kind: 1, offset: "borderSpacing", len: 0, typ: NTI33554450, name: "borderSpacing", sons: null}, +{kind: 1, offset: "borderStartEndRadius", len: 0, typ: NTI33554450, name: "borderStartEndRadius", sons: null}, +{kind: 1, offset: "borderStartStartRadius", len: 0, typ: NTI33554450, name: "borderStartStartRadius", sons: null}, +{kind: 1, offset: "borderStyle", len: 0, typ: NTI33554450, name: "borderStyle", sons: null}, +{kind: 1, offset: "borderTop", len: 0, typ: NTI33554450, name: "borderTop", sons: null}, +{kind: 1, offset: "borderTopColor", len: 0, typ: NTI33554450, name: "borderTopColor", sons: null}, +{kind: 1, offset: "borderTopLeftRadius", len: 0, typ: NTI33554450, name: "borderTopLeftRadius", sons: null}, +{kind: 1, offset: "borderTopRightRadius", len: 0, typ: NTI33554450, name: "borderTopRightRadius", sons: null}, +{kind: 1, offset: "borderTopStyle", len: 0, typ: NTI33554450, name: "borderTopStyle", sons: null}, +{kind: 1, offset: "borderTopWidth", len: 0, typ: NTI33554450, name: "borderTopWidth", sons: null}, +{kind: 1, offset: "borderWidth", len: 0, typ: NTI33554450, name: "borderWidth", sons: null}, +{kind: 1, offset: "bottom", len: 0, typ: NTI33554450, name: "bottom", sons: null}, +{kind: 1, offset: "boxDecorationBreak", len: 0, typ: NTI33554450, name: "boxDecorationBreak", sons: null}, +{kind: 1, offset: "boxShadow", len: 0, typ: NTI33554450, name: "boxShadow", sons: null}, +{kind: 1, offset: "boxSizing", len: 0, typ: NTI33554450, name: "boxSizing", sons: null}, +{kind: 1, offset: "breakAfter", len: 0, typ: NTI33554450, name: "breakAfter", sons: null}, +{kind: 1, offset: "breakBefore", len: 0, typ: NTI33554450, name: "breakBefore", sons: null}, +{kind: 1, offset: "breakInside", len: 0, typ: NTI33554450, name: "breakInside", sons: null}, +{kind: 1, offset: "captionSide", len: 0, typ: NTI33554450, name: "captionSide", sons: null}, +{kind: 1, offset: "caretColor", len: 0, typ: NTI33554450, name: "caretColor", sons: null}, +{kind: 1, offset: "clear", len: 0, typ: NTI33554450, name: "clear", sons: null}, +{kind: 1, offset: "clip", len: 0, typ: NTI33554450, name: "clip", sons: null}, +{kind: 1, offset: "clipPath", len: 0, typ: NTI33554450, name: "clipPath", sons: null}, +{kind: 1, offset: "color", len: 0, typ: NTI33554450, name: "color", sons: null}, +{kind: 1, offset: "colorAdjust", len: 0, typ: NTI33554450, name: "colorAdjust", sons: null}, +{kind: 1, offset: "columnCount", len: 0, typ: NTI33554450, name: "columnCount", sons: null}, +{kind: 1, offset: "columnFill", len: 0, typ: NTI33554450, name: "columnFill", sons: null}, +{kind: 1, offset: "columnGap", len: 0, typ: NTI33554450, name: "columnGap", sons: null}, +{kind: 1, offset: "columnRule", len: 0, typ: NTI33554450, name: "columnRule", sons: null}, +{kind: 1, offset: "columnRuleColor", len: 0, typ: NTI33554450, name: "columnRuleColor", sons: null}, +{kind: 1, offset: "columnRuleStyle", len: 0, typ: NTI33554450, name: "columnRuleStyle", sons: null}, +{kind: 1, offset: "columnRuleWidth", len: 0, typ: NTI33554450, name: "columnRuleWidth", sons: null}, +{kind: 1, offset: "columnSpan", len: 0, typ: NTI33554450, name: "columnSpan", sons: null}, +{kind: 1, offset: "columnWidth", len: 0, typ: NTI33554450, name: "columnWidth", sons: null}, +{kind: 1, offset: "columns", len: 0, typ: NTI33554450, name: "columns", sons: null}, +{kind: 1, offset: "contain", len: 0, typ: NTI33554450, name: "contain", sons: null}, +{kind: 1, offset: "content", len: 0, typ: NTI33554450, name: "content", sons: null}, +{kind: 1, offset: "counterIncrement", len: 0, typ: NTI33554450, name: "counterIncrement", sons: null}, +{kind: 1, offset: "counterReset", len: 0, typ: NTI33554450, name: "counterReset", sons: null}, +{kind: 1, offset: "counterSet", len: 0, typ: NTI33554450, name: "counterSet", sons: null}, +{kind: 1, offset: "cursor", len: 0, typ: NTI33554450, name: "cursor", sons: null}, +{kind: 1, offset: "direction", len: 0, typ: NTI33554450, name: "direction", sons: null}, +{kind: 1, offset: "display", len: 0, typ: NTI33554450, name: "display", sons: null}, +{kind: 1, offset: "emptyCells", len: 0, typ: NTI33554450, name: "emptyCells", sons: null}, +{kind: 1, offset: "filter", len: 0, typ: NTI33554450, name: "filter", sons: null}, +{kind: 1, offset: "flex", len: 0, typ: NTI33554450, name: "flex", sons: null}, +{kind: 1, offset: "flexBasis", len: 0, typ: NTI33554450, name: "flexBasis", sons: null}, +{kind: 1, offset: "flexDirection", len: 0, typ: NTI33554450, name: "flexDirection", sons: null}, +{kind: 1, offset: "flexFlow", len: 0, typ: NTI33554450, name: "flexFlow", sons: null}, +{kind: 1, offset: "flexGrow", len: 0, typ: NTI33554450, name: "flexGrow", sons: null}, +{kind: 1, offset: "flexShrink", len: 0, typ: NTI33554450, name: "flexShrink", sons: null}, +{kind: 1, offset: "flexWrap", len: 0, typ: NTI33554450, name: "flexWrap", sons: null}, +{kind: 1, offset: "cssFloat", len: 0, typ: NTI33554450, name: "cssFloat", sons: null}, +{kind: 1, offset: "font", len: 0, typ: NTI33554450, name: "font", sons: null}, +{kind: 1, offset: "fontFamily", len: 0, typ: NTI33554450, name: "fontFamily", sons: null}, +{kind: 1, offset: "fontFeatureSettings", len: 0, typ: NTI33554450, name: "fontFeatureSettings", sons: null}, +{kind: 1, offset: "fontKerning", len: 0, typ: NTI33554450, name: "fontKerning", sons: null}, +{kind: 1, offset: "fontLanguageOverride", len: 0, typ: NTI33554450, name: "fontLanguageOverride", sons: null}, +{kind: 1, offset: "fontOpticalSizing", len: 0, typ: NTI33554450, name: "fontOpticalSizing", sons: null}, +{kind: 1, offset: "fontSize", len: 0, typ: NTI33554450, name: "fontSize", sons: null}, +{kind: 1, offset: "fontSizeAdjust", len: 0, typ: NTI33554450, name: "fontSizeAdjust", sons: null}, +{kind: 1, offset: "fontStretch", len: 0, typ: NTI33554450, name: "fontStretch", sons: null}, +{kind: 1, offset: "fontStyle", len: 0, typ: NTI33554450, name: "fontStyle", sons: null}, +{kind: 1, offset: "fontSynthesis", len: 0, typ: NTI33554450, name: "fontSynthesis", sons: null}, +{kind: 1, offset: "fontVariant", len: 0, typ: NTI33554450, name: "fontVariant", sons: null}, +{kind: 1, offset: "fontVariantAlternates", len: 0, typ: NTI33554450, name: "fontVariantAlternates", sons: null}, +{kind: 1, offset: "fontVariantCaps", len: 0, typ: NTI33554450, name: "fontVariantCaps", sons: null}, +{kind: 1, offset: "fontVariantEastAsian", len: 0, typ: NTI33554450, name: "fontVariantEastAsian", sons: null}, +{kind: 1, offset: "fontVariantLigatures", len: 0, typ: NTI33554450, name: "fontVariantLigatures", sons: null}, +{kind: 1, offset: "fontVariantNumeric", len: 0, typ: NTI33554450, name: "fontVariantNumeric", sons: null}, +{kind: 1, offset: "fontVariantPosition", len: 0, typ: NTI33554450, name: "fontVariantPosition", sons: null}, +{kind: 1, offset: "fontVariationSettings", len: 0, typ: NTI33554450, name: "fontVariationSettings", sons: null}, +{kind: 1, offset: "fontWeight", len: 0, typ: NTI33554450, name: "fontWeight", sons: null}, +{kind: 1, offset: "gap", len: 0, typ: NTI33554450, name: "gap", sons: null}, +{kind: 1, offset: "grid", len: 0, typ: NTI33554450, name: "grid", sons: null}, +{kind: 1, offset: "gridArea", len: 0, typ: NTI33554450, name: "gridArea", sons: null}, +{kind: 1, offset: "gridAutoColumns", len: 0, typ: NTI33554450, name: "gridAutoColumns", sons: null}, +{kind: 1, offset: "gridAutoFlow", len: 0, typ: NTI33554450, name: "gridAutoFlow", sons: null}, +{kind: 1, offset: "gridAutoRows", len: 0, typ: NTI33554450, name: "gridAutoRows", sons: null}, +{kind: 1, offset: "gridColumn", len: 0, typ: NTI33554450, name: "gridColumn", sons: null}, +{kind: 1, offset: "gridColumnEnd", len: 0, typ: NTI33554450, name: "gridColumnEnd", sons: null}, +{kind: 1, offset: "gridColumnStart", len: 0, typ: NTI33554450, name: "gridColumnStart", sons: null}, +{kind: 1, offset: "gridRow", len: 0, typ: NTI33554450, name: "gridRow", sons: null}, +{kind: 1, offset: "gridRowEnd", len: 0, typ: NTI33554450, name: "gridRowEnd", sons: null}, +{kind: 1, offset: "gridRowStart", len: 0, typ: NTI33554450, name: "gridRowStart", sons: null}, +{kind: 1, offset: "gridTemplate", len: 0, typ: NTI33554450, name: "gridTemplate", sons: null}, +{kind: 1, offset: "gridTemplateAreas", len: 0, typ: NTI33554450, name: "gridTemplateAreas", sons: null}, +{kind: 1, offset: "gridTemplateColumns", len: 0, typ: NTI33554450, name: "gridTemplateColumns", sons: null}, +{kind: 1, offset: "gridTemplateRows", len: 0, typ: NTI33554450, name: "gridTemplateRows", sons: null}, +{kind: 1, offset: "hangingPunctuation", len: 0, typ: NTI33554450, name: "hangingPunctuation", sons: null}, +{kind: 1, offset: "height", len: 0, typ: NTI33554450, name: "height", sons: null}, +{kind: 1, offset: "hyphens", len: 0, typ: NTI33554450, name: "hyphens", sons: null}, +{kind: 1, offset: "imageOrientation", len: 0, typ: NTI33554450, name: "imageOrientation", sons: null}, +{kind: 1, offset: "imageRendering", len: 0, typ: NTI33554450, name: "imageRendering", sons: null}, +{kind: 1, offset: "inlineSize", len: 0, typ: NTI33554450, name: "inlineSize", sons: null}, +{kind: 1, offset: "inset", len: 0, typ: NTI33554450, name: "inset", sons: null}, +{kind: 1, offset: "insetBlock", len: 0, typ: NTI33554450, name: "insetBlock", sons: null}, +{kind: 1, offset: "insetBlockEnd", len: 0, typ: NTI33554450, name: "insetBlockEnd", sons: null}, +{kind: 1, offset: "insetBlockStart", len: 0, typ: NTI33554450, name: "insetBlockStart", sons: null}, +{kind: 1, offset: "insetInline", len: 0, typ: NTI33554450, name: "insetInline", sons: null}, +{kind: 1, offset: "insetInlineEnd", len: 0, typ: NTI33554450, name: "insetInlineEnd", sons: null}, +{kind: 1, offset: "insetInlineStart", len: 0, typ: NTI33554450, name: "insetInlineStart", sons: null}, +{kind: 1, offset: "isolation", len: 0, typ: NTI33554450, name: "isolation", sons: null}, +{kind: 1, offset: "justifyContent", len: 0, typ: NTI33554450, name: "justifyContent", sons: null}, +{kind: 1, offset: "justifyItems", len: 0, typ: NTI33554450, name: "justifyItems", sons: null}, +{kind: 1, offset: "justifySelf", len: 0, typ: NTI33554450, name: "justifySelf", sons: null}, +{kind: 1, offset: "left", len: 0, typ: NTI33554450, name: "left", sons: null}, +{kind: 1, offset: "letterSpacing", len: 0, typ: NTI33554450, name: "letterSpacing", sons: null}, +{kind: 1, offset: "lineBreak", len: 0, typ: NTI33554450, name: "lineBreak", sons: null}, +{kind: 1, offset: "lineHeight", len: 0, typ: NTI33554450, name: "lineHeight", sons: null}, +{kind: 1, offset: "listStyle", len: 0, typ: NTI33554450, name: "listStyle", sons: null}, +{kind: 1, offset: "listStyleImage", len: 0, typ: NTI33554450, name: "listStyleImage", sons: null}, +{kind: 1, offset: "listStylePosition", len: 0, typ: NTI33554450, name: "listStylePosition", sons: null}, +{kind: 1, offset: "listStyleType", len: 0, typ: NTI33554450, name: "listStyleType", sons: null}, +{kind: 1, offset: "margin", len: 0, typ: NTI33554450, name: "margin", sons: null}, +{kind: 1, offset: "marginBlock", len: 0, typ: NTI33554450, name: "marginBlock", sons: null}, +{kind: 1, offset: "marginBlockEnd", len: 0, typ: NTI33554450, name: "marginBlockEnd", sons: null}, +{kind: 1, offset: "marginBlockStart", len: 0, typ: NTI33554450, name: "marginBlockStart", sons: null}, +{kind: 1, offset: "marginBottom", len: 0, typ: NTI33554450, name: "marginBottom", sons: null}, +{kind: 1, offset: "marginInline", len: 0, typ: NTI33554450, name: "marginInline", sons: null}, +{kind: 1, offset: "marginInlineEnd", len: 0, typ: NTI33554450, name: "marginInlineEnd", sons: null}, +{kind: 1, offset: "marginInlineStart", len: 0, typ: NTI33554450, name: "marginInlineStart", sons: null}, +{kind: 1, offset: "marginLeft", len: 0, typ: NTI33554450, name: "marginLeft", sons: null}, +{kind: 1, offset: "marginRight", len: 0, typ: NTI33554450, name: "marginRight", sons: null}, +{kind: 1, offset: "marginTop", len: 0, typ: NTI33554450, name: "marginTop", sons: null}, +{kind: 1, offset: "mask", len: 0, typ: NTI33554450, name: "mask", sons: null}, +{kind: 1, offset: "maskBorder", len: 0, typ: NTI33554450, name: "maskBorder", sons: null}, +{kind: 1, offset: "maskBorderMode", len: 0, typ: NTI33554450, name: "maskBorderMode", sons: null}, +{kind: 1, offset: "maskBorderOutset", len: 0, typ: NTI33554450, name: "maskBorderOutset", sons: null}, +{kind: 1, offset: "maskBorderRepeat", len: 0, typ: NTI33554450, name: "maskBorderRepeat", sons: null}, +{kind: 1, offset: "maskBorderSlice", len: 0, typ: NTI33554450, name: "maskBorderSlice", sons: null}, +{kind: 1, offset: "maskBorderSource", len: 0, typ: NTI33554450, name: "maskBorderSource", sons: null}, +{kind: 1, offset: "maskBorderWidth", len: 0, typ: NTI33554450, name: "maskBorderWidth", sons: null}, +{kind: 1, offset: "maskClip", len: 0, typ: NTI33554450, name: "maskClip", sons: null}, +{kind: 1, offset: "maskComposite", len: 0, typ: NTI33554450, name: "maskComposite", sons: null}, +{kind: 1, offset: "maskImage", len: 0, typ: NTI33554450, name: "maskImage", sons: null}, +{kind: 1, offset: "maskMode", len: 0, typ: NTI33554450, name: "maskMode", sons: null}, +{kind: 1, offset: "maskOrigin", len: 0, typ: NTI33554450, name: "maskOrigin", sons: null}, +{kind: 1, offset: "maskPosition", len: 0, typ: NTI33554450, name: "maskPosition", sons: null}, +{kind: 1, offset: "maskRepeat", len: 0, typ: NTI33554450, name: "maskRepeat", sons: null}, +{kind: 1, offset: "maskSize", len: 0, typ: NTI33554450, name: "maskSize", sons: null}, +{kind: 1, offset: "maskType", len: 0, typ: NTI33554450, name: "maskType", sons: null}, +{kind: 1, offset: "maxBlockSize", len: 0, typ: NTI33554450, name: "maxBlockSize", sons: null}, +{kind: 1, offset: "maxHeight", len: 0, typ: NTI33554450, name: "maxHeight", sons: null}, +{kind: 1, offset: "maxInlineSize", len: 0, typ: NTI33554450, name: "maxInlineSize", sons: null}, +{kind: 1, offset: "maxWidth", len: 0, typ: NTI33554450, name: "maxWidth", sons: null}, +{kind: 1, offset: "minBlockSize", len: 0, typ: NTI33554450, name: "minBlockSize", sons: null}, +{kind: 1, offset: "minHeight", len: 0, typ: NTI33554450, name: "minHeight", sons: null}, +{kind: 1, offset: "minInlineSize", len: 0, typ: NTI33554450, name: "minInlineSize", sons: null}, +{kind: 1, offset: "minWidth", len: 0, typ: NTI33554450, name: "minWidth", sons: null}, +{kind: 1, offset: "mixBlendMode", len: 0, typ: NTI33554450, name: "mixBlendMode", sons: null}, +{kind: 1, offset: "objectFit", len: 0, typ: NTI33554450, name: "objectFit", sons: null}, +{kind: 1, offset: "objectPosition", len: 0, typ: NTI33554450, name: "objectPosition", sons: null}, +{kind: 1, offset: "offset", len: 0, typ: NTI33554450, name: "offset", sons: null}, +{kind: 1, offset: "offsetAnchor", len: 0, typ: NTI33554450, name: "offsetAnchor", sons: null}, +{kind: 1, offset: "offsetDistance", len: 0, typ: NTI33554450, name: "offsetDistance", sons: null}, +{kind: 1, offset: "offsetPath", len: 0, typ: NTI33554450, name: "offsetPath", sons: null}, +{kind: 1, offset: "offsetRotate", len: 0, typ: NTI33554450, name: "offsetRotate", sons: null}, +{kind: 1, offset: "opacity", len: 0, typ: NTI33554450, name: "opacity", sons: null}, +{kind: 1, offset: "order", len: 0, typ: NTI33554450, name: "order", sons: null}, +{kind: 1, offset: "orphans", len: 0, typ: NTI33554450, name: "orphans", sons: null}, +{kind: 1, offset: "outline", len: 0, typ: NTI33554450, name: "outline", sons: null}, +{kind: 1, offset: "outlineColor", len: 0, typ: NTI33554450, name: "outlineColor", sons: null}, +{kind: 1, offset: "outlineOffset", len: 0, typ: NTI33554450, name: "outlineOffset", sons: null}, +{kind: 1, offset: "outlineStyle", len: 0, typ: NTI33554450, name: "outlineStyle", sons: null}, +{kind: 1, offset: "outlineWidth", len: 0, typ: NTI33554450, name: "outlineWidth", sons: null}, +{kind: 1, offset: "overflow", len: 0, typ: NTI33554450, name: "overflow", sons: null}, +{kind: 1, offset: "overflowAnchor", len: 0, typ: NTI33554450, name: "overflowAnchor", sons: null}, +{kind: 1, offset: "overflowBlock", len: 0, typ: NTI33554450, name: "overflowBlock", sons: null}, +{kind: 1, offset: "overflowInline", len: 0, typ: NTI33554450, name: "overflowInline", sons: null}, +{kind: 1, offset: "overflowWrap", len: 0, typ: NTI33554450, name: "overflowWrap", sons: null}, +{kind: 1, offset: "overflowX", len: 0, typ: NTI33554450, name: "overflowX", sons: null}, +{kind: 1, offset: "overflowY", len: 0, typ: NTI33554450, name: "overflowY", sons: null}, +{kind: 1, offset: "overscrollBehavior", len: 0, typ: NTI33554450, name: "overscrollBehavior", sons: null}, +{kind: 1, offset: "overscrollBehaviorBlock", len: 0, typ: NTI33554450, name: "overscrollBehaviorBlock", sons: null}, +{kind: 1, offset: "overscrollBehaviorInline", len: 0, typ: NTI33554450, name: "overscrollBehaviorInline", sons: null}, +{kind: 1, offset: "overscrollBehaviorX", len: 0, typ: NTI33554450, name: "overscrollBehaviorX", sons: null}, +{kind: 1, offset: "overscrollBehaviorY", len: 0, typ: NTI33554450, name: "overscrollBehaviorY", sons: null}, +{kind: 1, offset: "padding", len: 0, typ: NTI33554450, name: "padding", sons: null}, +{kind: 1, offset: "paddingBlock", len: 0, typ: NTI33554450, name: "paddingBlock", sons: null}, +{kind: 1, offset: "paddingBlockEnd", len: 0, typ: NTI33554450, name: "paddingBlockEnd", sons: null}, +{kind: 1, offset: "paddingBlockStart", len: 0, typ: NTI33554450, name: "paddingBlockStart", sons: null}, +{kind: 1, offset: "paddingBottom", len: 0, typ: NTI33554450, name: "paddingBottom", sons: null}, +{kind: 1, offset: "paddingInline", len: 0, typ: NTI33554450, name: "paddingInline", sons: null}, +{kind: 1, offset: "paddingInlineEnd", len: 0, typ: NTI33554450, name: "paddingInlineEnd", sons: null}, +{kind: 1, offset: "paddingInlineStart", len: 0, typ: NTI33554450, name: "paddingInlineStart", sons: null}, +{kind: 1, offset: "paddingLeft", len: 0, typ: NTI33554450, name: "paddingLeft", sons: null}, +{kind: 1, offset: "paddingRight", len: 0, typ: NTI33554450, name: "paddingRight", sons: null}, +{kind: 1, offset: "paddingTop", len: 0, typ: NTI33554450, name: "paddingTop", sons: null}, +{kind: 1, offset: "pageBreakAfter", len: 0, typ: NTI33554450, name: "pageBreakAfter", sons: null}, +{kind: 1, offset: "pageBreakBefore", len: 0, typ: NTI33554450, name: "pageBreakBefore", sons: null}, +{kind: 1, offset: "pageBreakInside", len: 0, typ: NTI33554450, name: "pageBreakInside", sons: null}, +{kind: 1, offset: "paintOrder", len: 0, typ: NTI33554450, name: "paintOrder", sons: null}, +{kind: 1, offset: "perspective", len: 0, typ: NTI33554450, name: "perspective", sons: null}, +{kind: 1, offset: "perspectiveOrigin", len: 0, typ: NTI33554450, name: "perspectiveOrigin", sons: null}, +{kind: 1, offset: "placeContent", len: 0, typ: NTI33554450, name: "placeContent", sons: null}, +{kind: 1, offset: "placeItems", len: 0, typ: NTI33554450, name: "placeItems", sons: null}, +{kind: 1, offset: "placeSelf", len: 0, typ: NTI33554450, name: "placeSelf", sons: null}, +{kind: 1, offset: "pointerEvents", len: 0, typ: NTI33554450, name: "pointerEvents", sons: null}, +{kind: 1, offset: "position", len: 0, typ: NTI33554450, name: "position", sons: null}, +{kind: 1, offset: "quotes", len: 0, typ: NTI33554450, name: "quotes", sons: null}, +{kind: 1, offset: "resize", len: 0, typ: NTI33554450, name: "resize", sons: null}, +{kind: 1, offset: "right", len: 0, typ: NTI33554450, name: "right", sons: null}, +{kind: 1, offset: "rotate", len: 0, typ: NTI33554450, name: "rotate", sons: null}, +{kind: 1, offset: "rowGap", len: 0, typ: NTI33554450, name: "rowGap", sons: null}, +{kind: 1, offset: "scale", len: 0, typ: NTI33554450, name: "scale", sons: null}, +{kind: 1, offset: "scrollBehavior", len: 0, typ: NTI33554450, name: "scrollBehavior", sons: null}, +{kind: 1, offset: "scrollMargin", len: 0, typ: NTI33554450, name: "scrollMargin", sons: null}, +{kind: 1, offset: "scrollMarginBlock", len: 0, typ: NTI33554450, name: "scrollMarginBlock", sons: null}, +{kind: 1, offset: "scrollMarginBlockEnd", len: 0, typ: NTI33554450, name: "scrollMarginBlockEnd", sons: null}, +{kind: 1, offset: "scrollMarginBlockStart", len: 0, typ: NTI33554450, name: "scrollMarginBlockStart", sons: null}, +{kind: 1, offset: "scrollMarginBottom", len: 0, typ: NTI33554450, name: "scrollMarginBottom", sons: null}, +{kind: 1, offset: "scrollMarginInline", len: 0, typ: NTI33554450, name: "scrollMarginInline", sons: null}, +{kind: 1, offset: "scrollMarginInlineEnd", len: 0, typ: NTI33554450, name: "scrollMarginInlineEnd", sons: null}, +{kind: 1, offset: "scrollMarginInlineStart", len: 0, typ: NTI33554450, name: "scrollMarginInlineStart", sons: null}, +{kind: 1, offset: "scrollMarginLeft", len: 0, typ: NTI33554450, name: "scrollMarginLeft", sons: null}, +{kind: 1, offset: "scrollMarginRight", len: 0, typ: NTI33554450, name: "scrollMarginRight", sons: null}, +{kind: 1, offset: "scrollMarginTop", len: 0, typ: NTI33554450, name: "scrollMarginTop", sons: null}, +{kind: 1, offset: "scrollPadding", len: 0, typ: NTI33554450, name: "scrollPadding", sons: null}, +{kind: 1, offset: "scrollPaddingBlock", len: 0, typ: NTI33554450, name: "scrollPaddingBlock", sons: null}, +{kind: 1, offset: "scrollPaddingBlockEnd", len: 0, typ: NTI33554450, name: "scrollPaddingBlockEnd", sons: null}, +{kind: 1, offset: "scrollPaddingBlockStart", len: 0, typ: NTI33554450, name: "scrollPaddingBlockStart", sons: null}, +{kind: 1, offset: "scrollPaddingBottom", len: 0, typ: NTI33554450, name: "scrollPaddingBottom", sons: null}, +{kind: 1, offset: "scrollPaddingInline", len: 0, typ: NTI33554450, name: "scrollPaddingInline", sons: null}, +{kind: 1, offset: "scrollPaddingInlineEnd", len: 0, typ: NTI33554450, name: "scrollPaddingInlineEnd", sons: null}, +{kind: 1, offset: "scrollPaddingInlineStart", len: 0, typ: NTI33554450, name: "scrollPaddingInlineStart", sons: null}, +{kind: 1, offset: "scrollPaddingLeft", len: 0, typ: NTI33554450, name: "scrollPaddingLeft", sons: null}, +{kind: 1, offset: "scrollPaddingRight", len: 0, typ: NTI33554450, name: "scrollPaddingRight", sons: null}, +{kind: 1, offset: "scrollPaddingTop", len: 0, typ: NTI33554450, name: "scrollPaddingTop", sons: null}, +{kind: 1, offset: "scrollSnapAlign", len: 0, typ: NTI33554450, name: "scrollSnapAlign", sons: null}, +{kind: 1, offset: "scrollSnapStop", len: 0, typ: NTI33554450, name: "scrollSnapStop", sons: null}, +{kind: 1, offset: "scrollSnapType", len: 0, typ: NTI33554450, name: "scrollSnapType", sons: null}, +{kind: 1, offset: "scrollbar3dLightColor", len: 0, typ: NTI33554450, name: "scrollbar3dLightColor", sons: null}, +{kind: 1, offset: "scrollbarArrowColor", len: 0, typ: NTI33554450, name: "scrollbarArrowColor", sons: null}, +{kind: 1, offset: "scrollbarBaseColor", len: 0, typ: NTI33554450, name: "scrollbarBaseColor", sons: null}, +{kind: 1, offset: "scrollbarColor", len: 0, typ: NTI33554450, name: "scrollbarColor", sons: null}, +{kind: 1, offset: "scrollbarDarkshadowColor", len: 0, typ: NTI33554450, name: "scrollbarDarkshadowColor", sons: null}, +{kind: 1, offset: "scrollbarFaceColor", len: 0, typ: NTI33554450, name: "scrollbarFaceColor", sons: null}, +{kind: 1, offset: "scrollbarHighlightColor", len: 0, typ: NTI33554450, name: "scrollbarHighlightColor", sons: null}, +{kind: 1, offset: "scrollbarShadowColor", len: 0, typ: NTI33554450, name: "scrollbarShadowColor", sons: null}, +{kind: 1, offset: "scrollbarTrackColor", len: 0, typ: NTI33554450, name: "scrollbarTrackColor", sons: null}, +{kind: 1, offset: "scrollbarWidth", len: 0, typ: NTI33554450, name: "scrollbarWidth", sons: null}, +{kind: 1, offset: "shapeImageThreshold", len: 0, typ: NTI33554450, name: "shapeImageThreshold", sons: null}, +{kind: 1, offset: "shapeMargin", len: 0, typ: NTI33554450, name: "shapeMargin", sons: null}, +{kind: 1, offset: "shapeOutside", len: 0, typ: NTI33554450, name: "shapeOutside", sons: null}, +{kind: 1, offset: "tabSize", len: 0, typ: NTI33554450, name: "tabSize", sons: null}, +{kind: 1, offset: "tableLayout", len: 0, typ: NTI33554450, name: "tableLayout", sons: null}, +{kind: 1, offset: "textAlign", len: 0, typ: NTI33554450, name: "textAlign", sons: null}, +{kind: 1, offset: "textAlignLast", len: 0, typ: NTI33554450, name: "textAlignLast", sons: null}, +{kind: 1, offset: "textCombineUpright", len: 0, typ: NTI33554450, name: "textCombineUpright", sons: null}, +{kind: 1, offset: "textDecoration", len: 0, typ: NTI33554450, name: "textDecoration", sons: null}, +{kind: 1, offset: "textDecorationColor", len: 0, typ: NTI33554450, name: "textDecorationColor", sons: null}, +{kind: 1, offset: "textDecorationLine", len: 0, typ: NTI33554450, name: "textDecorationLine", sons: null}, +{kind: 1, offset: "textDecorationSkipInk", len: 0, typ: NTI33554450, name: "textDecorationSkipInk", sons: null}, +{kind: 1, offset: "textDecorationStyle", len: 0, typ: NTI33554450, name: "textDecorationStyle", sons: null}, +{kind: 1, offset: "textDecorationThickness", len: 0, typ: NTI33554450, name: "textDecorationThickness", sons: null}, +{kind: 1, offset: "textEmphasis", len: 0, typ: NTI33554450, name: "textEmphasis", sons: null}, +{kind: 1, offset: "textEmphasisColor", len: 0, typ: NTI33554450, name: "textEmphasisColor", sons: null}, +{kind: 1, offset: "textEmphasisPosition", len: 0, typ: NTI33554450, name: "textEmphasisPosition", sons: null}, +{kind: 1, offset: "textEmphasisStyle", len: 0, typ: NTI33554450, name: "textEmphasisStyle", sons: null}, +{kind: 1, offset: "textIndent", len: 0, typ: NTI33554450, name: "textIndent", sons: null}, +{kind: 1, offset: "textJustify", len: 0, typ: NTI33554450, name: "textJustify", sons: null}, +{kind: 1, offset: "textOrientation", len: 0, typ: NTI33554450, name: "textOrientation", sons: null}, +{kind: 1, offset: "textOverflow", len: 0, typ: NTI33554450, name: "textOverflow", sons: null}, +{kind: 1, offset: "textRendering", len: 0, typ: NTI33554450, name: "textRendering", sons: null}, +{kind: 1, offset: "textShadow", len: 0, typ: NTI33554450, name: "textShadow", sons: null}, +{kind: 1, offset: "textTransform", len: 0, typ: NTI33554450, name: "textTransform", sons: null}, +{kind: 1, offset: "textUnderlineOffset", len: 0, typ: NTI33554450, name: "textUnderlineOffset", sons: null}, +{kind: 1, offset: "textUnderlinePosition", len: 0, typ: NTI33554450, name: "textUnderlinePosition", sons: null}, +{kind: 1, offset: "top", len: 0, typ: NTI33554450, name: "top", sons: null}, +{kind: 1, offset: "touchAction", len: 0, typ: NTI33554450, name: "touchAction", sons: null}, +{kind: 1, offset: "transform", len: 0, typ: NTI33554450, name: "transform", sons: null}, +{kind: 1, offset: "transformBox", len: 0, typ: NTI33554450, name: "transformBox", sons: null}, +{kind: 1, offset: "transformOrigin", len: 0, typ: NTI33554450, name: "transformOrigin", sons: null}, +{kind: 1, offset: "transformStyle", len: 0, typ: NTI33554450, name: "transformStyle", sons: null}, +{kind: 1, offset: "transition", len: 0, typ: NTI33554450, name: "transition", sons: null}, +{kind: 1, offset: "transitionDelay", len: 0, typ: NTI33554450, name: "transitionDelay", sons: null}, +{kind: 1, offset: "transitionDuration", len: 0, typ: NTI33554450, name: "transitionDuration", sons: null}, +{kind: 1, offset: "transitionProperty", len: 0, typ: NTI33554450, name: "transitionProperty", sons: null}, +{kind: 1, offset: "transitionTimingFunction", len: 0, typ: NTI33554450, name: "transitionTimingFunction", sons: null}, +{kind: 1, offset: "translate", len: 0, typ: NTI33554450, name: "translate", sons: null}, +{kind: 1, offset: "unicodeBidi", len: 0, typ: NTI33554450, name: "unicodeBidi", sons: null}, +{kind: 1, offset: "verticalAlign", len: 0, typ: NTI33554450, name: "verticalAlign", sons: null}, +{kind: 1, offset: "visibility", len: 0, typ: NTI33554450, name: "visibility", sons: null}, +{kind: 1, offset: "whiteSpace", len: 0, typ: NTI33554450, name: "whiteSpace", sons: null}, +{kind: 1, offset: "widows", len: 0, typ: NTI33554450, name: "widows", sons: null}, +{kind: 1, offset: "width", len: 0, typ: NTI33554450, name: "width", sons: null}, +{kind: 1, offset: "willChange", len: 0, typ: NTI33554450, name: "willChange", sons: null}, +{kind: 1, offset: "wordBreak", len: 0, typ: NTI33554450, name: "wordBreak", sons: null}, +{kind: 1, offset: "wordSpacing", len: 0, typ: NTI33554450, name: "wordSpacing", sons: null}, +{kind: 1, offset: "writingMode", len: 0, typ: NTI33554450, name: "writingMode", sons: null}, +{kind: 1, offset: "zIndex", len: 0, typ: NTI33554450, name: "zIndex", sons: null}]}; +NTI671088782.node = NNI671088782; +NTI671088782.base = NTI33555167; +NTI671088670.base = NTI671088782; +var NNI671088754 = {kind: 2, len: 22, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "attributes", len: 0, typ: NTI671088755, name: "attributes", sons: null}, +{kind: 1, offset: "childNodes", len: 0, typ: NTI671088756, name: "childNodes", sons: null}, +{kind: 1, offset: "children", len: 0, typ: NTI671088757, name: "children", sons: null}, +{kind: 1, offset: "data", len: 0, typ: NTI33554450, name: "data", sons: null}, +{kind: 1, offset: "firstChild", len: 0, typ: NTI671088656, name: "firstChild", sons: null}, +{kind: 1, offset: "lastChild", len: 0, typ: NTI671088656, name: "lastChild", sons: null}, +{kind: 1, offset: "nextSibling", len: 0, typ: NTI671088656, name: "nextSibling", sons: null}, +{kind: 1, offset: "nodeName", len: 0, typ: NTI33554450, name: "nodeName", sons: null}, +{kind: 1, offset: "nodeType", len: 0, typ: NTI671088655, name: "nodeType", sons: null}, +{kind: 1, offset: "nodeValue", len: 0, typ: NTI33554450, name: "nodeValue", sons: null}, +{kind: 1, offset: "parentNode", len: 0, typ: NTI671088656, name: "parentNode", sons: null}, +{kind: 1, offset: "content", len: 0, typ: NTI671088656, name: "content", sons: null}, +{kind: 1, offset: "previousSibling", len: 0, typ: NTI671088656, name: "previousSibling", sons: null}, +{kind: 1, offset: "ownerDocument", len: 0, typ: NTI671088657, name: "ownerDocument", sons: null}, +{kind: 1, offset: "innerHTML", len: 0, typ: NTI33554450, name: "innerHTML", sons: null}, +{kind: 1, offset: "outerHTML", len: 0, typ: NTI33554450, name: "outerHTML", sons: null}, +{kind: 1, offset: "innerText", len: 0, typ: NTI33554450, name: "innerText", sons: null}, +{kind: 1, offset: "textContent", len: 0, typ: NTI33554450, name: "textContent", sons: null}, +{kind: 1, offset: "style", len: 0, typ: NTI671088670, name: "style", sons: null}, +{kind: 1, offset: "baseURI", len: 0, typ: NTI33554450, name: "baseURI", sons: null}, +{kind: 1, offset: "parentElement", len: 0, typ: NTI671088658, name: "parentElement", sons: null}, +{kind: 1, offset: "isConnected", len: 0, typ: NTI33554466, name: "isConnected", sons: null}]}; +NTI671088754.node = NNI671088754; +var NNI671088709 = {kind: 2, len: 24, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "onabort", len: 0, typ: NTI671088710, name: "onabort", sons: null}, +{kind: 1, offset: "onblur", len: 0, typ: NTI671088711, name: "onblur", sons: null}, +{kind: 1, offset: "onchange", len: 0, typ: NTI671088712, name: "onchange", sons: null}, +{kind: 1, offset: "onclick", len: 0, typ: NTI671088713, name: "onclick", sons: null}, +{kind: 1, offset: "ondblclick", len: 0, typ: NTI671088714, name: "ondblclick", sons: null}, +{kind: 1, offset: "onerror", len: 0, typ: NTI671088715, name: "onerror", sons: null}, +{kind: 1, offset: "onfocus", len: 0, typ: NTI671088716, name: "onfocus", sons: null}, +{kind: 1, offset: "onkeydown", len: 0, typ: NTI671088717, name: "onkeydown", sons: null}, +{kind: 1, offset: "onkeypress", len: 0, typ: NTI671088718, name: "onkeypress", sons: null}, +{kind: 1, offset: "onkeyup", len: 0, typ: NTI671088719, name: "onkeyup", sons: null}, +{kind: 1, offset: "onload", len: 0, typ: NTI671088720, name: "onload", sons: null}, +{kind: 1, offset: "onmousedown", len: 0, typ: NTI671088721, name: "onmousedown", sons: null}, +{kind: 1, offset: "onmousemove", len: 0, typ: NTI671088722, name: "onmousemove", sons: null}, +{kind: 1, offset: "onmouseout", len: 0, typ: NTI671088723, name: "onmouseout", sons: null}, +{kind: 1, offset: "onmouseover", len: 0, typ: NTI671088724, name: "onmouseover", sons: null}, +{kind: 1, offset: "onmouseup", len: 0, typ: NTI671088725, name: "onmouseup", sons: null}, +{kind: 1, offset: "onreset", len: 0, typ: NTI671088726, name: "onreset", sons: null}, +{kind: 1, offset: "onselect", len: 0, typ: NTI671088727, name: "onselect", sons: null}, +{kind: 1, offset: "onstorage", len: 0, typ: NTI671088728, name: "onstorage", sons: null}, +{kind: 1, offset: "onsubmit", len: 0, typ: NTI671088729, name: "onsubmit", sons: null}, +{kind: 1, offset: "onunload", len: 0, typ: NTI671088730, name: "onunload", sons: null}, +{kind: 1, offset: "onloadstart", len: 0, typ: NTI671088731, name: "onloadstart", sons: null}, +{kind: 1, offset: "onprogress", len: 0, typ: NTI671088732, name: "onprogress", sons: null}, +{kind: 1, offset: "onloadend", len: 0, typ: NTI671088733, name: "onloadend", sons: null}]}; +NTI671088709.node = NNI671088709; +NTI671088709.base = NTI33555167; +NTI671088754.base = NTI671088709; +NTI671088765.base = NTI671088754; +NTI671088658.base = NTI671088765; +var NNI671088777 = {kind: 2, len: 3, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "text", len: 0, typ: NTI33554450, name: "text", sons: null}, +{kind: 1, offset: "x", len: 0, typ: NTI33554435, name: "x", sons: null}, +{kind: 1, offset: "y", len: 0, typ: NTI33554435, name: "y", sons: null}]}; +NTI671088777.node = NNI671088777; +NTI671088777.base = NTI671088765; +NTI671088666.base = NTI671088777; +NTI671088759.base = NTI671088666; +NTI671088760.base = NTI671088668; +var NNI671088781 = {kind: 2, len: 8, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "border", len: 0, typ: NTI33554435, name: "border", sons: null}, +{kind: 1, offset: "complete", len: 0, typ: NTI33554466, name: "complete", sons: null}, +{kind: 1, offset: "height", len: 0, typ: NTI33554435, name: "height", sons: null}, +{kind: 1, offset: "hspace", len: 0, typ: NTI33554435, name: "hspace", sons: null}, +{kind: 1, offset: "lowsrc", len: 0, typ: NTI33554450, name: "lowsrc", sons: null}, +{kind: 1, offset: "src", len: 0, typ: NTI33554450, name: "src", sons: null}, +{kind: 1, offset: "vspace", len: 0, typ: NTI33554435, name: "vspace", sons: null}, +{kind: 1, offset: "width", len: 0, typ: NTI33554435, name: "width", sons: null}]}; +NTI671088781.node = NNI671088781; +NTI671088781.base = NTI671088765; +NTI671088669.base = NTI671088781; +NTI671088761.base = NTI671088669; +NTI671088762.base = NTI671088658; +var NNI671088776 = {kind: 2, len: 6, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "height", len: 0, typ: NTI33554435, name: "height", sons: null}, +{kind: 1, offset: "hspace", len: 0, typ: NTI33554435, name: "hspace", sons: null}, +{kind: 1, offset: "src", len: 0, typ: NTI33554450, name: "src", sons: null}, +{kind: 1, offset: "width", len: 0, typ: NTI33554435, name: "width", sons: null}, +{kind: 1, offset: "type", len: 0, typ: NTI33554450, name: "type", sons: null}, +{kind: 1, offset: "vspace", len: 0, typ: NTI33554435, name: "vspace", sons: null}]}; +NTI671088776.node = NNI671088776; +NTI671088776.base = NTI671088765; +NTI671088665.base = NTI671088776; +NTI671088763.base = NTI671088665; +var NNI671088775 = {kind: 2, len: 4, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "target", len: 0, typ: NTI33554450, name: "target", sons: null}, +{kind: 1, offset: "text", len: 0, typ: NTI33554450, name: "text", sons: null}, +{kind: 1, offset: "x", len: 0, typ: NTI33554435, name: "x", sons: null}, +{kind: 1, offset: "y", len: 0, typ: NTI33554435, name: "y", sons: null}]}; +NTI671088775.node = NNI671088775; +NTI671088775.base = NTI671088765; +NTI671088664.base = NTI671088775; +NTI671088764.base = NTI671088664; +var NNI671088825 = {kind: 1, offset: "then", len: 0, typ: NTI671088826, name: "then", sons: null}; +NTI671088825.node = NNI671088825; +NTI671088705.base = NTI671088825; +var NNI671088828 = {kind: 2, len: 2, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "ready", len: 0, typ: NTI671088705, name: "ready", sons: null}, +{kind: 1, offset: "onloadingdone", len: 0, typ: NTI671088829, name: "onloadingdone", sons: null}]}; +NTI671088828.node = NNI671088828; +NTI671088706.base = NTI671088828; +var NNI671088758 = {kind: 2, len: 25, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "activeElement", len: 0, typ: NTI671088658, name: "activeElement", sons: null}, +{kind: 1, offset: "documentElement", len: 0, typ: NTI671088658, name: "documentElement", sons: null}, +{kind: 1, offset: "alinkColor", len: 0, typ: NTI33554450, name: "alinkColor", sons: null}, +{kind: 1, offset: "bgColor", len: 0, typ: NTI33554450, name: "bgColor", sons: null}, +{kind: 1, offset: "body", len: 0, typ: NTI671088658, name: "body", sons: null}, +{kind: 1, offset: "charset", len: 0, typ: NTI33554450, name: "charset", sons: null}, +{kind: 1, offset: "cookie", len: 0, typ: NTI33554450, name: "cookie", sons: null}, +{kind: 1, offset: "defaultCharset", len: 0, typ: NTI33554450, name: "defaultCharset", sons: null}, +{kind: 1, offset: "fgColor", len: 0, typ: NTI33554450, name: "fgColor", sons: null}, +{kind: 1, offset: "head", len: 0, typ: NTI671088658, name: "head", sons: null}, +{kind: 1, offset: "hidden", len: 0, typ: NTI33554466, name: "hidden", sons: null}, +{kind: 1, offset: "lastModified", len: 0, typ: NTI33554450, name: "lastModified", sons: null}, +{kind: 1, offset: "linkColor", len: 0, typ: NTI33554450, name: "linkColor", sons: null}, +{kind: 1, offset: "referrer", len: 0, typ: NTI33554450, name: "referrer", sons: null}, +{kind: 1, offset: "title", len: 0, typ: NTI33554450, name: "title", sons: null}, +{kind: 1, offset: "URL", len: 0, typ: NTI33554450, name: "URL", sons: null}, +{kind: 1, offset: "visibilityState", len: 0, typ: NTI33554450, name: "visibilityState", sons: null}, +{kind: 1, offset: "vlinkColor", len: 0, typ: NTI33554450, name: "vlinkColor", sons: null}, +{kind: 1, offset: "anchors", len: 0, typ: NTI671088759, name: "anchors", sons: null}, +{kind: 1, offset: "forms", len: 0, typ: NTI671088760, name: "forms", sons: null}, +{kind: 1, offset: "images", len: 0, typ: NTI671088761, name: "images", sons: null}, +{kind: 1, offset: "applets", len: 0, typ: NTI671088762, name: "applets", sons: null}, +{kind: 1, offset: "embeds", len: 0, typ: NTI671088763, name: "embeds", sons: null}, +{kind: 1, offset: "links", len: 0, typ: NTI671088764, name: "links", sons: null}, +{kind: 1, offset: "fonts", len: 0, typ: NTI671088706, name: "fonts", sons: null}]}; +NTI671088758.node = NNI671088758; +NTI671088758.base = NTI671088754; + +function toJSStr(s_p0) { + var result_33556910 = null; + + var res_33556964 = newSeq__system_u2507((s_p0).length); + var i_33556965 = 0; + var j_33556966 = 0; + Label1: { + Label2: while (true) { + if (!(i_33556965 < (s_p0).length)) break Label2; + var c_33556967 = s_p0[i_33556965]; + if ((c_33556967 < 128)) { + res_33556964[j_33556966] = String.fromCharCode(c_33556967); + i_33556965 += 1; + } + else { + var helper_33556993 = newSeq__system_u2507(0); + Label3: { + Label4: while (true) { + if (!true) break Label4; + var code_33556994 = c_33556967.toString(16); + if ((((code_33556994) == null ? 0 : (code_33556994).length) == 1)) { + helper_33556993.push("%0");; + } + else { + helper_33556993.push("%");; + } + + helper_33556993.push(code_33556994);; + i_33556965 += 1; + if ((((s_p0).length <= i_33556965) || (s_p0[i_33556965] < 128))) { + break Label3; + } + + c_33556967 = s_p0[i_33556965]; + } + }; +++excHandler; + try { + res_33556964[j_33556966] = decodeURIComponent(helper_33556993.join("")); +--excHandler; +} catch (EXCEPTION) { + var prevJSError = lastJSError; + lastJSError = EXCEPTION; + --excHandler; + res_33556964[j_33556966] = helper_33556993.join(""); + lastJSError = prevJSError; + } finally { + } + } + + j_33556966 += 1; + } + }; + if (res_33556964.length < j_33556966) { for (var i = res_33556964.length ; i < j_33556966 ; ++i) res_33556964.push(null); } + else { res_33556964.length = j_33556966; }; + result_33556910 = res_33556964.join(""); + + return result_33556910; + +} + +function rawEcho() { + var buf = ""; + for (var i = 0; i < arguments.length; ++i) { + buf += toJSStr(arguments[i]); + } + console.log(buf); + + + +} +var F = {procname: "module dom", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/dom.nim", line: 0}; +framePtr = F; +F.line = 1399; +F.filename = "dom.nim"; +var document_671090049 = [{nodeType: 9, m_type: NTI671088758, activeElement: null, documentElement: null, alinkColor: null, bgColor: null, body: null, charset: null, cookie: null, defaultCharset: null, fgColor: null, head: null, hidden: false, lastModified: null, linkColor: null, referrer: null, title: null, URL: null, visibilityState: null, vlinkColor: null, anchors: [], forms: [], images: [], applets: [], embeds: [], links: [], fonts: null, attributes: [], childNodes: [], children: [], data: null, firstChild: null, lastChild: null, nextSibling: null, nodeName: null, nodeValue: null, parentNode: null, content: null, previousSibling: null, ownerDocument: null, innerHTML: null, outerHTML: null, innerText: null, textContent: null, style: null, baseURI: null, parentElement: null, isConnected: false, onabort: null, onblur: null, onchange: null, onclick: null, ondblclick: null, onerror: null, onfocus: null, onkeydown: null, onkeypress: null, onkeyup: null, onload: null, onmousedown: null, onmousemove: null, onmouseout: null, onmouseover: null, onmouseup: null, onreset: null, onselect: null, onstorage: null, onsubmit: null, onunload: null, onloadstart: null, onprogress: null, onloadend: null}]; +F.line = 1400; +document_671090049[0].ownerDocument = document_671090049[0]; +framePtr = F.prev; +var F = {procname: "module dom", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/dom.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function newSeq__system_u2507(len_p0) { + var result_33556943 = []; + + var F = {procname: "newSeq.newSeq", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system.nim", line: 0}; + framePtr = F; + F.line = 653; + F.filename = "system.nim"; + result_33556943 = new Array(len_p0); for (var i = 0 ; i < len_p0 ; ++i) { result_33556943[i] = null; } framePtr = F.prev; + + return result_33556943; + +} + +function example__dom95examples951_u3(e_p0) { + var F = {procname: "dom_examples_1.example", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_1.nim", line: 0}; + framePtr = F; + F.line = 18; + F.filename = "dom.nim"; + rawEcho([68,111,99,117,109,101,110,116,32,105,115,32,114,101,97,100,121]); + framePtr = F.prev; + + +} +var Temporary1; +var F = {procname: "module dom_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_1.nim", line: 0}; +framePtr = F; +F.line = 18; +F.filename = "dom.nim"; +Temporary1 = example__dom95examples951_u3.bind(null); Temporary1.ClP_0 = example__dom95examples951_u3; Temporary1.ClE_0 = null; +document_671090049[0].addEventListener("DOMContentLoaded", Temporary1, false); +framePtr = F.prev; +var F = {procname: "module dom_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_1.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function example__dom95examples952_u3() { + var F = {procname: "dom_examples_2.example", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_2.nim", line: 0}; + framePtr = F; + F.line = 22; + F.filename = "dom.nim"; + rawEcho([53,32,115,101,99,111,110,100,115,32,97,102,116,101,114,32,100,111,99,117,109,101,110,116,32,114,101,97,100,121]); + framePtr = F.prev; + + +} + +function domReady__dom95examples952_u4(e_p0) { + var Temporary1; + + var F = {procname: "dom_examples_2.domReady", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_2.nim", line: 0}; + framePtr = F; + F.line = 22; + F.filename = "dom.nim"; + Temporary1 = example__dom95examples952_u3.bind(null); Temporary1.ClP_0 = example__dom95examples952_u3; Temporary1.ClE_0 = null; + (setTimeout(Temporary1, 5000)); + framePtr = F.prev; + + +} +var Temporary1; +var F = {procname: "module dom_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_2.nim", line: 0}; +framePtr = F; +F.line = 22; +F.filename = "dom.nim"; +Temporary1 = domReady__dom95examples952_u4.bind(null); Temporary1.ClP_0 = domReady__dom95examples952_u4; Temporary1.ClE_0 = null; +document_671090049[0].addEventListener("DOMContentLoaded", Temporary1, false); +framePtr = F.prev; +var F = {procname: "module dom_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_2.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function example__dom95examples953_u3(e_p0) { + var F = {procname: "dom_examples_3.example", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_3.nim", line: 0}; + framePtr = F; + F.line = 30; + F.filename = "dom.nim"; + rawEcho([68,111,99,117,109,101,110,116,32,105,115,32,117,110,108,111,97,100,101,100]); + framePtr = F.prev; + + +} +var Temporary1; +var F = {procname: "module dom_examples_3", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_3.nim", line: 0}; +framePtr = F; +F.line = 30; +F.filename = "dom.nim"; +Temporary1 = example__dom95examples953_u3.bind(null); Temporary1.ClP_0 = example__dom95examples953_u3; Temporary1.ClE_0 = null; +document_671090049[0].addEventListener("unload", Temporary1, false); +framePtr = F.prev; +var F = {procname: "module dom_examples_3", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_3.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function example__dom95examples954_u3() { + var F = {procname: "dom_examples_4.example", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_4.nim", line: 0}; + framePtr = F; + F.line = 37; + F.filename = "dom.nim"; + window.location.reload(); + framePtr = F.prev; + + +} +var Temporary1; +var F = {procname: "module dom_examples_4", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_4.nim", line: 0}; +framePtr = F; +F.line = 37; +F.filename = "dom.nim"; +Temporary1 = example__dom95examples954_u3.bind(null); Temporary1.ClP_0 = example__dom95examples954_u3; Temporary1.ClE_0 = null; +(setTimeout(Temporary1, 5000)); +framePtr = F.prev; +var F = {procname: "module dom_examples_4", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_4.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module dom_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module dom_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; diff --git a/nimcache/runnableExamples/dom_group0_examples.nim b/nimcache/runnableExamples/dom_group0_examples.nim new file mode 100644 index 0000000000000..6651920522dd4 --- /dev/null +++ b/nimcache/runnableExamples/dom_group0_examples.nim @@ -0,0 +1,7 @@ +# autogenerated by docgen +# source: /home/runner/work/Nim/Nim/lib/js/dom.nim +# rdoccmd: -b:js -r:off +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_1.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_2.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_3.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/dom_examples_4.nim" diff --git a/nimcache/runnableExamples/jsbigints_examples_1.nim b/nimcache/runnableExamples/jsbigints_examples_1.nim new file mode 100644 index 0000000000000..70eca50796afe --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_1.nim @@ -0,0 +1,11 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(14, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 14, 3).}: + doAssert big(1234567890) == big"1234567890" + doAssert 0b1111100111.big == 0o1747.big and 0o1747.big == 999.big + diff --git a/nimcache/runnableExamples/jsbigints_examples_10.nim b/nimcache/runnableExamples/jsbigints_examples_10.nim new file mode 100644 index 0000000000000..491c5233133b4 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_10.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(81, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 81, 3).}: + doAssert (big"42" * big"9") == big"378" + diff --git a/nimcache/runnableExamples/jsbigints_examples_11.nim b/nimcache/runnableExamples/jsbigints_examples_11.nim new file mode 100644 index 0000000000000..bcaaaa92df639 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_11.nim @@ -0,0 +1,13 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(86, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 86, 3).}: + doAssert big"13" div big"3" == big"4" + doAssert big"-13" div big"3" == big"-4" + doAssert big"13" div big"-3" == big"-4" + doAssert big"-13" div big"-3" == big"4" + diff --git a/nimcache/runnableExamples/jsbigints_examples_12.nim b/nimcache/runnableExamples/jsbigints_examples_12.nim new file mode 100644 index 0000000000000..c0e16bb951161 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_12.nim @@ -0,0 +1,13 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(94, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 94, 3).}: + doAssert big"13" mod big"3" == big"1" + doAssert big"-13" mod big"3" == big"-1" + doAssert big"13" mod big"-3" == big"1" + doAssert big"-13" mod big"-3" == big"-1" + diff --git a/nimcache/runnableExamples/jsbigints_examples_13.nim b/nimcache/runnableExamples/jsbigints_examples_13.nim new file mode 100644 index 0000000000000..df93303ff3dee --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_13.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(101, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 101, 3).}: + doAssert big"2" < big"9" + diff --git a/nimcache/runnableExamples/jsbigints_examples_14.nim b/nimcache/runnableExamples/jsbigints_examples_14.nim new file mode 100644 index 0000000000000..4dbf6295b0e1d --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_14.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(105, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 105, 3).}: + doAssert big"1" <= big"5" + diff --git a/nimcache/runnableExamples/jsbigints_examples_15.nim b/nimcache/runnableExamples/jsbigints_examples_15.nim new file mode 100644 index 0000000000000..aebd711b79228 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_15.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(109, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 109, 3).}: + doAssert big"42" == big"42" + diff --git a/nimcache/runnableExamples/jsbigints_examples_16.nim b/nimcache/runnableExamples/jsbigints_examples_16.nim new file mode 100644 index 0000000000000..39a5b127cb2df --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_16.nim @@ -0,0 +1,17 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(114, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 114, 3).}: + doAssert big"2" ** big"64" == big"18446744073709551616" + doAssert big"-2" ** big"3" == big"-8" + doAssert -big"2" ** big"2" == big"4" # parsed as: (-2n) ** 2n + doAssert big"0" ** big"0" == big"1" # edge case + var ok = false + try: discard big"2" ** big"-1" # raises foreign `RangeError` + except: ok = true + doAssert ok + diff --git a/nimcache/runnableExamples/jsbigints_examples_17.nim b/nimcache/runnableExamples/jsbigints_examples_17.nim new file mode 100644 index 0000000000000..4b9ab9b23a173 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_17.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(125, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 125, 3).}: + doAssert (big"555" and big"2") == big"2" + diff --git a/nimcache/runnableExamples/jsbigints_examples_18.nim b/nimcache/runnableExamples/jsbigints_examples_18.nim new file mode 100644 index 0000000000000..3c3d00a63f2ca --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_18.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(129, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 129, 3).}: + doAssert (big"555" or big"2") == big"555" + diff --git a/nimcache/runnableExamples/jsbigints_examples_19.nim b/nimcache/runnableExamples/jsbigints_examples_19.nim new file mode 100644 index 0000000000000..ee9187f75661c --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_19.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(133, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 133, 3).}: + doAssert (big"555" xor big"2") == big"553" + diff --git a/nimcache/runnableExamples/jsbigints_examples_2.nim b/nimcache/runnableExamples/jsbigints_examples_2.nim new file mode 100644 index 0000000000000..bf57861f8d511 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_2.nim @@ -0,0 +1,18 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(21, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 21, 3).}: + doAssert -1'big == 1'big - 2'big + # supports decimal, binary, octal, hex: + doAssert -12'big == big"-12" + doAssert 12'big == 12.big + doAssert 0b101'big == 0b101.big + doAssert 0o701'big == 0o701.big + doAssert 0xdeadbeaf'big == 0xdeadbeaf.big + doAssert 0xffffffffffffffff'big == (1'big shl 64'big) - 1'big + doAssert not compiles(static(12'big)) + diff --git a/nimcache/runnableExamples/jsbigints_examples_20.nim b/nimcache/runnableExamples/jsbigints_examples_20.nim new file mode 100644 index 0000000000000..721932754f651 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_20.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(137, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 137, 3).}: + doAssert (big"999" shl big"2") == big"3996" + diff --git a/nimcache/runnableExamples/jsbigints_examples_21.nim b/nimcache/runnableExamples/jsbigints_examples_21.nim new file mode 100644 index 0000000000000..a2db3ef643812 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_21.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(141, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 141, 3).}: + doAssert (big"999" shr big"2") == big"249" + diff --git a/nimcache/runnableExamples/jsbigints_examples_22.nim b/nimcache/runnableExamples/jsbigints_examples_22.nim new file mode 100644 index 0000000000000..0956704ed3053 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_22.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(145, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 145, 3).}: + doAssert -(big"10101010101") == big"-10101010101" + diff --git a/nimcache/runnableExamples/jsbigints_examples_23.nim b/nimcache/runnableExamples/jsbigints_examples_23.nim new file mode 100644 index 0000000000000..28022007e2750 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_23.nim @@ -0,0 +1,12 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(149, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 149, 3).}: + var big1: JsBigInt = big"1" + inc big1 + doAssert big1 == big"2" + diff --git a/nimcache/runnableExamples/jsbigints_examples_24.nim b/nimcache/runnableExamples/jsbigints_examples_24.nim new file mode 100644 index 0000000000000..bce3bd1f5b615 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_24.nim @@ -0,0 +1,12 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(155, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 155, 3).}: + var big1: JsBigInt = big"2" + dec big1 + doAssert big1 == big"1" + diff --git a/nimcache/runnableExamples/jsbigints_examples_25.nim b/nimcache/runnableExamples/jsbigints_examples_25.nim new file mode 100644 index 0000000000000..dc5cbb49e7b50 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_25.nim @@ -0,0 +1,12 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(161, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 161, 3).}: + var big1: JsBigInt = big"1" + inc big1, big"2" + doAssert big1 == big"3" + diff --git a/nimcache/runnableExamples/jsbigints_examples_26.nim b/nimcache/runnableExamples/jsbigints_examples_26.nim new file mode 100644 index 0000000000000..9f63e690dd1b6 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_26.nim @@ -0,0 +1,12 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(167, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 167, 3).}: + var big1: JsBigInt = big"1" + dec big1, big"2" + doAssert big1 == big"-1" + diff --git a/nimcache/runnableExamples/jsbigints_examples_27.nim b/nimcache/runnableExamples/jsbigints_examples_27.nim new file mode 100644 index 0000000000000..5285b8ad719f8 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_27.nim @@ -0,0 +1,12 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(173, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 173, 3).}: + var big1: JsBigInt = big"1" + big1 += big"2" + doAssert big1 == big"3" + diff --git a/nimcache/runnableExamples/jsbigints_examples_28.nim b/nimcache/runnableExamples/jsbigints_examples_28.nim new file mode 100644 index 0000000000000..5157abbec8bd8 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_28.nim @@ -0,0 +1,12 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(179, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 179, 3).}: + var big1: JsBigInt = big"1" + big1 -= big"2" + doAssert big1 == big"-1" + diff --git a/nimcache/runnableExamples/jsbigints_examples_29.nim b/nimcache/runnableExamples/jsbigints_examples_29.nim new file mode 100644 index 0000000000000..0bbeab84f5a98 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_29.nim @@ -0,0 +1,12 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(185, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 185, 3).}: + var big1: JsBigInt = big"2" + big1 *= big"4" + doAssert big1 == big"8" + diff --git a/nimcache/runnableExamples/jsbigints_examples_3.nim b/nimcache/runnableExamples/jsbigints_examples_3.nim new file mode 100644 index 0000000000000..d3c22f367e2b9 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_3.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(41, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 41, 3).}: + doAssert big"2147483647".toCstring(2) == "1111111111111111111111111111111".cstring + diff --git a/nimcache/runnableExamples/jsbigints_examples_30.nim b/nimcache/runnableExamples/jsbigints_examples_30.nim new file mode 100644 index 0000000000000..f34dbf2954bc3 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_30.nim @@ -0,0 +1,12 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(192, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 192, 3).}: + var big1: JsBigInt = big"11" + big1 /= big"2" + doAssert big1 == big"5" + diff --git a/nimcache/runnableExamples/jsbigints_examples_31.nim b/nimcache/runnableExamples/jsbigints_examples_31.nim new file mode 100644 index 0000000000000..3a1c2061e191d --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_31.nim @@ -0,0 +1,29 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(208, 1) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 208, 1).}: + block: + let big1: JsBigInt = big"2147483647" + let big2: JsBigInt = big"666" + doAssert JsBigInt isnot int + doAssert big1 != big2 + doAssert big1 > big2 + doAssert big1 >= big2 + doAssert big2 < big1 + doAssert big2 <= big1 + doAssert not(big1 == big2) + let z = JsBigInt.default + doAssert $z == "0n" + block: + var a: seq[JsBigInt] + a.setLen 2 + doAssert a == @[big"0", big"0"] + doAssert a[^1] == big"0" + var b: JsBigInt + doAssert b == big"0" + doAssert b == JsBigInt.default + diff --git a/nimcache/runnableExamples/jsbigints_examples_4.nim b/nimcache/runnableExamples/jsbigints_examples_4.nim new file mode 100644 index 0000000000000..fab47c830039c --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_4.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(50, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 50, 3).}: + doAssert $big"1024" == "1024n" + diff --git a/nimcache/runnableExamples/jsbigints_examples_5.nim b/nimcache/runnableExamples/jsbigints_examples_5.nim new file mode 100644 index 0000000000000..940c8eab32abf --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_5.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(57, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 57, 3).}: + doAssert (big("3") + big("2") ** big("66")).wrapToInt(13) == big("3") + diff --git a/nimcache/runnableExamples/jsbigints_examples_6.nim b/nimcache/runnableExamples/jsbigints_examples_6.nim new file mode 100644 index 0000000000000..2ca7fd74c6e83 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_6.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(64, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 64, 3).}: + doAssert (big("3") + big("2") ** big("66")).wrapToUint(66) == big("3") + diff --git a/nimcache/runnableExamples/jsbigints_examples_7.nim b/nimcache/runnableExamples/jsbigints_examples_7.nim new file mode 100644 index 0000000000000..72230d2fcb4bb --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_7.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(69, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 69, 3).}: + doAssert toNumber(big"2147483647") == 2147483647.int + diff --git a/nimcache/runnableExamples/jsbigints_examples_8.nim b/nimcache/runnableExamples/jsbigints_examples_8.nim new file mode 100644 index 0000000000000..223bce2f6877a --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_8.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(73, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 73, 3).}: + doAssert (big"9" + big"1") == big"10" + diff --git a/nimcache/runnableExamples/jsbigints_examples_9.nim b/nimcache/runnableExamples/jsbigints_examples_9.nim new file mode 100644 index 0000000000000..d1927d27bd9fb --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_examples_9.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim(77, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", 77, 3).}: + doAssert (big"9" - big"1") == big"8" + diff --git a/nimcache/runnableExamples/jsbigints_group0_examples.js b/nimcache/runnableExamples/jsbigints_group0_examples.js new file mode 100644 index 0000000000000..f04a9ecc3649d --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_group0_examples.js @@ -0,0 +1,1391 @@ +/* Generated by the Nim Compiler v2.2.1 */ +var framePtr = null; +var excHandler = 0; +var lastJSError = null; +var NTI134217749 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217751 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217741 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217743 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554435 = {size: 0,kind: 31,base: null,node: null,finalizer: null}; +var NTI33555836 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI33555167 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555175 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554450 = {size: 0,kind: 29,base: null,node: null,finalizer: null}; +var NTI33555174 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33555171 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555172 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217745 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554449 = {size: 0,kind: 28,base: null,node: null,finalizer: null}; +var NNI134217745 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217745.node = NNI134217745; +var NNI33555172 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555172.node = NNI33555172; +NTI33555174.base = NTI33555171; +NTI33555175.base = NTI33555171; +var NNI33555171 = {kind: 2, len: 5, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "parent", len: 0, typ: NTI33555174, name: "parent", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}, +{kind: 1, offset: "message", len: 0, typ: NTI33554449, name: "msg", sons: null}, +{kind: 1, offset: "trace", len: 0, typ: NTI33554449, name: "trace", sons: null}, +{kind: 1, offset: "up", len: 0, typ: NTI33555175, name: "up", sons: null}]}; +NTI33555171.node = NNI33555171; +var NNI33555167 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555167.node = NNI33555167; +NTI33555171.base = NTI33555167; +NTI33555172.base = NTI33555171; +NTI134217745.base = NTI33555172; +var NNI33555836 = {kind: 2, len: 3, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "Field0", len: 0, typ: NTI33554450, name: "Field0", sons: null}, +{kind: 1, offset: "Field1", len: 0, typ: NTI33554435, name: "Field1", sons: null}, +{kind: 1, offset: "Field2", len: 0, typ: NTI33554450, name: "Field2", sons: null}]}; +NTI33555836.node = NNI33555836; +var NNI134217743 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217743.node = NNI134217743; +var NNI134217741 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217741.node = NNI134217741; +NTI134217741.base = NTI33555172; +NTI134217743.base = NTI134217741; +var NNI134217751 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217751.node = NNI134217751; +NTI134217751.base = NTI33555172; +var NNI134217749 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217749.node = NNI134217749; +NTI134217749.base = NTI33555172; + +function setConstr() { + var result = {}; + for (var i = 0; i < arguments.length; ++i) { + var x = arguments[i]; + if (typeof(x) == "object") { + for (var j = x[0]; j <= x[1]; ++j) { + result[j] = true; + } + } else { + result[x] = true; + } + } + return result; + + + +} +var ConstSet1 = setConstr(17, 16, 4, 18, 27, 19, 23, 22, 21); + +function nimCopy(dest_p0, src_p1, ti_p2) { + var result_33557321 = null; + + switch (ti_p2.kind) { + case 21: + case 22: + case 23: + case 5: + if (!(isFatPointer__system_u2869(ti_p2))) { + result_33557321 = src_p1; + } + else { + result_33557321 = [src_p1[0], src_p1[1]]; + } + + break; + case 19: + if (dest_p0 === null || dest_p0 === undefined) { + dest_p0 = {}; + } + else { + for (var key in dest_p0) { delete dest_p0[key]; } + } + for (var key in src_p1) { dest_p0[key] = src_p1[key]; } + result_33557321 = dest_p0; + + break; + case 18: + case 17: + if (!((ti_p2.base == null))) { + result_33557321 = nimCopy(dest_p0, src_p1, ti_p2.base); + } + else { + if ((ti_p2.kind == 17)) { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {m_type: ti_p2} : dest_p0; + } + else { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {} : dest_p0; + } + } + nimCopyAux(result_33557321, src_p1, ti_p2.node); + break; + case 4: + case 16: + if(ArrayBuffer.isView(src_p1)) { + if(dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new src_p1.constructor(src_p1); + } else { + dest_p0.set(src_p1, 0); + } + result_33557321 = dest_p0; + } else { + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + } + + break; + case 24: + case 27: + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + + break; + case 28: + if (src_p1 !== null) { + result_33557321 = src_p1.slice(0); + } + + break; + default: + result_33557321 = src_p1; + break; + } + + return result_33557321; + +} + +function arrayConstr(len_p0, value_p1, typ_p2) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; ++i) result[i] = nimCopy(null, value_p1, typ_p2); + return result; + + + +} + +function mnewString(len_p0) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; i++) {result[i] = 0;} + return result; + + + +} + +function addInt(a_p0, b_p1) { + var result = a_p0 + b_p1; + checkOverflowInt(result); + return result; + + + +} + +function chckRange(i_p0, a_p1, b_p2) { + var result_33557361 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557361 = i_p0; + break BeforeRet; + } + else { + raiseRangeError(); + } + + }; + + return result_33557361; + +} + +function chckIndx(i_p0, a_p1, b_p2) { + var result_33557356 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557356 = i_p0; + break BeforeRet; + } + else { + raiseIndexError(i_p0, a_p1, b_p2); + } + + }; + + return result_33557356; + +} + +function cstrToNimstr(c_p0) { + var ln = c_p0.length; + var result = new Array(ln); + var r = 0; + for (var i = 0; i < ln; ++i) { + var ch = c_p0.charCodeAt(i); + + if (ch < 128) { + result[r] = ch; + } + else { + if (ch < 2048) { + result[r] = (ch >> 6) | 192; + } + else { + if (ch < 55296 || ch >= 57344) { + result[r] = (ch >> 12) | 224; + } + else { + ++i; + ch = 65536 + (((ch & 1023) << 10) | (c_p0.charCodeAt(i) & 1023)); + result[r] = (ch >> 18) | 240; + ++r; + result[r] = ((ch >> 12) & 63) | 128; + } + ++r; + result[r] = ((ch >> 6) & 63) | 128; + } + ++r; + result[r] = (ch & 63) | 128; + } + ++r; + } + return result; + + + +} + +function toJSStr(s_p0) { + var result_33556910 = null; + + var res_33556964 = newSeq__system_u2507((s_p0).length); + var i_33556965 = 0; + var j_33556966 = 0; + Label1: { + Label2: while (true) { + if (!(i_33556965 < (s_p0).length)) break Label2; + var c_33556967 = s_p0[i_33556965]; + if ((c_33556967 < 128)) { + res_33556964[j_33556966] = String.fromCharCode(c_33556967); + i_33556965 += 1; + } + else { + var helper_33556993 = newSeq__system_u2507(0); + Label3: { + Label4: while (true) { + if (!true) break Label4; + var code_33556994 = c_33556967.toString(16); + if ((((code_33556994) == null ? 0 : (code_33556994).length) == 1)) { + helper_33556993.push("%0");; + } + else { + helper_33556993.push("%");; + } + + helper_33556993.push(code_33556994);; + i_33556965 += 1; + if ((((s_p0).length <= i_33556965) || (s_p0[i_33556965] < 128))) { + break Label3; + } + + c_33556967 = s_p0[i_33556965]; + } + }; +++excHandler; + try { + res_33556964[j_33556966] = decodeURIComponent(helper_33556993.join("")); +--excHandler; +} catch (EXCEPTION) { + var prevJSError = lastJSError; + lastJSError = EXCEPTION; + --excHandler; + res_33556964[j_33556966] = helper_33556993.join(""); + lastJSError = prevJSError; + } finally { + } + } + + j_33556966 += 1; + } + }; + if (res_33556964.length < j_33556966) { for (var i = res_33556964.length ; i < j_33556966 ; ++i) res_33556964.push(null); } + else { res_33556964.length = j_33556966; }; + result_33556910 = res_33556964.join(""); + + return result_33556910; + +} + +function raiseException(e_p0, ename_p1) { + e_p0.name = ename_p1; + if ((excHandler == 0)) { + unhandledException(e_p0); + } + + e_p0.trace = nimCopy(null, rawWriteStackTrace__system_u2180(), NTI33554449); + throw e_p0; + + +} + +function makeNimstrLit(c_p0) { + var result = []; + for (var i = 0; i < c_p0.length; ++i) { + result[i] = c_p0.charCodeAt(i); + } + return result; + + + +} + +function eqStrings(a_p0, b_p1) { + if (a_p0 == b_p1) return true; + if (a_p0 === null && b_p1.length == 0) return true; + if (b_p1 === null && a_p0.length == 0) return true; + if ((!a_p0) || (!b_p1)) return false; + var alen = a_p0.length; + if (alen != b_p1.length) return false; + for (var i = 0; i < alen; ++i) + if (a_p0[i] != b_p1[i]) return false; + return true; + + + +} + +function subInt(a_p0, b_p1) { + var result = a_p0 - b_p1; + checkOverflowInt(result); + return result; + + + +} +var F = {procname: "module jsbigints", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function isFatPointer__system_u2869(ti_p0) { + var result_33557303 = false; + + BeforeRet: { + result_33557303 = !((ConstSet1[ti_p0.base.kind] != undefined)); + break BeforeRet; + }; + + return result_33557303; + +} + +function nimCopyAux(dest_p0, src_p1, n_p2) { + switch (n_p2.kind) { + case 0: + break; + case 1: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + + break; + case 2: + for (var i = 0; i < n_p2.sons.length; i++) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i]); + } + + break; + case 3: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + for (var i = 0; i < n_p2.sons.length; ++i) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i][1]); + } + + break; + } + + +} + +function add__system_u1942(x_p0, x_p0_Idx, y_p1) { + if (x_p0[x_p0_Idx] === null) { x_p0[x_p0_Idx] = []; } + var off = x_p0[x_p0_Idx].length; + x_p0[x_p0_Idx].length += y_p1.length; + for (var i = 0; i < y_p1.length; ++i) { + x_p0[x_p0_Idx][off+i] = y_p1.charCodeAt(i); + } + + + +} + +function raiseOverflow() { + raiseException({message: [111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119], parent: null, m_type: NTI134217743, name: null, trace: [], up: null}, "OverflowDefect"); + + +} + +function checkOverflowInt(a_p0) { + if (a_p0 > 2147483647 || a_p0 < -2147483648) raiseOverflow(); + + + +} + +function raiseRangeError() { + raiseException({message: [118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101], parent: null, m_type: NTI134217751, name: null, trace: [], up: null}, "RangeDefect"); + + +} + +function raiseIndexError(i_p0, a_p1, b_p2) { + var Temporary1; + + if ((b_p2 < a_p1)) { + Temporary1 = [105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]; + } + else { + Temporary1 = ([105,110,100,101,120,32]).concat(HEX24__systemZdollars_u8(i_p0),[32,110,111,116,32,105,110,32],HEX24__systemZdollars_u8(a_p1),[32,46,46,32],HEX24__systemZdollars_u8(b_p2)); + } + + raiseException({message: nimCopy(null, Temporary1, NTI33554449), parent: null, m_type: NTI134217749, name: null, trace: [], up: null}, "IndexDefect"); + + +} + +function addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, start_p2, n_p3) { + var Temporary1; + + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 44; + F.filename = "digitsutils.nim"; + var old_301990096 = (result_p0[result_p0_Idx]).length; + F.line = 45; + if (result_p0[result_p0_Idx].length < (Temporary1 = chckRange(addInt(old_301990096, n_p3), 0, 2147483647), Temporary1)) { for (var i = result_p0[result_p0_Idx].length; i < Temporary1; ++i) result_p0[result_p0_Idx].push(0); } + else {result_p0[result_p0_Idx].length = Temporary1; }; + Label2: { + F.line = 47; + var iHEX60gensym4_301990110 = 0; + F.line = 128; + F.filename = "iterators_1.nim"; + var i_654311495 = 0; + Label3: { + F.line = 129; + Label4: while (true) { + if (!(i_654311495 < n_p3)) break Label4; + F.line = 50; + F.filename = "digitsutils.nim"; + iHEX60gensym4_301990110 = i_654311495; + F.line = 47; + result_p0[result_p0_Idx][chckIndx(addInt(old_301990096, iHEX60gensym4_301990110), 0, (result_p0[result_p0_Idx]).length - 1)] = x_p1.charCodeAt(chckIndx(addInt(start_p2, iHEX60gensym4_301990110), 0, (x_p1).length - 1)); + F.line = 131; + F.filename = "iterators_1.nim"; + i_654311495 = addInt(i_654311495, 1); + } + }; + }; + framePtr = F.prev; + + +} + +function addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 56; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, 0, ((x_p1) == null ? 0 : (x_p1).length)); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 112; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, ((x_p1) + "")); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u241(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 116; + F.filename = "digitsutils.nim"; + addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, BigInt(x_p1)); + framePtr = F.prev; + + +} + +function HEX24__systemZdollars_u8(x_p0) { + var result_369098762 = [[]]; + + var F = {procname: "dollars.$", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/dollars.nim", line: 0}; + framePtr = F; + F.line = 18; + F.filename = "dollars.nim"; + addInt__stdZprivateZdigitsutils_u241(result_369098762, 0, x_p0); + framePtr = F.prev; + + return result_369098762[0]; + +} + +function auxWriteStackTrace__system_u2084(f_p0) { + var result_33556518 = [[]]; + + var it_33556526 = f_p0; + var i_33556527 = 0; + var total_33556528 = 0; + var tempFrames_33556529 = arrayConstr(64, {Field0: null, Field1: 0, Field2: null}, NTI33555836); + Label1: { + Label2: while (true) { + if (!(!((it_33556526 == null)) && (i_33556527 <= 63))) break Label2; + tempFrames_33556529[i_33556527].Field0 = it_33556526.procname; + tempFrames_33556529[i_33556527].Field1 = it_33556526.line; + tempFrames_33556529[i_33556527].Field2 = it_33556526.filename; + i_33556527 += 1; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + Label3: { + Label4: while (true) { + if (!!((it_33556526 == null))) break Label4; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + result_33556518[0] = nimCopy(null, [], NTI33554449); + if (!((total_33556528 == i_33556527))) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + result_33556518[0].push.apply(result_33556518[0], HEX24__systemZdollars_u8((total_33556528 - i_33556527)));; + result_33556518[0].push.apply(result_33556518[0], [32,99,97,108,108,115,32,111,109,105,116,116,101,100,41,32,46,46,46,10]);; + } + + Label5: { + var j_33556562 = 0; + var colontmp__654311487 = 0; + colontmp__654311487 = (i_33556527 - 1); + var res_654311489 = colontmp__654311487; + Label6: { + Label7: while (true) { + if (!(0 <= res_654311489)) break Label7; + j_33556562 = res_654311489; + result_33556518[0].push.apply(result_33556518[0], cstrToNimstr(tempFrames_33556529[j_33556562].Field2));; + if ((0 < tempFrames_33556529[j_33556562].Field1)) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, tempFrames_33556529[j_33556562].Field1); + if (false) { + result_33556518[0].push.apply(result_33556518[0], [44,32]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, 0); + } + + result_33556518[0].push.apply(result_33556518[0], [41]);; + } + + result_33556518[0].push.apply(result_33556518[0], [32,97,116,32]);; + add__system_u1942(result_33556518, 0, tempFrames_33556529[j_33556562].Field0); + result_33556518[0].push.apply(result_33556518[0], [10]);; + res_654311489 -= 1; + } + }; + }; + + return result_33556518[0]; + +} + +function rawWriteStackTrace__system_u2180() { + var result_33556613 = []; + + if (!((framePtr == null))) { + result_33556613 = nimCopy(null, ([84,114,97,99,101,98,97,99,107,32,40,109,111,115,116,32,114,101,99,101,110,116,32,99,97,108,108,32,108,97,115,116,41,10]).concat(auxWriteStackTrace__system_u2084(framePtr)), NTI33554449); + } + else { + result_33556613 = nimCopy(null, [78,111,32,115,116,97,99,107,32,116,114,97,99,101,98,97,99,107,32,97,118,97,105,108,97,98,108,101,10], NTI33554449); + } + + + return result_33556613; + +} + +function newSeq__system_u2507(len_p0) { + var result_33556943 = []; + + var F = {procname: "newSeq.newSeq", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system.nim", line: 0}; + framePtr = F; + F.line = 653; + F.filename = "system.nim"; + result_33556943 = new Array(len_p0); for (var i = 0 ; i < len_p0 ; ++i) { result_33556943[i] = null; } framePtr = F.prev; + + return result_33556943; + +} + +function unhandledException(e_p0) { + var buf_33556658 = [[]]; + if (!(((e_p0.message).length == 0))) { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32]);; + buf_33556658[0].push.apply(buf_33556658[0], e_p0.message);; + } + else { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110]);; + } + + buf_33556658[0].push.apply(buf_33556658[0], [32,91]);; + add__system_u1942(buf_33556658, 0, e_p0.name); + buf_33556658[0].push.apply(buf_33556658[0], [93,10]);; + buf_33556658[0].push.apply(buf_33556658[0], rawWriteStackTrace__system_u2180());; + var cbuf_33556659 = toJSStr(buf_33556658[0]); + framePtr = null; + if (typeof(Error) !== "undefined") { + throw new Error(cbuf_33556659); + } + else { + throw cbuf_33556659; + } + + + +} + +function sysFatal__stdZassertions_u44(message_p1) { + var F = {procname: "sysFatal.sysFatal", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/fatal.nim", line: 0}; + framePtr = F; + F.line = 53; + F.filename = "fatal.nim"; + raiseException({message: nimCopy(null, message_p1, NTI33554449), m_type: NTI134217745, parent: null, name: null, trace: [], up: null}, "AssertionDefect"); + framePtr = F.prev; + + +} + +function raiseAssert__stdZassertions_u42(msg_p0) { + var F = {procname: "assertions.raiseAssert", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 36; + F.filename = "assertions.nim"; + sysFatal__stdZassertions_u44(msg_p0); + framePtr = F.prev; + + +} + +function failedAssertImpl__stdZassertions_u84(msg_p0) { + var F = {procname: "assertions.failedAssertImpl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 41; + F.filename = "assertions.nim"; + raiseAssert__stdZassertions_u42(msg_p0); + framePtr = F.prev; + + +} +var F = {procname: "module jsbigints_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_1.nim", line: 0}; +framePtr = F; +if (!((BigInt(1234567890) == BigInt("1234567890")))) { +F.line = 14; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_1.nim(9, 3) `big(1234567890) == big\"1234567890\"` ")); +} + +if (!(((BigInt(999) == BigInt(999)) && (BigInt(999) == BigInt(999))))) { +F.line = 14; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_1.nim(10, 3) `0b00000000000000000000001111100111.big == 0o000000001747.big and\x0A 0o000000001747.big == 999.big` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_1.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_2.nim", line: 0}; +framePtr = F; +if (!((BigInt("-1") == (BigInt("1") - BigInt("2"))))) { +F.line = 21; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_2.nim(9, 3) `-1\'big == 1\'big - 2\'big` ")); +} + +if (!((BigInt("-12") == BigInt("-12")))) { +F.line = 21; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_2.nim(11, 3) `-12\'big == big\"-12\"` ")); +} + +if (!((BigInt("12") == BigInt(12)))) { +F.line = 21; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_2.nim(12, 3) `12\'big == 12.big` ")); +} + +if (!((BigInt("0b101") == BigInt(5)))) { +F.line = 21; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_2.nim(13, 3) `0b101\'big == 0b00000000000000000000000000000101.big` ")); +} + +if (!((BigInt("0o701") == BigInt(449)))) { +F.line = 21; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_2.nim(14, 3) `0o701\'big == 0o000000000701.big` ")); +} + +if (!((BigInt("0xdeadbeaf") == BigInt(3735928495n)))) { +F.line = 21; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_2.nim(15, 3) `0xdeadbeaf\'big == 0x00000000DEADBEAF\'i64.big` ")); +} + +if (!((BigInt("0xffffffffffffffff") == ((BigInt("1") << BigInt("64")) - BigInt("1"))))) { +F.line = 21; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_2.nim(16, 3) `0xffffffffffffffff\'big == (1\'big shl 64\'big) - 1\'big` ")); +} + +if (false) { +F.line = 21; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_2.nim(17, 3) `not compiles(static(12\'big))` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_2.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_3", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_3.nim", line: 0}; +framePtr = F; +if (!((BigInt("2147483647").toString(2) == "1111111111111111111111111111111"))) { +F.line = 41; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_3.nim(9, 3) `big\"2147483647\".toCstring(2) == \"1111111111111111111111111111111\".cstring` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_3", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_3.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function HEX24__stdZjsbigints_u19(this_p0) { + var result_671088661 = []; + + var F = {procname: "jsbigints.$", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", line: 0}; + framePtr = F; + F.line = 49; + F.filename = "jsbigints.nim"; + result_671088661 = nimCopy(null, (cstrToNimstr(this_p0.toString())).concat([110]), NTI33554449); + framePtr = F.prev; + + return result_671088661; + +} +var F = {procname: "module jsbigints_examples_4", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_4.nim", line: 0}; +framePtr = F; +if (!(eqStrings(HEX24__stdZjsbigints_u19(BigInt("1024")), [49,48,50,52,110]))) { +F.line = 50; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_4.nim(9, 3) `$big\"1024\" == \"1024n\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_4", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_4.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_5", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_5.nim", line: 0}; +framePtr = F; +if (!(((() => { const i = (BigInt("3") + ((BigInt("2")) ** BigInt("66"))), b = 13; return BigInt.asIntN(b, i) })() == BigInt("3")))) { +F.line = 57; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_5.nim(9, 3) `(big(\"3\") + big(\"2\") ** big(\"66\")).wrapToInt(13) == big(\"3\")` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_5", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_5.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_6", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_6.nim", line: 0}; +framePtr = F; +if (!(((() => { const i = (BigInt("3") + ((BigInt("2")) ** BigInt("66"))), b = 66; return BigInt.asUintN(b, i) })() == BigInt("3")))) { +F.line = 64; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_6.nim(9, 3) `(big(\"3\") + big(\"2\") ** big(\"66\")).wrapToUint(66) == big(\"3\")` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_6", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_6.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_7", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_7.nim", line: 0}; +framePtr = F; +if (!((Number(BigInt("2147483647")) == 2147483647))) { +F.line = 69; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_7.nim(9, 3) `toNumber(big\"2147483647\") == 2147483647.int` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_7", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_7.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_8", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_8.nim", line: 0}; +framePtr = F; +if (!(((BigInt("9") + BigInt("1")) == BigInt("10")))) { +F.line = 73; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_8.nim(9, 3) `(big\"9\" + big\"1\") == big\"10\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_8", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_8.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_9", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_9.nim", line: 0}; +framePtr = F; +if (!(((BigInt("9") - BigInt("1")) == BigInt("8")))) { +F.line = 77; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_9.nim(9, 3) `(big\"9\" - big\"1\") == big\"8\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_9", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_9.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_10", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_10.nim", line: 0}; +framePtr = F; +if (!(((BigInt("42") * BigInt("9")) == BigInt("378")))) { +F.line = 81; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_10.nim(9, 3) `(big\"42\" * big\"9\") == big\"378\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_10", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_10.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_11", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_11.nim", line: 0}; +framePtr = F; +if (!(((BigInt("13") / BigInt("3")) == BigInt("4")))) { +F.line = 86; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_11.nim(9, 3) `big\"13\" div big\"3\" == big\"4\"` ")); +} + +if (!(((BigInt("-13") / BigInt("3")) == BigInt("-4")))) { +F.line = 86; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_11.nim(10, 3) `big\"-13\" div big\"3\" == big\"-4\"` ")); +} + +if (!(((BigInt("13") / BigInt("-3")) == BigInt("-4")))) { +F.line = 86; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_11.nim(11, 3) `big\"13\" div big\"-3\" == big\"-4\"` ")); +} + +if (!(((BigInt("-13") / BigInt("-3")) == BigInt("4")))) { +F.line = 86; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_11.nim(12, 3) `big\"-13\" div big\"-3\" == big\"4\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_11", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_11.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_12", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_12.nim", line: 0}; +framePtr = F; +if (!(((BigInt("13") % BigInt("3")) == BigInt("1")))) { +F.line = 94; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_12.nim(9, 3) `big\"13\" mod big\"3\" == big\"1\"` ")); +} + +if (!(((BigInt("-13") % BigInt("3")) == BigInt("-1")))) { +F.line = 94; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_12.nim(10, 3) `big\"-13\" mod big\"3\" == big\"-1\"` ")); +} + +if (!(((BigInt("13") % BigInt("-3")) == BigInt("1")))) { +F.line = 94; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_12.nim(11, 3) `big\"13\" mod big\"-3\" == big\"1\"` ")); +} + +if (!(((BigInt("-13") % BigInt("-3")) == BigInt("-1")))) { +F.line = 94; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_12.nim(12, 3) `big\"-13\" mod big\"-3\" == big\"-1\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_12", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_12.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_13", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_13.nim", line: 0}; +framePtr = F; +if (!((BigInt("2") < BigInt("9")))) { +F.line = 101; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_13.nim(9, 3) `big\"2\" < big\"9\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_13", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_13.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_14", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_14.nim", line: 0}; +framePtr = F; +if (!((BigInt("1") <= BigInt("5")))) { +F.line = 105; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_14.nim(9, 3) `big\"1\" <= big\"5\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_14", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_14.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_15", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_15.nim", line: 0}; +framePtr = F; +if (!((BigInt("42") == BigInt("42")))) { +F.line = 109; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_15.nim(9, 3) `big\"42\" == big\"42\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_15", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_15.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_16", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_16.nim", line: 0}; +framePtr = F; +if (!((((BigInt("2")) ** BigInt("64")) == BigInt("18446744073709551616")))) { +F.line = 114; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_16.nim(9, 3) `big\"2\" ** big\"64\" == big\"18446744073709551616\"` ")); +} + +if (!((((BigInt("-2")) ** BigInt("3")) == BigInt("-8")))) { +F.line = 114; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_16.nim(10, 3) `big\"-2\" ** big\"3\" == big\"-8\"` ")); +} + +if (!(((((-BigInt("2"))) ** BigInt("2")) == BigInt("4")))) { +F.line = 114; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_16.nim(11, 3) `-big\"2\" ** big\"2\" == big\"4\"` ")); +} + +if (!((((BigInt("0")) ** BigInt("0")) == BigInt("1")))) { +F.line = 114; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_16.nim(12, 3) `big\"0\" ** big\"0\" == big\"1\"` ")); +} + +F.line = 114; +var ok_922746903 = [false]; +F.line = 114; +++excHandler; +try { +F.line = 114; +(((BigInt("2")) ** BigInt("-1"))); +--excHandler; +} catch (EXCEPTION) { + var prevJSError = lastJSError; + lastJSError = EXCEPTION; + --excHandler; +framePtr = F; +F.line = 114; +ok_922746903[0] = true; +lastJSError = prevJSError; +} finally { +framePtr = F; +} +if (!(ok_922746903[0])) { +F.line = 114; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_16.nim(16, 3) `ok` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_16", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_16.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_17", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_17.nim", line: 0}; +framePtr = F; +if (!(((BigInt("555") & BigInt("2")) == BigInt("2")))) { +F.line = 125; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_17.nim(9, 3) `(big\"555\" and big\"2\") == big\"2\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_17", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_17.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_18", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_18.nim", line: 0}; +framePtr = F; +if (!(((BigInt("555") | BigInt("2")) == BigInt("555")))) { +F.line = 129; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_18.nim(9, 3) `(big\"555\" or big\"2\") == big\"555\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_18", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_18.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_19", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_19.nim", line: 0}; +framePtr = F; +if (!(((BigInt("555") ^ BigInt("2")) == BigInt("553")))) { +F.line = 133; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_19.nim(9, 3) `(big\"555\" xor big\"2\") == big\"553\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_19", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_19.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_20", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_20.nim", line: 0}; +framePtr = F; +if (!(((BigInt("999") << BigInt("2")) == BigInt("3996")))) { +F.line = 137; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_20.nim(9, 3) `(big\"999\" shl big\"2\") == big\"3996\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_20", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_20.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_21", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_21.nim", line: 0}; +framePtr = F; +if (!(((BigInt("999") >> BigInt("2")) == BigInt("249")))) { +F.line = 141; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_21.nim(9, 3) `(big\"999\" shr big\"2\") == big\"249\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_21", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_21.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_22", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_22.nim", line: 0}; +framePtr = F; +if (!(((-BigInt("10101010101")) == BigInt("-10101010101")))) { +F.line = 145; +F.filename = "jsbigints.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_22.nim(9, 3) `-(big\"10101010101\") == big\"-10101010101\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_22", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_22.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_23", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_23.nim", line: 0}; +framePtr = F; +F.line = 149; +F.filename = "jsbigints.nim"; +var big1_1040187395 = [BigInt("1")]; +F.line = 149; +(++[big1_1040187395, 0][0][0]); +if (!((big1_1040187395[0] == BigInt("2")))) { +F.line = 149; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_23.nim(11, 3) `big1 == big\"2\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_23", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_23.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_24", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_24.nim", line: 0}; +framePtr = F; +F.line = 155; +F.filename = "jsbigints.nim"; +var big1_1056964611 = [BigInt("2")]; +F.line = 155; +(--[big1_1056964611, 0][0][0]); +if (!((big1_1056964611[0] == BigInt("1")))) { +F.line = 155; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_24.nim(11, 3) `big1 == big\"1\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_24", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_24.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_25", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_25.nim", line: 0}; +framePtr = F; +F.line = 161; +F.filename = "jsbigints.nim"; +var big1_1073741827 = [BigInt("1")]; +F.line = 161; +([big1_1073741827, 0][0][0] += BigInt("2")); +if (!((big1_1073741827[0] == BigInt("3")))) { +F.line = 161; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_25.nim(11, 3) `big1 == big\"3\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_25", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_25.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_26", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_26.nim", line: 0}; +framePtr = F; +F.line = 167; +F.filename = "jsbigints.nim"; +var big1_1090519043 = [BigInt("1")]; +F.line = 167; +([big1_1090519043, 0][0][0] -= BigInt("2")); +if (!((big1_1090519043[0] == BigInt("-1")))) { +F.line = 167; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_26.nim(11, 3) `big1 == big\"-1\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_26", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_26.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_27", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_27.nim", line: 0}; +framePtr = F; +F.line = 173; +F.filename = "jsbigints.nim"; +var big1_1107296259 = [BigInt("1")]; +F.line = 173; +([big1_1107296259, 0][0][0] += BigInt("2")); +if (!((big1_1107296259[0] == BigInt("3")))) { +F.line = 173; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_27.nim(11, 3) `big1 == big\"3\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_27", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_27.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_28", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_28.nim", line: 0}; +framePtr = F; +F.line = 179; +F.filename = "jsbigints.nim"; +var big1_1124073475 = [BigInt("1")]; +F.line = 179; +([big1_1124073475, 0][0][0] -= BigInt("2")); +if (!((big1_1124073475[0] == BigInt("-1")))) { +F.line = 179; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_28.nim(11, 3) `big1 == big\"-1\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_28", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_28.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_29", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_29.nim", line: 0}; +framePtr = F; +F.line = 185; +F.filename = "jsbigints.nim"; +var big1_1140850691 = [BigInt("2")]; +F.line = 185; +([big1_1140850691, 0][0][0] *= BigInt("4")); +if (!((big1_1140850691[0] == BigInt("8")))) { +F.line = 185; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_29.nim(11, 3) `big1 == big\"8\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_29", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_29.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_30", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_30.nim", line: 0}; +framePtr = F; +F.line = 192; +F.filename = "jsbigints.nim"; +var big1_1157627907 = [BigInt("11")]; +F.line = 192; +([big1_1157627907, 0][0][0] /= BigInt("2")); +if (!((big1_1157627907[0] == BigInt("5")))) { +F.line = 192; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_30.nim(11, 3) `big1 == big\"5\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_30", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_30.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function HEX3DHEX3D__jsbigints95examples9531_u60(x_p0, y_p1) { + var result_1174405184 = false; + + var F = {procname: "==.==", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/comparisons.nim", line: 0}; + framePtr = F; + BeforeRet: { + F.line = 326; + F.filename = "comparisons.nim"; + var sameObject_1174405192 = false; + F.line = 327; + sameObject_1174405192 = x_p0 === y_p1; + if (sameObject_1174405192) { + F.line = 328; + result_1174405184 = true; + break BeforeRet; + } + + if (!(((x_p0).length == (y_p1).length))) { + F.line = 331; + result_1174405184 = false; + break BeforeRet; + } + + Label1: { + F.line = 333; + var i_1174405206 = 0; + F.line = 81; + F.filename = "iterators_1.nim"; + var colontmp__1174405307 = 0; + F.line = 333; + F.filename = "comparisons.nim"; + colontmp__1174405307 = subInt((x_p0).length, 1); + F.line = 96; + F.filename = "iterators_1.nim"; + var res_1174405309 = 0; + Label2: { + F.line = 97; + Label3: while (true) { + if (!(res_1174405309 <= colontmp__1174405307)) break Label3; + F.line = 333; + F.filename = "comparisons.nim"; + i_1174405206 = res_1174405309; + if (!((x_p0[chckIndx(i_1174405206, 0, (x_p0).length - 1)] == y_p1[chckIndx(i_1174405206, 0, (y_p1).length - 1)]))) { + F.line = 335; + result_1174405184 = false; + break BeforeRet; + } + + F.line = 102; + F.filename = "iterators_1.nim"; + res_1174405309 = addInt(res_1174405309, 1); + } + }; + }; + F.line = 337; + F.filename = "comparisons.nim"; + result_1174405184 = true; + break BeforeRet; + }; + framePtr = F.prev; + + return result_1174405184; + +} + +function HEX5BHEX5D__jsbigints95examples9531_u92(s_p0, i_p1) { + var result_1174405216 = null; + var result_1174405216_Idx = 0; + + var F = {procname: "[].[]", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/indices.nim", line: 0}; + framePtr = F; + F.line = 30; + F.filename = "indices.nim"; + result_1174405216 = s_p0; result_1174405216_Idx = chckIndx(subInt((s_p0).length, i_p1), 0, (s_p0).length - 1); + framePtr = F.prev; + + return [result_1174405216, result_1174405216_Idx]; + +} + var Temporary4; +var F = {procname: "module jsbigints_examples_31", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_31.nim", line: 0}; +framePtr = F; +Label2: { + F.line = 208; + F.filename = "jsbigints.nim"; + var big1_1174405123 = BigInt("2147483647"); + F.line = 208; + var big2_1174405124 = BigInt("666"); + if (false) { + F.line = 208; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_31.nim(12, 5) `JsBigInt isnot int` ")); + } + + if (!(!((big1_1174405123 == big2_1174405124)))) { + F.line = 208; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_31.nim(13, 5) `big1 != big2` ")); + } + + if (!((big2_1174405124 < big1_1174405123))) { + F.line = 208; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_31.nim(14, 5) `big1 > big2` ")); + } + + if (!((big2_1174405124 <= big1_1174405123))) { + F.line = 208; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_31.nim(15, 5) `big1 >= big2` ")); + } + + if (!((big2_1174405124 < big1_1174405123))) { + F.line = 208; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_31.nim(16, 5) `big2 < big1` ")); + } + + if (!((big2_1174405124 <= big1_1174405123))) { + F.line = 208; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_31.nim(17, 5) `big2 <= big1` ")); + } + + if (!(!((big1_1174405123 == big2_1174405124)))) { + F.line = 208; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_31.nim(18, 5) `not (big1 == big2)` ")); + } + + F.line = 208; + var z_1174405165 = 0n; + if (!(eqStrings(HEX24__stdZjsbigints_u19(z_1174405165), [48,110]))) { + F.line = 208; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_31.nim(20, 5) `$z == \"0n\"` ")); + } + +}; +Label3: { + F.line = 208; + var a_1174405171 = [[]]; + F.line = 208; + if (a_1174405171[0].length < 2) { for (var i = a_1174405171[0].length ; i < 2 ; ++i) a_1174405171[0].push(0n); } + else { a_1174405171[0].length = 2; }; + if (!(HEX3DHEX3D__jsbigints95examples9531_u60(a_1174405171[0], [BigInt("0"), BigInt("0")]))) { + F.line = 208; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_31.nim(24, 5) `a == @[big\"0\", big\"0\"]` ")); + } + + if (!(((Temporary4 = HEX5BHEX5D__jsbigints95examples9531_u92(a_1174405171[0], 1), Temporary4)[0][Temporary4[1]] == BigInt("0")))) { + F.line = 208; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_31.nim(25, 5) `a[^1] == big\"0\"` ")); + } + + F.line = 208; + var b_1174405242 = [0n]; + if (!((b_1174405242[0] == BigInt("0")))) { + F.line = 208; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_31.nim(27, 5) `b == big\"0\"` ")); + } + + if (!((b_1174405242[0] == 0n))) { + F.line = 208; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_31.nim(28, 5) `b == JsBigInt.default` ")); + } + +}; +framePtr = F.prev; +var F = {procname: "module jsbigints_examples_31", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_31.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; diff --git a/nimcache/runnableExamples/jsbigints_group0_examples.nim b/nimcache/runnableExamples/jsbigints_group0_examples.nim new file mode 100644 index 0000000000000..0f427bbca4f88 --- /dev/null +++ b/nimcache/runnableExamples/jsbigints_group0_examples.nim @@ -0,0 +1,34 @@ +# autogenerated by docgen +# source: /home/runner/work/Nim/Nim/lib/std/jsbigints.nim +# rdoccmd: +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_1.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_2.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_3.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_4.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_5.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_6.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_7.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_8.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_9.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_10.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_11.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_12.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_13.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_14.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_15.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_16.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_17.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_18.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_19.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_20.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_21.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_22.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_23.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_24.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_25.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_26.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_27.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_28.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_29.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_30.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsbigints_examples_31.nim" diff --git a/nimcache/runnableExamples/jsconsole_examples_1.nim b/nimcache/runnableExamples/jsconsole_examples_1.nim new file mode 100644 index 0000000000000..9789a1478647f --- /dev/null +++ b/nimcache/runnableExamples/jsconsole_examples_1.nim @@ -0,0 +1,11 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/jsconsole.nim(21, 17) +rdoccmd: -r:off +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/jsconsole.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/jsconsole.nim", 21, 17).}: + console.log "%c My Debug Message", "color: red" # Notice the "%c" + console.log "%c My Debug %c Message", "color: red", "font-size: 2em" + diff --git a/nimcache/runnableExamples/jsconsole_examples_2.nim b/nimcache/runnableExamples/jsconsole_examples_2.nim new file mode 100644 index 0000000000000..4a73daa081b8e --- /dev/null +++ b/nimcache/runnableExamples/jsconsole_examples_2.nim @@ -0,0 +1,13 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/jsconsole.nim(101, 5) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/jsconsole.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/jsconsole.nim", 101, 5).}: + console.jsAssert(42 == 42) # OK + console.jsAssert(42 != 42) # Fail, prints "Assertion failed" and continues + console.jsAssert('`' == '\n' and '\t' == '\0') # Message correctly formatted + assert 42 == 42 # Normal assertions keep working + diff --git a/nimcache/runnableExamples/jsconsole_group0_examples.js b/nimcache/runnableExamples/jsconsole_group0_examples.js new file mode 100644 index 0000000000000..9404df2ae554c --- /dev/null +++ b/nimcache/runnableExamples/jsconsole_group0_examples.js @@ -0,0 +1,27 @@ +/* Generated by the Nim Compiler v2.2.1 */ +var framePtr = null; +var excHandler = 0; +var lastJSError = null; +var F = {procname: "module jsconsole", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsconsole.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsconsole", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsconsole.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsconsole_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsconsole_examples_1.nim", line: 0}; +framePtr = F; +F.line = 21; +F.filename = "jsconsole.nim"; +console.log("%c My Debug Message", "color: red"); +F.line = 21; +console.log("%c My Debug %c Message", "color: red", "font-size: 2em"); +framePtr = F.prev; +var F = {procname: "module jsconsole_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsconsole_examples_1.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsconsole_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsconsole_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsconsole_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsconsole_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; diff --git a/nimcache/runnableExamples/jsconsole_group0_examples.nim b/nimcache/runnableExamples/jsconsole_group0_examples.nim new file mode 100644 index 0000000000000..0fd001d8615f2 --- /dev/null +++ b/nimcache/runnableExamples/jsconsole_group0_examples.nim @@ -0,0 +1,4 @@ +# autogenerated by docgen +# source: /home/runner/work/Nim/Nim/lib/js/jsconsole.nim +# rdoccmd: -r:off +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsconsole_examples_1.nim" diff --git a/nimcache/runnableExamples/jsconsole_group1_examples.js b/nimcache/runnableExamples/jsconsole_group1_examples.js new file mode 100644 index 0000000000000..7e59fdcb0a981 --- /dev/null +++ b/nimcache/runnableExamples/jsconsole_group1_examples.js @@ -0,0 +1,705 @@ +/* Generated by the Nim Compiler v2.2.1 */ +var framePtr = null; +var excHandler = 0; +var lastJSError = null; +var NTI134217749 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217751 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217741 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217743 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554435 = {size: 0,kind: 31,base: null,node: null,finalizer: null}; +var NTI33555836 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI33555167 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555175 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554450 = {size: 0,kind: 29,base: null,node: null,finalizer: null}; +var NTI33555174 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33555171 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555172 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217745 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554449 = {size: 0,kind: 28,base: null,node: null,finalizer: null}; +var NNI134217745 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217745.node = NNI134217745; +var NNI33555172 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555172.node = NNI33555172; +NTI33555174.base = NTI33555171; +NTI33555175.base = NTI33555171; +var NNI33555171 = {kind: 2, len: 5, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "parent", len: 0, typ: NTI33555174, name: "parent", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}, +{kind: 1, offset: "message", len: 0, typ: NTI33554449, name: "msg", sons: null}, +{kind: 1, offset: "trace", len: 0, typ: NTI33554449, name: "trace", sons: null}, +{kind: 1, offset: "up", len: 0, typ: NTI33555175, name: "up", sons: null}]}; +NTI33555171.node = NNI33555171; +var NNI33555167 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555167.node = NNI33555167; +NTI33555171.base = NTI33555167; +NTI33555172.base = NTI33555171; +NTI134217745.base = NTI33555172; +var NNI33555836 = {kind: 2, len: 3, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "Field0", len: 0, typ: NTI33554450, name: "Field0", sons: null}, +{kind: 1, offset: "Field1", len: 0, typ: NTI33554435, name: "Field1", sons: null}, +{kind: 1, offset: "Field2", len: 0, typ: NTI33554450, name: "Field2", sons: null}]}; +NTI33555836.node = NNI33555836; +var NNI134217743 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217743.node = NNI134217743; +var NNI134217741 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217741.node = NNI134217741; +NTI134217741.base = NTI33555172; +NTI134217743.base = NTI134217741; +var NNI134217751 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217751.node = NNI134217751; +NTI134217751.base = NTI33555172; +var NNI134217749 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217749.node = NNI134217749; +NTI134217749.base = NTI33555172; + +function setConstr() { + var result = {}; + for (var i = 0; i < arguments.length; ++i) { + var x = arguments[i]; + if (typeof(x) == "object") { + for (var j = x[0]; j <= x[1]; ++j) { + result[j] = true; + } + } else { + result[x] = true; + } + } + return result; + + + +} +var ConstSet1 = setConstr(17, 16, 4, 18, 27, 19, 23, 22, 21); + +function nimCopy(dest_p0, src_p1, ti_p2) { + var result_33557321 = null; + + switch (ti_p2.kind) { + case 21: + case 22: + case 23: + case 5: + if (!(isFatPointer__system_u2869(ti_p2))) { + result_33557321 = src_p1; + } + else { + result_33557321 = [src_p1[0], src_p1[1]]; + } + + break; + case 19: + if (dest_p0 === null || dest_p0 === undefined) { + dest_p0 = {}; + } + else { + for (var key in dest_p0) { delete dest_p0[key]; } + } + for (var key in src_p1) { dest_p0[key] = src_p1[key]; } + result_33557321 = dest_p0; + + break; + case 18: + case 17: + if (!((ti_p2.base == null))) { + result_33557321 = nimCopy(dest_p0, src_p1, ti_p2.base); + } + else { + if ((ti_p2.kind == 17)) { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {m_type: ti_p2} : dest_p0; + } + else { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {} : dest_p0; + } + } + nimCopyAux(result_33557321, src_p1, ti_p2.node); + break; + case 4: + case 16: + if(ArrayBuffer.isView(src_p1)) { + if(dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new src_p1.constructor(src_p1); + } else { + dest_p0.set(src_p1, 0); + } + result_33557321 = dest_p0; + } else { + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + } + + break; + case 24: + case 27: + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + + break; + case 28: + if (src_p1 !== null) { + result_33557321 = src_p1.slice(0); + } + + break; + default: + result_33557321 = src_p1; + break; + } + + return result_33557321; + +} + +function arrayConstr(len_p0, value_p1, typ_p2) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; ++i) result[i] = nimCopy(null, value_p1, typ_p2); + return result; + + + +} + +function mnewString(len_p0) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; i++) {result[i] = 0;} + return result; + + + +} + +function addInt(a_p0, b_p1) { + var result = a_p0 + b_p1; + checkOverflowInt(result); + return result; + + + +} + +function chckRange(i_p0, a_p1, b_p2) { + var result_33557361 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557361 = i_p0; + break BeforeRet; + } + else { + raiseRangeError(); + } + + }; + + return result_33557361; + +} + +function chckIndx(i_p0, a_p1, b_p2) { + var result_33557356 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557356 = i_p0; + break BeforeRet; + } + else { + raiseIndexError(i_p0, a_p1, b_p2); + } + + }; + + return result_33557356; + +} + +function cstrToNimstr(c_p0) { + var ln = c_p0.length; + var result = new Array(ln); + var r = 0; + for (var i = 0; i < ln; ++i) { + var ch = c_p0.charCodeAt(i); + + if (ch < 128) { + result[r] = ch; + } + else { + if (ch < 2048) { + result[r] = (ch >> 6) | 192; + } + else { + if (ch < 55296 || ch >= 57344) { + result[r] = (ch >> 12) | 224; + } + else { + ++i; + ch = 65536 + (((ch & 1023) << 10) | (c_p0.charCodeAt(i) & 1023)); + result[r] = (ch >> 18) | 240; + ++r; + result[r] = ((ch >> 12) & 63) | 128; + } + ++r; + result[r] = ((ch >> 6) & 63) | 128; + } + ++r; + result[r] = (ch & 63) | 128; + } + ++r; + } + return result; + + + +} + +function toJSStr(s_p0) { + var result_33556910 = null; + + var res_33556964 = newSeq__system_u2507((s_p0).length); + var i_33556965 = 0; + var j_33556966 = 0; + Label1: { + Label2: while (true) { + if (!(i_33556965 < (s_p0).length)) break Label2; + var c_33556967 = s_p0[i_33556965]; + if ((c_33556967 < 128)) { + res_33556964[j_33556966] = String.fromCharCode(c_33556967); + i_33556965 += 1; + } + else { + var helper_33556993 = newSeq__system_u2507(0); + Label3: { + Label4: while (true) { + if (!true) break Label4; + var code_33556994 = c_33556967.toString(16); + if ((((code_33556994) == null ? 0 : (code_33556994).length) == 1)) { + helper_33556993.push("%0");; + } + else { + helper_33556993.push("%");; + } + + helper_33556993.push(code_33556994);; + i_33556965 += 1; + if ((((s_p0).length <= i_33556965) || (s_p0[i_33556965] < 128))) { + break Label3; + } + + c_33556967 = s_p0[i_33556965]; + } + }; +++excHandler; + try { + res_33556964[j_33556966] = decodeURIComponent(helper_33556993.join("")); +--excHandler; +} catch (EXCEPTION) { + var prevJSError = lastJSError; + lastJSError = EXCEPTION; + --excHandler; + res_33556964[j_33556966] = helper_33556993.join(""); + lastJSError = prevJSError; + } finally { + } + } + + j_33556966 += 1; + } + }; + if (res_33556964.length < j_33556966) { for (var i = res_33556964.length ; i < j_33556966 ; ++i) res_33556964.push(null); } + else { res_33556964.length = j_33556966; }; + result_33556910 = res_33556964.join(""); + + return result_33556910; + +} + +function raiseException(e_p0, ename_p1) { + e_p0.name = ename_p1; + if ((excHandler == 0)) { + unhandledException(e_p0); + } + + e_p0.trace = nimCopy(null, rawWriteStackTrace__system_u2180(), NTI33554449); + throw e_p0; + + +} + +function makeNimstrLit(c_p0) { + var result = []; + for (var i = 0; i < c_p0.length; ++i) { + result[i] = c_p0.charCodeAt(i); + } + return result; + + + +} +var F = {procname: "module jsconsole", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsconsole.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsconsole", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsconsole.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function isFatPointer__system_u2869(ti_p0) { + var result_33557303 = false; + + BeforeRet: { + result_33557303 = !((ConstSet1[ti_p0.base.kind] != undefined)); + break BeforeRet; + }; + + return result_33557303; + +} + +function nimCopyAux(dest_p0, src_p1, n_p2) { + switch (n_p2.kind) { + case 0: + break; + case 1: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + + break; + case 2: + for (var i = 0; i < n_p2.sons.length; i++) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i]); + } + + break; + case 3: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + for (var i = 0; i < n_p2.sons.length; ++i) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i][1]); + } + + break; + } + + +} + +function add__system_u1942(x_p0, x_p0_Idx, y_p1) { + if (x_p0[x_p0_Idx] === null) { x_p0[x_p0_Idx] = []; } + var off = x_p0[x_p0_Idx].length; + x_p0[x_p0_Idx].length += y_p1.length; + for (var i = 0; i < y_p1.length; ++i) { + x_p0[x_p0_Idx][off+i] = y_p1.charCodeAt(i); + } + + + +} + +function raiseOverflow() { + raiseException({message: [111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119], parent: null, m_type: NTI134217743, name: null, trace: [], up: null}, "OverflowDefect"); + + +} + +function checkOverflowInt(a_p0) { + if (a_p0 > 2147483647 || a_p0 < -2147483648) raiseOverflow(); + + + +} + +function raiseRangeError() { + raiseException({message: [118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101], parent: null, m_type: NTI134217751, name: null, trace: [], up: null}, "RangeDefect"); + + +} + +function raiseIndexError(i_p0, a_p1, b_p2) { + var Temporary1; + + if ((b_p2 < a_p1)) { + Temporary1 = [105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]; + } + else { + Temporary1 = ([105,110,100,101,120,32]).concat(HEX24__systemZdollars_u8(i_p0),[32,110,111,116,32,105,110,32],HEX24__systemZdollars_u8(a_p1),[32,46,46,32],HEX24__systemZdollars_u8(b_p2)); + } + + raiseException({message: nimCopy(null, Temporary1, NTI33554449), parent: null, m_type: NTI134217749, name: null, trace: [], up: null}, "IndexDefect"); + + +} + +function addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, start_p2, n_p3) { + var Temporary1; + + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 44; + F.filename = "digitsutils.nim"; + var old_301990096 = (result_p0[result_p0_Idx]).length; + F.line = 45; + if (result_p0[result_p0_Idx].length < (Temporary1 = chckRange(addInt(old_301990096, n_p3), 0, 2147483647), Temporary1)) { for (var i = result_p0[result_p0_Idx].length; i < Temporary1; ++i) result_p0[result_p0_Idx].push(0); } + else {result_p0[result_p0_Idx].length = Temporary1; }; + Label2: { + F.line = 47; + var iHEX60gensym4_301990110 = 0; + F.line = 128; + F.filename = "iterators_1.nim"; + var i_654311460 = 0; + Label3: { + F.line = 129; + Label4: while (true) { + if (!(i_654311460 < n_p3)) break Label4; + F.line = 50; + F.filename = "digitsutils.nim"; + iHEX60gensym4_301990110 = i_654311460; + F.line = 47; + result_p0[result_p0_Idx][chckIndx(addInt(old_301990096, iHEX60gensym4_301990110), 0, (result_p0[result_p0_Idx]).length - 1)] = x_p1.charCodeAt(chckIndx(addInt(start_p2, iHEX60gensym4_301990110), 0, (x_p1).length - 1)); + F.line = 131; + F.filename = "iterators_1.nim"; + i_654311460 = addInt(i_654311460, 1); + } + }; + }; + framePtr = F.prev; + + +} + +function addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 56; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, 0, ((x_p1) == null ? 0 : (x_p1).length)); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 112; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, ((x_p1) + "")); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u241(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 116; + F.filename = "digitsutils.nim"; + addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, BigInt(x_p1)); + framePtr = F.prev; + + +} + +function HEX24__systemZdollars_u8(x_p0) { + var result_369098762 = [[]]; + + var F = {procname: "dollars.$", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/dollars.nim", line: 0}; + framePtr = F; + F.line = 18; + F.filename = "dollars.nim"; + addInt__stdZprivateZdigitsutils_u241(result_369098762, 0, x_p0); + framePtr = F.prev; + + return result_369098762[0]; + +} + +function auxWriteStackTrace__system_u2084(f_p0) { + var result_33556518 = [[]]; + + var it_33556526 = f_p0; + var i_33556527 = 0; + var total_33556528 = 0; + var tempFrames_33556529 = arrayConstr(64, {Field0: null, Field1: 0, Field2: null}, NTI33555836); + Label1: { + Label2: while (true) { + if (!(!((it_33556526 == null)) && (i_33556527 <= 63))) break Label2; + tempFrames_33556529[i_33556527].Field0 = it_33556526.procname; + tempFrames_33556529[i_33556527].Field1 = it_33556526.line; + tempFrames_33556529[i_33556527].Field2 = it_33556526.filename; + i_33556527 += 1; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + Label3: { + Label4: while (true) { + if (!!((it_33556526 == null))) break Label4; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + result_33556518[0] = nimCopy(null, [], NTI33554449); + if (!((total_33556528 == i_33556527))) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + result_33556518[0].push.apply(result_33556518[0], HEX24__systemZdollars_u8((total_33556528 - i_33556527)));; + result_33556518[0].push.apply(result_33556518[0], [32,99,97,108,108,115,32,111,109,105,116,116,101,100,41,32,46,46,46,10]);; + } + + Label5: { + var j_33556562 = 0; + var colontmp__654311452 = 0; + colontmp__654311452 = (i_33556527 - 1); + var res_654311454 = colontmp__654311452; + Label6: { + Label7: while (true) { + if (!(0 <= res_654311454)) break Label7; + j_33556562 = res_654311454; + result_33556518[0].push.apply(result_33556518[0], cstrToNimstr(tempFrames_33556529[j_33556562].Field2));; + if ((0 < tempFrames_33556529[j_33556562].Field1)) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, tempFrames_33556529[j_33556562].Field1); + if (false) { + result_33556518[0].push.apply(result_33556518[0], [44,32]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, 0); + } + + result_33556518[0].push.apply(result_33556518[0], [41]);; + } + + result_33556518[0].push.apply(result_33556518[0], [32,97,116,32]);; + add__system_u1942(result_33556518, 0, tempFrames_33556529[j_33556562].Field0); + result_33556518[0].push.apply(result_33556518[0], [10]);; + res_654311454 -= 1; + } + }; + }; + + return result_33556518[0]; + +} + +function rawWriteStackTrace__system_u2180() { + var result_33556613 = []; + + if (!((framePtr == null))) { + result_33556613 = nimCopy(null, ([84,114,97,99,101,98,97,99,107,32,40,109,111,115,116,32,114,101,99,101,110,116,32,99,97,108,108,32,108,97,115,116,41,10]).concat(auxWriteStackTrace__system_u2084(framePtr)), NTI33554449); + } + else { + result_33556613 = nimCopy(null, [78,111,32,115,116,97,99,107,32,116,114,97,99,101,98,97,99,107,32,97,118,97,105,108,97,98,108,101,10], NTI33554449); + } + + + return result_33556613; + +} + +function newSeq__system_u2507(len_p0) { + var result_33556943 = []; + + var F = {procname: "newSeq.newSeq", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system.nim", line: 0}; + framePtr = F; + F.line = 653; + F.filename = "system.nim"; + result_33556943 = new Array(len_p0); for (var i = 0 ; i < len_p0 ; ++i) { result_33556943[i] = null; } framePtr = F.prev; + + return result_33556943; + +} + +function unhandledException(e_p0) { + var buf_33556658 = [[]]; + if (!(((e_p0.message).length == 0))) { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32]);; + buf_33556658[0].push.apply(buf_33556658[0], e_p0.message);; + } + else { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110]);; + } + + buf_33556658[0].push.apply(buf_33556658[0], [32,91]);; + add__system_u1942(buf_33556658, 0, e_p0.name); + buf_33556658[0].push.apply(buf_33556658[0], [93,10]);; + buf_33556658[0].push.apply(buf_33556658[0], rawWriteStackTrace__system_u2180());; + var cbuf_33556659 = toJSStr(buf_33556658[0]); + framePtr = null; + if (typeof(Error) !== "undefined") { + throw new Error(cbuf_33556659); + } + else { + throw cbuf_33556659; + } + + + +} + +function sysFatal__stdZassertions_u44(message_p1) { + var F = {procname: "sysFatal.sysFatal", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/fatal.nim", line: 0}; + framePtr = F; + F.line = 53; + F.filename = "fatal.nim"; + raiseException({message: nimCopy(null, message_p1, NTI33554449), m_type: NTI134217745, parent: null, name: null, trace: [], up: null}, "AssertionDefect"); + framePtr = F.prev; + + +} + +function raiseAssert__stdZassertions_u42(msg_p0) { + var F = {procname: "assertions.raiseAssert", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 36; + F.filename = "assertions.nim"; + sysFatal__stdZassertions_u44(msg_p0); + framePtr = F.prev; + + +} + +function failedAssertImpl__stdZassertions_u84(msg_p0) { + var F = {procname: "assertions.failedAssertImpl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 41; + F.filename = "assertions.nim"; + raiseAssert__stdZassertions_u42(msg_p0); + framePtr = F.prev; + + +} +var F = {procname: "module jsconsole_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsconsole_examples_2.nim", line: 0}; +framePtr = F; +F.line = 101; +F.filename = "jsconsole.nim"; +console.assert(true, "[jsAssert] /home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsconsole_examples_2.nim(9, 10)","42 == 42"); +F.line = 101; +console.assert(false, "[jsAssert] /home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsconsole_examples_2.nim(10, 10)","42 != 42"); +F.line = 101; +console.assert(false, "[jsAssert] /home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsconsole_examples_2.nim(11, 10)","\'`\' == \'\\n\' and \'\\t\' == \'\\x00\'"); +if (false) { +F.line = 101; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsconsole_examples_2.nim(12, 3) `42 == 42` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsconsole_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsconsole_examples_2.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsconsole_group1_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsconsole_group1_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsconsole_group1_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsconsole_group1_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; diff --git a/nimcache/runnableExamples/jsconsole_group1_examples.nim b/nimcache/runnableExamples/jsconsole_group1_examples.nim new file mode 100644 index 0000000000000..a33f27969ca0c --- /dev/null +++ b/nimcache/runnableExamples/jsconsole_group1_examples.nim @@ -0,0 +1,4 @@ +# autogenerated by docgen +# source: /home/runner/work/Nim/Nim/lib/js/jsconsole.nim +# rdoccmd: +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsconsole_examples_2.nim" diff --git a/nimcache/runnableExamples/jscore_examples_1.nim b/nimcache/runnableExamples/jscore_examples_1.nim new file mode 100644 index 0000000000000..ab70f890aa02a --- /dev/null +++ b/nimcache/runnableExamples/jscore_examples_1.nim @@ -0,0 +1,15 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/jscore.nim(133, 5) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/jscore.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/jscore.nim", 133, 5).}: + assert ['a', 'b', 'c', 'd', 'e'].copyWithin(0, 3, 4) == @['d', 'b', 'c', 'd', 'e'] + assert ['a', 'b', 'c', 'd', 'e'].copyWithin(1, 3) == @['a', 'd', 'e', 'd', 'e'] + assert [1, 2, 3, 4, 5].copyWithin(-2) == @[1, 2, 3, 1, 2] + assert [1, 2, 3, 4, 5].copyWithin(0, 3) == @[4, 5, 3, 4, 5] + assert [1, 2, 3, 4, 5].copyWithin(0, 3, 4) == @[4, 2, 3, 4, 5] + assert [1, 2, 3, 4, 5].copyWithin(-2, -3, -1) == @[1, 2, 3, 3, 4] + diff --git a/nimcache/runnableExamples/jscore_examples_2.nim b/nimcache/runnableExamples/jscore_examples_2.nim new file mode 100644 index 0000000000000..98f50baae1495 --- /dev/null +++ b/nimcache/runnableExamples/jscore_examples_2.nim @@ -0,0 +1,12 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/jscore.nim(145, 5) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/jscore.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/jscore.nim", 145, 5).}: + var arrai = @[1, 2, 3] + assert arrai.shift() == 1 + assert arrai == @[2, 3] + diff --git a/nimcache/runnableExamples/jscore_examples_3.nim b/nimcache/runnableExamples/jscore_examples_3.nim new file mode 100644 index 0000000000000..e8367f65e3b3d --- /dev/null +++ b/nimcache/runnableExamples/jscore_examples_3.nim @@ -0,0 +1,10 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/jscore.nim(153, 21) +rdoccmd: -r:off +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/jscore.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/jscore.nim", 153, 21).}: + queueMicrotask(proc() = echo "Microtask") + diff --git a/nimcache/runnableExamples/jscore_group0_examples.js b/nimcache/runnableExamples/jscore_group0_examples.js new file mode 100644 index 0000000000000..d23fe97d02fac --- /dev/null +++ b/nimcache/runnableExamples/jscore_group0_examples.js @@ -0,0 +1,894 @@ +/* Generated by the Nim Compiler v2.2.1 */ +var framePtr = null; +var excHandler = 0; +var lastJSError = null; +var NTI134217745 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217749 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217751 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554435 = {size: 0,kind: 31,base: null,node: null,finalizer: null}; +var NTI33555836 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI33555167 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555175 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554449 = {size: 0,kind: 28,base: null,node: null,finalizer: null}; +var NTI33554450 = {size: 0,kind: 29,base: null,node: null,finalizer: null}; +var NTI33555174 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33555171 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555172 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217741 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217743 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NNI134217743 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217743.node = NNI134217743; +var NNI134217741 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217741.node = NNI134217741; +var NNI33555172 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555172.node = NNI33555172; +NTI33555174.base = NTI33555171; +NTI33555175.base = NTI33555171; +var NNI33555171 = {kind: 2, len: 5, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "parent", len: 0, typ: NTI33555174, name: "parent", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}, +{kind: 1, offset: "message", len: 0, typ: NTI33554449, name: "msg", sons: null}, +{kind: 1, offset: "trace", len: 0, typ: NTI33554449, name: "trace", sons: null}, +{kind: 1, offset: "up", len: 0, typ: NTI33555175, name: "up", sons: null}]}; +NTI33555171.node = NNI33555171; +var NNI33555167 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555167.node = NNI33555167; +NTI33555171.base = NTI33555167; +NTI33555172.base = NTI33555171; +NTI134217741.base = NTI33555172; +NTI134217743.base = NTI134217741; +var NNI33555836 = {kind: 2, len: 3, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "Field0", len: 0, typ: NTI33554450, name: "Field0", sons: null}, +{kind: 1, offset: "Field1", len: 0, typ: NTI33554435, name: "Field1", sons: null}, +{kind: 1, offset: "Field2", len: 0, typ: NTI33554450, name: "Field2", sons: null}]}; +NTI33555836.node = NNI33555836; +var NNI134217751 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217751.node = NNI134217751; +NTI134217751.base = NTI33555172; +var NNI134217749 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217749.node = NNI134217749; +NTI134217749.base = NTI33555172; +var NNI134217745 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217745.node = NNI134217745; +NTI134217745.base = NTI33555172; + +function arrayConstr(len_p0, value_p1, typ_p2) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; ++i) result[i] = nimCopy(null, value_p1, typ_p2); + return result; + + + +} + +function setConstr() { + var result = {}; + for (var i = 0; i < arguments.length; ++i) { + var x = arguments[i]; + if (typeof(x) == "object") { + for (var j = x[0]; j <= x[1]; ++j) { + result[j] = true; + } + } else { + result[x] = true; + } + } + return result; + + + +} +var ConstSet1 = setConstr(17, 16, 4, 18, 27, 19, 23, 22, 21); + +function nimCopy(dest_p0, src_p1, ti_p2) { + var result_33557321 = null; + + switch (ti_p2.kind) { + case 21: + case 22: + case 23: + case 5: + if (!(isFatPointer__system_u2869(ti_p2))) { + result_33557321 = src_p1; + } + else { + result_33557321 = [src_p1[0], src_p1[1]]; + } + + break; + case 19: + if (dest_p0 === null || dest_p0 === undefined) { + dest_p0 = {}; + } + else { + for (var key in dest_p0) { delete dest_p0[key]; } + } + for (var key in src_p1) { dest_p0[key] = src_p1[key]; } + result_33557321 = dest_p0; + + break; + case 18: + case 17: + if (!((ti_p2.base == null))) { + result_33557321 = nimCopy(dest_p0, src_p1, ti_p2.base); + } + else { + if ((ti_p2.kind == 17)) { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {m_type: ti_p2} : dest_p0; + } + else { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {} : dest_p0; + } + } + nimCopyAux(result_33557321, src_p1, ti_p2.node); + break; + case 4: + case 16: + if(ArrayBuffer.isView(src_p1)) { + if(dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new src_p1.constructor(src_p1); + } else { + dest_p0.set(src_p1, 0); + } + result_33557321 = dest_p0; + } else { + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + } + + break; + case 24: + case 27: + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + + break; + case 28: + if (src_p1 !== null) { + result_33557321 = src_p1.slice(0); + } + + break; + default: + result_33557321 = src_p1; + break; + } + + return result_33557321; + +} + +function mnewString(len_p0) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; i++) {result[i] = 0;} + return result; + + + +} + +function addInt(a_p0, b_p1) { + var result = a_p0 + b_p1; + checkOverflowInt(result); + return result; + + + +} + +function chckRange(i_p0, a_p1, b_p2) { + var result_33557361 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557361 = i_p0; + break BeforeRet; + } + else { + raiseRangeError(); + } + + }; + + return result_33557361; + +} + +function chckIndx(i_p0, a_p1, b_p2) { + var result_33557356 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557356 = i_p0; + break BeforeRet; + } + else { + raiseIndexError(i_p0, a_p1, b_p2); + } + + }; + + return result_33557356; + +} + +function cstrToNimstr(c_p0) { + var ln = c_p0.length; + var result = new Array(ln); + var r = 0; + for (var i = 0; i < ln; ++i) { + var ch = c_p0.charCodeAt(i); + + if (ch < 128) { + result[r] = ch; + } + else { + if (ch < 2048) { + result[r] = (ch >> 6) | 192; + } + else { + if (ch < 55296 || ch >= 57344) { + result[r] = (ch >> 12) | 224; + } + else { + ++i; + ch = 65536 + (((ch & 1023) << 10) | (c_p0.charCodeAt(i) & 1023)); + result[r] = (ch >> 18) | 240; + ++r; + result[r] = ((ch >> 12) & 63) | 128; + } + ++r; + result[r] = ((ch >> 6) & 63) | 128; + } + ++r; + result[r] = (ch & 63) | 128; + } + ++r; + } + return result; + + + +} + +function toJSStr(s_p0) { + var result_33556910 = null; + + var res_33556964 = newSeq__system_u2507((s_p0).length); + var i_33556965 = 0; + var j_33556966 = 0; + Label1: { + Label2: while (true) { + if (!(i_33556965 < (s_p0).length)) break Label2; + var c_33556967 = s_p0[i_33556965]; + if ((c_33556967 < 128)) { + res_33556964[j_33556966] = String.fromCharCode(c_33556967); + i_33556965 += 1; + } + else { + var helper_33556993 = newSeq__system_u2507(0); + Label3: { + Label4: while (true) { + if (!true) break Label4; + var code_33556994 = c_33556967.toString(16); + if ((((code_33556994) == null ? 0 : (code_33556994).length) == 1)) { + helper_33556993.push("%0");; + } + else { + helper_33556993.push("%");; + } + + helper_33556993.push(code_33556994);; + i_33556965 += 1; + if ((((s_p0).length <= i_33556965) || (s_p0[i_33556965] < 128))) { + break Label3; + } + + c_33556967 = s_p0[i_33556965]; + } + }; +++excHandler; + try { + res_33556964[j_33556966] = decodeURIComponent(helper_33556993.join("")); +--excHandler; +} catch (EXCEPTION) { + var prevJSError = lastJSError; + lastJSError = EXCEPTION; + --excHandler; + res_33556964[j_33556966] = helper_33556993.join(""); + lastJSError = prevJSError; + } finally { + } + } + + j_33556966 += 1; + } + }; + if (res_33556964.length < j_33556966) { for (var i = res_33556964.length ; i < j_33556966 ; ++i) res_33556964.push(null); } + else { res_33556964.length = j_33556966; }; + result_33556910 = res_33556964.join(""); + + return result_33556910; + +} + +function raiseException(e_p0, ename_p1) { + e_p0.name = ename_p1; + if ((excHandler == 0)) { + unhandledException(e_p0); + } + + e_p0.trace = nimCopy(null, rawWriteStackTrace__system_u2180(), NTI33554449); + throw e_p0; + + +} + +function subInt(a_p0, b_p1) { + var result = a_p0 - b_p1; + checkOverflowInt(result); + return result; + + + +} + +function makeNimstrLit(c_p0) { + var result = []; + for (var i = 0; i < c_p0.length; ++i) { + result[i] = c_p0.charCodeAt(i); + } + return result; + + + +} +var F = {procname: "module jsbigints", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jscore", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jscore.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jscore", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jscore.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function add__system_u1942(x_p0, x_p0_Idx, y_p1) { + if (x_p0[x_p0_Idx] === null) { x_p0[x_p0_Idx] = []; } + var off = x_p0[x_p0_Idx].length; + x_p0[x_p0_Idx].length += y_p1.length; + for (var i = 0; i < y_p1.length; ++i) { + x_p0[x_p0_Idx][off+i] = y_p1.charCodeAt(i); + } + + + +} + +function isFatPointer__system_u2869(ti_p0) { + var result_33557303 = false; + + BeforeRet: { + result_33557303 = !((ConstSet1[ti_p0.base.kind] != undefined)); + break BeforeRet; + }; + + return result_33557303; + +} + +function nimCopyAux(dest_p0, src_p1, n_p2) { + switch (n_p2.kind) { + case 0: + break; + case 1: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + + break; + case 2: + for (var i = 0; i < n_p2.sons.length; i++) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i]); + } + + break; + case 3: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + for (var i = 0; i < n_p2.sons.length; ++i) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i][1]); + } + + break; + } + + +} + +function raiseRangeError() { + raiseException({message: [118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101], parent: null, m_type: NTI134217751, name: null, trace: [], up: null}, "RangeDefect"); + + +} + +function raiseIndexError(i_p0, a_p1, b_p2) { + var Temporary1; + + if ((b_p2 < a_p1)) { + Temporary1 = [105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]; + } + else { + Temporary1 = ([105,110,100,101,120,32]).concat(HEX24__systemZdollars_u8(i_p0),[32,110,111,116,32,105,110,32],HEX24__systemZdollars_u8(a_p1),[32,46,46,32],HEX24__systemZdollars_u8(b_p2)); + } + + raiseException({message: nimCopy(null, Temporary1, NTI33554449), parent: null, m_type: NTI134217749, name: null, trace: [], up: null}, "IndexDefect"); + + +} + +function addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, start_p2, n_p3) { + var Temporary1; + + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 44; + F.filename = "digitsutils.nim"; + var old_301990096 = (result_p0[result_p0_Idx]).length; + F.line = 45; + if (result_p0[result_p0_Idx].length < (Temporary1 = chckRange(addInt(old_301990096, n_p3), 0, 2147483647), Temporary1)) { for (var i = result_p0[result_p0_Idx].length; i < Temporary1; ++i) result_p0[result_p0_Idx].push(0); } + else {result_p0[result_p0_Idx].length = Temporary1; }; + Label2: { + F.line = 47; + var iHEX60gensym4_301990110 = 0; + F.line = 128; + F.filename = "iterators_1.nim"; + var i_654311680 = 0; + Label3: { + F.line = 129; + Label4: while (true) { + if (!(i_654311680 < n_p3)) break Label4; + F.line = 50; + F.filename = "digitsutils.nim"; + iHEX60gensym4_301990110 = i_654311680; + F.line = 47; + result_p0[result_p0_Idx][chckIndx(addInt(old_301990096, iHEX60gensym4_301990110), 0, (result_p0[result_p0_Idx]).length - 1)] = x_p1.charCodeAt(chckIndx(addInt(start_p2, iHEX60gensym4_301990110), 0, (x_p1).length - 1)); + F.line = 131; + F.filename = "iterators_1.nim"; + i_654311680 = addInt(i_654311680, 1); + } + }; + }; + framePtr = F.prev; + + +} + +function addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 56; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, 0, ((x_p1) == null ? 0 : (x_p1).length)); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 112; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, ((x_p1) + "")); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u241(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 116; + F.filename = "digitsutils.nim"; + addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, BigInt(x_p1)); + framePtr = F.prev; + + +} + +function HEX24__systemZdollars_u8(x_p0) { + var result_369098762 = [[]]; + + var F = {procname: "dollars.$", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/dollars.nim", line: 0}; + framePtr = F; + F.line = 18; + F.filename = "dollars.nim"; + addInt__stdZprivateZdigitsutils_u241(result_369098762, 0, x_p0); + framePtr = F.prev; + + return result_369098762[0]; + +} + +function auxWriteStackTrace__system_u2084(f_p0) { + var result_33556518 = [[]]; + + var it_33556526 = f_p0; + var i_33556527 = 0; + var total_33556528 = 0; + var tempFrames_33556529 = arrayConstr(64, {Field0: null, Field1: 0, Field2: null}, NTI33555836); + Label1: { + Label2: while (true) { + if (!(!((it_33556526 == null)) && (i_33556527 <= 63))) break Label2; + tempFrames_33556529[i_33556527].Field0 = it_33556526.procname; + tempFrames_33556529[i_33556527].Field1 = it_33556526.line; + tempFrames_33556529[i_33556527].Field2 = it_33556526.filename; + i_33556527 += 1; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + Label3: { + Label4: while (true) { + if (!!((it_33556526 == null))) break Label4; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + result_33556518[0] = nimCopy(null, [], NTI33554449); + if (!((total_33556528 == i_33556527))) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + result_33556518[0].push.apply(result_33556518[0], HEX24__systemZdollars_u8((total_33556528 - i_33556527)));; + result_33556518[0].push.apply(result_33556518[0], [32,99,97,108,108,115,32,111,109,105,116,116,101,100,41,32,46,46,46,10]);; + } + + Label5: { + var j_33556562 = 0; + var colontmp__654311672 = 0; + colontmp__654311672 = (i_33556527 - 1); + var res_654311674 = colontmp__654311672; + Label6: { + Label7: while (true) { + if (!(0 <= res_654311674)) break Label7; + j_33556562 = res_654311674; + result_33556518[0].push.apply(result_33556518[0], cstrToNimstr(tempFrames_33556529[j_33556562].Field2));; + if ((0 < tempFrames_33556529[j_33556562].Field1)) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, tempFrames_33556529[j_33556562].Field1); + if (false) { + result_33556518[0].push.apply(result_33556518[0], [44,32]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, 0); + } + + result_33556518[0].push.apply(result_33556518[0], [41]);; + } + + result_33556518[0].push.apply(result_33556518[0], [32,97,116,32]);; + add__system_u1942(result_33556518, 0, tempFrames_33556529[j_33556562].Field0); + result_33556518[0].push.apply(result_33556518[0], [10]);; + res_654311674 -= 1; + } + }; + }; + + return result_33556518[0]; + +} + +function rawWriteStackTrace__system_u2180() { + var result_33556613 = []; + + if (!((framePtr == null))) { + result_33556613 = nimCopy(null, ([84,114,97,99,101,98,97,99,107,32,40,109,111,115,116,32,114,101,99,101,110,116,32,99,97,108,108,32,108,97,115,116,41,10]).concat(auxWriteStackTrace__system_u2084(framePtr)), NTI33554449); + } + else { + result_33556613 = nimCopy(null, [78,111,32,115,116,97,99,107,32,116,114,97,99,101,98,97,99,107,32,97,118,97,105,108,97,98,108,101,10], NTI33554449); + } + + + return result_33556613; + +} + +function newSeq__system_u2507(len_p0) { + var result_33556943 = []; + + var F = {procname: "newSeq.newSeq", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system.nim", line: 0}; + framePtr = F; + F.line = 653; + F.filename = "system.nim"; + result_33556943 = new Array(len_p0); for (var i = 0 ; i < len_p0 ; ++i) { result_33556943[i] = null; } framePtr = F.prev; + + return result_33556943; + +} + +function unhandledException(e_p0) { + var buf_33556658 = [[]]; + if (!(((e_p0.message).length == 0))) { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32]);; + buf_33556658[0].push.apply(buf_33556658[0], e_p0.message);; + } + else { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110]);; + } + + buf_33556658[0].push.apply(buf_33556658[0], [32,91]);; + add__system_u1942(buf_33556658, 0, e_p0.name); + buf_33556658[0].push.apply(buf_33556658[0], [93,10]);; + buf_33556658[0].push.apply(buf_33556658[0], rawWriteStackTrace__system_u2180());; + var cbuf_33556659 = toJSStr(buf_33556658[0]); + framePtr = null; + if (typeof(Error) !== "undefined") { + throw new Error(cbuf_33556659); + } + else { + throw cbuf_33556659; + } + + + +} + +function raiseOverflow() { + raiseException({message: [111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119], parent: null, m_type: NTI134217743, name: null, trace: [], up: null}, "OverflowDefect"); + + +} + +function checkOverflowInt(a_p0) { + if (a_p0 > 2147483647 || a_p0 < -2147483648) raiseOverflow(); + + + +} + +function HEX3DHEX3D__jscore95examples951_u14(x_p0, y_p1) { + var result_654311442 = false; + + var F = {procname: "==.==", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/comparisons.nim", line: 0}; + framePtr = F; + BeforeRet: { + F.line = 326; + F.filename = "comparisons.nim"; + var sameObject_654311450 = false; + F.line = 327; + sameObject_654311450 = x_p0 === y_p1; + if (sameObject_654311450) { + F.line = 328; + result_654311442 = true; + break BeforeRet; + } + + if (!(((x_p0).length == (y_p1).length))) { + F.line = 331; + result_654311442 = false; + break BeforeRet; + } + + Label1: { + F.line = 333; + var i_654311464 = 0; + F.line = 81; + F.filename = "iterators_1.nim"; + var colontmp__654311665 = 0; + F.line = 333; + F.filename = "comparisons.nim"; + colontmp__654311665 = subInt((x_p0).length, 1); + F.line = 96; + F.filename = "iterators_1.nim"; + var res_654311667 = 0; + Label2: { + F.line = 97; + Label3: while (true) { + if (!(res_654311667 <= colontmp__654311665)) break Label3; + F.line = 333; + F.filename = "comparisons.nim"; + i_654311464 = res_654311667; + if (!((x_p0[chckIndx(i_654311464, 0, (x_p0).length - 1)] == y_p1[chckIndx(i_654311464, 0, (y_p1).length - 1)]))) { + F.line = 335; + result_654311442 = false; + break BeforeRet; + } + + F.line = 102; + F.filename = "iterators_1.nim"; + res_654311667 = addInt(res_654311667, 1); + } + }; + }; + F.line = 337; + F.filename = "comparisons.nim"; + result_654311442 = true; + break BeforeRet; + }; + framePtr = F.prev; + + return result_654311442; + +} + +function sysFatal__stdZassertions_u44(message_p1) { + var F = {procname: "sysFatal.sysFatal", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/fatal.nim", line: 0}; + framePtr = F; + F.line = 53; + F.filename = "fatal.nim"; + raiseException({message: nimCopy(null, message_p1, NTI33554449), m_type: NTI134217745, parent: null, name: null, trace: [], up: null}, "AssertionDefect"); + framePtr = F.prev; + + +} + +function raiseAssert__stdZassertions_u42(msg_p0) { + var F = {procname: "assertions.raiseAssert", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 36; + F.filename = "assertions.nim"; + sysFatal__stdZassertions_u44(msg_p0); + framePtr = F.prev; + + +} + +function failedAssertImpl__stdZassertions_u84(msg_p0) { + var F = {procname: "assertions.failedAssertImpl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 41; + F.filename = "assertions.nim"; + raiseAssert__stdZassertions_u42(msg_p0); + framePtr = F.prev; + + +} + +function HEX3DHEX3D__jscore95examples951_u72(x_p0, y_p1) { + var result_654311500 = false; + + var F = {procname: "==.==", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/comparisons.nim", line: 0}; + framePtr = F; + BeforeRet: { + F.line = 326; + F.filename = "comparisons.nim"; + var sameObject_654311508 = false; + F.line = 327; + sameObject_654311508 = x_p0 === y_p1; + if (sameObject_654311508) { + F.line = 328; + result_654311500 = true; + break BeforeRet; + } + + if (!(((x_p0).length == (y_p1).length))) { + F.line = 331; + result_654311500 = false; + break BeforeRet; + } + + Label1: { + F.line = 333; + var i_654311522 = 0; + F.line = 81; + F.filename = "iterators_1.nim"; + var colontmp__654311685 = 0; + F.line = 333; + F.filename = "comparisons.nim"; + colontmp__654311685 = subInt((x_p0).length, 1); + F.line = 96; + F.filename = "iterators_1.nim"; + var res_654311686 = 0; + Label2: { + F.line = 97; + Label3: while (true) { + if (!(res_654311686 <= colontmp__654311685)) break Label3; + F.line = 333; + F.filename = "comparisons.nim"; + i_654311522 = res_654311686; + if (!((x_p0[chckIndx(i_654311522, 0, (x_p0).length - 1)] == y_p1[chckIndx(i_654311522, 0, (y_p1).length - 1)]))) { + F.line = 335; + result_654311500 = false; + break BeforeRet; + } + + F.line = 102; + F.filename = "iterators_1.nim"; + res_654311686 = addInt(res_654311686, 1); + } + }; + }; + F.line = 337; + F.filename = "comparisons.nim"; + result_654311500 = true; + break BeforeRet; + }; + framePtr = F.prev; + + return result_654311500; + +} +var F = {procname: "module jscore_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_1.nim", line: 0}; +framePtr = F; +if (!(HEX3DHEX3D__jscore95examples951_u14(new Uint8Array([97, 98, 99, 100, 101]).copyWithin(0, 3, 4), [100, 98, 99, 100, 101]))) { +F.line = 133; +F.filename = "jscore.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_1.nim(9, 3) `[\'a\', \'b\', \'c\', \'d\', \'e\'].copyWithin(0, 3, 4) == @[\'d\', \'b\', \'c\', \'d\', \'e\']` ")); +} + +if (!(HEX3DHEX3D__jscore95examples951_u14(new Uint8Array([97, 98, 99, 100, 101]).copyWithin(1, 3), [97, 100, 101, 100, 101]))) { +F.line = 133; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_1.nim(10, 3) `[\'a\', \'b\', \'c\', \'d\', \'e\'].copyWithin(1, 3) == @[\'a\', \'d\', \'e\', \'d\', \'e\']` ")); +} + +if (!(HEX3DHEX3D__jscore95examples951_u72(new Int32Array([1, 2, 3, 4, 5]).copyWithin((-2)), [1, 2, 3, 1, 2]))) { +F.line = 133; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_1.nim(11, 3) `[1, 2, 3, 4, 5].copyWithin(-2) == @[1, 2, 3, 1, 2]` ")); +} + +if (!(HEX3DHEX3D__jscore95examples951_u72(new Int32Array([1, 2, 3, 4, 5]).copyWithin(0, 3), [4, 5, 3, 4, 5]))) { +F.line = 133; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_1.nim(12, 3) `[1, 2, 3, 4, 5].copyWithin(0, 3) == @[4, 5, 3, 4, 5]` ")); +} + +if (!(HEX3DHEX3D__jscore95examples951_u72(new Int32Array([1, 2, 3, 4, 5]).copyWithin(0, 3, 4), [4, 2, 3, 4, 5]))) { +F.line = 133; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_1.nim(13, 3) `[1, 2, 3, 4, 5].copyWithin(0, 3, 4) == @[4, 2, 3, 4, 5]` ")); +} + +if (!(HEX3DHEX3D__jscore95examples951_u72(new Int32Array([1, 2, 3, 4, 5]).copyWithin((-2), (-3), (-1)), [1, 2, 3, 3, 4]))) { +F.line = 133; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_1.nim(14, 3) `[1, 2, 3, 4, 5].copyWithin(-2, -3, -1) == @[1, 2, 3, 3, 4]` ")); +} + +framePtr = F.prev; +var F = {procname: "module jscore_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_1.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jscore_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_2.nim", line: 0}; +framePtr = F; +F.line = 145; +F.filename = "jscore.nim"; +var arrai_721420295 = [[1, 2, 3]]; +if (!((arrai_721420295[0].shift() == 1))) { +F.line = 145; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_2.nim(10, 3) `arrai.shift() == 1` ")); +} + +if (!(HEX3DHEX3D__jscore95examples951_u72(arrai_721420295[0], [2, 3]))) { +F.line = 145; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_2.nim(11, 3) `arrai == @[2, 3]` ")); +} + +framePtr = F.prev; +var F = {procname: "module jscore_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_2.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jscore_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jscore_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; diff --git a/nimcache/runnableExamples/jscore_group0_examples.nim b/nimcache/runnableExamples/jscore_group0_examples.nim new file mode 100644 index 0000000000000..0137bdfcfa3d8 --- /dev/null +++ b/nimcache/runnableExamples/jscore_group0_examples.nim @@ -0,0 +1,5 @@ +# autogenerated by docgen +# source: /home/runner/work/Nim/Nim/lib/js/jscore.nim +# rdoccmd: +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_1.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_2.nim" diff --git a/nimcache/runnableExamples/jscore_group1_examples.js b/nimcache/runnableExamples/jscore_group1_examples.js new file mode 100644 index 0000000000000..40887ef4da8fd --- /dev/null +++ b/nimcache/runnableExamples/jscore_group1_examples.js @@ -0,0 +1,133 @@ +/* Generated by the Nim Compiler v2.2.1 */ +var framePtr = null; +var excHandler = 0; +var lastJSError = null; + +function toJSStr(s_p0) { + var result_33556910 = null; + + var res_33556964 = newSeq__system_u2507((s_p0).length); + var i_33556965 = 0; + var j_33556966 = 0; + Label1: { + Label2: while (true) { + if (!(i_33556965 < (s_p0).length)) break Label2; + var c_33556967 = s_p0[i_33556965]; + if ((c_33556967 < 128)) { + res_33556964[j_33556966] = String.fromCharCode(c_33556967); + i_33556965 += 1; + } + else { + var helper_33556993 = newSeq__system_u2507(0); + Label3: { + Label4: while (true) { + if (!true) break Label4; + var code_33556994 = c_33556967.toString(16); + if ((((code_33556994) == null ? 0 : (code_33556994).length) == 1)) { + helper_33556993.push("%0");; + } + else { + helper_33556993.push("%");; + } + + helper_33556993.push(code_33556994);; + i_33556965 += 1; + if ((((s_p0).length <= i_33556965) || (s_p0[i_33556965] < 128))) { + break Label3; + } + + c_33556967 = s_p0[i_33556965]; + } + }; +++excHandler; + try { + res_33556964[j_33556966] = decodeURIComponent(helper_33556993.join("")); +--excHandler; +} catch (EXCEPTION) { + var prevJSError = lastJSError; + lastJSError = EXCEPTION; + --excHandler; + res_33556964[j_33556966] = helper_33556993.join(""); + lastJSError = prevJSError; + } finally { + } + } + + j_33556966 += 1; + } + }; + if (res_33556964.length < j_33556966) { for (var i = res_33556964.length ; i < j_33556966 ; ++i) res_33556964.push(null); } + else { res_33556964.length = j_33556966; }; + result_33556910 = res_33556964.join(""); + + return result_33556910; + +} + +function rawEcho() { + var buf = ""; + for (var i = 0; i < arguments.length; ++i) { + buf += toJSStr(arguments[i]); + } + console.log(buf); + + + +} +var F = {procname: "module jsbigints", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jscore", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jscore.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jscore", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jscore.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function newSeq__system_u2507(len_p0) { + var result_33556943 = []; + + var F = {procname: "newSeq.newSeq", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system.nim", line: 0}; + framePtr = F; + F.line = 653; + F.filename = "system.nim"; + result_33556943 = new Array(len_p0); for (var i = 0 ; i < len_p0 ; ++i) { result_33556943[i] = null; } framePtr = F.prev; + + return result_33556943; + +} + +function HEX3Aanonymous__jscore95examples953_u3() { + var F = {procname: "jscore_examples_3.:anonymous", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_3.nim", line: 0}; + framePtr = F; + F.line = 153; + F.filename = "jscore.nim"; + rawEcho([77,105,99,114,111,116,97,115,107]); + framePtr = F.prev; + + +} +var F = {procname: "module jscore_examples_3", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_3.nim", line: 0}; +framePtr = F; +F.line = 153; +F.filename = "jscore.nim"; +queueMicrotask(HEX3Aanonymous__jscore95examples953_u3); +framePtr = F.prev; +var F = {procname: "module jscore_examples_3", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_3.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jscore_group1_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_group1_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jscore_group1_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_group1_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; diff --git a/nimcache/runnableExamples/jscore_group1_examples.nim b/nimcache/runnableExamples/jscore_group1_examples.nim new file mode 100644 index 0000000000000..51ac17c54ac66 --- /dev/null +++ b/nimcache/runnableExamples/jscore_group1_examples.nim @@ -0,0 +1,4 @@ +# autogenerated by docgen +# source: /home/runner/work/Nim/Nim/lib/js/jscore.nim +# rdoccmd: -r:off +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jscore_examples_3.nim" diff --git a/nimcache/runnableExamples/jsfetch_examples_1.nim b/nimcache/runnableExamples/jsfetch_examples_1.nim new file mode 100644 index 0000000000000..12f93f3dd3989 --- /dev/null +++ b/nimcache/runnableExamples/jsfetch_examples_1.nim @@ -0,0 +1,92 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsfetch.nim(119, 17) +rdoccmd: -r:off +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsfetch.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsfetch.nim", 119, 17).}: + import std/[asyncjs, jsconsole, jsformdata, jsheaders] + from std/httpcore import HttpMethod + from std/jsffi import JsObject + from std/sugar import `=>` + + block: + let options0: FetchOptions = unsafeNewFetchOptions( + metod = "POST".cstring, + body = """{"key": "value"}""".cstring, + mode = "no-cors".cstring, + credentials = "omit".cstring, + cache = "no-cache".cstring, + referrerPolicy = "no-referrer".cstring, + keepalive = false, + redirect = "follow".cstring, + referrer = "client".cstring, + integrity = "".cstring, + headers = newHeaders() + ) + assert options0.keepalive == false + assert options0.metod == "POST".cstring + assert options0.body == """{"key": "value"}""".cstring + assert options0.mode == "no-cors".cstring + assert options0.credentials == "omit".cstring + assert options0.cache == "no-cache".cstring + assert options0.referrerPolicy == "no-referrer".cstring + assert options0.redirect == "follow".cstring + assert options0.referrer == "client".cstring + assert options0.integrity == "".cstring + assert options0.headers.len == 0 + + block: + let options1: FetchOptions = newFetchOptions( + metod = HttpPost, + body = """{"key": "value"}""".cstring, + mode = fmNoCors, + credentials = fcOmit, + cache = fchNoCache, + referrerPolicy = frpNoReferrer, + keepalive = false, + redirect = frFollow, + referrer = "client".cstring, + integrity = "".cstring, + headers = newHeaders() + ) + assert options1.keepalive == false + assert options1.metod == $HttpPost + assert options1.body == """{"key": "value"}""".cstring + assert options1.mode == $fmNoCors + assert options1.credentials == $fcOmit + assert options1.cache == $fchNoCache + assert options1.referrerPolicy == $frpNoReferrer + assert options1.redirect == $frFollow + assert options1.referrer == "client".cstring + assert options1.integrity == "".cstring + assert options1.headers.len == 0 + + block: + let response: Response = newResponse(body = "-. .. --".cstring) + let request: Request = newRequest(url = "http://nim-lang.org".cstring) + + if not defined(nodejs): + block: + proc doFetch(): Future[Response] {.async.} = + fetch "https://httpbin.org/get".cstring + + proc example() {.async.} = + let response: Response = await doFetch() + assert response.ok + assert response.status == 200.cint + assert response.headers is Headers + assert response.body is cstring + + discard example() + + block: + proc example2 {.async.} = + await fetch("https://api.github.com/users/torvalds".cstring) + .then((response: Response) => response.json()) + .then((json: JsObject) => console.log(json)) + .catch((err: Error) => console.log("Request Failed", err)) + + discard example2() + diff --git a/nimcache/runnableExamples/jsfetch_group0_examples.js b/nimcache/runnableExamples/jsfetch_group0_examples.js new file mode 100644 index 0000000000000..7c00dd2ed96d6 --- /dev/null +++ b/nimcache/runnableExamples/jsfetch_group0_examples.js @@ -0,0 +1,1931 @@ +/* Generated by the Nim Compiler v2.2.1 */ +var framePtr = null; +var excHandler = 0; +var lastJSError = null; +var NTI33555177 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI989855748 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI989855747 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI671088651 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI671088647 = {size: 0, kind: 14, base: null, node: null, finalizer: null}; +var NTI671088648 = {size: 0, kind: 14, base: null, node: null, finalizer: null}; +var NTI671088646 = {size: 0, kind: 14, base: null, node: null, finalizer: null}; +var NTI671088645 = {size: 0, kind: 14, base: null, node: null, finalizer: null}; +var NTI671088644 = {size: 0, kind: 14, base: null, node: null, finalizer: null}; +var NTI134217749 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217751 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217741 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217743 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555836 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI33555175 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33555174 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33555171 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555172 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217745 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554449 = {size: 0,kind: 28,base: null,node: null,finalizer: null}; +var NTI973078717 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078714 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078713 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI973078593 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI973078716 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI973078594 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI973078663 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI973078552 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI973078652 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI973078664 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI973078553 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI973078651 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI973078650 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI973078669 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI973078557 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI973078649 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI973078648 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI973078665 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI973078554 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI973078647 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI973078621 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078620 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078619 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078618 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078617 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078616 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078615 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078614 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078613 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078612 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078611 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078610 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078609 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078608 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078607 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078606 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078605 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078604 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078603 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078602 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078601 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078600 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078599 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078598 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI973078597 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI973078670 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI973078558 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI973078545 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI973078543 = {size: 0, kind: 14, base: null, node: null, finalizer: null}; +var NTI973078645 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI973078644 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI973078544 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI973078643 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI973078642 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI973078655 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI973078666 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI973078555 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI973078654 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI33554435 = {size: 0,kind: 31,base: null,node: null,finalizer: null}; +var NTI973078668 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI973078667 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI973078556 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554466 = {size: 0,kind: 1,base: null,node: null,finalizer: null}; +var NTI33555167 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI973078639 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI973078542 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554450 = {size: 0,kind: 29,base: null,node: null,finalizer: null}; +var NTI973078653 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI973078546 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI973078646 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NNI973078639 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI973078639.node = NNI973078639; +var NNI33555167 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555167.node = NNI33555167; +NTI973078639.base = NTI33555167; +NTI973078542.base = NTI973078639; +NTI973078668.base = NTI973078546; +var NNI973078667 = {kind: 2, len: 10, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "acceptCharset", len: 0, typ: NTI33554450, name: "acceptCharset", sons: null}, +{kind: 1, offset: "action", len: 0, typ: NTI33554450, name: "action", sons: null}, +{kind: 1, offset: "autocomplete", len: 0, typ: NTI33554450, name: "autocomplete", sons: null}, +{kind: 1, offset: "elements", len: 0, typ: NTI973078668, name: "elements", sons: null}, +{kind: 1, offset: "encoding", len: 0, typ: NTI33554450, name: "encoding", sons: null}, +{kind: 1, offset: "enctype", len: 0, typ: NTI33554450, name: "enctype", sons: null}, +{kind: 1, offset: "length", len: 0, typ: NTI33554435, name: "length", sons: null}, +{kind: 1, offset: "method", len: 0, typ: NTI33554450, name: "method", sons: null}, +{kind: 1, offset: "noValidate", len: 0, typ: NTI33554466, name: "noValidate", sons: null}, +{kind: 1, offset: "target", len: 0, typ: NTI33554450, name: "target", sons: null}]}; +NTI973078667.node = NNI973078667; +NTI973078667.base = NTI973078653; +NTI973078556.base = NTI973078667; +var NNI973078666 = {kind: 2, len: 5, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "defaultSelected", len: 0, typ: NTI33554466, name: "defaultSelected", sons: null}, +{kind: 1, offset: "selected", len: 0, typ: NTI33554466, name: "selected", sons: null}, +{kind: 1, offset: "selectedIndex", len: 0, typ: NTI33554435, name: "selectedIndex", sons: null}, +{kind: 1, offset: "text", len: 0, typ: NTI33554450, name: "text", sons: null}, +{kind: 1, offset: "value", len: 0, typ: NTI33554450, name: "value", sons: null}]}; +NTI973078666.node = NNI973078666; +NTI973078666.base = NTI973078653; +NTI973078555.base = NTI973078666; +NTI973078654.base = NTI973078555; +NTI973078655.base = NTI973078555; +var NNI973078653 = {kind: 2, len: 20, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "className", len: 0, typ: NTI33554450, name: "className", sons: null}, +{kind: 1, offset: "classList", len: 0, typ: NTI973078542, name: "classList", sons: null}, +{kind: 1, offset: "checked", len: 0, typ: NTI33554466, name: "checked", sons: null}, +{kind: 1, offset: "defaultChecked", len: 0, typ: NTI33554466, name: "defaultChecked", sons: null}, +{kind: 1, offset: "defaultValue", len: 0, typ: NTI33554450, name: "defaultValue", sons: null}, +{kind: 1, offset: "disabled", len: 0, typ: NTI33554466, name: "disabled", sons: null}, +{kind: 1, offset: "form", len: 0, typ: NTI973078556, name: "form", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}, +{kind: 1, offset: "readOnly", len: 0, typ: NTI33554466, name: "readOnly", sons: null}, +{kind: 1, offset: "options", len: 0, typ: NTI973078654, name: "options", sons: null}, +{kind: 1, offset: "selectedOptions", len: 0, typ: NTI973078655, name: "selectedOptions", sons: null}, +{kind: 1, offset: "clientWidth", len: 0, typ: NTI33554435, name: "clientWidth", sons: null}, +{kind: 1, offset: "clientHeight", len: 0, typ: NTI33554435, name: "clientHeight", sons: null}, +{kind: 1, offset: "contentEditable", len: 0, typ: NTI33554450, name: "contentEditable", sons: null}, +{kind: 1, offset: "isContentEditable", len: 0, typ: NTI33554466, name: "isContentEditable", sons: null}, +{kind: 1, offset: "dir", len: 0, typ: NTI33554450, name: "dir", sons: null}, +{kind: 1, offset: "offsetHeight", len: 0, typ: NTI33554435, name: "offsetHeight", sons: null}, +{kind: 1, offset: "offsetWidth", len: 0, typ: NTI33554435, name: "offsetWidth", sons: null}, +{kind: 1, offset: "offsetLeft", len: 0, typ: NTI33554435, name: "offsetLeft", sons: null}, +{kind: 1, offset: "offsetTop", len: 0, typ: NTI33554435, name: "offsetTop", sons: null}]}; +NTI973078653.node = NNI973078653; +NTI973078544.base = NTI973078642; +NTI973078643.base = NTI973078544; +NTI973078644.base = NTI973078544; +NTI973078645.base = NTI973078544; +var NNI973078543 = {kind: 2, offset: 0, typ: null, name: null, len: 12, sons: {"1": {kind: 1, offset: 1, typ: NTI973078543, name: "ElementNode", len: 0, sons: null}, +"2": {kind: 1, offset: 2, typ: NTI973078543, name: "AttributeNode", len: 0, sons: null}, +"3": {kind: 1, offset: 3, typ: NTI973078543, name: "TextNode", len: 0, sons: null}, +"4": {kind: 1, offset: 4, typ: NTI973078543, name: "CDATANode", len: 0, sons: null}, +"5": {kind: 1, offset: 5, typ: NTI973078543, name: "EntityRefNode", len: 0, sons: null}, +"6": {kind: 1, offset: 6, typ: NTI973078543, name: "EntityNode", len: 0, sons: null}, +"7": {kind: 1, offset: 7, typ: NTI973078543, name: "ProcessingInstructionNode", len: 0, sons: null}, +"8": {kind: 1, offset: 8, typ: NTI973078543, name: "CommentNode", len: 0, sons: null}, +"9": {kind: 1, offset: 9, typ: NTI973078543, name: "DocumentNode", len: 0, sons: null}, +"10": {kind: 1, offset: 10, typ: NTI973078543, name: "DocumentTypeNode", len: 0, sons: null}, +"11": {kind: 1, offset: 11, typ: NTI973078543, name: "DocumentFragmentNode", len: 0, sons: null}, +"12": {kind: 1, offset: 12, typ: NTI973078543, name: "NotationNode", len: 0, sons: null}}}; +NTI973078543.node = NNI973078543; +NTI973078545.base = NTI973078646; +var NNI973078670 = {kind: 2, len: 368, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "alignContent", len: 0, typ: NTI33554450, name: "alignContent", sons: null}, +{kind: 1, offset: "alignItems", len: 0, typ: NTI33554450, name: "alignItems", sons: null}, +{kind: 1, offset: "alignSelf", len: 0, typ: NTI33554450, name: "alignSelf", sons: null}, +{kind: 1, offset: "all", len: 0, typ: NTI33554450, name: "all", sons: null}, +{kind: 1, offset: "animation", len: 0, typ: NTI33554450, name: "animation", sons: null}, +{kind: 1, offset: "animationDelay", len: 0, typ: NTI33554450, name: "animationDelay", sons: null}, +{kind: 1, offset: "animationDirection", len: 0, typ: NTI33554450, name: "animationDirection", sons: null}, +{kind: 1, offset: "animationDuration", len: 0, typ: NTI33554450, name: "animationDuration", sons: null}, +{kind: 1, offset: "animationFillMode", len: 0, typ: NTI33554450, name: "animationFillMode", sons: null}, +{kind: 1, offset: "animationIterationCount", len: 0, typ: NTI33554450, name: "animationIterationCount", sons: null}, +{kind: 1, offset: "animationName", len: 0, typ: NTI33554450, name: "animationName", sons: null}, +{kind: 1, offset: "animationPlayState", len: 0, typ: NTI33554450, name: "animationPlayState", sons: null}, +{kind: 1, offset: "animationTimingFunction", len: 0, typ: NTI33554450, name: "animationTimingFunction", sons: null}, +{kind: 1, offset: "backdropFilter", len: 0, typ: NTI33554450, name: "backdropFilter", sons: null}, +{kind: 1, offset: "backfaceVisibility", len: 0, typ: NTI33554450, name: "backfaceVisibility", sons: null}, +{kind: 1, offset: "background", len: 0, typ: NTI33554450, name: "background", sons: null}, +{kind: 1, offset: "backgroundAttachment", len: 0, typ: NTI33554450, name: "backgroundAttachment", sons: null}, +{kind: 1, offset: "backgroundBlendMode", len: 0, typ: NTI33554450, name: "backgroundBlendMode", sons: null}, +{kind: 1, offset: "backgroundClip", len: 0, typ: NTI33554450, name: "backgroundClip", sons: null}, +{kind: 1, offset: "backgroundColor", len: 0, typ: NTI33554450, name: "backgroundColor", sons: null}, +{kind: 1, offset: "backgroundImage", len: 0, typ: NTI33554450, name: "backgroundImage", sons: null}, +{kind: 1, offset: "backgroundOrigin", len: 0, typ: NTI33554450, name: "backgroundOrigin", sons: null}, +{kind: 1, offset: "backgroundPosition", len: 0, typ: NTI33554450, name: "backgroundPosition", sons: null}, +{kind: 1, offset: "backgroundRepeat", len: 0, typ: NTI33554450, name: "backgroundRepeat", sons: null}, +{kind: 1, offset: "backgroundSize", len: 0, typ: NTI33554450, name: "backgroundSize", sons: null}, +{kind: 1, offset: "blockSize", len: 0, typ: NTI33554450, name: "blockSize", sons: null}, +{kind: 1, offset: "border", len: 0, typ: NTI33554450, name: "border", sons: null}, +{kind: 1, offset: "borderBlock", len: 0, typ: NTI33554450, name: "borderBlock", sons: null}, +{kind: 1, offset: "borderBlockColor", len: 0, typ: NTI33554450, name: "borderBlockColor", sons: null}, +{kind: 1, offset: "borderBlockEnd", len: 0, typ: NTI33554450, name: "borderBlockEnd", sons: null}, +{kind: 1, offset: "borderBlockEndColor", len: 0, typ: NTI33554450, name: "borderBlockEndColor", sons: null}, +{kind: 1, offset: "borderBlockEndStyle", len: 0, typ: NTI33554450, name: "borderBlockEndStyle", sons: null}, +{kind: 1, offset: "borderBlockEndWidth", len: 0, typ: NTI33554450, name: "borderBlockEndWidth", sons: null}, +{kind: 1, offset: "borderBlockStart", len: 0, typ: NTI33554450, name: "borderBlockStart", sons: null}, +{kind: 1, offset: "borderBlockStartColor", len: 0, typ: NTI33554450, name: "borderBlockStartColor", sons: null}, +{kind: 1, offset: "borderBlockStartStyle", len: 0, typ: NTI33554450, name: "borderBlockStartStyle", sons: null}, +{kind: 1, offset: "borderBlockStartWidth", len: 0, typ: NTI33554450, name: "borderBlockStartWidth", sons: null}, +{kind: 1, offset: "borderBlockStyle", len: 0, typ: NTI33554450, name: "borderBlockStyle", sons: null}, +{kind: 1, offset: "borderBlockWidth", len: 0, typ: NTI33554450, name: "borderBlockWidth", sons: null}, +{kind: 1, offset: "borderBottom", len: 0, typ: NTI33554450, name: "borderBottom", sons: null}, +{kind: 1, offset: "borderBottomColor", len: 0, typ: NTI33554450, name: "borderBottomColor", sons: null}, +{kind: 1, offset: "borderBottomLeftRadius", len: 0, typ: NTI33554450, name: "borderBottomLeftRadius", sons: null}, +{kind: 1, offset: "borderBottomRightRadius", len: 0, typ: NTI33554450, name: "borderBottomRightRadius", sons: null}, +{kind: 1, offset: "borderBottomStyle", len: 0, typ: NTI33554450, name: "borderBottomStyle", sons: null}, +{kind: 1, offset: "borderBottomWidth", len: 0, typ: NTI33554450, name: "borderBottomWidth", sons: null}, +{kind: 1, offset: "borderCollapse", len: 0, typ: NTI33554450, name: "borderCollapse", sons: null}, +{kind: 1, offset: "borderColor", len: 0, typ: NTI33554450, name: "borderColor", sons: null}, +{kind: 1, offset: "borderEndEndRadius", len: 0, typ: NTI33554450, name: "borderEndEndRadius", sons: null}, +{kind: 1, offset: "borderEndStartRadius", len: 0, typ: NTI33554450, name: "borderEndStartRadius", sons: null}, +{kind: 1, offset: "borderImage", len: 0, typ: NTI33554450, name: "borderImage", sons: null}, +{kind: 1, offset: "borderImageOutset", len: 0, typ: NTI33554450, name: "borderImageOutset", sons: null}, +{kind: 1, offset: "borderImageRepeat", len: 0, typ: NTI33554450, name: "borderImageRepeat", sons: null}, +{kind: 1, offset: "borderImageSlice", len: 0, typ: NTI33554450, name: "borderImageSlice", sons: null}, +{kind: 1, offset: "borderImageSource", len: 0, typ: NTI33554450, name: "borderImageSource", sons: null}, +{kind: 1, offset: "borderImageWidth", len: 0, typ: NTI33554450, name: "borderImageWidth", sons: null}, +{kind: 1, offset: "borderInline", len: 0, typ: NTI33554450, name: "borderInline", sons: null}, +{kind: 1, offset: "borderInlineColor", len: 0, typ: NTI33554450, name: "borderInlineColor", sons: null}, +{kind: 1, offset: "borderInlineEnd", len: 0, typ: NTI33554450, name: "borderInlineEnd", sons: null}, +{kind: 1, offset: "borderInlineEndColor", len: 0, typ: NTI33554450, name: "borderInlineEndColor", sons: null}, +{kind: 1, offset: "borderInlineEndStyle", len: 0, typ: NTI33554450, name: "borderInlineEndStyle", sons: null}, +{kind: 1, offset: "borderInlineEndWidth", len: 0, typ: NTI33554450, name: "borderInlineEndWidth", sons: null}, +{kind: 1, offset: "borderInlineStart", len: 0, typ: NTI33554450, name: "borderInlineStart", sons: null}, +{kind: 1, offset: "borderInlineStartColor", len: 0, typ: NTI33554450, name: "borderInlineStartColor", sons: null}, +{kind: 1, offset: "borderInlineStartStyle", len: 0, typ: NTI33554450, name: "borderInlineStartStyle", sons: null}, +{kind: 1, offset: "borderInlineStartWidth", len: 0, typ: NTI33554450, name: "borderInlineStartWidth", sons: null}, +{kind: 1, offset: "borderInlineStyle", len: 0, typ: NTI33554450, name: "borderInlineStyle", sons: null}, +{kind: 1, offset: "borderInlineWidth", len: 0, typ: NTI33554450, name: "borderInlineWidth", sons: null}, +{kind: 1, offset: "borderLeft", len: 0, typ: NTI33554450, name: "borderLeft", sons: null}, +{kind: 1, offset: "borderLeftColor", len: 0, typ: NTI33554450, name: "borderLeftColor", sons: null}, +{kind: 1, offset: "borderLeftStyle", len: 0, typ: NTI33554450, name: "borderLeftStyle", sons: null}, +{kind: 1, offset: "borderLeftWidth", len: 0, typ: NTI33554450, name: "borderLeftWidth", sons: null}, +{kind: 1, offset: "borderRadius", len: 0, typ: NTI33554450, name: "borderRadius", sons: null}, +{kind: 1, offset: "borderRight", len: 0, typ: NTI33554450, name: "borderRight", sons: null}, +{kind: 1, offset: "borderRightColor", len: 0, typ: NTI33554450, name: "borderRightColor", sons: null}, +{kind: 1, offset: "borderRightStyle", len: 0, typ: NTI33554450, name: "borderRightStyle", sons: null}, +{kind: 1, offset: "borderRightWidth", len: 0, typ: NTI33554450, name: "borderRightWidth", sons: null}, +{kind: 1, offset: "borderSpacing", len: 0, typ: NTI33554450, name: "borderSpacing", sons: null}, +{kind: 1, offset: "borderStartEndRadius", len: 0, typ: NTI33554450, name: "borderStartEndRadius", sons: null}, +{kind: 1, offset: "borderStartStartRadius", len: 0, typ: NTI33554450, name: "borderStartStartRadius", sons: null}, +{kind: 1, offset: "borderStyle", len: 0, typ: NTI33554450, name: "borderStyle", sons: null}, +{kind: 1, offset: "borderTop", len: 0, typ: NTI33554450, name: "borderTop", sons: null}, +{kind: 1, offset: "borderTopColor", len: 0, typ: NTI33554450, name: "borderTopColor", sons: null}, +{kind: 1, offset: "borderTopLeftRadius", len: 0, typ: NTI33554450, name: "borderTopLeftRadius", sons: null}, +{kind: 1, offset: "borderTopRightRadius", len: 0, typ: NTI33554450, name: "borderTopRightRadius", sons: null}, +{kind: 1, offset: "borderTopStyle", len: 0, typ: NTI33554450, name: "borderTopStyle", sons: null}, +{kind: 1, offset: "borderTopWidth", len: 0, typ: NTI33554450, name: "borderTopWidth", sons: null}, +{kind: 1, offset: "borderWidth", len: 0, typ: NTI33554450, name: "borderWidth", sons: null}, +{kind: 1, offset: "bottom", len: 0, typ: NTI33554450, name: "bottom", sons: null}, +{kind: 1, offset: "boxDecorationBreak", len: 0, typ: NTI33554450, name: "boxDecorationBreak", sons: null}, +{kind: 1, offset: "boxShadow", len: 0, typ: NTI33554450, name: "boxShadow", sons: null}, +{kind: 1, offset: "boxSizing", len: 0, typ: NTI33554450, name: "boxSizing", sons: null}, +{kind: 1, offset: "breakAfter", len: 0, typ: NTI33554450, name: "breakAfter", sons: null}, +{kind: 1, offset: "breakBefore", len: 0, typ: NTI33554450, name: "breakBefore", sons: null}, +{kind: 1, offset: "breakInside", len: 0, typ: NTI33554450, name: "breakInside", sons: null}, +{kind: 1, offset: "captionSide", len: 0, typ: NTI33554450, name: "captionSide", sons: null}, +{kind: 1, offset: "caretColor", len: 0, typ: NTI33554450, name: "caretColor", sons: null}, +{kind: 1, offset: "clear", len: 0, typ: NTI33554450, name: "clear", sons: null}, +{kind: 1, offset: "clip", len: 0, typ: NTI33554450, name: "clip", sons: null}, +{kind: 1, offset: "clipPath", len: 0, typ: NTI33554450, name: "clipPath", sons: null}, +{kind: 1, offset: "color", len: 0, typ: NTI33554450, name: "color", sons: null}, +{kind: 1, offset: "colorAdjust", len: 0, typ: NTI33554450, name: "colorAdjust", sons: null}, +{kind: 1, offset: "columnCount", len: 0, typ: NTI33554450, name: "columnCount", sons: null}, +{kind: 1, offset: "columnFill", len: 0, typ: NTI33554450, name: "columnFill", sons: null}, +{kind: 1, offset: "columnGap", len: 0, typ: NTI33554450, name: "columnGap", sons: null}, +{kind: 1, offset: "columnRule", len: 0, typ: NTI33554450, name: "columnRule", sons: null}, +{kind: 1, offset: "columnRuleColor", len: 0, typ: NTI33554450, name: "columnRuleColor", sons: null}, +{kind: 1, offset: "columnRuleStyle", len: 0, typ: NTI33554450, name: "columnRuleStyle", sons: null}, +{kind: 1, offset: "columnRuleWidth", len: 0, typ: NTI33554450, name: "columnRuleWidth", sons: null}, +{kind: 1, offset: "columnSpan", len: 0, typ: NTI33554450, name: "columnSpan", sons: null}, +{kind: 1, offset: "columnWidth", len: 0, typ: NTI33554450, name: "columnWidth", sons: null}, +{kind: 1, offset: "columns", len: 0, typ: NTI33554450, name: "columns", sons: null}, +{kind: 1, offset: "contain", len: 0, typ: NTI33554450, name: "contain", sons: null}, +{kind: 1, offset: "content", len: 0, typ: NTI33554450, name: "content", sons: null}, +{kind: 1, offset: "counterIncrement", len: 0, typ: NTI33554450, name: "counterIncrement", sons: null}, +{kind: 1, offset: "counterReset", len: 0, typ: NTI33554450, name: "counterReset", sons: null}, +{kind: 1, offset: "counterSet", len: 0, typ: NTI33554450, name: "counterSet", sons: null}, +{kind: 1, offset: "cursor", len: 0, typ: NTI33554450, name: "cursor", sons: null}, +{kind: 1, offset: "direction", len: 0, typ: NTI33554450, name: "direction", sons: null}, +{kind: 1, offset: "display", len: 0, typ: NTI33554450, name: "display", sons: null}, +{kind: 1, offset: "emptyCells", len: 0, typ: NTI33554450, name: "emptyCells", sons: null}, +{kind: 1, offset: "filter", len: 0, typ: NTI33554450, name: "filter", sons: null}, +{kind: 1, offset: "flex", len: 0, typ: NTI33554450, name: "flex", sons: null}, +{kind: 1, offset: "flexBasis", len: 0, typ: NTI33554450, name: "flexBasis", sons: null}, +{kind: 1, offset: "flexDirection", len: 0, typ: NTI33554450, name: "flexDirection", sons: null}, +{kind: 1, offset: "flexFlow", len: 0, typ: NTI33554450, name: "flexFlow", sons: null}, +{kind: 1, offset: "flexGrow", len: 0, typ: NTI33554450, name: "flexGrow", sons: null}, +{kind: 1, offset: "flexShrink", len: 0, typ: NTI33554450, name: "flexShrink", sons: null}, +{kind: 1, offset: "flexWrap", len: 0, typ: NTI33554450, name: "flexWrap", sons: null}, +{kind: 1, offset: "cssFloat", len: 0, typ: NTI33554450, name: "cssFloat", sons: null}, +{kind: 1, offset: "font", len: 0, typ: NTI33554450, name: "font", sons: null}, +{kind: 1, offset: "fontFamily", len: 0, typ: NTI33554450, name: "fontFamily", sons: null}, +{kind: 1, offset: "fontFeatureSettings", len: 0, typ: NTI33554450, name: "fontFeatureSettings", sons: null}, +{kind: 1, offset: "fontKerning", len: 0, typ: NTI33554450, name: "fontKerning", sons: null}, +{kind: 1, offset: "fontLanguageOverride", len: 0, typ: NTI33554450, name: "fontLanguageOverride", sons: null}, +{kind: 1, offset: "fontOpticalSizing", len: 0, typ: NTI33554450, name: "fontOpticalSizing", sons: null}, +{kind: 1, offset: "fontSize", len: 0, typ: NTI33554450, name: "fontSize", sons: null}, +{kind: 1, offset: "fontSizeAdjust", len: 0, typ: NTI33554450, name: "fontSizeAdjust", sons: null}, +{kind: 1, offset: "fontStretch", len: 0, typ: NTI33554450, name: "fontStretch", sons: null}, +{kind: 1, offset: "fontStyle", len: 0, typ: NTI33554450, name: "fontStyle", sons: null}, +{kind: 1, offset: "fontSynthesis", len: 0, typ: NTI33554450, name: "fontSynthesis", sons: null}, +{kind: 1, offset: "fontVariant", len: 0, typ: NTI33554450, name: "fontVariant", sons: null}, +{kind: 1, offset: "fontVariantAlternates", len: 0, typ: NTI33554450, name: "fontVariantAlternates", sons: null}, +{kind: 1, offset: "fontVariantCaps", len: 0, typ: NTI33554450, name: "fontVariantCaps", sons: null}, +{kind: 1, offset: "fontVariantEastAsian", len: 0, typ: NTI33554450, name: "fontVariantEastAsian", sons: null}, +{kind: 1, offset: "fontVariantLigatures", len: 0, typ: NTI33554450, name: "fontVariantLigatures", sons: null}, +{kind: 1, offset: "fontVariantNumeric", len: 0, typ: NTI33554450, name: "fontVariantNumeric", sons: null}, +{kind: 1, offset: "fontVariantPosition", len: 0, typ: NTI33554450, name: "fontVariantPosition", sons: null}, +{kind: 1, offset: "fontVariationSettings", len: 0, typ: NTI33554450, name: "fontVariationSettings", sons: null}, +{kind: 1, offset: "fontWeight", len: 0, typ: NTI33554450, name: "fontWeight", sons: null}, +{kind: 1, offset: "gap", len: 0, typ: NTI33554450, name: "gap", sons: null}, +{kind: 1, offset: "grid", len: 0, typ: NTI33554450, name: "grid", sons: null}, +{kind: 1, offset: "gridArea", len: 0, typ: NTI33554450, name: "gridArea", sons: null}, +{kind: 1, offset: "gridAutoColumns", len: 0, typ: NTI33554450, name: "gridAutoColumns", sons: null}, +{kind: 1, offset: "gridAutoFlow", len: 0, typ: NTI33554450, name: "gridAutoFlow", sons: null}, +{kind: 1, offset: "gridAutoRows", len: 0, typ: NTI33554450, name: "gridAutoRows", sons: null}, +{kind: 1, offset: "gridColumn", len: 0, typ: NTI33554450, name: "gridColumn", sons: null}, +{kind: 1, offset: "gridColumnEnd", len: 0, typ: NTI33554450, name: "gridColumnEnd", sons: null}, +{kind: 1, offset: "gridColumnStart", len: 0, typ: NTI33554450, name: "gridColumnStart", sons: null}, +{kind: 1, offset: "gridRow", len: 0, typ: NTI33554450, name: "gridRow", sons: null}, +{kind: 1, offset: "gridRowEnd", len: 0, typ: NTI33554450, name: "gridRowEnd", sons: null}, +{kind: 1, offset: "gridRowStart", len: 0, typ: NTI33554450, name: "gridRowStart", sons: null}, +{kind: 1, offset: "gridTemplate", len: 0, typ: NTI33554450, name: "gridTemplate", sons: null}, +{kind: 1, offset: "gridTemplateAreas", len: 0, typ: NTI33554450, name: "gridTemplateAreas", sons: null}, +{kind: 1, offset: "gridTemplateColumns", len: 0, typ: NTI33554450, name: "gridTemplateColumns", sons: null}, +{kind: 1, offset: "gridTemplateRows", len: 0, typ: NTI33554450, name: "gridTemplateRows", sons: null}, +{kind: 1, offset: "hangingPunctuation", len: 0, typ: NTI33554450, name: "hangingPunctuation", sons: null}, +{kind: 1, offset: "height", len: 0, typ: NTI33554450, name: "height", sons: null}, +{kind: 1, offset: "hyphens", len: 0, typ: NTI33554450, name: "hyphens", sons: null}, +{kind: 1, offset: "imageOrientation", len: 0, typ: NTI33554450, name: "imageOrientation", sons: null}, +{kind: 1, offset: "imageRendering", len: 0, typ: NTI33554450, name: "imageRendering", sons: null}, +{kind: 1, offset: "inlineSize", len: 0, typ: NTI33554450, name: "inlineSize", sons: null}, +{kind: 1, offset: "inset", len: 0, typ: NTI33554450, name: "inset", sons: null}, +{kind: 1, offset: "insetBlock", len: 0, typ: NTI33554450, name: "insetBlock", sons: null}, +{kind: 1, offset: "insetBlockEnd", len: 0, typ: NTI33554450, name: "insetBlockEnd", sons: null}, +{kind: 1, offset: "insetBlockStart", len: 0, typ: NTI33554450, name: "insetBlockStart", sons: null}, +{kind: 1, offset: "insetInline", len: 0, typ: NTI33554450, name: "insetInline", sons: null}, +{kind: 1, offset: "insetInlineEnd", len: 0, typ: NTI33554450, name: "insetInlineEnd", sons: null}, +{kind: 1, offset: "insetInlineStart", len: 0, typ: NTI33554450, name: "insetInlineStart", sons: null}, +{kind: 1, offset: "isolation", len: 0, typ: NTI33554450, name: "isolation", sons: null}, +{kind: 1, offset: "justifyContent", len: 0, typ: NTI33554450, name: "justifyContent", sons: null}, +{kind: 1, offset: "justifyItems", len: 0, typ: NTI33554450, name: "justifyItems", sons: null}, +{kind: 1, offset: "justifySelf", len: 0, typ: NTI33554450, name: "justifySelf", sons: null}, +{kind: 1, offset: "left", len: 0, typ: NTI33554450, name: "left", sons: null}, +{kind: 1, offset: "letterSpacing", len: 0, typ: NTI33554450, name: "letterSpacing", sons: null}, +{kind: 1, offset: "lineBreak", len: 0, typ: NTI33554450, name: "lineBreak", sons: null}, +{kind: 1, offset: "lineHeight", len: 0, typ: NTI33554450, name: "lineHeight", sons: null}, +{kind: 1, offset: "listStyle", len: 0, typ: NTI33554450, name: "listStyle", sons: null}, +{kind: 1, offset: "listStyleImage", len: 0, typ: NTI33554450, name: "listStyleImage", sons: null}, +{kind: 1, offset: "listStylePosition", len: 0, typ: NTI33554450, name: "listStylePosition", sons: null}, +{kind: 1, offset: "listStyleType", len: 0, typ: NTI33554450, name: "listStyleType", sons: null}, +{kind: 1, offset: "margin", len: 0, typ: NTI33554450, name: "margin", sons: null}, +{kind: 1, offset: "marginBlock", len: 0, typ: NTI33554450, name: "marginBlock", sons: null}, +{kind: 1, offset: "marginBlockEnd", len: 0, typ: NTI33554450, name: "marginBlockEnd", sons: null}, +{kind: 1, offset: "marginBlockStart", len: 0, typ: NTI33554450, name: "marginBlockStart", sons: null}, +{kind: 1, offset: "marginBottom", len: 0, typ: NTI33554450, name: "marginBottom", sons: null}, +{kind: 1, offset: "marginInline", len: 0, typ: NTI33554450, name: "marginInline", sons: null}, +{kind: 1, offset: "marginInlineEnd", len: 0, typ: NTI33554450, name: "marginInlineEnd", sons: null}, +{kind: 1, offset: "marginInlineStart", len: 0, typ: NTI33554450, name: "marginInlineStart", sons: null}, +{kind: 1, offset: "marginLeft", len: 0, typ: NTI33554450, name: "marginLeft", sons: null}, +{kind: 1, offset: "marginRight", len: 0, typ: NTI33554450, name: "marginRight", sons: null}, +{kind: 1, offset: "marginTop", len: 0, typ: NTI33554450, name: "marginTop", sons: null}, +{kind: 1, offset: "mask", len: 0, typ: NTI33554450, name: "mask", sons: null}, +{kind: 1, offset: "maskBorder", len: 0, typ: NTI33554450, name: "maskBorder", sons: null}, +{kind: 1, offset: "maskBorderMode", len: 0, typ: NTI33554450, name: "maskBorderMode", sons: null}, +{kind: 1, offset: "maskBorderOutset", len: 0, typ: NTI33554450, name: "maskBorderOutset", sons: null}, +{kind: 1, offset: "maskBorderRepeat", len: 0, typ: NTI33554450, name: "maskBorderRepeat", sons: null}, +{kind: 1, offset: "maskBorderSlice", len: 0, typ: NTI33554450, name: "maskBorderSlice", sons: null}, +{kind: 1, offset: "maskBorderSource", len: 0, typ: NTI33554450, name: "maskBorderSource", sons: null}, +{kind: 1, offset: "maskBorderWidth", len: 0, typ: NTI33554450, name: "maskBorderWidth", sons: null}, +{kind: 1, offset: "maskClip", len: 0, typ: NTI33554450, name: "maskClip", sons: null}, +{kind: 1, offset: "maskComposite", len: 0, typ: NTI33554450, name: "maskComposite", sons: null}, +{kind: 1, offset: "maskImage", len: 0, typ: NTI33554450, name: "maskImage", sons: null}, +{kind: 1, offset: "maskMode", len: 0, typ: NTI33554450, name: "maskMode", sons: null}, +{kind: 1, offset: "maskOrigin", len: 0, typ: NTI33554450, name: "maskOrigin", sons: null}, +{kind: 1, offset: "maskPosition", len: 0, typ: NTI33554450, name: "maskPosition", sons: null}, +{kind: 1, offset: "maskRepeat", len: 0, typ: NTI33554450, name: "maskRepeat", sons: null}, +{kind: 1, offset: "maskSize", len: 0, typ: NTI33554450, name: "maskSize", sons: null}, +{kind: 1, offset: "maskType", len: 0, typ: NTI33554450, name: "maskType", sons: null}, +{kind: 1, offset: "maxBlockSize", len: 0, typ: NTI33554450, name: "maxBlockSize", sons: null}, +{kind: 1, offset: "maxHeight", len: 0, typ: NTI33554450, name: "maxHeight", sons: null}, +{kind: 1, offset: "maxInlineSize", len: 0, typ: NTI33554450, name: "maxInlineSize", sons: null}, +{kind: 1, offset: "maxWidth", len: 0, typ: NTI33554450, name: "maxWidth", sons: null}, +{kind: 1, offset: "minBlockSize", len: 0, typ: NTI33554450, name: "minBlockSize", sons: null}, +{kind: 1, offset: "minHeight", len: 0, typ: NTI33554450, name: "minHeight", sons: null}, +{kind: 1, offset: "minInlineSize", len: 0, typ: NTI33554450, name: "minInlineSize", sons: null}, +{kind: 1, offset: "minWidth", len: 0, typ: NTI33554450, name: "minWidth", sons: null}, +{kind: 1, offset: "mixBlendMode", len: 0, typ: NTI33554450, name: "mixBlendMode", sons: null}, +{kind: 1, offset: "objectFit", len: 0, typ: NTI33554450, name: "objectFit", sons: null}, +{kind: 1, offset: "objectPosition", len: 0, typ: NTI33554450, name: "objectPosition", sons: null}, +{kind: 1, offset: "offset", len: 0, typ: NTI33554450, name: "offset", sons: null}, +{kind: 1, offset: "offsetAnchor", len: 0, typ: NTI33554450, name: "offsetAnchor", sons: null}, +{kind: 1, offset: "offsetDistance", len: 0, typ: NTI33554450, name: "offsetDistance", sons: null}, +{kind: 1, offset: "offsetPath", len: 0, typ: NTI33554450, name: "offsetPath", sons: null}, +{kind: 1, offset: "offsetRotate", len: 0, typ: NTI33554450, name: "offsetRotate", sons: null}, +{kind: 1, offset: "opacity", len: 0, typ: NTI33554450, name: "opacity", sons: null}, +{kind: 1, offset: "order", len: 0, typ: NTI33554450, name: "order", sons: null}, +{kind: 1, offset: "orphans", len: 0, typ: NTI33554450, name: "orphans", sons: null}, +{kind: 1, offset: "outline", len: 0, typ: NTI33554450, name: "outline", sons: null}, +{kind: 1, offset: "outlineColor", len: 0, typ: NTI33554450, name: "outlineColor", sons: null}, +{kind: 1, offset: "outlineOffset", len: 0, typ: NTI33554450, name: "outlineOffset", sons: null}, +{kind: 1, offset: "outlineStyle", len: 0, typ: NTI33554450, name: "outlineStyle", sons: null}, +{kind: 1, offset: "outlineWidth", len: 0, typ: NTI33554450, name: "outlineWidth", sons: null}, +{kind: 1, offset: "overflow", len: 0, typ: NTI33554450, name: "overflow", sons: null}, +{kind: 1, offset: "overflowAnchor", len: 0, typ: NTI33554450, name: "overflowAnchor", sons: null}, +{kind: 1, offset: "overflowBlock", len: 0, typ: NTI33554450, name: "overflowBlock", sons: null}, +{kind: 1, offset: "overflowInline", len: 0, typ: NTI33554450, name: "overflowInline", sons: null}, +{kind: 1, offset: "overflowWrap", len: 0, typ: NTI33554450, name: "overflowWrap", sons: null}, +{kind: 1, offset: "overflowX", len: 0, typ: NTI33554450, name: "overflowX", sons: null}, +{kind: 1, offset: "overflowY", len: 0, typ: NTI33554450, name: "overflowY", sons: null}, +{kind: 1, offset: "overscrollBehavior", len: 0, typ: NTI33554450, name: "overscrollBehavior", sons: null}, +{kind: 1, offset: "overscrollBehaviorBlock", len: 0, typ: NTI33554450, name: "overscrollBehaviorBlock", sons: null}, +{kind: 1, offset: "overscrollBehaviorInline", len: 0, typ: NTI33554450, name: "overscrollBehaviorInline", sons: null}, +{kind: 1, offset: "overscrollBehaviorX", len: 0, typ: NTI33554450, name: "overscrollBehaviorX", sons: null}, +{kind: 1, offset: "overscrollBehaviorY", len: 0, typ: NTI33554450, name: "overscrollBehaviorY", sons: null}, +{kind: 1, offset: "padding", len: 0, typ: NTI33554450, name: "padding", sons: null}, +{kind: 1, offset: "paddingBlock", len: 0, typ: NTI33554450, name: "paddingBlock", sons: null}, +{kind: 1, offset: "paddingBlockEnd", len: 0, typ: NTI33554450, name: "paddingBlockEnd", sons: null}, +{kind: 1, offset: "paddingBlockStart", len: 0, typ: NTI33554450, name: "paddingBlockStart", sons: null}, +{kind: 1, offset: "paddingBottom", len: 0, typ: NTI33554450, name: "paddingBottom", sons: null}, +{kind: 1, offset: "paddingInline", len: 0, typ: NTI33554450, name: "paddingInline", sons: null}, +{kind: 1, offset: "paddingInlineEnd", len: 0, typ: NTI33554450, name: "paddingInlineEnd", sons: null}, +{kind: 1, offset: "paddingInlineStart", len: 0, typ: NTI33554450, name: "paddingInlineStart", sons: null}, +{kind: 1, offset: "paddingLeft", len: 0, typ: NTI33554450, name: "paddingLeft", sons: null}, +{kind: 1, offset: "paddingRight", len: 0, typ: NTI33554450, name: "paddingRight", sons: null}, +{kind: 1, offset: "paddingTop", len: 0, typ: NTI33554450, name: "paddingTop", sons: null}, +{kind: 1, offset: "pageBreakAfter", len: 0, typ: NTI33554450, name: "pageBreakAfter", sons: null}, +{kind: 1, offset: "pageBreakBefore", len: 0, typ: NTI33554450, name: "pageBreakBefore", sons: null}, +{kind: 1, offset: "pageBreakInside", len: 0, typ: NTI33554450, name: "pageBreakInside", sons: null}, +{kind: 1, offset: "paintOrder", len: 0, typ: NTI33554450, name: "paintOrder", sons: null}, +{kind: 1, offset: "perspective", len: 0, typ: NTI33554450, name: "perspective", sons: null}, +{kind: 1, offset: "perspectiveOrigin", len: 0, typ: NTI33554450, name: "perspectiveOrigin", sons: null}, +{kind: 1, offset: "placeContent", len: 0, typ: NTI33554450, name: "placeContent", sons: null}, +{kind: 1, offset: "placeItems", len: 0, typ: NTI33554450, name: "placeItems", sons: null}, +{kind: 1, offset: "placeSelf", len: 0, typ: NTI33554450, name: "placeSelf", sons: null}, +{kind: 1, offset: "pointerEvents", len: 0, typ: NTI33554450, name: "pointerEvents", sons: null}, +{kind: 1, offset: "position", len: 0, typ: NTI33554450, name: "position", sons: null}, +{kind: 1, offset: "quotes", len: 0, typ: NTI33554450, name: "quotes", sons: null}, +{kind: 1, offset: "resize", len: 0, typ: NTI33554450, name: "resize", sons: null}, +{kind: 1, offset: "right", len: 0, typ: NTI33554450, name: "right", sons: null}, +{kind: 1, offset: "rotate", len: 0, typ: NTI33554450, name: "rotate", sons: null}, +{kind: 1, offset: "rowGap", len: 0, typ: NTI33554450, name: "rowGap", sons: null}, +{kind: 1, offset: "scale", len: 0, typ: NTI33554450, name: "scale", sons: null}, +{kind: 1, offset: "scrollBehavior", len: 0, typ: NTI33554450, name: "scrollBehavior", sons: null}, +{kind: 1, offset: "scrollMargin", len: 0, typ: NTI33554450, name: "scrollMargin", sons: null}, +{kind: 1, offset: "scrollMarginBlock", len: 0, typ: NTI33554450, name: "scrollMarginBlock", sons: null}, +{kind: 1, offset: "scrollMarginBlockEnd", len: 0, typ: NTI33554450, name: "scrollMarginBlockEnd", sons: null}, +{kind: 1, offset: "scrollMarginBlockStart", len: 0, typ: NTI33554450, name: "scrollMarginBlockStart", sons: null}, +{kind: 1, offset: "scrollMarginBottom", len: 0, typ: NTI33554450, name: "scrollMarginBottom", sons: null}, +{kind: 1, offset: "scrollMarginInline", len: 0, typ: NTI33554450, name: "scrollMarginInline", sons: null}, +{kind: 1, offset: "scrollMarginInlineEnd", len: 0, typ: NTI33554450, name: "scrollMarginInlineEnd", sons: null}, +{kind: 1, offset: "scrollMarginInlineStart", len: 0, typ: NTI33554450, name: "scrollMarginInlineStart", sons: null}, +{kind: 1, offset: "scrollMarginLeft", len: 0, typ: NTI33554450, name: "scrollMarginLeft", sons: null}, +{kind: 1, offset: "scrollMarginRight", len: 0, typ: NTI33554450, name: "scrollMarginRight", sons: null}, +{kind: 1, offset: "scrollMarginTop", len: 0, typ: NTI33554450, name: "scrollMarginTop", sons: null}, +{kind: 1, offset: "scrollPadding", len: 0, typ: NTI33554450, name: "scrollPadding", sons: null}, +{kind: 1, offset: "scrollPaddingBlock", len: 0, typ: NTI33554450, name: "scrollPaddingBlock", sons: null}, +{kind: 1, offset: "scrollPaddingBlockEnd", len: 0, typ: NTI33554450, name: "scrollPaddingBlockEnd", sons: null}, +{kind: 1, offset: "scrollPaddingBlockStart", len: 0, typ: NTI33554450, name: "scrollPaddingBlockStart", sons: null}, +{kind: 1, offset: "scrollPaddingBottom", len: 0, typ: NTI33554450, name: "scrollPaddingBottom", sons: null}, +{kind: 1, offset: "scrollPaddingInline", len: 0, typ: NTI33554450, name: "scrollPaddingInline", sons: null}, +{kind: 1, offset: "scrollPaddingInlineEnd", len: 0, typ: NTI33554450, name: "scrollPaddingInlineEnd", sons: null}, +{kind: 1, offset: "scrollPaddingInlineStart", len: 0, typ: NTI33554450, name: "scrollPaddingInlineStart", sons: null}, +{kind: 1, offset: "scrollPaddingLeft", len: 0, typ: NTI33554450, name: "scrollPaddingLeft", sons: null}, +{kind: 1, offset: "scrollPaddingRight", len: 0, typ: NTI33554450, name: "scrollPaddingRight", sons: null}, +{kind: 1, offset: "scrollPaddingTop", len: 0, typ: NTI33554450, name: "scrollPaddingTop", sons: null}, +{kind: 1, offset: "scrollSnapAlign", len: 0, typ: NTI33554450, name: "scrollSnapAlign", sons: null}, +{kind: 1, offset: "scrollSnapStop", len: 0, typ: NTI33554450, name: "scrollSnapStop", sons: null}, +{kind: 1, offset: "scrollSnapType", len: 0, typ: NTI33554450, name: "scrollSnapType", sons: null}, +{kind: 1, offset: "scrollbar3dLightColor", len: 0, typ: NTI33554450, name: "scrollbar3dLightColor", sons: null}, +{kind: 1, offset: "scrollbarArrowColor", len: 0, typ: NTI33554450, name: "scrollbarArrowColor", sons: null}, +{kind: 1, offset: "scrollbarBaseColor", len: 0, typ: NTI33554450, name: "scrollbarBaseColor", sons: null}, +{kind: 1, offset: "scrollbarColor", len: 0, typ: NTI33554450, name: "scrollbarColor", sons: null}, +{kind: 1, offset: "scrollbarDarkshadowColor", len: 0, typ: NTI33554450, name: "scrollbarDarkshadowColor", sons: null}, +{kind: 1, offset: "scrollbarFaceColor", len: 0, typ: NTI33554450, name: "scrollbarFaceColor", sons: null}, +{kind: 1, offset: "scrollbarHighlightColor", len: 0, typ: NTI33554450, name: "scrollbarHighlightColor", sons: null}, +{kind: 1, offset: "scrollbarShadowColor", len: 0, typ: NTI33554450, name: "scrollbarShadowColor", sons: null}, +{kind: 1, offset: "scrollbarTrackColor", len: 0, typ: NTI33554450, name: "scrollbarTrackColor", sons: null}, +{kind: 1, offset: "scrollbarWidth", len: 0, typ: NTI33554450, name: "scrollbarWidth", sons: null}, +{kind: 1, offset: "shapeImageThreshold", len: 0, typ: NTI33554450, name: "shapeImageThreshold", sons: null}, +{kind: 1, offset: "shapeMargin", len: 0, typ: NTI33554450, name: "shapeMargin", sons: null}, +{kind: 1, offset: "shapeOutside", len: 0, typ: NTI33554450, name: "shapeOutside", sons: null}, +{kind: 1, offset: "tabSize", len: 0, typ: NTI33554450, name: "tabSize", sons: null}, +{kind: 1, offset: "tableLayout", len: 0, typ: NTI33554450, name: "tableLayout", sons: null}, +{kind: 1, offset: "textAlign", len: 0, typ: NTI33554450, name: "textAlign", sons: null}, +{kind: 1, offset: "textAlignLast", len: 0, typ: NTI33554450, name: "textAlignLast", sons: null}, +{kind: 1, offset: "textCombineUpright", len: 0, typ: NTI33554450, name: "textCombineUpright", sons: null}, +{kind: 1, offset: "textDecoration", len: 0, typ: NTI33554450, name: "textDecoration", sons: null}, +{kind: 1, offset: "textDecorationColor", len: 0, typ: NTI33554450, name: "textDecorationColor", sons: null}, +{kind: 1, offset: "textDecorationLine", len: 0, typ: NTI33554450, name: "textDecorationLine", sons: null}, +{kind: 1, offset: "textDecorationSkipInk", len: 0, typ: NTI33554450, name: "textDecorationSkipInk", sons: null}, +{kind: 1, offset: "textDecorationStyle", len: 0, typ: NTI33554450, name: "textDecorationStyle", sons: null}, +{kind: 1, offset: "textDecorationThickness", len: 0, typ: NTI33554450, name: "textDecorationThickness", sons: null}, +{kind: 1, offset: "textEmphasis", len: 0, typ: NTI33554450, name: "textEmphasis", sons: null}, +{kind: 1, offset: "textEmphasisColor", len: 0, typ: NTI33554450, name: "textEmphasisColor", sons: null}, +{kind: 1, offset: "textEmphasisPosition", len: 0, typ: NTI33554450, name: "textEmphasisPosition", sons: null}, +{kind: 1, offset: "textEmphasisStyle", len: 0, typ: NTI33554450, name: "textEmphasisStyle", sons: null}, +{kind: 1, offset: "textIndent", len: 0, typ: NTI33554450, name: "textIndent", sons: null}, +{kind: 1, offset: "textJustify", len: 0, typ: NTI33554450, name: "textJustify", sons: null}, +{kind: 1, offset: "textOrientation", len: 0, typ: NTI33554450, name: "textOrientation", sons: null}, +{kind: 1, offset: "textOverflow", len: 0, typ: NTI33554450, name: "textOverflow", sons: null}, +{kind: 1, offset: "textRendering", len: 0, typ: NTI33554450, name: "textRendering", sons: null}, +{kind: 1, offset: "textShadow", len: 0, typ: NTI33554450, name: "textShadow", sons: null}, +{kind: 1, offset: "textTransform", len: 0, typ: NTI33554450, name: "textTransform", sons: null}, +{kind: 1, offset: "textUnderlineOffset", len: 0, typ: NTI33554450, name: "textUnderlineOffset", sons: null}, +{kind: 1, offset: "textUnderlinePosition", len: 0, typ: NTI33554450, name: "textUnderlinePosition", sons: null}, +{kind: 1, offset: "top", len: 0, typ: NTI33554450, name: "top", sons: null}, +{kind: 1, offset: "touchAction", len: 0, typ: NTI33554450, name: "touchAction", sons: null}, +{kind: 1, offset: "transform", len: 0, typ: NTI33554450, name: "transform", sons: null}, +{kind: 1, offset: "transformBox", len: 0, typ: NTI33554450, name: "transformBox", sons: null}, +{kind: 1, offset: "transformOrigin", len: 0, typ: NTI33554450, name: "transformOrigin", sons: null}, +{kind: 1, offset: "transformStyle", len: 0, typ: NTI33554450, name: "transformStyle", sons: null}, +{kind: 1, offset: "transition", len: 0, typ: NTI33554450, name: "transition", sons: null}, +{kind: 1, offset: "transitionDelay", len: 0, typ: NTI33554450, name: "transitionDelay", sons: null}, +{kind: 1, offset: "transitionDuration", len: 0, typ: NTI33554450, name: "transitionDuration", sons: null}, +{kind: 1, offset: "transitionProperty", len: 0, typ: NTI33554450, name: "transitionProperty", sons: null}, +{kind: 1, offset: "transitionTimingFunction", len: 0, typ: NTI33554450, name: "transitionTimingFunction", sons: null}, +{kind: 1, offset: "translate", len: 0, typ: NTI33554450, name: "translate", sons: null}, +{kind: 1, offset: "unicodeBidi", len: 0, typ: NTI33554450, name: "unicodeBidi", sons: null}, +{kind: 1, offset: "verticalAlign", len: 0, typ: NTI33554450, name: "verticalAlign", sons: null}, +{kind: 1, offset: "visibility", len: 0, typ: NTI33554450, name: "visibility", sons: null}, +{kind: 1, offset: "whiteSpace", len: 0, typ: NTI33554450, name: "whiteSpace", sons: null}, +{kind: 1, offset: "widows", len: 0, typ: NTI33554450, name: "widows", sons: null}, +{kind: 1, offset: "width", len: 0, typ: NTI33554450, name: "width", sons: null}, +{kind: 1, offset: "willChange", len: 0, typ: NTI33554450, name: "willChange", sons: null}, +{kind: 1, offset: "wordBreak", len: 0, typ: NTI33554450, name: "wordBreak", sons: null}, +{kind: 1, offset: "wordSpacing", len: 0, typ: NTI33554450, name: "wordSpacing", sons: null}, +{kind: 1, offset: "writingMode", len: 0, typ: NTI33554450, name: "writingMode", sons: null}, +{kind: 1, offset: "zIndex", len: 0, typ: NTI33554450, name: "zIndex", sons: null}]}; +NTI973078670.node = NNI973078670; +NTI973078670.base = NTI33555167; +NTI973078558.base = NTI973078670; +var NNI973078642 = {kind: 2, len: 22, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "attributes", len: 0, typ: NTI973078643, name: "attributes", sons: null}, +{kind: 1, offset: "childNodes", len: 0, typ: NTI973078644, name: "childNodes", sons: null}, +{kind: 1, offset: "children", len: 0, typ: NTI973078645, name: "children", sons: null}, +{kind: 1, offset: "data", len: 0, typ: NTI33554450, name: "data", sons: null}, +{kind: 1, offset: "firstChild", len: 0, typ: NTI973078544, name: "firstChild", sons: null}, +{kind: 1, offset: "lastChild", len: 0, typ: NTI973078544, name: "lastChild", sons: null}, +{kind: 1, offset: "nextSibling", len: 0, typ: NTI973078544, name: "nextSibling", sons: null}, +{kind: 1, offset: "nodeName", len: 0, typ: NTI33554450, name: "nodeName", sons: null}, +{kind: 1, offset: "nodeType", len: 0, typ: NTI973078543, name: "nodeType", sons: null}, +{kind: 1, offset: "nodeValue", len: 0, typ: NTI33554450, name: "nodeValue", sons: null}, +{kind: 1, offset: "parentNode", len: 0, typ: NTI973078544, name: "parentNode", sons: null}, +{kind: 1, offset: "content", len: 0, typ: NTI973078544, name: "content", sons: null}, +{kind: 1, offset: "previousSibling", len: 0, typ: NTI973078544, name: "previousSibling", sons: null}, +{kind: 1, offset: "ownerDocument", len: 0, typ: NTI973078545, name: "ownerDocument", sons: null}, +{kind: 1, offset: "innerHTML", len: 0, typ: NTI33554450, name: "innerHTML", sons: null}, +{kind: 1, offset: "outerHTML", len: 0, typ: NTI33554450, name: "outerHTML", sons: null}, +{kind: 1, offset: "innerText", len: 0, typ: NTI33554450, name: "innerText", sons: null}, +{kind: 1, offset: "textContent", len: 0, typ: NTI33554450, name: "textContent", sons: null}, +{kind: 1, offset: "style", len: 0, typ: NTI973078558, name: "style", sons: null}, +{kind: 1, offset: "baseURI", len: 0, typ: NTI33554450, name: "baseURI", sons: null}, +{kind: 1, offset: "parentElement", len: 0, typ: NTI973078546, name: "parentElement", sons: null}, +{kind: 1, offset: "isConnected", len: 0, typ: NTI33554466, name: "isConnected", sons: null}]}; +NTI973078642.node = NNI973078642; +var NNI973078597 = {kind: 2, len: 24, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "onabort", len: 0, typ: NTI973078598, name: "onabort", sons: null}, +{kind: 1, offset: "onblur", len: 0, typ: NTI973078599, name: "onblur", sons: null}, +{kind: 1, offset: "onchange", len: 0, typ: NTI973078600, name: "onchange", sons: null}, +{kind: 1, offset: "onclick", len: 0, typ: NTI973078601, name: "onclick", sons: null}, +{kind: 1, offset: "ondblclick", len: 0, typ: NTI973078602, name: "ondblclick", sons: null}, +{kind: 1, offset: "onerror", len: 0, typ: NTI973078603, name: "onerror", sons: null}, +{kind: 1, offset: "onfocus", len: 0, typ: NTI973078604, name: "onfocus", sons: null}, +{kind: 1, offset: "onkeydown", len: 0, typ: NTI973078605, name: "onkeydown", sons: null}, +{kind: 1, offset: "onkeypress", len: 0, typ: NTI973078606, name: "onkeypress", sons: null}, +{kind: 1, offset: "onkeyup", len: 0, typ: NTI973078607, name: "onkeyup", sons: null}, +{kind: 1, offset: "onload", len: 0, typ: NTI973078608, name: "onload", sons: null}, +{kind: 1, offset: "onmousedown", len: 0, typ: NTI973078609, name: "onmousedown", sons: null}, +{kind: 1, offset: "onmousemove", len: 0, typ: NTI973078610, name: "onmousemove", sons: null}, +{kind: 1, offset: "onmouseout", len: 0, typ: NTI973078611, name: "onmouseout", sons: null}, +{kind: 1, offset: "onmouseover", len: 0, typ: NTI973078612, name: "onmouseover", sons: null}, +{kind: 1, offset: "onmouseup", len: 0, typ: NTI973078613, name: "onmouseup", sons: null}, +{kind: 1, offset: "onreset", len: 0, typ: NTI973078614, name: "onreset", sons: null}, +{kind: 1, offset: "onselect", len: 0, typ: NTI973078615, name: "onselect", sons: null}, +{kind: 1, offset: "onstorage", len: 0, typ: NTI973078616, name: "onstorage", sons: null}, +{kind: 1, offset: "onsubmit", len: 0, typ: NTI973078617, name: "onsubmit", sons: null}, +{kind: 1, offset: "onunload", len: 0, typ: NTI973078618, name: "onunload", sons: null}, +{kind: 1, offset: "onloadstart", len: 0, typ: NTI973078619, name: "onloadstart", sons: null}, +{kind: 1, offset: "onprogress", len: 0, typ: NTI973078620, name: "onprogress", sons: null}, +{kind: 1, offset: "onloadend", len: 0, typ: NTI973078621, name: "onloadend", sons: null}]}; +NTI973078597.node = NNI973078597; +NTI973078597.base = NTI33555167; +NTI973078642.base = NTI973078597; +NTI973078653.base = NTI973078642; +NTI973078546.base = NTI973078653; +var NNI973078665 = {kind: 2, len: 3, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "text", len: 0, typ: NTI33554450, name: "text", sons: null}, +{kind: 1, offset: "x", len: 0, typ: NTI33554435, name: "x", sons: null}, +{kind: 1, offset: "y", len: 0, typ: NTI33554435, name: "y", sons: null}]}; +NTI973078665.node = NNI973078665; +NTI973078665.base = NTI973078653; +NTI973078554.base = NTI973078665; +NTI973078647.base = NTI973078554; +NTI973078648.base = NTI973078556; +var NNI973078669 = {kind: 2, len: 8, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "border", len: 0, typ: NTI33554435, name: "border", sons: null}, +{kind: 1, offset: "complete", len: 0, typ: NTI33554466, name: "complete", sons: null}, +{kind: 1, offset: "height", len: 0, typ: NTI33554435, name: "height", sons: null}, +{kind: 1, offset: "hspace", len: 0, typ: NTI33554435, name: "hspace", sons: null}, +{kind: 1, offset: "lowsrc", len: 0, typ: NTI33554450, name: "lowsrc", sons: null}, +{kind: 1, offset: "src", len: 0, typ: NTI33554450, name: "src", sons: null}, +{kind: 1, offset: "vspace", len: 0, typ: NTI33554435, name: "vspace", sons: null}, +{kind: 1, offset: "width", len: 0, typ: NTI33554435, name: "width", sons: null}]}; +NTI973078669.node = NNI973078669; +NTI973078669.base = NTI973078653; +NTI973078557.base = NTI973078669; +NTI973078649.base = NTI973078557; +NTI973078650.base = NTI973078546; +var NNI973078664 = {kind: 2, len: 6, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "height", len: 0, typ: NTI33554435, name: "height", sons: null}, +{kind: 1, offset: "hspace", len: 0, typ: NTI33554435, name: "hspace", sons: null}, +{kind: 1, offset: "src", len: 0, typ: NTI33554450, name: "src", sons: null}, +{kind: 1, offset: "width", len: 0, typ: NTI33554435, name: "width", sons: null}, +{kind: 1, offset: "type", len: 0, typ: NTI33554450, name: "type", sons: null}, +{kind: 1, offset: "vspace", len: 0, typ: NTI33554435, name: "vspace", sons: null}]}; +NTI973078664.node = NNI973078664; +NTI973078664.base = NTI973078653; +NTI973078553.base = NTI973078664; +NTI973078651.base = NTI973078553; +var NNI973078663 = {kind: 2, len: 4, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "target", len: 0, typ: NTI33554450, name: "target", sons: null}, +{kind: 1, offset: "text", len: 0, typ: NTI33554450, name: "text", sons: null}, +{kind: 1, offset: "x", len: 0, typ: NTI33554435, name: "x", sons: null}, +{kind: 1, offset: "y", len: 0, typ: NTI33554435, name: "y", sons: null}]}; +NTI973078663.node = NNI973078663; +NTI973078663.base = NTI973078653; +NTI973078552.base = NTI973078663; +NTI973078652.base = NTI973078552; +var NNI973078713 = {kind: 1, offset: "then", len: 0, typ: NTI973078714, name: "then", sons: null}; +NTI973078713.node = NNI973078713; +NTI973078593.base = NTI973078713; +var NNI973078716 = {kind: 2, len: 2, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "ready", len: 0, typ: NTI973078593, name: "ready", sons: null}, +{kind: 1, offset: "onloadingdone", len: 0, typ: NTI973078717, name: "onloadingdone", sons: null}]}; +NTI973078716.node = NNI973078716; +NTI973078594.base = NTI973078716; +var NNI973078646 = {kind: 2, len: 25, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "activeElement", len: 0, typ: NTI973078546, name: "activeElement", sons: null}, +{kind: 1, offset: "documentElement", len: 0, typ: NTI973078546, name: "documentElement", sons: null}, +{kind: 1, offset: "alinkColor", len: 0, typ: NTI33554450, name: "alinkColor", sons: null}, +{kind: 1, offset: "bgColor", len: 0, typ: NTI33554450, name: "bgColor", sons: null}, +{kind: 1, offset: "body", len: 0, typ: NTI973078546, name: "body", sons: null}, +{kind: 1, offset: "charset", len: 0, typ: NTI33554450, name: "charset", sons: null}, +{kind: 1, offset: "cookie", len: 0, typ: NTI33554450, name: "cookie", sons: null}, +{kind: 1, offset: "defaultCharset", len: 0, typ: NTI33554450, name: "defaultCharset", sons: null}, +{kind: 1, offset: "fgColor", len: 0, typ: NTI33554450, name: "fgColor", sons: null}, +{kind: 1, offset: "head", len: 0, typ: NTI973078546, name: "head", sons: null}, +{kind: 1, offset: "hidden", len: 0, typ: NTI33554466, name: "hidden", sons: null}, +{kind: 1, offset: "lastModified", len: 0, typ: NTI33554450, name: "lastModified", sons: null}, +{kind: 1, offset: "linkColor", len: 0, typ: NTI33554450, name: "linkColor", sons: null}, +{kind: 1, offset: "referrer", len: 0, typ: NTI33554450, name: "referrer", sons: null}, +{kind: 1, offset: "title", len: 0, typ: NTI33554450, name: "title", sons: null}, +{kind: 1, offset: "URL", len: 0, typ: NTI33554450, name: "URL", sons: null}, +{kind: 1, offset: "visibilityState", len: 0, typ: NTI33554450, name: "visibilityState", sons: null}, +{kind: 1, offset: "vlinkColor", len: 0, typ: NTI33554450, name: "vlinkColor", sons: null}, +{kind: 1, offset: "anchors", len: 0, typ: NTI973078647, name: "anchors", sons: null}, +{kind: 1, offset: "forms", len: 0, typ: NTI973078648, name: "forms", sons: null}, +{kind: 1, offset: "images", len: 0, typ: NTI973078649, name: "images", sons: null}, +{kind: 1, offset: "applets", len: 0, typ: NTI973078650, name: "applets", sons: null}, +{kind: 1, offset: "embeds", len: 0, typ: NTI973078651, name: "embeds", sons: null}, +{kind: 1, offset: "links", len: 0, typ: NTI973078652, name: "links", sons: null}, +{kind: 1, offset: "fonts", len: 0, typ: NTI973078594, name: "fonts", sons: null}]}; +NTI973078646.node = NNI973078646; +NTI973078646.base = NTI973078642; +var NNI134217745 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217745.node = NNI134217745; +var NNI33555172 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555172.node = NNI33555172; +NTI33555174.base = NTI33555171; +NTI33555175.base = NTI33555171; +var NNI33555171 = {kind: 2, len: 5, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "parent", len: 0, typ: NTI33555174, name: "parent", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}, +{kind: 1, offset: "message", len: 0, typ: NTI33554449, name: "msg", sons: null}, +{kind: 1, offset: "trace", len: 0, typ: NTI33554449, name: "trace", sons: null}, +{kind: 1, offset: "up", len: 0, typ: NTI33555175, name: "up", sons: null}]}; +NTI33555171.node = NNI33555171; +NTI33555171.base = NTI33555167; +NTI33555172.base = NTI33555171; +NTI134217745.base = NTI33555172; +var NNI33555836 = {kind: 2, len: 3, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "Field0", len: 0, typ: NTI33554450, name: "Field0", sons: null}, +{kind: 1, offset: "Field1", len: 0, typ: NTI33554435, name: "Field1", sons: null}, +{kind: 1, offset: "Field2", len: 0, typ: NTI33554450, name: "Field2", sons: null}]}; +NTI33555836.node = NNI33555836; +var NNI134217743 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217743.node = NNI134217743; +var NNI134217741 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217741.node = NNI134217741; +NTI134217741.base = NTI33555172; +NTI134217743.base = NTI134217741; +var NNI134217751 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217751.node = NNI134217751; +NTI134217751.base = NTI33555172; +var NNI134217749 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217749.node = NNI134217749; +NTI134217749.base = NTI33555172; +var NNI671088644 = {kind: 2, offset: 0, typ: null, name: null, len: 3, sons: {"0": {kind: 1, offset: 0, typ: NTI671088644, name: "cors", len: 0, sons: null}, +"1": {kind: 1, offset: 1, typ: NTI671088644, name: "no-cors", len: 0, sons: null}, +"2": {kind: 1, offset: 2, typ: NTI671088644, name: "same-origin", len: 0, sons: null}}}; +NTI671088644.node = NNI671088644; +var NNI671088645 = {kind: 2, offset: 0, typ: null, name: null, len: 3, sons: {"0": {kind: 1, offset: 0, typ: NTI671088645, name: "include", len: 0, sons: null}, +"1": {kind: 1, offset: 1, typ: NTI671088645, name: "same-origin", len: 0, sons: null}, +"2": {kind: 1, offset: 2, typ: NTI671088645, name: "omit", len: 0, sons: null}}}; +NTI671088645.node = NNI671088645; +var NNI671088646 = {kind: 2, offset: 0, typ: null, name: null, len: 5, sons: {"0": {kind: 1, offset: 0, typ: NTI671088646, name: "default", len: 0, sons: null}, +"1": {kind: 1, offset: 1, typ: NTI671088646, name: "no-store", len: 0, sons: null}, +"2": {kind: 1, offset: 2, typ: NTI671088646, name: "reload", len: 0, sons: null}, +"3": {kind: 1, offset: 3, typ: NTI671088646, name: "no-cache", len: 0, sons: null}, +"4": {kind: 1, offset: 4, typ: NTI671088646, name: "force-cache", len: 0, sons: null}}}; +NTI671088646.node = NNI671088646; +var NNI671088648 = {kind: 2, offset: 0, typ: null, name: null, len: 5, sons: {"0": {kind: 1, offset: 0, typ: NTI671088648, name: "no-referrer", len: 0, sons: null}, +"1": {kind: 1, offset: 1, typ: NTI671088648, name: "no-referrer-when-downgrade", len: 0, sons: null}, +"2": {kind: 1, offset: 2, typ: NTI671088648, name: "origin", len: 0, sons: null}, +"3": {kind: 1, offset: 3, typ: NTI671088648, name: "origin-when-cross-origin", len: 0, sons: null}, +"4": {kind: 1, offset: 4, typ: NTI671088648, name: "unsafe-url", len: 0, sons: null}}}; +NTI671088648.node = NNI671088648; +var NNI671088647 = {kind: 2, offset: 0, typ: null, name: null, len: 3, sons: {"0": {kind: 1, offset: 0, typ: NTI671088647, name: "follow", len: 0, sons: null}, +"1": {kind: 1, offset: 1, typ: NTI671088647, name: "error", len: 0, sons: null}, +"2": {kind: 1, offset: 2, typ: NTI671088647, name: "manual", len: 0, sons: null}}}; +NTI671088647.node = NNI671088647; +var NNI989855748 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI989855748.node = NNI989855748; +var NNI33555177 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555177.node = NNI33555177; +NTI33555177.base = NTI33555167; +NTI989855748.base = NTI33555177; +NTI989855747.base = NTI989855748; +var NNI671088651 = {kind: 2, len: 11, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "keepalive", len: 0, typ: NTI33554466, name: "keepalive", sons: null}, +{kind: 1, offset: "method", len: 0, typ: NTI33554450, name: "metod", sons: null}, +{kind: 1, offset: "body", len: 0, typ: NTI33554450, name: "body", sons: null}, +{kind: 1, offset: "integrity", len: 0, typ: NTI33554450, name: "integrity", sons: null}, +{kind: 1, offset: "referrer", len: 0, typ: NTI33554450, name: "referrer", sons: null}, +{kind: 1, offset: "mode", len: 0, typ: NTI33554450, name: "mode", sons: null}, +{kind: 1, offset: "credentials", len: 0, typ: NTI33554450, name: "credentials", sons: null}, +{kind: 1, offset: "cache", len: 0, typ: NTI33554450, name: "cache", sons: null}, +{kind: 1, offset: "redirect", len: 0, typ: NTI33554450, name: "redirect", sons: null}, +{kind: 1, offset: "referrerPolicy", len: 0, typ: NTI33554450, name: "referrerPolicy", sons: null}, +{kind: 1, offset: "headers", len: 0, typ: NTI989855747, name: "headers", sons: null}]}; +NTI671088651.node = NNI671088651; +NTI671088651.base = NTI33555177; + +function setConstr() { + var result = {}; + for (var i = 0; i < arguments.length; ++i) { + var x = arguments[i]; + if (typeof(x) == "object") { + for (var j = x[0]; j <= x[1]; ++j) { + result[j] = true; + } + } else { + result[x] = true; + } + } + return result; + + + +} +var ConstSet1 = setConstr(17, 16, 4, 18, 27, 19, 23, 22, 21); + +function nimCopy(dest_p0, src_p1, ti_p2) { + var result_33557321 = null; + + switch (ti_p2.kind) { + case 21: + case 22: + case 23: + case 5: + if (!(isFatPointer__system_u2869(ti_p2))) { + result_33557321 = src_p1; + } + else { + result_33557321 = [src_p1[0], src_p1[1]]; + } + + break; + case 19: + if (dest_p0 === null || dest_p0 === undefined) { + dest_p0 = {}; + } + else { + for (var key in dest_p0) { delete dest_p0[key]; } + } + for (var key in src_p1) { dest_p0[key] = src_p1[key]; } + result_33557321 = dest_p0; + + break; + case 18: + case 17: + if (!((ti_p2.base == null))) { + result_33557321 = nimCopy(dest_p0, src_p1, ti_p2.base); + } + else { + if ((ti_p2.kind == 17)) { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {m_type: ti_p2} : dest_p0; + } + else { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {} : dest_p0; + } + } + nimCopyAux(result_33557321, src_p1, ti_p2.node); + break; + case 4: + case 16: + if(ArrayBuffer.isView(src_p1)) { + if(dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new src_p1.constructor(src_p1); + } else { + dest_p0.set(src_p1, 0); + } + result_33557321 = dest_p0; + } else { + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + } + + break; + case 24: + case 27: + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + + break; + case 28: + if (src_p1 !== null) { + result_33557321 = src_p1.slice(0); + } + + break; + default: + result_33557321 = src_p1; + break; + } + + return result_33557321; + +} + +function arrayConstr(len_p0, value_p1, typ_p2) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; ++i) result[i] = nimCopy(null, value_p1, typ_p2); + return result; + + + +} + +function mnewString(len_p0) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; i++) {result[i] = 0;} + return result; + + + +} + +function addInt(a_p0, b_p1) { + var result = a_p0 + b_p1; + checkOverflowInt(result); + return result; + + + +} + +function chckRange(i_p0, a_p1, b_p2) { + var result_33557361 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557361 = i_p0; + break BeforeRet; + } + else { + raiseRangeError(); + } + + }; + + return result_33557361; + +} + +function chckIndx(i_p0, a_p1, b_p2) { + var result_33557356 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557356 = i_p0; + break BeforeRet; + } + else { + raiseIndexError(i_p0, a_p1, b_p2); + } + + }; + + return result_33557356; + +} + +function cstrToNimstr(c_p0) { + var ln = c_p0.length; + var result = new Array(ln); + var r = 0; + for (var i = 0; i < ln; ++i) { + var ch = c_p0.charCodeAt(i); + + if (ch < 128) { + result[r] = ch; + } + else { + if (ch < 2048) { + result[r] = (ch >> 6) | 192; + } + else { + if (ch < 55296 || ch >= 57344) { + result[r] = (ch >> 12) | 224; + } + else { + ++i; + ch = 65536 + (((ch & 1023) << 10) | (c_p0.charCodeAt(i) & 1023)); + result[r] = (ch >> 18) | 240; + ++r; + result[r] = ((ch >> 12) & 63) | 128; + } + ++r; + result[r] = ((ch >> 6) & 63) | 128; + } + ++r; + result[r] = (ch & 63) | 128; + } + ++r; + } + return result; + + + +} + +function toJSStr(s_p0) { + var result_33556910 = null; + + var res_33556964 = newSeq__system_u2507((s_p0).length); + var i_33556965 = 0; + var j_33556966 = 0; + Label1: { + Label2: while (true) { + if (!(i_33556965 < (s_p0).length)) break Label2; + var c_33556967 = s_p0[i_33556965]; + if ((c_33556967 < 128)) { + res_33556964[j_33556966] = String.fromCharCode(c_33556967); + i_33556965 += 1; + } + else { + var helper_33556993 = newSeq__system_u2507(0); + Label3: { + Label4: while (true) { + if (!true) break Label4; + var code_33556994 = c_33556967.toString(16); + if ((((code_33556994) == null ? 0 : (code_33556994).length) == 1)) { + helper_33556993.push("%0");; + } + else { + helper_33556993.push("%");; + } + + helper_33556993.push(code_33556994);; + i_33556965 += 1; + if ((((s_p0).length <= i_33556965) || (s_p0[i_33556965] < 128))) { + break Label3; + } + + c_33556967 = s_p0[i_33556965]; + } + }; +++excHandler; + try { + res_33556964[j_33556966] = decodeURIComponent(helper_33556993.join("")); +--excHandler; +} catch (EXCEPTION) { + var prevJSError = lastJSError; + lastJSError = EXCEPTION; + --excHandler; + res_33556964[j_33556966] = helper_33556993.join(""); + lastJSError = prevJSError; + } finally { + } + } + + j_33556966 += 1; + } + }; + if (res_33556964.length < j_33556966) { for (var i = res_33556964.length ; i < j_33556966 ; ++i) res_33556964.push(null); } + else { res_33556964.length = j_33556966; }; + result_33556910 = res_33556964.join(""); + + return result_33556910; + +} + +function raiseException(e_p0, ename_p1) { + e_p0.name = ename_p1; + if ((excHandler == 0)) { + unhandledException(e_p0); + } + + e_p0.trace = nimCopy(null, rawWriteStackTrace__system_u2180(), NTI33554449); + throw e_p0; + + +} + +function makeNimstrLit(c_p0) { + var result = []; + for (var i = 0; i < c_p0.length; ++i) { + result[i] = c_p0.charCodeAt(i); + } + return result; + + + +} +var ConstSet2 = setConstr(0, 1); + +function reprEnum(e_p0, typ_p1) { + var result_33557626 = []; + + var F = {procname: "system.reprEnum", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/reprjs.nim", line: 0}; + framePtr = F; + F.line = 30; + F.filename = "reprjs.nim"; + var tmp_33557627 = false; + F.line = 31; + var item_33557628 = typ_p1.node.sons[e_p0]; + F.line = 32; + tmp_33557627 = item_33557628 !== undefined; + if (tmp_33557627) { + F.line = 34; + result_33557626 = nimCopy(null, makeNimstrLit(item_33557628.name), NTI33554449); + } + else { + F.line = 36; + result_33557626 = nimCopy(null, (HEX24__systemZdollars_u8(e_p0)).concat([32,40,105,110,118,97,108,105,100,32,100,97,116,97,33,41]), NTI33554449); + } + + framePtr = F.prev; + + return result_33557626; + +} +var F = {procname: "module macros", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/core/macros.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module macros", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/core/macros.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module hashes", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/hashes.nim", line: 0}; +framePtr = F; +F.line = 218; +F.filename = "hashes.nim"; +var objectID_754974898 = [0]; +framePtr = F.prev; +var F = {procname: "module hashes", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/hashes.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops_utils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/bitops_utils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops_utils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/bitops_utils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module countbits_impl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/countbits_impl.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module countbits_impl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/countbits_impl.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/bitops.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/bitops.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module fenv", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/fenv.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module fenv", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/fenv.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module math", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/math.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module math", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/math.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module algorithm", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/algorithm.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module algorithm", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/algorithm.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module outparams", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/outparams.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module outparams", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/outparams.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module tables", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/collections/tables.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module tables", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/collections/tables.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsffi", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsffi.nim", line: 0}; +framePtr = F; +F.line = 45; +F.filename = "jsffi.nim"; +F.line = 46; +framePtr = F.prev; +var F = {procname: "module jsffi", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsffi.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module asyncjs", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/asyncjs.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module asyncjs", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/asyncjs.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module dom", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/dom.nim", line: 0}; +framePtr = F; +F.line = 1399; +F.filename = "dom.nim"; +var document_973079937 = [{nodeType: 9, m_type: NTI973078646, activeElement: null, documentElement: null, alinkColor: null, bgColor: null, body: null, charset: null, cookie: null, defaultCharset: null, fgColor: null, head: null, hidden: false, lastModified: null, linkColor: null, referrer: null, title: null, URL: null, visibilityState: null, vlinkColor: null, anchors: [], forms: [], images: [], applets: [], embeds: [], links: [], fonts: null, attributes: [], childNodes: [], children: [], data: null, firstChild: null, lastChild: null, nextSibling: null, nodeName: null, nodeValue: null, parentNode: null, content: null, previousSibling: null, ownerDocument: null, innerHTML: null, outerHTML: null, innerText: null, textContent: null, style: null, baseURI: null, parentElement: null, isConnected: false, onabort: null, onblur: null, onchange: null, onclick: null, ondblclick: null, onerror: null, onfocus: null, onkeydown: null, onkeypress: null, onkeyup: null, onload: null, onmousedown: null, onmousemove: null, onmouseout: null, onmouseover: null, onmouseup: null, onreset: null, onselect: null, onstorage: null, onsubmit: null, onunload: null, onloadstart: null, onprogress: null, onloadend: null}]; +F.line = 1400; +document_973079937[0].ownerDocument = document_973079937[0]; +framePtr = F.prev; +var F = {procname: "module dom", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/dom.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsformdata", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsformdata.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsformdata", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsformdata.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsheaders", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsheaders.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsheaders", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsheaders.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module parseutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/parseutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module parseutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/parseutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module typetraits", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/typetraits.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module typetraits", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/typetraits.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module enumutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/enumutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module enumutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/enumutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module strbasics", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/strbasics.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module strbasics", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/strbasics.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module unicode", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/unicode.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module unicode", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/unicode.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module strimpl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/strimpl.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module strimpl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/strimpl.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module strutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/strutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module strutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/strutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module httpcore", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/httpcore.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module httpcore", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/httpcore.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsfetch", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsfetch.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsfetch", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsfetch.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsconsole", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsconsole.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsconsole", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsconsole.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module underscored_calls", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/underscored_calls.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module underscored_calls", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/underscored_calls.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module sugar", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/sugar.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module sugar", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/sugar.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function isFatPointer__system_u2869(ti_p0) { + var result_33557303 = false; + + BeforeRet: { + result_33557303 = !((ConstSet1[ti_p0.base.kind] != undefined)); + break BeforeRet; + }; + + return result_33557303; + +} + +function nimCopyAux(dest_p0, src_p1, n_p2) { + switch (n_p2.kind) { + case 0: + break; + case 1: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + + break; + case 2: + for (var i = 0; i < n_p2.sons.length; i++) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i]); + } + + break; + case 3: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + for (var i = 0; i < n_p2.sons.length; ++i) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i][1]); + } + + break; + } + + +} + +function add__system_u1942(x_p0, x_p0_Idx, y_p1) { + if (x_p0[x_p0_Idx] === null) { x_p0[x_p0_Idx] = []; } + var off = x_p0[x_p0_Idx].length; + x_p0[x_p0_Idx].length += y_p1.length; + for (var i = 0; i < y_p1.length; ++i) { + x_p0[x_p0_Idx][off+i] = y_p1.charCodeAt(i); + } + + + +} + +function raiseOverflow() { + raiseException({message: [111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119], parent: null, m_type: NTI134217743, name: null, trace: [], up: null}, "OverflowDefect"); + + +} + +function checkOverflowInt(a_p0) { + if (a_p0 > 2147483647 || a_p0 < -2147483648) raiseOverflow(); + + + +} + +function raiseRangeError() { + raiseException({message: [118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101], parent: null, m_type: NTI134217751, name: null, trace: [], up: null}, "RangeDefect"); + + +} + +function raiseIndexError(i_p0, a_p1, b_p2) { + var Temporary1; + + if ((b_p2 < a_p1)) { + Temporary1 = [105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]; + } + else { + Temporary1 = ([105,110,100,101,120,32]).concat(HEX24__systemZdollars_u8(i_p0),[32,110,111,116,32,105,110,32],HEX24__systemZdollars_u8(a_p1),[32,46,46,32],HEX24__systemZdollars_u8(b_p2)); + } + + raiseException({message: nimCopy(null, Temporary1, NTI33554449), parent: null, m_type: NTI134217749, name: null, trace: [], up: null}, "IndexDefect"); + + +} + +function addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, start_p2, n_p3) { + var Temporary1; + + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 44; + F.filename = "digitsutils.nim"; + var old_301990096 = (result_p0[result_p0_Idx]).length; + F.line = 45; + if (result_p0[result_p0_Idx].length < (Temporary1 = chckRange(addInt(old_301990096, n_p3), 0, 2147483647), Temporary1)) { for (var i = result_p0[result_p0_Idx].length; i < Temporary1; ++i) result_p0[result_p0_Idx].push(0); } + else {result_p0[result_p0_Idx].length = Temporary1; }; + Label2: { + F.line = 47; + var iHEX60gensym4_301990110 = 0; + F.line = 128; + F.filename = "iterators_1.nim"; + var i_654311882 = 0; + Label3: { + F.line = 129; + Label4: while (true) { + if (!(i_654311882 < n_p3)) break Label4; + F.line = 50; + F.filename = "digitsutils.nim"; + iHEX60gensym4_301990110 = i_654311882; + F.line = 47; + result_p0[result_p0_Idx][chckIndx(addInt(old_301990096, iHEX60gensym4_301990110), 0, (result_p0[result_p0_Idx]).length - 1)] = x_p1.charCodeAt(chckIndx(addInt(start_p2, iHEX60gensym4_301990110), 0, (x_p1).length - 1)); + F.line = 131; + F.filename = "iterators_1.nim"; + i_654311882 = addInt(i_654311882, 1); + } + }; + }; + framePtr = F.prev; + + +} + +function addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 56; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, 0, ((x_p1) == null ? 0 : (x_p1).length)); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 112; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, ((x_p1) + "")); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u241(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 116; + F.filename = "digitsutils.nim"; + addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, BigInt(x_p1)); + framePtr = F.prev; + + +} + +function HEX24__systemZdollars_u8(x_p0) { + var result_369098762 = [[]]; + + var F = {procname: "dollars.$", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/dollars.nim", line: 0}; + framePtr = F; + F.line = 18; + F.filename = "dollars.nim"; + addInt__stdZprivateZdigitsutils_u241(result_369098762, 0, x_p0); + framePtr = F.prev; + + return result_369098762[0]; + +} + +function auxWriteStackTrace__system_u2084(f_p0) { + var result_33556518 = [[]]; + + var it_33556526 = f_p0; + var i_33556527 = 0; + var total_33556528 = 0; + var tempFrames_33556529 = arrayConstr(64, {Field0: null, Field1: 0, Field2: null}, NTI33555836); + Label1: { + Label2: while (true) { + if (!(!((it_33556526 == null)) && (i_33556527 <= 63))) break Label2; + tempFrames_33556529[i_33556527].Field0 = it_33556526.procname; + tempFrames_33556529[i_33556527].Field1 = it_33556526.line; + tempFrames_33556529[i_33556527].Field2 = it_33556526.filename; + i_33556527 += 1; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + Label3: { + Label4: while (true) { + if (!!((it_33556526 == null))) break Label4; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + result_33556518[0] = nimCopy(null, [], NTI33554449); + if (!((total_33556528 == i_33556527))) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + result_33556518[0].push.apply(result_33556518[0], HEX24__systemZdollars_u8((total_33556528 - i_33556527)));; + result_33556518[0].push.apply(result_33556518[0], [32,99,97,108,108,115,32,111,109,105,116,116,101,100,41,32,46,46,46,10]);; + } + + Label5: { + var j_33556562 = 0; + var colontmp__654311874 = 0; + colontmp__654311874 = (i_33556527 - 1); + var res_654311876 = colontmp__654311874; + Label6: { + Label7: while (true) { + if (!(0 <= res_654311876)) break Label7; + j_33556562 = res_654311876; + result_33556518[0].push.apply(result_33556518[0], cstrToNimstr(tempFrames_33556529[j_33556562].Field2));; + if ((0 < tempFrames_33556529[j_33556562].Field1)) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, tempFrames_33556529[j_33556562].Field1); + if (false) { + result_33556518[0].push.apply(result_33556518[0], [44,32]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, 0); + } + + result_33556518[0].push.apply(result_33556518[0], [41]);; + } + + result_33556518[0].push.apply(result_33556518[0], [32,97,116,32]);; + add__system_u1942(result_33556518, 0, tempFrames_33556529[j_33556562].Field0); + result_33556518[0].push.apply(result_33556518[0], [10]);; + res_654311876 -= 1; + } + }; + }; + + return result_33556518[0]; + +} + +function rawWriteStackTrace__system_u2180() { + var result_33556613 = []; + + if (!((framePtr == null))) { + result_33556613 = nimCopy(null, ([84,114,97,99,101,98,97,99,107,32,40,109,111,115,116,32,114,101,99,101,110,116,32,99,97,108,108,32,108,97,115,116,41,10]).concat(auxWriteStackTrace__system_u2084(framePtr)), NTI33554449); + } + else { + result_33556613 = nimCopy(null, [78,111,32,115,116,97,99,107,32,116,114,97,99,101,98,97,99,107,32,97,118,97,105,108,97,98,108,101,10], NTI33554449); + } + + + return result_33556613; + +} + +function newSeq__system_u2507(len_p0) { + var result_33556943 = []; + + var F = {procname: "newSeq.newSeq", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system.nim", line: 0}; + framePtr = F; + F.line = 653; + F.filename = "system.nim"; + result_33556943 = new Array(len_p0); for (var i = 0 ; i < len_p0 ; ++i) { result_33556943[i] = null; } framePtr = F.prev; + + return result_33556943; + +} + +function unhandledException(e_p0) { + var buf_33556658 = [[]]; + if (!(((e_p0.message).length == 0))) { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32]);; + buf_33556658[0].push.apply(buf_33556658[0], e_p0.message);; + } + else { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110]);; + } + + buf_33556658[0].push.apply(buf_33556658[0], [32,91]);; + add__system_u1942(buf_33556658, 0, e_p0.name); + buf_33556658[0].push.apply(buf_33556658[0], [93,10]);; + buf_33556658[0].push.apply(buf_33556658[0], rawWriteStackTrace__system_u2180());; + var cbuf_33556659 = toJSStr(buf_33556658[0]); + framePtr = null; + if (typeof(Error) !== "undefined") { + throw new Error(cbuf_33556659); + } + else { + throw cbuf_33556659; + } + + + +} + +function sysFatal__stdZassertions_u44(message_p1) { + var F = {procname: "sysFatal.sysFatal", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/fatal.nim", line: 0}; + framePtr = F; + F.line = 53; + F.filename = "fatal.nim"; + raiseException({message: nimCopy(null, message_p1, NTI33554449), m_type: NTI134217745, parent: null, name: null, trace: [], up: null}, "AssertionDefect"); + framePtr = F.prev; + + +} + +function raiseAssert__stdZassertions_u42(msg_p0) { + var F = {procname: "assertions.raiseAssert", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 36; + F.filename = "assertions.nim"; + sysFatal__stdZassertions_u44(msg_p0); + framePtr = F.prev; + + +} + +function failedAssertImpl__stdZassertions_u84(msg_p0) { + var F = {procname: "assertions.failedAssertImpl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 41; + F.filename = "assertions.nim"; + raiseAssert__stdZassertions_u42(msg_p0); + framePtr = F.prev; + + +} + +function newfetchOptions__stdZjsfetch_u115(metod_p0, body_p1, mode_p2, credentials_p3, cache_p4, referrerPolicy_p5, keepalive_p6, redirect_p7, referrer_p8, integrity_p9, headers_p10) { + var Temporary1; + var Temporary2; + + var result_671088767 = null; + + var F = {procname: "jsfetch.newfetchOptions", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsfetch.nim", line: 0}; + framePtr = F; + F.line = 93; + F.filename = "jsfetch.nim"; + if (!((ConstSet2[metod_p0] != undefined))) { + Temporary1 = body_p1; + } + else { + Temporary1 = null; + } + + F.line = 97; + switch (metod_p0) { + case 0: + Temporary2 = "HEAD"; + break; + case 1: + Temporary2 = "GET"; + break; + case 2: + Temporary2 = "POST"; + break; + case 3: + Temporary2 = "PUT"; + break; + case 4: + Temporary2 = "DELETE"; + break; + case 8: + Temporary2 = "PATCH"; + break; + default: + Temporary2 = "GET"; + break; + } + result_671088767 = {body: Temporary1, mode: toJSStr(reprEnum(mode_p2, NTI671088644)), credentials: toJSStr(reprEnum(credentials_p3, NTI671088645)), cache: toJSStr(reprEnum(cache_p4, NTI671088646)), referrerPolicy: toJSStr(reprEnum(referrerPolicy_p5, NTI671088648)), keepalive: keepalive_p6, redirect: toJSStr(reprEnum(redirect_p7, NTI671088647)), referrer: referrer_p8, integrity: integrity_p9, headers: headers_p10, method: Temporary2, m_type: NTI671088651}; + framePtr = F.prev; + + return result_671088767; + +} +async function doFetch__jsfetch95examples951_u170() { + var result_654311596 = null; + + var F = {procname: "jsfetch_examples_1.doFetch", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim", line: 0}; + framePtr = F; + F.line = 119; + F.filename = "jsfetch.nim"; + result_654311596 = fetch("https://httpbin.org/get"); + framePtr = F.prev; + + return result_654311596; + +} +async function example__jsfetch95examples951_u202() { + var result_654311628 = null; + + var F = {procname: "jsfetch_examples_1.example", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim", line: 0}; + framePtr = F; + BeforeRet: { + F.line = 119; + F.filename = "jsfetch.nim"; + var response_654311638 = (await doFetch__jsfetch95examples951_u170()); + if (!(response_654311638.ok)) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(77, 9) `response.ok` ")); + } + + if (!((response_654311638.status == 200))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(78, 9) `response.status == 200.cint` ")); + } + + if (false) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(79, 9) `response.headers is Headers` ")); + } + + if (false) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(80, 9) `response.body is cstring` ")); + } + + F.line = 119; + result_654311628 = undefined; + break BeforeRet; + }; + framePtr = F.prev; + + return result_654311628; + +} + +function catch__jsfetch95examples951_u386(future_p0, onReject_p1) { + var result_654311814 = null; + + var F = {procname: "catch.catch", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/asyncjs.nim", line: 0}; + framePtr = F; + F.line = 269; + F.filename = "asyncjs.nim"; + result_654311814 = future_p0.catch(onReject_p1); + framePtr = F.prev; + + return result_654311814; + +} + +function then__jsfetch95examples951_u360(future_p0, onSuccess_p1, onReject_p2) { + var result_654311790 = null; + + var F = {procname: "then.then", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/asyncjs.nim", line: 0}; + framePtr = F; + BeforeRet: { + F.line = 245; + F.filename = "asyncjs.nim"; + var ret_654311805 = null; + F.line = 246; + ret_654311805 = future_p0.then(onSuccess_p1, onReject_p2); + F.line = 247; + result_654311790 = ret_654311805; + break BeforeRet; + }; + framePtr = F.prev; + + return result_654311790; + +} + +function then__jsfetch95examples951_u319(future_p0, onSuccess_p1, onReject_p2) { + var result_654311749 = null; + + var F = {procname: "then.then", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/asyncjs.nim", line: 0}; + framePtr = F; + BeforeRet: { + F.line = 245; + F.filename = "asyncjs.nim"; + var ret_654311779 = null; + F.line = 246; + ret_654311779 = future_p0.then(onSuccess_p1, onReject_p2); + F.line = 247; + result_654311749 = ret_654311779; + break BeforeRet; + }; + framePtr = F.prev; + + return result_654311749; + +} +async function example2__jsfetch95examples951_u270() { + +function HEX3Aanonymous__jsfetch95examples951_u300(response_p0) { + var result_654311726 = null; + + var F = {procname: "example2.:anonymous", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim", line: 0}; + framePtr = F; + F.line = 87; + F.filename = "jsfetch_examples_1.nim"; + result_654311726 = response_p0.json(); + framePtr = F.prev; + + return result_654311726; + +} + +function HEX3Aanonymous__jsfetch95examples951_u357(json_p0) { + var F = {procname: "example2.:anonymous", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim", line: 0}; + framePtr = F; + F.line = 88; + F.filename = "jsfetch_examples_1.nim"; + console.log(json_p0); + framePtr = F.prev; + + +} + var Temporary1; + +function HEX3Aanonymous__jsfetch95examples951_u383(err_p0) { + var F = {procname: "example2.:anonymous", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim", line: 0}; + framePtr = F; + F.line = 119; + F.filename = "jsfetch.nim"; + console.log("Request Failed", err_p0); + framePtr = F.prev; + + +} + + var result_654311696 = null; + + var F = {procname: "jsfetch_examples_1.example2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim", line: 0}; + framePtr = F; + BeforeRet: { + F.line = 119; + F.filename = "jsfetch.nim"; + Temporary1 = HEX3Aanonymous__jsfetch95examples951_u383.bind(null); Temporary1.ClP_0 = HEX3Aanonymous__jsfetch95examples951_u383; Temporary1.ClE_0 = null; + (await catch__jsfetch95examples951_u386(then__jsfetch95examples951_u360(then__jsfetch95examples951_u319(fetch("https://api.github.com/users/torvalds"), HEX3Aanonymous__jsfetch95examples951_u300, null), HEX3Aanonymous__jsfetch95examples951_u357, null), Temporary1)); + F.line = 119; + result_654311696 = undefined; + break BeforeRet; + }; + framePtr = F.prev; + + return result_654311696; + +} +var F = {procname: "module jsfetch_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim", line: 0}; +framePtr = F; +Label1: { + F.line = 119; + F.filename = "jsfetch.nim"; + var options0_654311434 = {method: "POST", body: "{\"key\": \"value\"}", mode: "no-cors", credentials: "omit", cache: "no-cache", referrerPolicy: "no-referrer", keepalive: false, redirect: "follow", referrer: "client", integrity: "", headers: new Headers()}; + if (!((options0_654311434.keepalive == false))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(28, 5) `options0.keepalive == false` ")); + } + + if (!((options0_654311434.method == "POST"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(29, 5) `options0.metod == \"POST\".cstring` ")); + } + + if (!((options0_654311434.body == "{\"key\": \"value\"}"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(30, 5) `options0.body == \"\"\"{\"key\": \"value\"}\"\"\".cstring` ")); + } + + if (!((options0_654311434.mode == "no-cors"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(31, 5) `options0.mode == \"no-cors\".cstring` ")); + } + + if (!((options0_654311434.credentials == "omit"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(32, 5) `options0.credentials == \"omit\".cstring` ")); + } + + if (!((options0_654311434.cache == "no-cache"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(33, 5) `options0.cache == \"no-cache\".cstring` ")); + } + + if (!((options0_654311434.referrerPolicy == "no-referrer"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(34, 5) `options0.referrerPolicy == \"no-referrer\".cstring` ")); + } + + if (!((options0_654311434.redirect == "follow"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(35, 5) `options0.redirect == \"follow\".cstring` ")); + } + + if (!((options0_654311434.referrer == "client"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(36, 5) `options0.referrer == \"client\".cstring` ")); + } + + if (!((options0_654311434.integrity == ""))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(37, 5) `options0.integrity == \"\".cstring` ")); + } + + if (!((Array.from(options0_654311434.headers.entries()).length == 0))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(38, 5) `options0.headers.len == 0` ")); + } + +}; +Label2: { + F.line = 119; + var options1_654311490 = newfetchOptions__stdZjsfetch_u115(2, "{\"key\": \"value\"}", 1, 2, 3, 0, false, 0, "client", "", new Headers()); + if (!((options1_654311490.keepalive == false))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(54, 5) `options1.keepalive == false` ")); + } + + if (!((options1_654311490.method == "POST"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(55, 5) `options1.metod == $HttpPost` ")); + } + + if (!((options1_654311490.body == "{\"key\": \"value\"}"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(56, 5) `options1.body == \"\"\"{\"key\": \"value\"}\"\"\".cstring` ")); + } + + if (!((options1_654311490.mode == "no-cors"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(57, 5) `options1.mode == $fmNoCors` ")); + } + + if (!((options1_654311490.credentials == "omit"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(58, 5) `options1.credentials == $fcOmit` ")); + } + + if (!((options1_654311490.cache == "no-cache"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(59, 5) `options1.cache == $fchNoCache` ")); + } + + if (!((options1_654311490.referrerPolicy == "no-referrer"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(60, 5) `options1.referrerPolicy == $frpNoReferrer` ")); + } + + if (!((options1_654311490.redirect == "follow"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(61, 5) `options1.redirect == $frFollow` ")); + } + + if (!((options1_654311490.referrer == "client"))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(62, 5) `options1.referrer == \"client\".cstring` ")); + } + + if (!((options1_654311490.integrity == ""))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(63, 5) `options1.integrity == \"\".cstring` ")); + } + + if (!((Array.from(options1_654311490.headers.entries()).length == 0))) { + F.line = 119; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim(64, 5) `options1.headers.len == 0` ")); + } + +}; +Label3: { + F.line = 119; + var response_654311567 = (new Response("-. .. --")); + F.line = 119; + var request_654311568 = (new Request("http://nim-lang.org")); +}; +if (false) { +Label4: { + F.line = 119; + (example__jsfetch95examples951_u202()); +}; +Label5: { + F.line = 119; + (example2__jsfetch95examples951_u270()); +}; +} + +framePtr = F.prev; +var F = {procname: "module jsfetch_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsfetch_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsfetch_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; diff --git a/nimcache/runnableExamples/jsfetch_group0_examples.nim b/nimcache/runnableExamples/jsfetch_group0_examples.nim new file mode 100644 index 0000000000000..af92302f7855c --- /dev/null +++ b/nimcache/runnableExamples/jsfetch_group0_examples.nim @@ -0,0 +1,4 @@ +# autogenerated by docgen +# source: /home/runner/work/Nim/Nim/lib/std/jsfetch.nim +# rdoccmd: -r:off +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsfetch_examples_1.nim" diff --git a/nimcache/runnableExamples/jsffi_examples_1.nim b/nimcache/runnableExamples/jsffi_examples_1.nim new file mode 100644 index 0000000000000..dfa5de867b15e --- /dev/null +++ b/nimcache/runnableExamples/jsffi_examples_1.nim @@ -0,0 +1,25 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/jsffi.nim(16, 1) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/jsffi.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/jsffi.nim", 16, 1).}: + # Here, we are using jQuery for just a few calls and do not want to wrap the + # whole library: + + # import the document object and the console + var document {.importc, nodecl.}: JsObject + var console {.importc, nodecl.}: JsObject + # import the "$" function + proc jq(selector: JsObject): JsObject {.importjs: "$$(#)".} + + # Use jQuery to make the following code run, after the document is ready. + # This uses an experimental `.()` operator for `JsObject`, to emit + # JavaScript calls, when no corresponding proc exists for `JsObject`. + proc main = + jq(document).ready(proc() = + console.log("Hello JavaScript!") + ) + diff --git a/nimcache/runnableExamples/jsffi_examples_2.nim b/nimcache/runnableExamples/jsffi_examples_2.nim new file mode 100644 index 0000000000000..aaa21e9fc5fe7 --- /dev/null +++ b/nimcache/runnableExamples/jsffi_examples_2.nim @@ -0,0 +1,12 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/jsffi.nim(224, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/jsffi.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/jsffi.nim", 224, 3).}: + let obj = newJsObject() + obj.a = 20 + assert obj.a.to(int) == 20 + diff --git a/nimcache/runnableExamples/jsffi_group0_examples.js b/nimcache/runnableExamples/jsffi_group0_examples.js new file mode 100644 index 0000000000000..11970c53469c5 --- /dev/null +++ b/nimcache/runnableExamples/jsffi_group0_examples.js @@ -0,0 +1,787 @@ +/* Generated by the Nim Compiler v2.2.1 */ +var framePtr = null; +var excHandler = 0; +var lastJSError = null; +var NTI134217749 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217751 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217741 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217743 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554435 = {size: 0,kind: 31,base: null,node: null,finalizer: null}; +var NTI33555836 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI33555167 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555175 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554450 = {size: 0,kind: 29,base: null,node: null,finalizer: null}; +var NTI33555174 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33555171 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555172 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217745 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554449 = {size: 0,kind: 28,base: null,node: null,finalizer: null}; +var NNI134217745 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217745.node = NNI134217745; +var NNI33555172 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555172.node = NNI33555172; +NTI33555174.base = NTI33555171; +NTI33555175.base = NTI33555171; +var NNI33555171 = {kind: 2, len: 5, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "parent", len: 0, typ: NTI33555174, name: "parent", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}, +{kind: 1, offset: "message", len: 0, typ: NTI33554449, name: "msg", sons: null}, +{kind: 1, offset: "trace", len: 0, typ: NTI33554449, name: "trace", sons: null}, +{kind: 1, offset: "up", len: 0, typ: NTI33555175, name: "up", sons: null}]}; +NTI33555171.node = NNI33555171; +var NNI33555167 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555167.node = NNI33555167; +NTI33555171.base = NTI33555167; +NTI33555172.base = NTI33555171; +NTI134217745.base = NTI33555172; +var NNI33555836 = {kind: 2, len: 3, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "Field0", len: 0, typ: NTI33554450, name: "Field0", sons: null}, +{kind: 1, offset: "Field1", len: 0, typ: NTI33554435, name: "Field1", sons: null}, +{kind: 1, offset: "Field2", len: 0, typ: NTI33554450, name: "Field2", sons: null}]}; +NTI33555836.node = NNI33555836; +var NNI134217743 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217743.node = NNI134217743; +var NNI134217741 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217741.node = NNI134217741; +NTI134217741.base = NTI33555172; +NTI134217743.base = NTI134217741; +var NNI134217751 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217751.node = NNI134217751; +NTI134217751.base = NTI33555172; +var NNI134217749 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217749.node = NNI134217749; +NTI134217749.base = NTI33555172; + +function setConstr() { + var result = {}; + for (var i = 0; i < arguments.length; ++i) { + var x = arguments[i]; + if (typeof(x) == "object") { + for (var j = x[0]; j <= x[1]; ++j) { + result[j] = true; + } + } else { + result[x] = true; + } + } + return result; + + + +} +var ConstSet1 = setConstr(17, 16, 4, 18, 27, 19, 23, 22, 21); + +function nimCopy(dest_p0, src_p1, ti_p2) { + var result_33557321 = null; + + switch (ti_p2.kind) { + case 21: + case 22: + case 23: + case 5: + if (!(isFatPointer__system_u2869(ti_p2))) { + result_33557321 = src_p1; + } + else { + result_33557321 = [src_p1[0], src_p1[1]]; + } + + break; + case 19: + if (dest_p0 === null || dest_p0 === undefined) { + dest_p0 = {}; + } + else { + for (var key in dest_p0) { delete dest_p0[key]; } + } + for (var key in src_p1) { dest_p0[key] = src_p1[key]; } + result_33557321 = dest_p0; + + break; + case 18: + case 17: + if (!((ti_p2.base == null))) { + result_33557321 = nimCopy(dest_p0, src_p1, ti_p2.base); + } + else { + if ((ti_p2.kind == 17)) { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {m_type: ti_p2} : dest_p0; + } + else { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {} : dest_p0; + } + } + nimCopyAux(result_33557321, src_p1, ti_p2.node); + break; + case 4: + case 16: + if(ArrayBuffer.isView(src_p1)) { + if(dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new src_p1.constructor(src_p1); + } else { + dest_p0.set(src_p1, 0); + } + result_33557321 = dest_p0; + } else { + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + } + + break; + case 24: + case 27: + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + + break; + case 28: + if (src_p1 !== null) { + result_33557321 = src_p1.slice(0); + } + + break; + default: + result_33557321 = src_p1; + break; + } + + return result_33557321; + +} + +function arrayConstr(len_p0, value_p1, typ_p2) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; ++i) result[i] = nimCopy(null, value_p1, typ_p2); + return result; + + + +} + +function mnewString(len_p0) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; i++) {result[i] = 0;} + return result; + + + +} + +function addInt(a_p0, b_p1) { + var result = a_p0 + b_p1; + checkOverflowInt(result); + return result; + + + +} + +function chckRange(i_p0, a_p1, b_p2) { + var result_33557361 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557361 = i_p0; + break BeforeRet; + } + else { + raiseRangeError(); + } + + }; + + return result_33557361; + +} + +function chckIndx(i_p0, a_p1, b_p2) { + var result_33557356 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557356 = i_p0; + break BeforeRet; + } + else { + raiseIndexError(i_p0, a_p1, b_p2); + } + + }; + + return result_33557356; + +} + +function cstrToNimstr(c_p0) { + var ln = c_p0.length; + var result = new Array(ln); + var r = 0; + for (var i = 0; i < ln; ++i) { + var ch = c_p0.charCodeAt(i); + + if (ch < 128) { + result[r] = ch; + } + else { + if (ch < 2048) { + result[r] = (ch >> 6) | 192; + } + else { + if (ch < 55296 || ch >= 57344) { + result[r] = (ch >> 12) | 224; + } + else { + ++i; + ch = 65536 + (((ch & 1023) << 10) | (c_p0.charCodeAt(i) & 1023)); + result[r] = (ch >> 18) | 240; + ++r; + result[r] = ((ch >> 12) & 63) | 128; + } + ++r; + result[r] = ((ch >> 6) & 63) | 128; + } + ++r; + result[r] = (ch & 63) | 128; + } + ++r; + } + return result; + + + +} + +function toJSStr(s_p0) { + var result_33556910 = null; + + var res_33556964 = newSeq__system_u2507((s_p0).length); + var i_33556965 = 0; + var j_33556966 = 0; + Label1: { + Label2: while (true) { + if (!(i_33556965 < (s_p0).length)) break Label2; + var c_33556967 = s_p0[i_33556965]; + if ((c_33556967 < 128)) { + res_33556964[j_33556966] = String.fromCharCode(c_33556967); + i_33556965 += 1; + } + else { + var helper_33556993 = newSeq__system_u2507(0); + Label3: { + Label4: while (true) { + if (!true) break Label4; + var code_33556994 = c_33556967.toString(16); + if ((((code_33556994) == null ? 0 : (code_33556994).length) == 1)) { + helper_33556993.push("%0");; + } + else { + helper_33556993.push("%");; + } + + helper_33556993.push(code_33556994);; + i_33556965 += 1; + if ((((s_p0).length <= i_33556965) || (s_p0[i_33556965] < 128))) { + break Label3; + } + + c_33556967 = s_p0[i_33556965]; + } + }; +++excHandler; + try { + res_33556964[j_33556966] = decodeURIComponent(helper_33556993.join("")); +--excHandler; +} catch (EXCEPTION) { + var prevJSError = lastJSError; + lastJSError = EXCEPTION; + --excHandler; + res_33556964[j_33556966] = helper_33556993.join(""); + lastJSError = prevJSError; + } finally { + } + } + + j_33556966 += 1; + } + }; + if (res_33556964.length < j_33556966) { for (var i = res_33556964.length ; i < j_33556966 ; ++i) res_33556964.push(null); } + else { res_33556964.length = j_33556966; }; + result_33556910 = res_33556964.join(""); + + return result_33556910; + +} + +function raiseException(e_p0, ename_p1) { + e_p0.name = ename_p1; + if ((excHandler == 0)) { + unhandledException(e_p0); + } + + e_p0.trace = nimCopy(null, rawWriteStackTrace__system_u2180(), NTI33554449); + throw e_p0; + + +} + +function makeNimstrLit(c_p0) { + var result = []; + for (var i = 0; i < c_p0.length; ++i) { + result[i] = c_p0.charCodeAt(i); + } + return result; + + + +} +var F = {procname: "module macros", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/core/macros.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module macros", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/core/macros.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module hashes", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/hashes.nim", line: 0}; +framePtr = F; +F.line = 218; +F.filename = "hashes.nim"; +var objectID_721420466 = [0]; +framePtr = F.prev; +var F = {procname: "module hashes", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/hashes.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops_utils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/bitops_utils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops_utils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/bitops_utils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module countbits_impl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/countbits_impl.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module countbits_impl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/countbits_impl.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/bitops.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/bitops.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module fenv", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/fenv.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module fenv", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/fenv.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module math", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/math.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module math", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/math.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module algorithm", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/algorithm.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module algorithm", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/algorithm.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module outparams", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/outparams.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module outparams", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/outparams.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module tables", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/collections/tables.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module tables", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/collections/tables.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsffi", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsffi.nim", line: 0}; +framePtr = F; +F.line = 45; +F.filename = "jsffi.nim"; +F.line = 46; +framePtr = F.prev; +var F = {procname: "module jsffi", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsffi.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsffi_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsffi_examples_1.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsffi_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsffi_examples_1.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function isFatPointer__system_u2869(ti_p0) { + var result_33557303 = false; + + BeforeRet: { + result_33557303 = !((ConstSet1[ti_p0.base.kind] != undefined)); + break BeforeRet; + }; + + return result_33557303; + +} + +function nimCopyAux(dest_p0, src_p1, n_p2) { + switch (n_p2.kind) { + case 0: + break; + case 1: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + + break; + case 2: + for (var i = 0; i < n_p2.sons.length; i++) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i]); + } + + break; + case 3: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + for (var i = 0; i < n_p2.sons.length; ++i) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i][1]); + } + + break; + } + + +} + +function add__system_u1942(x_p0, x_p0_Idx, y_p1) { + if (x_p0[x_p0_Idx] === null) { x_p0[x_p0_Idx] = []; } + var off = x_p0[x_p0_Idx].length; + x_p0[x_p0_Idx].length += y_p1.length; + for (var i = 0; i < y_p1.length; ++i) { + x_p0[x_p0_Idx][off+i] = y_p1.charCodeAt(i); + } + + + +} + +function raiseOverflow() { + raiseException({message: [111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119], parent: null, m_type: NTI134217743, name: null, trace: [], up: null}, "OverflowDefect"); + + +} + +function checkOverflowInt(a_p0) { + if (a_p0 > 2147483647 || a_p0 < -2147483648) raiseOverflow(); + + + +} + +function raiseRangeError() { + raiseException({message: [118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101], parent: null, m_type: NTI134217751, name: null, trace: [], up: null}, "RangeDefect"); + + +} + +function raiseIndexError(i_p0, a_p1, b_p2) { + var Temporary1; + + if ((b_p2 < a_p1)) { + Temporary1 = [105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]; + } + else { + Temporary1 = ([105,110,100,101,120,32]).concat(HEX24__systemZdollars_u8(i_p0),[32,110,111,116,32,105,110,32],HEX24__systemZdollars_u8(a_p1),[32,46,46,32],HEX24__systemZdollars_u8(b_p2)); + } + + raiseException({message: nimCopy(null, Temporary1, NTI33554449), parent: null, m_type: NTI134217749, name: null, trace: [], up: null}, "IndexDefect"); + + +} + +function addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, start_p2, n_p3) { + var Temporary1; + + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 44; + F.filename = "digitsutils.nim"; + var old_301990096 = (result_p0[result_p0_Idx]).length; + F.line = 45; + if (result_p0[result_p0_Idx].length < (Temporary1 = chckRange(addInt(old_301990096, n_p3), 0, 2147483647), Temporary1)) { for (var i = result_p0[result_p0_Idx].length; i < Temporary1; ++i) result_p0[result_p0_Idx].push(0); } + else {result_p0[result_p0_Idx].length = Temporary1; }; + Label2: { + F.line = 47; + var iHEX60gensym4_301990110 = 0; + F.line = 128; + F.filename = "iterators_1.nim"; + var i_922746917 = 0; + Label3: { + F.line = 129; + Label4: while (true) { + if (!(i_922746917 < n_p3)) break Label4; + F.line = 50; + F.filename = "digitsutils.nim"; + iHEX60gensym4_301990110 = i_922746917; + F.line = 47; + result_p0[result_p0_Idx][chckIndx(addInt(old_301990096, iHEX60gensym4_301990110), 0, (result_p0[result_p0_Idx]).length - 1)] = x_p1.charCodeAt(chckIndx(addInt(start_p2, iHEX60gensym4_301990110), 0, (x_p1).length - 1)); + F.line = 131; + F.filename = "iterators_1.nim"; + i_922746917 = addInt(i_922746917, 1); + } + }; + }; + framePtr = F.prev; + + +} + +function addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 56; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, 0, ((x_p1) == null ? 0 : (x_p1).length)); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 112; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, ((x_p1) + "")); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u241(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 116; + F.filename = "digitsutils.nim"; + addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, BigInt(x_p1)); + framePtr = F.prev; + + +} + +function HEX24__systemZdollars_u8(x_p0) { + var result_369098762 = [[]]; + + var F = {procname: "dollars.$", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/dollars.nim", line: 0}; + framePtr = F; + F.line = 18; + F.filename = "dollars.nim"; + addInt__stdZprivateZdigitsutils_u241(result_369098762, 0, x_p0); + framePtr = F.prev; + + return result_369098762[0]; + +} + +function auxWriteStackTrace__system_u2084(f_p0) { + var result_33556518 = [[]]; + + var it_33556526 = f_p0; + var i_33556527 = 0; + var total_33556528 = 0; + var tempFrames_33556529 = arrayConstr(64, {Field0: null, Field1: 0, Field2: null}, NTI33555836); + Label1: { + Label2: while (true) { + if (!(!((it_33556526 == null)) && (i_33556527 <= 63))) break Label2; + tempFrames_33556529[i_33556527].Field0 = it_33556526.procname; + tempFrames_33556529[i_33556527].Field1 = it_33556526.line; + tempFrames_33556529[i_33556527].Field2 = it_33556526.filename; + i_33556527 += 1; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + Label3: { + Label4: while (true) { + if (!!((it_33556526 == null))) break Label4; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + result_33556518[0] = nimCopy(null, [], NTI33554449); + if (!((total_33556528 == i_33556527))) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + result_33556518[0].push.apply(result_33556518[0], HEX24__systemZdollars_u8((total_33556528 - i_33556527)));; + result_33556518[0].push.apply(result_33556518[0], [32,99,97,108,108,115,32,111,109,105,116,116,101,100,41,32,46,46,46,10]);; + } + + Label5: { + var j_33556562 = 0; + var colontmp__922746909 = 0; + colontmp__922746909 = (i_33556527 - 1); + var res_922746911 = colontmp__922746909; + Label6: { + Label7: while (true) { + if (!(0 <= res_922746911)) break Label7; + j_33556562 = res_922746911; + result_33556518[0].push.apply(result_33556518[0], cstrToNimstr(tempFrames_33556529[j_33556562].Field2));; + if ((0 < tempFrames_33556529[j_33556562].Field1)) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, tempFrames_33556529[j_33556562].Field1); + if (false) { + result_33556518[0].push.apply(result_33556518[0], [44,32]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, 0); + } + + result_33556518[0].push.apply(result_33556518[0], [41]);; + } + + result_33556518[0].push.apply(result_33556518[0], [32,97,116,32]);; + add__system_u1942(result_33556518, 0, tempFrames_33556529[j_33556562].Field0); + result_33556518[0].push.apply(result_33556518[0], [10]);; + res_922746911 -= 1; + } + }; + }; + + return result_33556518[0]; + +} + +function rawWriteStackTrace__system_u2180() { + var result_33556613 = []; + + if (!((framePtr == null))) { + result_33556613 = nimCopy(null, ([84,114,97,99,101,98,97,99,107,32,40,109,111,115,116,32,114,101,99,101,110,116,32,99,97,108,108,32,108,97,115,116,41,10]).concat(auxWriteStackTrace__system_u2084(framePtr)), NTI33554449); + } + else { + result_33556613 = nimCopy(null, [78,111,32,115,116,97,99,107,32,116,114,97,99,101,98,97,99,107,32,97,118,97,105,108,97,98,108,101,10], NTI33554449); + } + + + return result_33556613; + +} + +function newSeq__system_u2507(len_p0) { + var result_33556943 = []; + + var F = {procname: "newSeq.newSeq", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system.nim", line: 0}; + framePtr = F; + F.line = 653; + F.filename = "system.nim"; + result_33556943 = new Array(len_p0); for (var i = 0 ; i < len_p0 ; ++i) { result_33556943[i] = null; } framePtr = F.prev; + + return result_33556943; + +} + +function unhandledException(e_p0) { + var buf_33556658 = [[]]; + if (!(((e_p0.message).length == 0))) { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32]);; + buf_33556658[0].push.apply(buf_33556658[0], e_p0.message);; + } + else { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110]);; + } + + buf_33556658[0].push.apply(buf_33556658[0], [32,91]);; + add__system_u1942(buf_33556658, 0, e_p0.name); + buf_33556658[0].push.apply(buf_33556658[0], [93,10]);; + buf_33556658[0].push.apply(buf_33556658[0], rawWriteStackTrace__system_u2180());; + var cbuf_33556659 = toJSStr(buf_33556658[0]); + framePtr = null; + if (typeof(Error) !== "undefined") { + throw new Error(cbuf_33556659); + } + else { + throw cbuf_33556659; + } + + + +} + +function sysFatal__stdZassertions_u44(message_p1) { + var F = {procname: "sysFatal.sysFatal", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/fatal.nim", line: 0}; + framePtr = F; + F.line = 53; + F.filename = "fatal.nim"; + raiseException({message: nimCopy(null, message_p1, NTI33554449), m_type: NTI134217745, parent: null, name: null, trace: [], up: null}, "AssertionDefect"); + framePtr = F.prev; + + +} + +function raiseAssert__stdZassertions_u42(msg_p0) { + var F = {procname: "assertions.raiseAssert", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 36; + F.filename = "assertions.nim"; + sysFatal__stdZassertions_u44(msg_p0); + framePtr = F.prev; + + +} + +function failedAssertImpl__stdZassertions_u84(msg_p0) { + var F = {procname: "assertions.failedAssertImpl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 41; + F.filename = "assertions.nim"; + raiseAssert__stdZassertions_u42(msg_p0); + framePtr = F.prev; + + +} +var F = {procname: "module jsffi_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsffi_examples_2.nim", line: 0}; +framePtr = F; +F.line = 224; +F.filename = "jsffi.nim"; +var obj_922746883 = {}; +F.line = 224; +obj_922746883.a = 20; +if (!(((obj_922746883.a) == 20))) { +F.line = 224; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsffi_examples_2.nim(11, 3) `obj.a.to(int) == 20` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsffi_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsffi_examples_2.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsffi_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsffi_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsffi_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsffi_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; diff --git a/nimcache/runnableExamples/jsffi_group0_examples.nim b/nimcache/runnableExamples/jsffi_group0_examples.nim new file mode 100644 index 0000000000000..4b66ef3d4e2c6 --- /dev/null +++ b/nimcache/runnableExamples/jsffi_group0_examples.nim @@ -0,0 +1,5 @@ +# autogenerated by docgen +# source: /home/runner/work/Nim/Nim/lib/js/jsffi.nim +# rdoccmd: +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsffi_examples_1.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsffi_examples_2.nim" diff --git a/nimcache/runnableExamples/jsformdata_examples_1.nim b/nimcache/runnableExamples/jsformdata_examples_1.nim new file mode 100644 index 0000000000000..def7ead84643d --- /dev/null +++ b/nimcache/runnableExamples/jsformdata_examples_1.nim @@ -0,0 +1,17 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsformdata.nim(61, 17) +rdoccmd: -r:off +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsformdata.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsformdata.nim", 61, 17).}: + let data: FormData = newFormData() + data["key0"] = "value0".cstring + data.add("key1".cstring, "value1".cstring) + data.delete("key1") + assert data.hasKey("key0") + assert data["key0"] == "value0".cstring + data.clear() + assert data.len == 0 + diff --git a/nimcache/runnableExamples/jsformdata_group0_examples.js b/nimcache/runnableExamples/jsformdata_group0_examples.js new file mode 100644 index 0000000000000..5ca19fda4c394 --- /dev/null +++ b/nimcache/runnableExamples/jsformdata_group0_examples.js @@ -0,0 +1,1360 @@ +/* Generated by the Nim Compiler v2.2.1 */ +var framePtr = null; +var excHandler = 0; +var lastJSError = null; +var NTI134217749 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217751 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217741 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217743 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555836 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI33555175 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33555174 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33555171 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555172 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217745 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554449 = {size: 0,kind: 28,base: null,node: null,finalizer: null}; +var NTI687866045 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687866042 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687866041 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI687865921 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI687866044 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI687865922 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI687865991 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI687865880 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI687865980 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI687865992 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI687865881 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI687865979 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI687865978 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI687865997 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI687865885 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI687865977 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI687865976 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI687865993 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI687865882 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI687865975 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI687865949 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865948 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865947 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865946 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865945 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865944 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865943 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865942 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865941 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865940 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865939 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865938 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865937 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865936 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865935 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865934 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865933 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865932 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865931 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865930 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865929 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865928 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865927 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865926 = {size: 0,kind: 25,base: null,node: null,finalizer: null}; +var NTI687865925 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI687865998 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI687865886 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI687865873 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI687865871 = {size: 0, kind: 14, base: null, node: null, finalizer: null}; +var NTI687865973 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI687865972 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI687865872 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI687865971 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI687865970 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI687865983 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI687865994 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI687865883 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI687865982 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI33554435 = {size: 0,kind: 31,base: null,node: null,finalizer: null}; +var NTI687865996 = {size: 0, kind: 24, base: null, node: null, finalizer: null}; +var NTI687865995 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI687865884 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554466 = {size: 0,kind: 1,base: null,node: null,finalizer: null}; +var NTI33555167 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI687865967 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI687865870 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554450 = {size: 0,kind: 29,base: null,node: null,finalizer: null}; +var NTI687865981 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI687865874 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI687865974 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NNI687865967 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI687865967.node = NNI687865967; +var NNI33555167 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555167.node = NNI33555167; +NTI687865967.base = NTI33555167; +NTI687865870.base = NTI687865967; +NTI687865996.base = NTI687865874; +var NNI687865995 = {kind: 2, len: 10, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "acceptCharset", len: 0, typ: NTI33554450, name: "acceptCharset", sons: null}, +{kind: 1, offset: "action", len: 0, typ: NTI33554450, name: "action", sons: null}, +{kind: 1, offset: "autocomplete", len: 0, typ: NTI33554450, name: "autocomplete", sons: null}, +{kind: 1, offset: "elements", len: 0, typ: NTI687865996, name: "elements", sons: null}, +{kind: 1, offset: "encoding", len: 0, typ: NTI33554450, name: "encoding", sons: null}, +{kind: 1, offset: "enctype", len: 0, typ: NTI33554450, name: "enctype", sons: null}, +{kind: 1, offset: "length", len: 0, typ: NTI33554435, name: "length", sons: null}, +{kind: 1, offset: "method", len: 0, typ: NTI33554450, name: "method", sons: null}, +{kind: 1, offset: "noValidate", len: 0, typ: NTI33554466, name: "noValidate", sons: null}, +{kind: 1, offset: "target", len: 0, typ: NTI33554450, name: "target", sons: null}]}; +NTI687865995.node = NNI687865995; +NTI687865995.base = NTI687865981; +NTI687865884.base = NTI687865995; +var NNI687865994 = {kind: 2, len: 5, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "defaultSelected", len: 0, typ: NTI33554466, name: "defaultSelected", sons: null}, +{kind: 1, offset: "selected", len: 0, typ: NTI33554466, name: "selected", sons: null}, +{kind: 1, offset: "selectedIndex", len: 0, typ: NTI33554435, name: "selectedIndex", sons: null}, +{kind: 1, offset: "text", len: 0, typ: NTI33554450, name: "text", sons: null}, +{kind: 1, offset: "value", len: 0, typ: NTI33554450, name: "value", sons: null}]}; +NTI687865994.node = NNI687865994; +NTI687865994.base = NTI687865981; +NTI687865883.base = NTI687865994; +NTI687865982.base = NTI687865883; +NTI687865983.base = NTI687865883; +var NNI687865981 = {kind: 2, len: 20, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "className", len: 0, typ: NTI33554450, name: "className", sons: null}, +{kind: 1, offset: "classList", len: 0, typ: NTI687865870, name: "classList", sons: null}, +{kind: 1, offset: "checked", len: 0, typ: NTI33554466, name: "checked", sons: null}, +{kind: 1, offset: "defaultChecked", len: 0, typ: NTI33554466, name: "defaultChecked", sons: null}, +{kind: 1, offset: "defaultValue", len: 0, typ: NTI33554450, name: "defaultValue", sons: null}, +{kind: 1, offset: "disabled", len: 0, typ: NTI33554466, name: "disabled", sons: null}, +{kind: 1, offset: "form", len: 0, typ: NTI687865884, name: "form", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}, +{kind: 1, offset: "readOnly", len: 0, typ: NTI33554466, name: "readOnly", sons: null}, +{kind: 1, offset: "options", len: 0, typ: NTI687865982, name: "options", sons: null}, +{kind: 1, offset: "selectedOptions", len: 0, typ: NTI687865983, name: "selectedOptions", sons: null}, +{kind: 1, offset: "clientWidth", len: 0, typ: NTI33554435, name: "clientWidth", sons: null}, +{kind: 1, offset: "clientHeight", len: 0, typ: NTI33554435, name: "clientHeight", sons: null}, +{kind: 1, offset: "contentEditable", len: 0, typ: NTI33554450, name: "contentEditable", sons: null}, +{kind: 1, offset: "isContentEditable", len: 0, typ: NTI33554466, name: "isContentEditable", sons: null}, +{kind: 1, offset: "dir", len: 0, typ: NTI33554450, name: "dir", sons: null}, +{kind: 1, offset: "offsetHeight", len: 0, typ: NTI33554435, name: "offsetHeight", sons: null}, +{kind: 1, offset: "offsetWidth", len: 0, typ: NTI33554435, name: "offsetWidth", sons: null}, +{kind: 1, offset: "offsetLeft", len: 0, typ: NTI33554435, name: "offsetLeft", sons: null}, +{kind: 1, offset: "offsetTop", len: 0, typ: NTI33554435, name: "offsetTop", sons: null}]}; +NTI687865981.node = NNI687865981; +NTI687865872.base = NTI687865970; +NTI687865971.base = NTI687865872; +NTI687865972.base = NTI687865872; +NTI687865973.base = NTI687865872; +var NNI687865871 = {kind: 2, offset: 0, typ: null, name: null, len: 12, sons: {"1": {kind: 1, offset: 1, typ: NTI687865871, name: "ElementNode", len: 0, sons: null}, +"2": {kind: 1, offset: 2, typ: NTI687865871, name: "AttributeNode", len: 0, sons: null}, +"3": {kind: 1, offset: 3, typ: NTI687865871, name: "TextNode", len: 0, sons: null}, +"4": {kind: 1, offset: 4, typ: NTI687865871, name: "CDATANode", len: 0, sons: null}, +"5": {kind: 1, offset: 5, typ: NTI687865871, name: "EntityRefNode", len: 0, sons: null}, +"6": {kind: 1, offset: 6, typ: NTI687865871, name: "EntityNode", len: 0, sons: null}, +"7": {kind: 1, offset: 7, typ: NTI687865871, name: "ProcessingInstructionNode", len: 0, sons: null}, +"8": {kind: 1, offset: 8, typ: NTI687865871, name: "CommentNode", len: 0, sons: null}, +"9": {kind: 1, offset: 9, typ: NTI687865871, name: "DocumentNode", len: 0, sons: null}, +"10": {kind: 1, offset: 10, typ: NTI687865871, name: "DocumentTypeNode", len: 0, sons: null}, +"11": {kind: 1, offset: 11, typ: NTI687865871, name: "DocumentFragmentNode", len: 0, sons: null}, +"12": {kind: 1, offset: 12, typ: NTI687865871, name: "NotationNode", len: 0, sons: null}}}; +NTI687865871.node = NNI687865871; +NTI687865873.base = NTI687865974; +var NNI687865998 = {kind: 2, len: 368, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "alignContent", len: 0, typ: NTI33554450, name: "alignContent", sons: null}, +{kind: 1, offset: "alignItems", len: 0, typ: NTI33554450, name: "alignItems", sons: null}, +{kind: 1, offset: "alignSelf", len: 0, typ: NTI33554450, name: "alignSelf", sons: null}, +{kind: 1, offset: "all", len: 0, typ: NTI33554450, name: "all", sons: null}, +{kind: 1, offset: "animation", len: 0, typ: NTI33554450, name: "animation", sons: null}, +{kind: 1, offset: "animationDelay", len: 0, typ: NTI33554450, name: "animationDelay", sons: null}, +{kind: 1, offset: "animationDirection", len: 0, typ: NTI33554450, name: "animationDirection", sons: null}, +{kind: 1, offset: "animationDuration", len: 0, typ: NTI33554450, name: "animationDuration", sons: null}, +{kind: 1, offset: "animationFillMode", len: 0, typ: NTI33554450, name: "animationFillMode", sons: null}, +{kind: 1, offset: "animationIterationCount", len: 0, typ: NTI33554450, name: "animationIterationCount", sons: null}, +{kind: 1, offset: "animationName", len: 0, typ: NTI33554450, name: "animationName", sons: null}, +{kind: 1, offset: "animationPlayState", len: 0, typ: NTI33554450, name: "animationPlayState", sons: null}, +{kind: 1, offset: "animationTimingFunction", len: 0, typ: NTI33554450, name: "animationTimingFunction", sons: null}, +{kind: 1, offset: "backdropFilter", len: 0, typ: NTI33554450, name: "backdropFilter", sons: null}, +{kind: 1, offset: "backfaceVisibility", len: 0, typ: NTI33554450, name: "backfaceVisibility", sons: null}, +{kind: 1, offset: "background", len: 0, typ: NTI33554450, name: "background", sons: null}, +{kind: 1, offset: "backgroundAttachment", len: 0, typ: NTI33554450, name: "backgroundAttachment", sons: null}, +{kind: 1, offset: "backgroundBlendMode", len: 0, typ: NTI33554450, name: "backgroundBlendMode", sons: null}, +{kind: 1, offset: "backgroundClip", len: 0, typ: NTI33554450, name: "backgroundClip", sons: null}, +{kind: 1, offset: "backgroundColor", len: 0, typ: NTI33554450, name: "backgroundColor", sons: null}, +{kind: 1, offset: "backgroundImage", len: 0, typ: NTI33554450, name: "backgroundImage", sons: null}, +{kind: 1, offset: "backgroundOrigin", len: 0, typ: NTI33554450, name: "backgroundOrigin", sons: null}, +{kind: 1, offset: "backgroundPosition", len: 0, typ: NTI33554450, name: "backgroundPosition", sons: null}, +{kind: 1, offset: "backgroundRepeat", len: 0, typ: NTI33554450, name: "backgroundRepeat", sons: null}, +{kind: 1, offset: "backgroundSize", len: 0, typ: NTI33554450, name: "backgroundSize", sons: null}, +{kind: 1, offset: "blockSize", len: 0, typ: NTI33554450, name: "blockSize", sons: null}, +{kind: 1, offset: "border", len: 0, typ: NTI33554450, name: "border", sons: null}, +{kind: 1, offset: "borderBlock", len: 0, typ: NTI33554450, name: "borderBlock", sons: null}, +{kind: 1, offset: "borderBlockColor", len: 0, typ: NTI33554450, name: "borderBlockColor", sons: null}, +{kind: 1, offset: "borderBlockEnd", len: 0, typ: NTI33554450, name: "borderBlockEnd", sons: null}, +{kind: 1, offset: "borderBlockEndColor", len: 0, typ: NTI33554450, name: "borderBlockEndColor", sons: null}, +{kind: 1, offset: "borderBlockEndStyle", len: 0, typ: NTI33554450, name: "borderBlockEndStyle", sons: null}, +{kind: 1, offset: "borderBlockEndWidth", len: 0, typ: NTI33554450, name: "borderBlockEndWidth", sons: null}, +{kind: 1, offset: "borderBlockStart", len: 0, typ: NTI33554450, name: "borderBlockStart", sons: null}, +{kind: 1, offset: "borderBlockStartColor", len: 0, typ: NTI33554450, name: "borderBlockStartColor", sons: null}, +{kind: 1, offset: "borderBlockStartStyle", len: 0, typ: NTI33554450, name: "borderBlockStartStyle", sons: null}, +{kind: 1, offset: "borderBlockStartWidth", len: 0, typ: NTI33554450, name: "borderBlockStartWidth", sons: null}, +{kind: 1, offset: "borderBlockStyle", len: 0, typ: NTI33554450, name: "borderBlockStyle", sons: null}, +{kind: 1, offset: "borderBlockWidth", len: 0, typ: NTI33554450, name: "borderBlockWidth", sons: null}, +{kind: 1, offset: "borderBottom", len: 0, typ: NTI33554450, name: "borderBottom", sons: null}, +{kind: 1, offset: "borderBottomColor", len: 0, typ: NTI33554450, name: "borderBottomColor", sons: null}, +{kind: 1, offset: "borderBottomLeftRadius", len: 0, typ: NTI33554450, name: "borderBottomLeftRadius", sons: null}, +{kind: 1, offset: "borderBottomRightRadius", len: 0, typ: NTI33554450, name: "borderBottomRightRadius", sons: null}, +{kind: 1, offset: "borderBottomStyle", len: 0, typ: NTI33554450, name: "borderBottomStyle", sons: null}, +{kind: 1, offset: "borderBottomWidth", len: 0, typ: NTI33554450, name: "borderBottomWidth", sons: null}, +{kind: 1, offset: "borderCollapse", len: 0, typ: NTI33554450, name: "borderCollapse", sons: null}, +{kind: 1, offset: "borderColor", len: 0, typ: NTI33554450, name: "borderColor", sons: null}, +{kind: 1, offset: "borderEndEndRadius", len: 0, typ: NTI33554450, name: "borderEndEndRadius", sons: null}, +{kind: 1, offset: "borderEndStartRadius", len: 0, typ: NTI33554450, name: "borderEndStartRadius", sons: null}, +{kind: 1, offset: "borderImage", len: 0, typ: NTI33554450, name: "borderImage", sons: null}, +{kind: 1, offset: "borderImageOutset", len: 0, typ: NTI33554450, name: "borderImageOutset", sons: null}, +{kind: 1, offset: "borderImageRepeat", len: 0, typ: NTI33554450, name: "borderImageRepeat", sons: null}, +{kind: 1, offset: "borderImageSlice", len: 0, typ: NTI33554450, name: "borderImageSlice", sons: null}, +{kind: 1, offset: "borderImageSource", len: 0, typ: NTI33554450, name: "borderImageSource", sons: null}, +{kind: 1, offset: "borderImageWidth", len: 0, typ: NTI33554450, name: "borderImageWidth", sons: null}, +{kind: 1, offset: "borderInline", len: 0, typ: NTI33554450, name: "borderInline", sons: null}, +{kind: 1, offset: "borderInlineColor", len: 0, typ: NTI33554450, name: "borderInlineColor", sons: null}, +{kind: 1, offset: "borderInlineEnd", len: 0, typ: NTI33554450, name: "borderInlineEnd", sons: null}, +{kind: 1, offset: "borderInlineEndColor", len: 0, typ: NTI33554450, name: "borderInlineEndColor", sons: null}, +{kind: 1, offset: "borderInlineEndStyle", len: 0, typ: NTI33554450, name: "borderInlineEndStyle", sons: null}, +{kind: 1, offset: "borderInlineEndWidth", len: 0, typ: NTI33554450, name: "borderInlineEndWidth", sons: null}, +{kind: 1, offset: "borderInlineStart", len: 0, typ: NTI33554450, name: "borderInlineStart", sons: null}, +{kind: 1, offset: "borderInlineStartColor", len: 0, typ: NTI33554450, name: "borderInlineStartColor", sons: null}, +{kind: 1, offset: "borderInlineStartStyle", len: 0, typ: NTI33554450, name: "borderInlineStartStyle", sons: null}, +{kind: 1, offset: "borderInlineStartWidth", len: 0, typ: NTI33554450, name: "borderInlineStartWidth", sons: null}, +{kind: 1, offset: "borderInlineStyle", len: 0, typ: NTI33554450, name: "borderInlineStyle", sons: null}, +{kind: 1, offset: "borderInlineWidth", len: 0, typ: NTI33554450, name: "borderInlineWidth", sons: null}, +{kind: 1, offset: "borderLeft", len: 0, typ: NTI33554450, name: "borderLeft", sons: null}, +{kind: 1, offset: "borderLeftColor", len: 0, typ: NTI33554450, name: "borderLeftColor", sons: null}, +{kind: 1, offset: "borderLeftStyle", len: 0, typ: NTI33554450, name: "borderLeftStyle", sons: null}, +{kind: 1, offset: "borderLeftWidth", len: 0, typ: NTI33554450, name: "borderLeftWidth", sons: null}, +{kind: 1, offset: "borderRadius", len: 0, typ: NTI33554450, name: "borderRadius", sons: null}, +{kind: 1, offset: "borderRight", len: 0, typ: NTI33554450, name: "borderRight", sons: null}, +{kind: 1, offset: "borderRightColor", len: 0, typ: NTI33554450, name: "borderRightColor", sons: null}, +{kind: 1, offset: "borderRightStyle", len: 0, typ: NTI33554450, name: "borderRightStyle", sons: null}, +{kind: 1, offset: "borderRightWidth", len: 0, typ: NTI33554450, name: "borderRightWidth", sons: null}, +{kind: 1, offset: "borderSpacing", len: 0, typ: NTI33554450, name: "borderSpacing", sons: null}, +{kind: 1, offset: "borderStartEndRadius", len: 0, typ: NTI33554450, name: "borderStartEndRadius", sons: null}, +{kind: 1, offset: "borderStartStartRadius", len: 0, typ: NTI33554450, name: "borderStartStartRadius", sons: null}, +{kind: 1, offset: "borderStyle", len: 0, typ: NTI33554450, name: "borderStyle", sons: null}, +{kind: 1, offset: "borderTop", len: 0, typ: NTI33554450, name: "borderTop", sons: null}, +{kind: 1, offset: "borderTopColor", len: 0, typ: NTI33554450, name: "borderTopColor", sons: null}, +{kind: 1, offset: "borderTopLeftRadius", len: 0, typ: NTI33554450, name: "borderTopLeftRadius", sons: null}, +{kind: 1, offset: "borderTopRightRadius", len: 0, typ: NTI33554450, name: "borderTopRightRadius", sons: null}, +{kind: 1, offset: "borderTopStyle", len: 0, typ: NTI33554450, name: "borderTopStyle", sons: null}, +{kind: 1, offset: "borderTopWidth", len: 0, typ: NTI33554450, name: "borderTopWidth", sons: null}, +{kind: 1, offset: "borderWidth", len: 0, typ: NTI33554450, name: "borderWidth", sons: null}, +{kind: 1, offset: "bottom", len: 0, typ: NTI33554450, name: "bottom", sons: null}, +{kind: 1, offset: "boxDecorationBreak", len: 0, typ: NTI33554450, name: "boxDecorationBreak", sons: null}, +{kind: 1, offset: "boxShadow", len: 0, typ: NTI33554450, name: "boxShadow", sons: null}, +{kind: 1, offset: "boxSizing", len: 0, typ: NTI33554450, name: "boxSizing", sons: null}, +{kind: 1, offset: "breakAfter", len: 0, typ: NTI33554450, name: "breakAfter", sons: null}, +{kind: 1, offset: "breakBefore", len: 0, typ: NTI33554450, name: "breakBefore", sons: null}, +{kind: 1, offset: "breakInside", len: 0, typ: NTI33554450, name: "breakInside", sons: null}, +{kind: 1, offset: "captionSide", len: 0, typ: NTI33554450, name: "captionSide", sons: null}, +{kind: 1, offset: "caretColor", len: 0, typ: NTI33554450, name: "caretColor", sons: null}, +{kind: 1, offset: "clear", len: 0, typ: NTI33554450, name: "clear", sons: null}, +{kind: 1, offset: "clip", len: 0, typ: NTI33554450, name: "clip", sons: null}, +{kind: 1, offset: "clipPath", len: 0, typ: NTI33554450, name: "clipPath", sons: null}, +{kind: 1, offset: "color", len: 0, typ: NTI33554450, name: "color", sons: null}, +{kind: 1, offset: "colorAdjust", len: 0, typ: NTI33554450, name: "colorAdjust", sons: null}, +{kind: 1, offset: "columnCount", len: 0, typ: NTI33554450, name: "columnCount", sons: null}, +{kind: 1, offset: "columnFill", len: 0, typ: NTI33554450, name: "columnFill", sons: null}, +{kind: 1, offset: "columnGap", len: 0, typ: NTI33554450, name: "columnGap", sons: null}, +{kind: 1, offset: "columnRule", len: 0, typ: NTI33554450, name: "columnRule", sons: null}, +{kind: 1, offset: "columnRuleColor", len: 0, typ: NTI33554450, name: "columnRuleColor", sons: null}, +{kind: 1, offset: "columnRuleStyle", len: 0, typ: NTI33554450, name: "columnRuleStyle", sons: null}, +{kind: 1, offset: "columnRuleWidth", len: 0, typ: NTI33554450, name: "columnRuleWidth", sons: null}, +{kind: 1, offset: "columnSpan", len: 0, typ: NTI33554450, name: "columnSpan", sons: null}, +{kind: 1, offset: "columnWidth", len: 0, typ: NTI33554450, name: "columnWidth", sons: null}, +{kind: 1, offset: "columns", len: 0, typ: NTI33554450, name: "columns", sons: null}, +{kind: 1, offset: "contain", len: 0, typ: NTI33554450, name: "contain", sons: null}, +{kind: 1, offset: "content", len: 0, typ: NTI33554450, name: "content", sons: null}, +{kind: 1, offset: "counterIncrement", len: 0, typ: NTI33554450, name: "counterIncrement", sons: null}, +{kind: 1, offset: "counterReset", len: 0, typ: NTI33554450, name: "counterReset", sons: null}, +{kind: 1, offset: "counterSet", len: 0, typ: NTI33554450, name: "counterSet", sons: null}, +{kind: 1, offset: "cursor", len: 0, typ: NTI33554450, name: "cursor", sons: null}, +{kind: 1, offset: "direction", len: 0, typ: NTI33554450, name: "direction", sons: null}, +{kind: 1, offset: "display", len: 0, typ: NTI33554450, name: "display", sons: null}, +{kind: 1, offset: "emptyCells", len: 0, typ: NTI33554450, name: "emptyCells", sons: null}, +{kind: 1, offset: "filter", len: 0, typ: NTI33554450, name: "filter", sons: null}, +{kind: 1, offset: "flex", len: 0, typ: NTI33554450, name: "flex", sons: null}, +{kind: 1, offset: "flexBasis", len: 0, typ: NTI33554450, name: "flexBasis", sons: null}, +{kind: 1, offset: "flexDirection", len: 0, typ: NTI33554450, name: "flexDirection", sons: null}, +{kind: 1, offset: "flexFlow", len: 0, typ: NTI33554450, name: "flexFlow", sons: null}, +{kind: 1, offset: "flexGrow", len: 0, typ: NTI33554450, name: "flexGrow", sons: null}, +{kind: 1, offset: "flexShrink", len: 0, typ: NTI33554450, name: "flexShrink", sons: null}, +{kind: 1, offset: "flexWrap", len: 0, typ: NTI33554450, name: "flexWrap", sons: null}, +{kind: 1, offset: "cssFloat", len: 0, typ: NTI33554450, name: "cssFloat", sons: null}, +{kind: 1, offset: "font", len: 0, typ: NTI33554450, name: "font", sons: null}, +{kind: 1, offset: "fontFamily", len: 0, typ: NTI33554450, name: "fontFamily", sons: null}, +{kind: 1, offset: "fontFeatureSettings", len: 0, typ: NTI33554450, name: "fontFeatureSettings", sons: null}, +{kind: 1, offset: "fontKerning", len: 0, typ: NTI33554450, name: "fontKerning", sons: null}, +{kind: 1, offset: "fontLanguageOverride", len: 0, typ: NTI33554450, name: "fontLanguageOverride", sons: null}, +{kind: 1, offset: "fontOpticalSizing", len: 0, typ: NTI33554450, name: "fontOpticalSizing", sons: null}, +{kind: 1, offset: "fontSize", len: 0, typ: NTI33554450, name: "fontSize", sons: null}, +{kind: 1, offset: "fontSizeAdjust", len: 0, typ: NTI33554450, name: "fontSizeAdjust", sons: null}, +{kind: 1, offset: "fontStretch", len: 0, typ: NTI33554450, name: "fontStretch", sons: null}, +{kind: 1, offset: "fontStyle", len: 0, typ: NTI33554450, name: "fontStyle", sons: null}, +{kind: 1, offset: "fontSynthesis", len: 0, typ: NTI33554450, name: "fontSynthesis", sons: null}, +{kind: 1, offset: "fontVariant", len: 0, typ: NTI33554450, name: "fontVariant", sons: null}, +{kind: 1, offset: "fontVariantAlternates", len: 0, typ: NTI33554450, name: "fontVariantAlternates", sons: null}, +{kind: 1, offset: "fontVariantCaps", len: 0, typ: NTI33554450, name: "fontVariantCaps", sons: null}, +{kind: 1, offset: "fontVariantEastAsian", len: 0, typ: NTI33554450, name: "fontVariantEastAsian", sons: null}, +{kind: 1, offset: "fontVariantLigatures", len: 0, typ: NTI33554450, name: "fontVariantLigatures", sons: null}, +{kind: 1, offset: "fontVariantNumeric", len: 0, typ: NTI33554450, name: "fontVariantNumeric", sons: null}, +{kind: 1, offset: "fontVariantPosition", len: 0, typ: NTI33554450, name: "fontVariantPosition", sons: null}, +{kind: 1, offset: "fontVariationSettings", len: 0, typ: NTI33554450, name: "fontVariationSettings", sons: null}, +{kind: 1, offset: "fontWeight", len: 0, typ: NTI33554450, name: "fontWeight", sons: null}, +{kind: 1, offset: "gap", len: 0, typ: NTI33554450, name: "gap", sons: null}, +{kind: 1, offset: "grid", len: 0, typ: NTI33554450, name: "grid", sons: null}, +{kind: 1, offset: "gridArea", len: 0, typ: NTI33554450, name: "gridArea", sons: null}, +{kind: 1, offset: "gridAutoColumns", len: 0, typ: NTI33554450, name: "gridAutoColumns", sons: null}, +{kind: 1, offset: "gridAutoFlow", len: 0, typ: NTI33554450, name: "gridAutoFlow", sons: null}, +{kind: 1, offset: "gridAutoRows", len: 0, typ: NTI33554450, name: "gridAutoRows", sons: null}, +{kind: 1, offset: "gridColumn", len: 0, typ: NTI33554450, name: "gridColumn", sons: null}, +{kind: 1, offset: "gridColumnEnd", len: 0, typ: NTI33554450, name: "gridColumnEnd", sons: null}, +{kind: 1, offset: "gridColumnStart", len: 0, typ: NTI33554450, name: "gridColumnStart", sons: null}, +{kind: 1, offset: "gridRow", len: 0, typ: NTI33554450, name: "gridRow", sons: null}, +{kind: 1, offset: "gridRowEnd", len: 0, typ: NTI33554450, name: "gridRowEnd", sons: null}, +{kind: 1, offset: "gridRowStart", len: 0, typ: NTI33554450, name: "gridRowStart", sons: null}, +{kind: 1, offset: "gridTemplate", len: 0, typ: NTI33554450, name: "gridTemplate", sons: null}, +{kind: 1, offset: "gridTemplateAreas", len: 0, typ: NTI33554450, name: "gridTemplateAreas", sons: null}, +{kind: 1, offset: "gridTemplateColumns", len: 0, typ: NTI33554450, name: "gridTemplateColumns", sons: null}, +{kind: 1, offset: "gridTemplateRows", len: 0, typ: NTI33554450, name: "gridTemplateRows", sons: null}, +{kind: 1, offset: "hangingPunctuation", len: 0, typ: NTI33554450, name: "hangingPunctuation", sons: null}, +{kind: 1, offset: "height", len: 0, typ: NTI33554450, name: "height", sons: null}, +{kind: 1, offset: "hyphens", len: 0, typ: NTI33554450, name: "hyphens", sons: null}, +{kind: 1, offset: "imageOrientation", len: 0, typ: NTI33554450, name: "imageOrientation", sons: null}, +{kind: 1, offset: "imageRendering", len: 0, typ: NTI33554450, name: "imageRendering", sons: null}, +{kind: 1, offset: "inlineSize", len: 0, typ: NTI33554450, name: "inlineSize", sons: null}, +{kind: 1, offset: "inset", len: 0, typ: NTI33554450, name: "inset", sons: null}, +{kind: 1, offset: "insetBlock", len: 0, typ: NTI33554450, name: "insetBlock", sons: null}, +{kind: 1, offset: "insetBlockEnd", len: 0, typ: NTI33554450, name: "insetBlockEnd", sons: null}, +{kind: 1, offset: "insetBlockStart", len: 0, typ: NTI33554450, name: "insetBlockStart", sons: null}, +{kind: 1, offset: "insetInline", len: 0, typ: NTI33554450, name: "insetInline", sons: null}, +{kind: 1, offset: "insetInlineEnd", len: 0, typ: NTI33554450, name: "insetInlineEnd", sons: null}, +{kind: 1, offset: "insetInlineStart", len: 0, typ: NTI33554450, name: "insetInlineStart", sons: null}, +{kind: 1, offset: "isolation", len: 0, typ: NTI33554450, name: "isolation", sons: null}, +{kind: 1, offset: "justifyContent", len: 0, typ: NTI33554450, name: "justifyContent", sons: null}, +{kind: 1, offset: "justifyItems", len: 0, typ: NTI33554450, name: "justifyItems", sons: null}, +{kind: 1, offset: "justifySelf", len: 0, typ: NTI33554450, name: "justifySelf", sons: null}, +{kind: 1, offset: "left", len: 0, typ: NTI33554450, name: "left", sons: null}, +{kind: 1, offset: "letterSpacing", len: 0, typ: NTI33554450, name: "letterSpacing", sons: null}, +{kind: 1, offset: "lineBreak", len: 0, typ: NTI33554450, name: "lineBreak", sons: null}, +{kind: 1, offset: "lineHeight", len: 0, typ: NTI33554450, name: "lineHeight", sons: null}, +{kind: 1, offset: "listStyle", len: 0, typ: NTI33554450, name: "listStyle", sons: null}, +{kind: 1, offset: "listStyleImage", len: 0, typ: NTI33554450, name: "listStyleImage", sons: null}, +{kind: 1, offset: "listStylePosition", len: 0, typ: NTI33554450, name: "listStylePosition", sons: null}, +{kind: 1, offset: "listStyleType", len: 0, typ: NTI33554450, name: "listStyleType", sons: null}, +{kind: 1, offset: "margin", len: 0, typ: NTI33554450, name: "margin", sons: null}, +{kind: 1, offset: "marginBlock", len: 0, typ: NTI33554450, name: "marginBlock", sons: null}, +{kind: 1, offset: "marginBlockEnd", len: 0, typ: NTI33554450, name: "marginBlockEnd", sons: null}, +{kind: 1, offset: "marginBlockStart", len: 0, typ: NTI33554450, name: "marginBlockStart", sons: null}, +{kind: 1, offset: "marginBottom", len: 0, typ: NTI33554450, name: "marginBottom", sons: null}, +{kind: 1, offset: "marginInline", len: 0, typ: NTI33554450, name: "marginInline", sons: null}, +{kind: 1, offset: "marginInlineEnd", len: 0, typ: NTI33554450, name: "marginInlineEnd", sons: null}, +{kind: 1, offset: "marginInlineStart", len: 0, typ: NTI33554450, name: "marginInlineStart", sons: null}, +{kind: 1, offset: "marginLeft", len: 0, typ: NTI33554450, name: "marginLeft", sons: null}, +{kind: 1, offset: "marginRight", len: 0, typ: NTI33554450, name: "marginRight", sons: null}, +{kind: 1, offset: "marginTop", len: 0, typ: NTI33554450, name: "marginTop", sons: null}, +{kind: 1, offset: "mask", len: 0, typ: NTI33554450, name: "mask", sons: null}, +{kind: 1, offset: "maskBorder", len: 0, typ: NTI33554450, name: "maskBorder", sons: null}, +{kind: 1, offset: "maskBorderMode", len: 0, typ: NTI33554450, name: "maskBorderMode", sons: null}, +{kind: 1, offset: "maskBorderOutset", len: 0, typ: NTI33554450, name: "maskBorderOutset", sons: null}, +{kind: 1, offset: "maskBorderRepeat", len: 0, typ: NTI33554450, name: "maskBorderRepeat", sons: null}, +{kind: 1, offset: "maskBorderSlice", len: 0, typ: NTI33554450, name: "maskBorderSlice", sons: null}, +{kind: 1, offset: "maskBorderSource", len: 0, typ: NTI33554450, name: "maskBorderSource", sons: null}, +{kind: 1, offset: "maskBorderWidth", len: 0, typ: NTI33554450, name: "maskBorderWidth", sons: null}, +{kind: 1, offset: "maskClip", len: 0, typ: NTI33554450, name: "maskClip", sons: null}, +{kind: 1, offset: "maskComposite", len: 0, typ: NTI33554450, name: "maskComposite", sons: null}, +{kind: 1, offset: "maskImage", len: 0, typ: NTI33554450, name: "maskImage", sons: null}, +{kind: 1, offset: "maskMode", len: 0, typ: NTI33554450, name: "maskMode", sons: null}, +{kind: 1, offset: "maskOrigin", len: 0, typ: NTI33554450, name: "maskOrigin", sons: null}, +{kind: 1, offset: "maskPosition", len: 0, typ: NTI33554450, name: "maskPosition", sons: null}, +{kind: 1, offset: "maskRepeat", len: 0, typ: NTI33554450, name: "maskRepeat", sons: null}, +{kind: 1, offset: "maskSize", len: 0, typ: NTI33554450, name: "maskSize", sons: null}, +{kind: 1, offset: "maskType", len: 0, typ: NTI33554450, name: "maskType", sons: null}, +{kind: 1, offset: "maxBlockSize", len: 0, typ: NTI33554450, name: "maxBlockSize", sons: null}, +{kind: 1, offset: "maxHeight", len: 0, typ: NTI33554450, name: "maxHeight", sons: null}, +{kind: 1, offset: "maxInlineSize", len: 0, typ: NTI33554450, name: "maxInlineSize", sons: null}, +{kind: 1, offset: "maxWidth", len: 0, typ: NTI33554450, name: "maxWidth", sons: null}, +{kind: 1, offset: "minBlockSize", len: 0, typ: NTI33554450, name: "minBlockSize", sons: null}, +{kind: 1, offset: "minHeight", len: 0, typ: NTI33554450, name: "minHeight", sons: null}, +{kind: 1, offset: "minInlineSize", len: 0, typ: NTI33554450, name: "minInlineSize", sons: null}, +{kind: 1, offset: "minWidth", len: 0, typ: NTI33554450, name: "minWidth", sons: null}, +{kind: 1, offset: "mixBlendMode", len: 0, typ: NTI33554450, name: "mixBlendMode", sons: null}, +{kind: 1, offset: "objectFit", len: 0, typ: NTI33554450, name: "objectFit", sons: null}, +{kind: 1, offset: "objectPosition", len: 0, typ: NTI33554450, name: "objectPosition", sons: null}, +{kind: 1, offset: "offset", len: 0, typ: NTI33554450, name: "offset", sons: null}, +{kind: 1, offset: "offsetAnchor", len: 0, typ: NTI33554450, name: "offsetAnchor", sons: null}, +{kind: 1, offset: "offsetDistance", len: 0, typ: NTI33554450, name: "offsetDistance", sons: null}, +{kind: 1, offset: "offsetPath", len: 0, typ: NTI33554450, name: "offsetPath", sons: null}, +{kind: 1, offset: "offsetRotate", len: 0, typ: NTI33554450, name: "offsetRotate", sons: null}, +{kind: 1, offset: "opacity", len: 0, typ: NTI33554450, name: "opacity", sons: null}, +{kind: 1, offset: "order", len: 0, typ: NTI33554450, name: "order", sons: null}, +{kind: 1, offset: "orphans", len: 0, typ: NTI33554450, name: "orphans", sons: null}, +{kind: 1, offset: "outline", len: 0, typ: NTI33554450, name: "outline", sons: null}, +{kind: 1, offset: "outlineColor", len: 0, typ: NTI33554450, name: "outlineColor", sons: null}, +{kind: 1, offset: "outlineOffset", len: 0, typ: NTI33554450, name: "outlineOffset", sons: null}, +{kind: 1, offset: "outlineStyle", len: 0, typ: NTI33554450, name: "outlineStyle", sons: null}, +{kind: 1, offset: "outlineWidth", len: 0, typ: NTI33554450, name: "outlineWidth", sons: null}, +{kind: 1, offset: "overflow", len: 0, typ: NTI33554450, name: "overflow", sons: null}, +{kind: 1, offset: "overflowAnchor", len: 0, typ: NTI33554450, name: "overflowAnchor", sons: null}, +{kind: 1, offset: "overflowBlock", len: 0, typ: NTI33554450, name: "overflowBlock", sons: null}, +{kind: 1, offset: "overflowInline", len: 0, typ: NTI33554450, name: "overflowInline", sons: null}, +{kind: 1, offset: "overflowWrap", len: 0, typ: NTI33554450, name: "overflowWrap", sons: null}, +{kind: 1, offset: "overflowX", len: 0, typ: NTI33554450, name: "overflowX", sons: null}, +{kind: 1, offset: "overflowY", len: 0, typ: NTI33554450, name: "overflowY", sons: null}, +{kind: 1, offset: "overscrollBehavior", len: 0, typ: NTI33554450, name: "overscrollBehavior", sons: null}, +{kind: 1, offset: "overscrollBehaviorBlock", len: 0, typ: NTI33554450, name: "overscrollBehaviorBlock", sons: null}, +{kind: 1, offset: "overscrollBehaviorInline", len: 0, typ: NTI33554450, name: "overscrollBehaviorInline", sons: null}, +{kind: 1, offset: "overscrollBehaviorX", len: 0, typ: NTI33554450, name: "overscrollBehaviorX", sons: null}, +{kind: 1, offset: "overscrollBehaviorY", len: 0, typ: NTI33554450, name: "overscrollBehaviorY", sons: null}, +{kind: 1, offset: "padding", len: 0, typ: NTI33554450, name: "padding", sons: null}, +{kind: 1, offset: "paddingBlock", len: 0, typ: NTI33554450, name: "paddingBlock", sons: null}, +{kind: 1, offset: "paddingBlockEnd", len: 0, typ: NTI33554450, name: "paddingBlockEnd", sons: null}, +{kind: 1, offset: "paddingBlockStart", len: 0, typ: NTI33554450, name: "paddingBlockStart", sons: null}, +{kind: 1, offset: "paddingBottom", len: 0, typ: NTI33554450, name: "paddingBottom", sons: null}, +{kind: 1, offset: "paddingInline", len: 0, typ: NTI33554450, name: "paddingInline", sons: null}, +{kind: 1, offset: "paddingInlineEnd", len: 0, typ: NTI33554450, name: "paddingInlineEnd", sons: null}, +{kind: 1, offset: "paddingInlineStart", len: 0, typ: NTI33554450, name: "paddingInlineStart", sons: null}, +{kind: 1, offset: "paddingLeft", len: 0, typ: NTI33554450, name: "paddingLeft", sons: null}, +{kind: 1, offset: "paddingRight", len: 0, typ: NTI33554450, name: "paddingRight", sons: null}, +{kind: 1, offset: "paddingTop", len: 0, typ: NTI33554450, name: "paddingTop", sons: null}, +{kind: 1, offset: "pageBreakAfter", len: 0, typ: NTI33554450, name: "pageBreakAfter", sons: null}, +{kind: 1, offset: "pageBreakBefore", len: 0, typ: NTI33554450, name: "pageBreakBefore", sons: null}, +{kind: 1, offset: "pageBreakInside", len: 0, typ: NTI33554450, name: "pageBreakInside", sons: null}, +{kind: 1, offset: "paintOrder", len: 0, typ: NTI33554450, name: "paintOrder", sons: null}, +{kind: 1, offset: "perspective", len: 0, typ: NTI33554450, name: "perspective", sons: null}, +{kind: 1, offset: "perspectiveOrigin", len: 0, typ: NTI33554450, name: "perspectiveOrigin", sons: null}, +{kind: 1, offset: "placeContent", len: 0, typ: NTI33554450, name: "placeContent", sons: null}, +{kind: 1, offset: "placeItems", len: 0, typ: NTI33554450, name: "placeItems", sons: null}, +{kind: 1, offset: "placeSelf", len: 0, typ: NTI33554450, name: "placeSelf", sons: null}, +{kind: 1, offset: "pointerEvents", len: 0, typ: NTI33554450, name: "pointerEvents", sons: null}, +{kind: 1, offset: "position", len: 0, typ: NTI33554450, name: "position", sons: null}, +{kind: 1, offset: "quotes", len: 0, typ: NTI33554450, name: "quotes", sons: null}, +{kind: 1, offset: "resize", len: 0, typ: NTI33554450, name: "resize", sons: null}, +{kind: 1, offset: "right", len: 0, typ: NTI33554450, name: "right", sons: null}, +{kind: 1, offset: "rotate", len: 0, typ: NTI33554450, name: "rotate", sons: null}, +{kind: 1, offset: "rowGap", len: 0, typ: NTI33554450, name: "rowGap", sons: null}, +{kind: 1, offset: "scale", len: 0, typ: NTI33554450, name: "scale", sons: null}, +{kind: 1, offset: "scrollBehavior", len: 0, typ: NTI33554450, name: "scrollBehavior", sons: null}, +{kind: 1, offset: "scrollMargin", len: 0, typ: NTI33554450, name: "scrollMargin", sons: null}, +{kind: 1, offset: "scrollMarginBlock", len: 0, typ: NTI33554450, name: "scrollMarginBlock", sons: null}, +{kind: 1, offset: "scrollMarginBlockEnd", len: 0, typ: NTI33554450, name: "scrollMarginBlockEnd", sons: null}, +{kind: 1, offset: "scrollMarginBlockStart", len: 0, typ: NTI33554450, name: "scrollMarginBlockStart", sons: null}, +{kind: 1, offset: "scrollMarginBottom", len: 0, typ: NTI33554450, name: "scrollMarginBottom", sons: null}, +{kind: 1, offset: "scrollMarginInline", len: 0, typ: NTI33554450, name: "scrollMarginInline", sons: null}, +{kind: 1, offset: "scrollMarginInlineEnd", len: 0, typ: NTI33554450, name: "scrollMarginInlineEnd", sons: null}, +{kind: 1, offset: "scrollMarginInlineStart", len: 0, typ: NTI33554450, name: "scrollMarginInlineStart", sons: null}, +{kind: 1, offset: "scrollMarginLeft", len: 0, typ: NTI33554450, name: "scrollMarginLeft", sons: null}, +{kind: 1, offset: "scrollMarginRight", len: 0, typ: NTI33554450, name: "scrollMarginRight", sons: null}, +{kind: 1, offset: "scrollMarginTop", len: 0, typ: NTI33554450, name: "scrollMarginTop", sons: null}, +{kind: 1, offset: "scrollPadding", len: 0, typ: NTI33554450, name: "scrollPadding", sons: null}, +{kind: 1, offset: "scrollPaddingBlock", len: 0, typ: NTI33554450, name: "scrollPaddingBlock", sons: null}, +{kind: 1, offset: "scrollPaddingBlockEnd", len: 0, typ: NTI33554450, name: "scrollPaddingBlockEnd", sons: null}, +{kind: 1, offset: "scrollPaddingBlockStart", len: 0, typ: NTI33554450, name: "scrollPaddingBlockStart", sons: null}, +{kind: 1, offset: "scrollPaddingBottom", len: 0, typ: NTI33554450, name: "scrollPaddingBottom", sons: null}, +{kind: 1, offset: "scrollPaddingInline", len: 0, typ: NTI33554450, name: "scrollPaddingInline", sons: null}, +{kind: 1, offset: "scrollPaddingInlineEnd", len: 0, typ: NTI33554450, name: "scrollPaddingInlineEnd", sons: null}, +{kind: 1, offset: "scrollPaddingInlineStart", len: 0, typ: NTI33554450, name: "scrollPaddingInlineStart", sons: null}, +{kind: 1, offset: "scrollPaddingLeft", len: 0, typ: NTI33554450, name: "scrollPaddingLeft", sons: null}, +{kind: 1, offset: "scrollPaddingRight", len: 0, typ: NTI33554450, name: "scrollPaddingRight", sons: null}, +{kind: 1, offset: "scrollPaddingTop", len: 0, typ: NTI33554450, name: "scrollPaddingTop", sons: null}, +{kind: 1, offset: "scrollSnapAlign", len: 0, typ: NTI33554450, name: "scrollSnapAlign", sons: null}, +{kind: 1, offset: "scrollSnapStop", len: 0, typ: NTI33554450, name: "scrollSnapStop", sons: null}, +{kind: 1, offset: "scrollSnapType", len: 0, typ: NTI33554450, name: "scrollSnapType", sons: null}, +{kind: 1, offset: "scrollbar3dLightColor", len: 0, typ: NTI33554450, name: "scrollbar3dLightColor", sons: null}, +{kind: 1, offset: "scrollbarArrowColor", len: 0, typ: NTI33554450, name: "scrollbarArrowColor", sons: null}, +{kind: 1, offset: "scrollbarBaseColor", len: 0, typ: NTI33554450, name: "scrollbarBaseColor", sons: null}, +{kind: 1, offset: "scrollbarColor", len: 0, typ: NTI33554450, name: "scrollbarColor", sons: null}, +{kind: 1, offset: "scrollbarDarkshadowColor", len: 0, typ: NTI33554450, name: "scrollbarDarkshadowColor", sons: null}, +{kind: 1, offset: "scrollbarFaceColor", len: 0, typ: NTI33554450, name: "scrollbarFaceColor", sons: null}, +{kind: 1, offset: "scrollbarHighlightColor", len: 0, typ: NTI33554450, name: "scrollbarHighlightColor", sons: null}, +{kind: 1, offset: "scrollbarShadowColor", len: 0, typ: NTI33554450, name: "scrollbarShadowColor", sons: null}, +{kind: 1, offset: "scrollbarTrackColor", len: 0, typ: NTI33554450, name: "scrollbarTrackColor", sons: null}, +{kind: 1, offset: "scrollbarWidth", len: 0, typ: NTI33554450, name: "scrollbarWidth", sons: null}, +{kind: 1, offset: "shapeImageThreshold", len: 0, typ: NTI33554450, name: "shapeImageThreshold", sons: null}, +{kind: 1, offset: "shapeMargin", len: 0, typ: NTI33554450, name: "shapeMargin", sons: null}, +{kind: 1, offset: "shapeOutside", len: 0, typ: NTI33554450, name: "shapeOutside", sons: null}, +{kind: 1, offset: "tabSize", len: 0, typ: NTI33554450, name: "tabSize", sons: null}, +{kind: 1, offset: "tableLayout", len: 0, typ: NTI33554450, name: "tableLayout", sons: null}, +{kind: 1, offset: "textAlign", len: 0, typ: NTI33554450, name: "textAlign", sons: null}, +{kind: 1, offset: "textAlignLast", len: 0, typ: NTI33554450, name: "textAlignLast", sons: null}, +{kind: 1, offset: "textCombineUpright", len: 0, typ: NTI33554450, name: "textCombineUpright", sons: null}, +{kind: 1, offset: "textDecoration", len: 0, typ: NTI33554450, name: "textDecoration", sons: null}, +{kind: 1, offset: "textDecorationColor", len: 0, typ: NTI33554450, name: "textDecorationColor", sons: null}, +{kind: 1, offset: "textDecorationLine", len: 0, typ: NTI33554450, name: "textDecorationLine", sons: null}, +{kind: 1, offset: "textDecorationSkipInk", len: 0, typ: NTI33554450, name: "textDecorationSkipInk", sons: null}, +{kind: 1, offset: "textDecorationStyle", len: 0, typ: NTI33554450, name: "textDecorationStyle", sons: null}, +{kind: 1, offset: "textDecorationThickness", len: 0, typ: NTI33554450, name: "textDecorationThickness", sons: null}, +{kind: 1, offset: "textEmphasis", len: 0, typ: NTI33554450, name: "textEmphasis", sons: null}, +{kind: 1, offset: "textEmphasisColor", len: 0, typ: NTI33554450, name: "textEmphasisColor", sons: null}, +{kind: 1, offset: "textEmphasisPosition", len: 0, typ: NTI33554450, name: "textEmphasisPosition", sons: null}, +{kind: 1, offset: "textEmphasisStyle", len: 0, typ: NTI33554450, name: "textEmphasisStyle", sons: null}, +{kind: 1, offset: "textIndent", len: 0, typ: NTI33554450, name: "textIndent", sons: null}, +{kind: 1, offset: "textJustify", len: 0, typ: NTI33554450, name: "textJustify", sons: null}, +{kind: 1, offset: "textOrientation", len: 0, typ: NTI33554450, name: "textOrientation", sons: null}, +{kind: 1, offset: "textOverflow", len: 0, typ: NTI33554450, name: "textOverflow", sons: null}, +{kind: 1, offset: "textRendering", len: 0, typ: NTI33554450, name: "textRendering", sons: null}, +{kind: 1, offset: "textShadow", len: 0, typ: NTI33554450, name: "textShadow", sons: null}, +{kind: 1, offset: "textTransform", len: 0, typ: NTI33554450, name: "textTransform", sons: null}, +{kind: 1, offset: "textUnderlineOffset", len: 0, typ: NTI33554450, name: "textUnderlineOffset", sons: null}, +{kind: 1, offset: "textUnderlinePosition", len: 0, typ: NTI33554450, name: "textUnderlinePosition", sons: null}, +{kind: 1, offset: "top", len: 0, typ: NTI33554450, name: "top", sons: null}, +{kind: 1, offset: "touchAction", len: 0, typ: NTI33554450, name: "touchAction", sons: null}, +{kind: 1, offset: "transform", len: 0, typ: NTI33554450, name: "transform", sons: null}, +{kind: 1, offset: "transformBox", len: 0, typ: NTI33554450, name: "transformBox", sons: null}, +{kind: 1, offset: "transformOrigin", len: 0, typ: NTI33554450, name: "transformOrigin", sons: null}, +{kind: 1, offset: "transformStyle", len: 0, typ: NTI33554450, name: "transformStyle", sons: null}, +{kind: 1, offset: "transition", len: 0, typ: NTI33554450, name: "transition", sons: null}, +{kind: 1, offset: "transitionDelay", len: 0, typ: NTI33554450, name: "transitionDelay", sons: null}, +{kind: 1, offset: "transitionDuration", len: 0, typ: NTI33554450, name: "transitionDuration", sons: null}, +{kind: 1, offset: "transitionProperty", len: 0, typ: NTI33554450, name: "transitionProperty", sons: null}, +{kind: 1, offset: "transitionTimingFunction", len: 0, typ: NTI33554450, name: "transitionTimingFunction", sons: null}, +{kind: 1, offset: "translate", len: 0, typ: NTI33554450, name: "translate", sons: null}, +{kind: 1, offset: "unicodeBidi", len: 0, typ: NTI33554450, name: "unicodeBidi", sons: null}, +{kind: 1, offset: "verticalAlign", len: 0, typ: NTI33554450, name: "verticalAlign", sons: null}, +{kind: 1, offset: "visibility", len: 0, typ: NTI33554450, name: "visibility", sons: null}, +{kind: 1, offset: "whiteSpace", len: 0, typ: NTI33554450, name: "whiteSpace", sons: null}, +{kind: 1, offset: "widows", len: 0, typ: NTI33554450, name: "widows", sons: null}, +{kind: 1, offset: "width", len: 0, typ: NTI33554450, name: "width", sons: null}, +{kind: 1, offset: "willChange", len: 0, typ: NTI33554450, name: "willChange", sons: null}, +{kind: 1, offset: "wordBreak", len: 0, typ: NTI33554450, name: "wordBreak", sons: null}, +{kind: 1, offset: "wordSpacing", len: 0, typ: NTI33554450, name: "wordSpacing", sons: null}, +{kind: 1, offset: "writingMode", len: 0, typ: NTI33554450, name: "writingMode", sons: null}, +{kind: 1, offset: "zIndex", len: 0, typ: NTI33554450, name: "zIndex", sons: null}]}; +NTI687865998.node = NNI687865998; +NTI687865998.base = NTI33555167; +NTI687865886.base = NTI687865998; +var NNI687865970 = {kind: 2, len: 22, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "attributes", len: 0, typ: NTI687865971, name: "attributes", sons: null}, +{kind: 1, offset: "childNodes", len: 0, typ: NTI687865972, name: "childNodes", sons: null}, +{kind: 1, offset: "children", len: 0, typ: NTI687865973, name: "children", sons: null}, +{kind: 1, offset: "data", len: 0, typ: NTI33554450, name: "data", sons: null}, +{kind: 1, offset: "firstChild", len: 0, typ: NTI687865872, name: "firstChild", sons: null}, +{kind: 1, offset: "lastChild", len: 0, typ: NTI687865872, name: "lastChild", sons: null}, +{kind: 1, offset: "nextSibling", len: 0, typ: NTI687865872, name: "nextSibling", sons: null}, +{kind: 1, offset: "nodeName", len: 0, typ: NTI33554450, name: "nodeName", sons: null}, +{kind: 1, offset: "nodeType", len: 0, typ: NTI687865871, name: "nodeType", sons: null}, +{kind: 1, offset: "nodeValue", len: 0, typ: NTI33554450, name: "nodeValue", sons: null}, +{kind: 1, offset: "parentNode", len: 0, typ: NTI687865872, name: "parentNode", sons: null}, +{kind: 1, offset: "content", len: 0, typ: NTI687865872, name: "content", sons: null}, +{kind: 1, offset: "previousSibling", len: 0, typ: NTI687865872, name: "previousSibling", sons: null}, +{kind: 1, offset: "ownerDocument", len: 0, typ: NTI687865873, name: "ownerDocument", sons: null}, +{kind: 1, offset: "innerHTML", len: 0, typ: NTI33554450, name: "innerHTML", sons: null}, +{kind: 1, offset: "outerHTML", len: 0, typ: NTI33554450, name: "outerHTML", sons: null}, +{kind: 1, offset: "innerText", len: 0, typ: NTI33554450, name: "innerText", sons: null}, +{kind: 1, offset: "textContent", len: 0, typ: NTI33554450, name: "textContent", sons: null}, +{kind: 1, offset: "style", len: 0, typ: NTI687865886, name: "style", sons: null}, +{kind: 1, offset: "baseURI", len: 0, typ: NTI33554450, name: "baseURI", sons: null}, +{kind: 1, offset: "parentElement", len: 0, typ: NTI687865874, name: "parentElement", sons: null}, +{kind: 1, offset: "isConnected", len: 0, typ: NTI33554466, name: "isConnected", sons: null}]}; +NTI687865970.node = NNI687865970; +var NNI687865925 = {kind: 2, len: 24, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "onabort", len: 0, typ: NTI687865926, name: "onabort", sons: null}, +{kind: 1, offset: "onblur", len: 0, typ: NTI687865927, name: "onblur", sons: null}, +{kind: 1, offset: "onchange", len: 0, typ: NTI687865928, name: "onchange", sons: null}, +{kind: 1, offset: "onclick", len: 0, typ: NTI687865929, name: "onclick", sons: null}, +{kind: 1, offset: "ondblclick", len: 0, typ: NTI687865930, name: "ondblclick", sons: null}, +{kind: 1, offset: "onerror", len: 0, typ: NTI687865931, name: "onerror", sons: null}, +{kind: 1, offset: "onfocus", len: 0, typ: NTI687865932, name: "onfocus", sons: null}, +{kind: 1, offset: "onkeydown", len: 0, typ: NTI687865933, name: "onkeydown", sons: null}, +{kind: 1, offset: "onkeypress", len: 0, typ: NTI687865934, name: "onkeypress", sons: null}, +{kind: 1, offset: "onkeyup", len: 0, typ: NTI687865935, name: "onkeyup", sons: null}, +{kind: 1, offset: "onload", len: 0, typ: NTI687865936, name: "onload", sons: null}, +{kind: 1, offset: "onmousedown", len: 0, typ: NTI687865937, name: "onmousedown", sons: null}, +{kind: 1, offset: "onmousemove", len: 0, typ: NTI687865938, name: "onmousemove", sons: null}, +{kind: 1, offset: "onmouseout", len: 0, typ: NTI687865939, name: "onmouseout", sons: null}, +{kind: 1, offset: "onmouseover", len: 0, typ: NTI687865940, name: "onmouseover", sons: null}, +{kind: 1, offset: "onmouseup", len: 0, typ: NTI687865941, name: "onmouseup", sons: null}, +{kind: 1, offset: "onreset", len: 0, typ: NTI687865942, name: "onreset", sons: null}, +{kind: 1, offset: "onselect", len: 0, typ: NTI687865943, name: "onselect", sons: null}, +{kind: 1, offset: "onstorage", len: 0, typ: NTI687865944, name: "onstorage", sons: null}, +{kind: 1, offset: "onsubmit", len: 0, typ: NTI687865945, name: "onsubmit", sons: null}, +{kind: 1, offset: "onunload", len: 0, typ: NTI687865946, name: "onunload", sons: null}, +{kind: 1, offset: "onloadstart", len: 0, typ: NTI687865947, name: "onloadstart", sons: null}, +{kind: 1, offset: "onprogress", len: 0, typ: NTI687865948, name: "onprogress", sons: null}, +{kind: 1, offset: "onloadend", len: 0, typ: NTI687865949, name: "onloadend", sons: null}]}; +NTI687865925.node = NNI687865925; +NTI687865925.base = NTI33555167; +NTI687865970.base = NTI687865925; +NTI687865981.base = NTI687865970; +NTI687865874.base = NTI687865981; +var NNI687865993 = {kind: 2, len: 3, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "text", len: 0, typ: NTI33554450, name: "text", sons: null}, +{kind: 1, offset: "x", len: 0, typ: NTI33554435, name: "x", sons: null}, +{kind: 1, offset: "y", len: 0, typ: NTI33554435, name: "y", sons: null}]}; +NTI687865993.node = NNI687865993; +NTI687865993.base = NTI687865981; +NTI687865882.base = NTI687865993; +NTI687865975.base = NTI687865882; +NTI687865976.base = NTI687865884; +var NNI687865997 = {kind: 2, len: 8, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "border", len: 0, typ: NTI33554435, name: "border", sons: null}, +{kind: 1, offset: "complete", len: 0, typ: NTI33554466, name: "complete", sons: null}, +{kind: 1, offset: "height", len: 0, typ: NTI33554435, name: "height", sons: null}, +{kind: 1, offset: "hspace", len: 0, typ: NTI33554435, name: "hspace", sons: null}, +{kind: 1, offset: "lowsrc", len: 0, typ: NTI33554450, name: "lowsrc", sons: null}, +{kind: 1, offset: "src", len: 0, typ: NTI33554450, name: "src", sons: null}, +{kind: 1, offset: "vspace", len: 0, typ: NTI33554435, name: "vspace", sons: null}, +{kind: 1, offset: "width", len: 0, typ: NTI33554435, name: "width", sons: null}]}; +NTI687865997.node = NNI687865997; +NTI687865997.base = NTI687865981; +NTI687865885.base = NTI687865997; +NTI687865977.base = NTI687865885; +NTI687865978.base = NTI687865874; +var NNI687865992 = {kind: 2, len: 6, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "height", len: 0, typ: NTI33554435, name: "height", sons: null}, +{kind: 1, offset: "hspace", len: 0, typ: NTI33554435, name: "hspace", sons: null}, +{kind: 1, offset: "src", len: 0, typ: NTI33554450, name: "src", sons: null}, +{kind: 1, offset: "width", len: 0, typ: NTI33554435, name: "width", sons: null}, +{kind: 1, offset: "type", len: 0, typ: NTI33554450, name: "type", sons: null}, +{kind: 1, offset: "vspace", len: 0, typ: NTI33554435, name: "vspace", sons: null}]}; +NTI687865992.node = NNI687865992; +NTI687865992.base = NTI687865981; +NTI687865881.base = NTI687865992; +NTI687865979.base = NTI687865881; +var NNI687865991 = {kind: 2, len: 4, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "target", len: 0, typ: NTI33554450, name: "target", sons: null}, +{kind: 1, offset: "text", len: 0, typ: NTI33554450, name: "text", sons: null}, +{kind: 1, offset: "x", len: 0, typ: NTI33554435, name: "x", sons: null}, +{kind: 1, offset: "y", len: 0, typ: NTI33554435, name: "y", sons: null}]}; +NTI687865991.node = NNI687865991; +NTI687865991.base = NTI687865981; +NTI687865880.base = NTI687865991; +NTI687865980.base = NTI687865880; +var NNI687866041 = {kind: 1, offset: "then", len: 0, typ: NTI687866042, name: "then", sons: null}; +NTI687866041.node = NNI687866041; +NTI687865921.base = NTI687866041; +var NNI687866044 = {kind: 2, len: 2, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "ready", len: 0, typ: NTI687865921, name: "ready", sons: null}, +{kind: 1, offset: "onloadingdone", len: 0, typ: NTI687866045, name: "onloadingdone", sons: null}]}; +NTI687866044.node = NNI687866044; +NTI687865922.base = NTI687866044; +var NNI687865974 = {kind: 2, len: 25, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "activeElement", len: 0, typ: NTI687865874, name: "activeElement", sons: null}, +{kind: 1, offset: "documentElement", len: 0, typ: NTI687865874, name: "documentElement", sons: null}, +{kind: 1, offset: "alinkColor", len: 0, typ: NTI33554450, name: "alinkColor", sons: null}, +{kind: 1, offset: "bgColor", len: 0, typ: NTI33554450, name: "bgColor", sons: null}, +{kind: 1, offset: "body", len: 0, typ: NTI687865874, name: "body", sons: null}, +{kind: 1, offset: "charset", len: 0, typ: NTI33554450, name: "charset", sons: null}, +{kind: 1, offset: "cookie", len: 0, typ: NTI33554450, name: "cookie", sons: null}, +{kind: 1, offset: "defaultCharset", len: 0, typ: NTI33554450, name: "defaultCharset", sons: null}, +{kind: 1, offset: "fgColor", len: 0, typ: NTI33554450, name: "fgColor", sons: null}, +{kind: 1, offset: "head", len: 0, typ: NTI687865874, name: "head", sons: null}, +{kind: 1, offset: "hidden", len: 0, typ: NTI33554466, name: "hidden", sons: null}, +{kind: 1, offset: "lastModified", len: 0, typ: NTI33554450, name: "lastModified", sons: null}, +{kind: 1, offset: "linkColor", len: 0, typ: NTI33554450, name: "linkColor", sons: null}, +{kind: 1, offset: "referrer", len: 0, typ: NTI33554450, name: "referrer", sons: null}, +{kind: 1, offset: "title", len: 0, typ: NTI33554450, name: "title", sons: null}, +{kind: 1, offset: "URL", len: 0, typ: NTI33554450, name: "URL", sons: null}, +{kind: 1, offset: "visibilityState", len: 0, typ: NTI33554450, name: "visibilityState", sons: null}, +{kind: 1, offset: "vlinkColor", len: 0, typ: NTI33554450, name: "vlinkColor", sons: null}, +{kind: 1, offset: "anchors", len: 0, typ: NTI687865975, name: "anchors", sons: null}, +{kind: 1, offset: "forms", len: 0, typ: NTI687865976, name: "forms", sons: null}, +{kind: 1, offset: "images", len: 0, typ: NTI687865977, name: "images", sons: null}, +{kind: 1, offset: "applets", len: 0, typ: NTI687865978, name: "applets", sons: null}, +{kind: 1, offset: "embeds", len: 0, typ: NTI687865979, name: "embeds", sons: null}, +{kind: 1, offset: "links", len: 0, typ: NTI687865980, name: "links", sons: null}, +{kind: 1, offset: "fonts", len: 0, typ: NTI687865922, name: "fonts", sons: null}]}; +NTI687865974.node = NNI687865974; +NTI687865974.base = NTI687865970; +var NNI134217745 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217745.node = NNI134217745; +var NNI33555172 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555172.node = NNI33555172; +NTI33555174.base = NTI33555171; +NTI33555175.base = NTI33555171; +var NNI33555171 = {kind: 2, len: 5, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "parent", len: 0, typ: NTI33555174, name: "parent", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}, +{kind: 1, offset: "message", len: 0, typ: NTI33554449, name: "msg", sons: null}, +{kind: 1, offset: "trace", len: 0, typ: NTI33554449, name: "trace", sons: null}, +{kind: 1, offset: "up", len: 0, typ: NTI33555175, name: "up", sons: null}]}; +NTI33555171.node = NNI33555171; +NTI33555171.base = NTI33555167; +NTI33555172.base = NTI33555171; +NTI134217745.base = NTI33555172; +var NNI33555836 = {kind: 2, len: 3, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "Field0", len: 0, typ: NTI33554450, name: "Field0", sons: null}, +{kind: 1, offset: "Field1", len: 0, typ: NTI33554435, name: "Field1", sons: null}, +{kind: 1, offset: "Field2", len: 0, typ: NTI33554450, name: "Field2", sons: null}]}; +NTI33555836.node = NNI33555836; +var NNI134217743 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217743.node = NNI134217743; +var NNI134217741 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217741.node = NNI134217741; +NTI134217741.base = NTI33555172; +NTI134217743.base = NTI134217741; +var NNI134217751 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217751.node = NNI134217751; +NTI134217751.base = NTI33555172; +var NNI134217749 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217749.node = NNI134217749; +NTI134217749.base = NTI33555172; + +function setConstr() { + var result = {}; + for (var i = 0; i < arguments.length; ++i) { + var x = arguments[i]; + if (typeof(x) == "object") { + for (var j = x[0]; j <= x[1]; ++j) { + result[j] = true; + } + } else { + result[x] = true; + } + } + return result; + + + +} +var ConstSet1 = setConstr(17, 16, 4, 18, 27, 19, 23, 22, 21); + +function nimCopy(dest_p0, src_p1, ti_p2) { + var result_33557321 = null; + + switch (ti_p2.kind) { + case 21: + case 22: + case 23: + case 5: + if (!(isFatPointer__system_u2869(ti_p2))) { + result_33557321 = src_p1; + } + else { + result_33557321 = [src_p1[0], src_p1[1]]; + } + + break; + case 19: + if (dest_p0 === null || dest_p0 === undefined) { + dest_p0 = {}; + } + else { + for (var key in dest_p0) { delete dest_p0[key]; } + } + for (var key in src_p1) { dest_p0[key] = src_p1[key]; } + result_33557321 = dest_p0; + + break; + case 18: + case 17: + if (!((ti_p2.base == null))) { + result_33557321 = nimCopy(dest_p0, src_p1, ti_p2.base); + } + else { + if ((ti_p2.kind == 17)) { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {m_type: ti_p2} : dest_p0; + } + else { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {} : dest_p0; + } + } + nimCopyAux(result_33557321, src_p1, ti_p2.node); + break; + case 4: + case 16: + if(ArrayBuffer.isView(src_p1)) { + if(dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new src_p1.constructor(src_p1); + } else { + dest_p0.set(src_p1, 0); + } + result_33557321 = dest_p0; + } else { + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + } + + break; + case 24: + case 27: + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + + break; + case 28: + if (src_p1 !== null) { + result_33557321 = src_p1.slice(0); + } + + break; + default: + result_33557321 = src_p1; + break; + } + + return result_33557321; + +} + +function arrayConstr(len_p0, value_p1, typ_p2) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; ++i) result[i] = nimCopy(null, value_p1, typ_p2); + return result; + + + +} + +function mnewString(len_p0) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; i++) {result[i] = 0;} + return result; + + + +} + +function addInt(a_p0, b_p1) { + var result = a_p0 + b_p1; + checkOverflowInt(result); + return result; + + + +} + +function chckRange(i_p0, a_p1, b_p2) { + var result_33557361 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557361 = i_p0; + break BeforeRet; + } + else { + raiseRangeError(); + } + + }; + + return result_33557361; + +} + +function chckIndx(i_p0, a_p1, b_p2) { + var result_33557356 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557356 = i_p0; + break BeforeRet; + } + else { + raiseIndexError(i_p0, a_p1, b_p2); + } + + }; + + return result_33557356; + +} + +function cstrToNimstr(c_p0) { + var ln = c_p0.length; + var result = new Array(ln); + var r = 0; + for (var i = 0; i < ln; ++i) { + var ch = c_p0.charCodeAt(i); + + if (ch < 128) { + result[r] = ch; + } + else { + if (ch < 2048) { + result[r] = (ch >> 6) | 192; + } + else { + if (ch < 55296 || ch >= 57344) { + result[r] = (ch >> 12) | 224; + } + else { + ++i; + ch = 65536 + (((ch & 1023) << 10) | (c_p0.charCodeAt(i) & 1023)); + result[r] = (ch >> 18) | 240; + ++r; + result[r] = ((ch >> 12) & 63) | 128; + } + ++r; + result[r] = ((ch >> 6) & 63) | 128; + } + ++r; + result[r] = (ch & 63) | 128; + } + ++r; + } + return result; + + + +} + +function toJSStr(s_p0) { + var result_33556910 = null; + + var res_33556964 = newSeq__system_u2507((s_p0).length); + var i_33556965 = 0; + var j_33556966 = 0; + Label1: { + Label2: while (true) { + if (!(i_33556965 < (s_p0).length)) break Label2; + var c_33556967 = s_p0[i_33556965]; + if ((c_33556967 < 128)) { + res_33556964[j_33556966] = String.fromCharCode(c_33556967); + i_33556965 += 1; + } + else { + var helper_33556993 = newSeq__system_u2507(0); + Label3: { + Label4: while (true) { + if (!true) break Label4; + var code_33556994 = c_33556967.toString(16); + if ((((code_33556994) == null ? 0 : (code_33556994).length) == 1)) { + helper_33556993.push("%0");; + } + else { + helper_33556993.push("%");; + } + + helper_33556993.push(code_33556994);; + i_33556965 += 1; + if ((((s_p0).length <= i_33556965) || (s_p0[i_33556965] < 128))) { + break Label3; + } + + c_33556967 = s_p0[i_33556965]; + } + }; +++excHandler; + try { + res_33556964[j_33556966] = decodeURIComponent(helper_33556993.join("")); +--excHandler; +} catch (EXCEPTION) { + var prevJSError = lastJSError; + lastJSError = EXCEPTION; + --excHandler; + res_33556964[j_33556966] = helper_33556993.join(""); + lastJSError = prevJSError; + } finally { + } + } + + j_33556966 += 1; + } + }; + if (res_33556964.length < j_33556966) { for (var i = res_33556964.length ; i < j_33556966 ; ++i) res_33556964.push(null); } + else { res_33556964.length = j_33556966; }; + result_33556910 = res_33556964.join(""); + + return result_33556910; + +} + +function raiseException(e_p0, ename_p1) { + e_p0.name = ename_p1; + if ((excHandler == 0)) { + unhandledException(e_p0); + } + + e_p0.trace = nimCopy(null, rawWriteStackTrace__system_u2180(), NTI33554449); + throw e_p0; + + +} + +function makeNimstrLit(c_p0) { + var result = []; + for (var i = 0; i < c_p0.length; ++i) { + result[i] = c_p0.charCodeAt(i); + } + return result; + + + +} +var F = {procname: "module dom", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/dom.nim", line: 0}; +framePtr = F; +F.line = 1399; +F.filename = "dom.nim"; +var document_687867265 = [{nodeType: 9, m_type: NTI687865974, activeElement: null, documentElement: null, alinkColor: null, bgColor: null, body: null, charset: null, cookie: null, defaultCharset: null, fgColor: null, head: null, hidden: false, lastModified: null, linkColor: null, referrer: null, title: null, URL: null, visibilityState: null, vlinkColor: null, anchors: [], forms: [], images: [], applets: [], embeds: [], links: [], fonts: null, attributes: [], childNodes: [], children: [], data: null, firstChild: null, lastChild: null, nextSibling: null, nodeName: null, nodeValue: null, parentNode: null, content: null, previousSibling: null, ownerDocument: null, innerHTML: null, outerHTML: null, innerText: null, textContent: null, style: null, baseURI: null, parentElement: null, isConnected: false, onabort: null, onblur: null, onchange: null, onclick: null, ondblclick: null, onerror: null, onfocus: null, onkeydown: null, onkeypress: null, onkeyup: null, onload: null, onmousedown: null, onmousemove: null, onmouseout: null, onmouseover: null, onmouseup: null, onreset: null, onselect: null, onstorage: null, onsubmit: null, onunload: null, onloadstart: null, onprogress: null, onloadend: null}]; +F.line = 1400; +document_687867265[0].ownerDocument = document_687867265[0]; +framePtr = F.prev; +var F = {procname: "module dom", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/dom.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsformdata", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsformdata.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsformdata", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsformdata.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function isFatPointer__system_u2869(ti_p0) { + var result_33557303 = false; + + BeforeRet: { + result_33557303 = !((ConstSet1[ti_p0.base.kind] != undefined)); + break BeforeRet; + }; + + return result_33557303; + +} + +function nimCopyAux(dest_p0, src_p1, n_p2) { + switch (n_p2.kind) { + case 0: + break; + case 1: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + + break; + case 2: + for (var i = 0; i < n_p2.sons.length; i++) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i]); + } + + break; + case 3: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + for (var i = 0; i < n_p2.sons.length; ++i) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i][1]); + } + + break; + } + + +} + +function add__system_u1942(x_p0, x_p0_Idx, y_p1) { + if (x_p0[x_p0_Idx] === null) { x_p0[x_p0_Idx] = []; } + var off = x_p0[x_p0_Idx].length; + x_p0[x_p0_Idx].length += y_p1.length; + for (var i = 0; i < y_p1.length; ++i) { + x_p0[x_p0_Idx][off+i] = y_p1.charCodeAt(i); + } + + + +} + +function raiseOverflow() { + raiseException({message: [111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119], parent: null, m_type: NTI134217743, name: null, trace: [], up: null}, "OverflowDefect"); + + +} + +function checkOverflowInt(a_p0) { + if (a_p0 > 2147483647 || a_p0 < -2147483648) raiseOverflow(); + + + +} + +function raiseRangeError() { + raiseException({message: [118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101], parent: null, m_type: NTI134217751, name: null, trace: [], up: null}, "RangeDefect"); + + +} + +function raiseIndexError(i_p0, a_p1, b_p2) { + var Temporary1; + + if ((b_p2 < a_p1)) { + Temporary1 = [105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]; + } + else { + Temporary1 = ([105,110,100,101,120,32]).concat(HEX24__systemZdollars_u8(i_p0),[32,110,111,116,32,105,110,32],HEX24__systemZdollars_u8(a_p1),[32,46,46,32],HEX24__systemZdollars_u8(b_p2)); + } + + raiseException({message: nimCopy(null, Temporary1, NTI33554449), parent: null, m_type: NTI134217749, name: null, trace: [], up: null}, "IndexDefect"); + + +} + +function addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, start_p2, n_p3) { + var Temporary1; + + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 44; + F.filename = "digitsutils.nim"; + var old_301990096 = (result_p0[result_p0_Idx]).length; + F.line = 45; + if (result_p0[result_p0_Idx].length < (Temporary1 = chckRange(addInt(old_301990096, n_p3), 0, 2147483647), Temporary1)) { for (var i = result_p0[result_p0_Idx].length; i < Temporary1; ++i) result_p0[result_p0_Idx].push(0); } + else {result_p0[result_p0_Idx].length = Temporary1; }; + Label2: { + F.line = 47; + var iHEX60gensym4_301990110 = 0; + F.line = 128; + F.filename = "iterators_1.nim"; + var i_654311480 = 0; + Label3: { + F.line = 129; + Label4: while (true) { + if (!(i_654311480 < n_p3)) break Label4; + F.line = 50; + F.filename = "digitsutils.nim"; + iHEX60gensym4_301990110 = i_654311480; + F.line = 47; + result_p0[result_p0_Idx][chckIndx(addInt(old_301990096, iHEX60gensym4_301990110), 0, (result_p0[result_p0_Idx]).length - 1)] = x_p1.charCodeAt(chckIndx(addInt(start_p2, iHEX60gensym4_301990110), 0, (x_p1).length - 1)); + F.line = 131; + F.filename = "iterators_1.nim"; + i_654311480 = addInt(i_654311480, 1); + } + }; + }; + framePtr = F.prev; + + +} + +function addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 56; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, 0, ((x_p1) == null ? 0 : (x_p1).length)); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 112; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, ((x_p1) + "")); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u241(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 116; + F.filename = "digitsutils.nim"; + addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, BigInt(x_p1)); + framePtr = F.prev; + + +} + +function HEX24__systemZdollars_u8(x_p0) { + var result_369098762 = [[]]; + + var F = {procname: "dollars.$", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/dollars.nim", line: 0}; + framePtr = F; + F.line = 18; + F.filename = "dollars.nim"; + addInt__stdZprivateZdigitsutils_u241(result_369098762, 0, x_p0); + framePtr = F.prev; + + return result_369098762[0]; + +} + +function auxWriteStackTrace__system_u2084(f_p0) { + var result_33556518 = [[]]; + + var it_33556526 = f_p0; + var i_33556527 = 0; + var total_33556528 = 0; + var tempFrames_33556529 = arrayConstr(64, {Field0: null, Field1: 0, Field2: null}, NTI33555836); + Label1: { + Label2: while (true) { + if (!(!((it_33556526 == null)) && (i_33556527 <= 63))) break Label2; + tempFrames_33556529[i_33556527].Field0 = it_33556526.procname; + tempFrames_33556529[i_33556527].Field1 = it_33556526.line; + tempFrames_33556529[i_33556527].Field2 = it_33556526.filename; + i_33556527 += 1; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + Label3: { + Label4: while (true) { + if (!!((it_33556526 == null))) break Label4; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + result_33556518[0] = nimCopy(null, [], NTI33554449); + if (!((total_33556528 == i_33556527))) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + result_33556518[0].push.apply(result_33556518[0], HEX24__systemZdollars_u8((total_33556528 - i_33556527)));; + result_33556518[0].push.apply(result_33556518[0], [32,99,97,108,108,115,32,111,109,105,116,116,101,100,41,32,46,46,46,10]);; + } + + Label5: { + var j_33556562 = 0; + var colontmp__654311472 = 0; + colontmp__654311472 = (i_33556527 - 1); + var res_654311474 = colontmp__654311472; + Label6: { + Label7: while (true) { + if (!(0 <= res_654311474)) break Label7; + j_33556562 = res_654311474; + result_33556518[0].push.apply(result_33556518[0], cstrToNimstr(tempFrames_33556529[j_33556562].Field2));; + if ((0 < tempFrames_33556529[j_33556562].Field1)) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, tempFrames_33556529[j_33556562].Field1); + if (false) { + result_33556518[0].push.apply(result_33556518[0], [44,32]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, 0); + } + + result_33556518[0].push.apply(result_33556518[0], [41]);; + } + + result_33556518[0].push.apply(result_33556518[0], [32,97,116,32]);; + add__system_u1942(result_33556518, 0, tempFrames_33556529[j_33556562].Field0); + result_33556518[0].push.apply(result_33556518[0], [10]);; + res_654311474 -= 1; + } + }; + }; + + return result_33556518[0]; + +} + +function rawWriteStackTrace__system_u2180() { + var result_33556613 = []; + + if (!((framePtr == null))) { + result_33556613 = nimCopy(null, ([84,114,97,99,101,98,97,99,107,32,40,109,111,115,116,32,114,101,99,101,110,116,32,99,97,108,108,32,108,97,115,116,41,10]).concat(auxWriteStackTrace__system_u2084(framePtr)), NTI33554449); + } + else { + result_33556613 = nimCopy(null, [78,111,32,115,116,97,99,107,32,116,114,97,99,101,98,97,99,107,32,97,118,97,105,108,97,98,108,101,10], NTI33554449); + } + + + return result_33556613; + +} + +function newSeq__system_u2507(len_p0) { + var result_33556943 = []; + + var F = {procname: "newSeq.newSeq", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system.nim", line: 0}; + framePtr = F; + F.line = 653; + F.filename = "system.nim"; + result_33556943 = new Array(len_p0); for (var i = 0 ; i < len_p0 ; ++i) { result_33556943[i] = null; } framePtr = F.prev; + + return result_33556943; + +} + +function unhandledException(e_p0) { + var buf_33556658 = [[]]; + if (!(((e_p0.message).length == 0))) { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32]);; + buf_33556658[0].push.apply(buf_33556658[0], e_p0.message);; + } + else { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110]);; + } + + buf_33556658[0].push.apply(buf_33556658[0], [32,91]);; + add__system_u1942(buf_33556658, 0, e_p0.name); + buf_33556658[0].push.apply(buf_33556658[0], [93,10]);; + buf_33556658[0].push.apply(buf_33556658[0], rawWriteStackTrace__system_u2180());; + var cbuf_33556659 = toJSStr(buf_33556658[0]); + framePtr = null; + if (typeof(Error) !== "undefined") { + throw new Error(cbuf_33556659); + } + else { + throw cbuf_33556659; + } + + + +} + +function sysFatal__stdZassertions_u44(message_p1) { + var F = {procname: "sysFatal.sysFatal", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/fatal.nim", line: 0}; + framePtr = F; + F.line = 53; + F.filename = "fatal.nim"; + raiseException({message: nimCopy(null, message_p1, NTI33554449), m_type: NTI134217745, parent: null, name: null, trace: [], up: null}, "AssertionDefect"); + framePtr = F.prev; + + +} + +function raiseAssert__stdZassertions_u42(msg_p0) { + var F = {procname: "assertions.raiseAssert", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 36; + F.filename = "assertions.nim"; + sysFatal__stdZassertions_u44(msg_p0); + framePtr = F.prev; + + +} + +function failedAssertImpl__stdZassertions_u84(msg_p0) { + var F = {procname: "assertions.failedAssertImpl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 41; + F.filename = "assertions.nim"; + raiseAssert__stdZassertions_u42(msg_p0); + framePtr = F.prev; + + +} +var F = {procname: "module jsformdata_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsformdata_examples_1.nim", line: 0}; +framePtr = F; +F.line = 61; +F.filename = "jsformdata.nim"; +var data_654311427 = new FormData(); +F.line = 61; +data_654311427.set("key0", "value0"); +F.line = 61; +data_654311427.append("key1", "value1"); +F.line = 61; +data_654311427.delete("key1"); +if (!(data_654311427.has("key0"))) { +F.line = 61; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsformdata_examples_1.nim(13, 3) `data.hasKey(\"key0\")` ")); +} + +if (!((data_654311427.get("key0") == "value0"))) { +F.line = 61; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsformdata_examples_1.nim(14, 3) `data[\"key0\"] == \"value0\".cstring` ")); +} + +F.line = 61; +(() => { const frmdt = data_654311427; Array.from(frmdt.keys()).forEach((key) => frmdt.delete(key)) })(); +if (!((Array.from(data_654311427.entries()).length == 0))) { +F.line = 61; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsformdata_examples_1.nim(16, 3) `data.len == 0` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsformdata_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsformdata_examples_1.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsformdata_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsformdata_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsformdata_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsformdata_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; diff --git a/nimcache/runnableExamples/jsformdata_group0_examples.nim b/nimcache/runnableExamples/jsformdata_group0_examples.nim new file mode 100644 index 0000000000000..92ed1e2912dba --- /dev/null +++ b/nimcache/runnableExamples/jsformdata_group0_examples.nim @@ -0,0 +1,4 @@ +# autogenerated by docgen +# source: /home/runner/work/Nim/Nim/lib/std/jsformdata.nim +# rdoccmd: -r:off +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsformdata_examples_1.nim" diff --git a/nimcache/runnableExamples/jsheaders_examples_1.nim b/nimcache/runnableExamples/jsheaders_examples_1.nim new file mode 100644 index 0000000000000..b94371b68b94d --- /dev/null +++ b/nimcache/runnableExamples/jsheaders_examples_1.nim @@ -0,0 +1,41 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/jsheaders.nim(51, 17) +rdoccmd: -r:off +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/jsheaders.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/jsheaders.nim", 51, 17).}: + + block: + let header: Headers = newHeaders() + header.add("key", "value") + assert header.hasKey("key") + assert header.keys() == @["key".cstring] + assert header.values() == @["value".cstring] + assert header["key"] == "value".cstring + header["other"] = "another".cstring + assert header["other"] == "another".cstring + assert header.entries() == @[("key".cstring, "value".cstring), ("other".cstring, "another".cstring)] + assert header.toCstring() == """[["key","value"],["other","another"]]""".cstring + header.delete("other") + assert header.entries() == @[("key".cstring, "value".cstring)] + header.clear() + assert header.entries() == @[] + assert header.len == 0 + + block: + let header: Headers = newHeaders() + header.add("key", "a") + header.add("key", "b") ## Duplicated. + header.add("key", "c") ## Duplicated. + assert header["key"] == "a, b, c".cstring + header["key"] = "value".cstring + assert header["key"] == "value".cstring + + block: + let header: Headers = newHeaders() + header["key"] = "a" + header["key"] = "b" ## Overwrites. + assert header["key"] == "b".cstring + diff --git a/nimcache/runnableExamples/jsheaders_group0_examples.js b/nimcache/runnableExamples/jsheaders_group0_examples.js new file mode 100644 index 0000000000000..a4f2629a1e090 --- /dev/null +++ b/nimcache/runnableExamples/jsheaders_group0_examples.js @@ -0,0 +1,973 @@ +/* Generated by the Nim Compiler v2.2.1 */ +var framePtr = null; +var excHandler = 0; +var lastJSError = null; +var NTI654311515 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI654311481 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI134217749 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217751 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217741 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217743 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554435 = {size: 0,kind: 31,base: null,node: null,finalizer: null}; +var NTI33555836 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI33555167 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555175 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554450 = {size: 0,kind: 29,base: null,node: null,finalizer: null}; +var NTI33555174 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33555171 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555172 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217745 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554449 = {size: 0,kind: 28,base: null,node: null,finalizer: null}; +var NNI134217745 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217745.node = NNI134217745; +var NNI33555172 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555172.node = NNI33555172; +NTI33555174.base = NTI33555171; +NTI33555175.base = NTI33555171; +var NNI33555171 = {kind: 2, len: 5, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "parent", len: 0, typ: NTI33555174, name: "parent", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}, +{kind: 1, offset: "message", len: 0, typ: NTI33554449, name: "msg", sons: null}, +{kind: 1, offset: "trace", len: 0, typ: NTI33554449, name: "trace", sons: null}, +{kind: 1, offset: "up", len: 0, typ: NTI33555175, name: "up", sons: null}]}; +NTI33555171.node = NNI33555171; +var NNI33555167 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555167.node = NNI33555167; +NTI33555171.base = NTI33555167; +NTI33555172.base = NTI33555171; +NTI134217745.base = NTI33555172; +var NNI33555836 = {kind: 2, len: 3, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "Field0", len: 0, typ: NTI33554450, name: "Field0", sons: null}, +{kind: 1, offset: "Field1", len: 0, typ: NTI33554435, name: "Field1", sons: null}, +{kind: 1, offset: "Field2", len: 0, typ: NTI33554450, name: "Field2", sons: null}]}; +NTI33555836.node = NNI33555836; +var NNI134217743 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217743.node = NNI134217743; +var NNI134217741 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217741.node = NNI134217741; +NTI134217741.base = NTI33555172; +NTI134217743.base = NTI134217741; +var NNI134217751 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217751.node = NNI134217751; +NTI134217751.base = NTI33555172; +var NNI134217749 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217749.node = NNI134217749; +NTI134217749.base = NTI33555172; +var NNI654311481 = {kind: 2, len: 2, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "Field0", len: 0, typ: NTI33554450, name: "Field0", sons: null}, +{kind: 1, offset: "Field1", len: 0, typ: NTI33554450, name: "Field1", sons: null}]}; +NTI654311481.node = NNI654311481; +var NNI654311515 = {kind: 2, len: 2, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "Field0", len: 0, typ: NTI33554450, name: "Field0", sons: null}, +{kind: 1, offset: "Field1", len: 0, typ: NTI33554450, name: "Field1", sons: null}]}; +NTI654311515.node = NNI654311515; + +function setConstr() { + var result = {}; + for (var i = 0; i < arguments.length; ++i) { + var x = arguments[i]; + if (typeof(x) == "object") { + for (var j = x[0]; j <= x[1]; ++j) { + result[j] = true; + } + } else { + result[x] = true; + } + } + return result; + + + +} +var ConstSet1 = setConstr(17, 16, 4, 18, 27, 19, 23, 22, 21); + +function nimCopy(dest_p0, src_p1, ti_p2) { + var result_33557321 = null; + + switch (ti_p2.kind) { + case 21: + case 22: + case 23: + case 5: + if (!(isFatPointer__system_u2869(ti_p2))) { + result_33557321 = src_p1; + } + else { + result_33557321 = [src_p1[0], src_p1[1]]; + } + + break; + case 19: + if (dest_p0 === null || dest_p0 === undefined) { + dest_p0 = {}; + } + else { + for (var key in dest_p0) { delete dest_p0[key]; } + } + for (var key in src_p1) { dest_p0[key] = src_p1[key]; } + result_33557321 = dest_p0; + + break; + case 18: + case 17: + if (!((ti_p2.base == null))) { + result_33557321 = nimCopy(dest_p0, src_p1, ti_p2.base); + } + else { + if ((ti_p2.kind == 17)) { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {m_type: ti_p2} : dest_p0; + } + else { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {} : dest_p0; + } + } + nimCopyAux(result_33557321, src_p1, ti_p2.node); + break; + case 4: + case 16: + if(ArrayBuffer.isView(src_p1)) { + if(dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new src_p1.constructor(src_p1); + } else { + dest_p0.set(src_p1, 0); + } + result_33557321 = dest_p0; + } else { + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + } + + break; + case 24: + case 27: + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + + break; + case 28: + if (src_p1 !== null) { + result_33557321 = src_p1.slice(0); + } + + break; + default: + result_33557321 = src_p1; + break; + } + + return result_33557321; + +} + +function arrayConstr(len_p0, value_p1, typ_p2) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; ++i) result[i] = nimCopy(null, value_p1, typ_p2); + return result; + + + +} + +function mnewString(len_p0) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; i++) {result[i] = 0;} + return result; + + + +} + +function addInt(a_p0, b_p1) { + var result = a_p0 + b_p1; + checkOverflowInt(result); + return result; + + + +} + +function chckRange(i_p0, a_p1, b_p2) { + var result_33557361 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557361 = i_p0; + break BeforeRet; + } + else { + raiseRangeError(); + } + + }; + + return result_33557361; + +} + +function chckIndx(i_p0, a_p1, b_p2) { + var result_33557356 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557356 = i_p0; + break BeforeRet; + } + else { + raiseIndexError(i_p0, a_p1, b_p2); + } + + }; + + return result_33557356; + +} + +function cstrToNimstr(c_p0) { + var ln = c_p0.length; + var result = new Array(ln); + var r = 0; + for (var i = 0; i < ln; ++i) { + var ch = c_p0.charCodeAt(i); + + if (ch < 128) { + result[r] = ch; + } + else { + if (ch < 2048) { + result[r] = (ch >> 6) | 192; + } + else { + if (ch < 55296 || ch >= 57344) { + result[r] = (ch >> 12) | 224; + } + else { + ++i; + ch = 65536 + (((ch & 1023) << 10) | (c_p0.charCodeAt(i) & 1023)); + result[r] = (ch >> 18) | 240; + ++r; + result[r] = ((ch >> 12) & 63) | 128; + } + ++r; + result[r] = ((ch >> 6) & 63) | 128; + } + ++r; + result[r] = (ch & 63) | 128; + } + ++r; + } + return result; + + + +} + +function toJSStr(s_p0) { + var result_33556910 = null; + + var res_33556964 = newSeq__system_u2507((s_p0).length); + var i_33556965 = 0; + var j_33556966 = 0; + Label1: { + Label2: while (true) { + if (!(i_33556965 < (s_p0).length)) break Label2; + var c_33556967 = s_p0[i_33556965]; + if ((c_33556967 < 128)) { + res_33556964[j_33556966] = String.fromCharCode(c_33556967); + i_33556965 += 1; + } + else { + var helper_33556993 = newSeq__system_u2507(0); + Label3: { + Label4: while (true) { + if (!true) break Label4; + var code_33556994 = c_33556967.toString(16); + if ((((code_33556994) == null ? 0 : (code_33556994).length) == 1)) { + helper_33556993.push("%0");; + } + else { + helper_33556993.push("%");; + } + + helper_33556993.push(code_33556994);; + i_33556965 += 1; + if ((((s_p0).length <= i_33556965) || (s_p0[i_33556965] < 128))) { + break Label3; + } + + c_33556967 = s_p0[i_33556965]; + } + }; +++excHandler; + try { + res_33556964[j_33556966] = decodeURIComponent(helper_33556993.join("")); +--excHandler; +} catch (EXCEPTION) { + var prevJSError = lastJSError; + lastJSError = EXCEPTION; + --excHandler; + res_33556964[j_33556966] = helper_33556993.join(""); + lastJSError = prevJSError; + } finally { + } + } + + j_33556966 += 1; + } + }; + if (res_33556964.length < j_33556966) { for (var i = res_33556964.length ; i < j_33556966 ; ++i) res_33556964.push(null); } + else { res_33556964.length = j_33556966; }; + result_33556910 = res_33556964.join(""); + + return result_33556910; + +} + +function raiseException(e_p0, ename_p1) { + e_p0.name = ename_p1; + if ((excHandler == 0)) { + unhandledException(e_p0); + } + + e_p0.trace = nimCopy(null, rawWriteStackTrace__system_u2180(), NTI33554449); + throw e_p0; + + +} + +function makeNimstrLit(c_p0) { + var result = []; + for (var i = 0; i < c_p0.length; ++i) { + result[i] = c_p0.charCodeAt(i); + } + return result; + + + +} + +function subInt(a_p0, b_p1) { + var result = a_p0 - b_p1; + checkOverflowInt(result); + return result; + + + +} +var F = {procname: "module jsheaders", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsheaders.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsheaders", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsheaders.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function isFatPointer__system_u2869(ti_p0) { + var result_33557303 = false; + + BeforeRet: { + result_33557303 = !((ConstSet1[ti_p0.base.kind] != undefined)); + break BeforeRet; + }; + + return result_33557303; + +} + +function nimCopyAux(dest_p0, src_p1, n_p2) { + switch (n_p2.kind) { + case 0: + break; + case 1: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + + break; + case 2: + for (var i = 0; i < n_p2.sons.length; i++) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i]); + } + + break; + case 3: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + for (var i = 0; i < n_p2.sons.length; ++i) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i][1]); + } + + break; + } + + +} + +function add__system_u1942(x_p0, x_p0_Idx, y_p1) { + if (x_p0[x_p0_Idx] === null) { x_p0[x_p0_Idx] = []; } + var off = x_p0[x_p0_Idx].length; + x_p0[x_p0_Idx].length += y_p1.length; + for (var i = 0; i < y_p1.length; ++i) { + x_p0[x_p0_Idx][off+i] = y_p1.charCodeAt(i); + } + + + +} + +function raiseOverflow() { + raiseException({message: [111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119], parent: null, m_type: NTI134217743, name: null, trace: [], up: null}, "OverflowDefect"); + + +} + +function checkOverflowInt(a_p0) { + if (a_p0 > 2147483647 || a_p0 < -2147483648) raiseOverflow(); + + + +} + +function raiseRangeError() { + raiseException({message: [118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101], parent: null, m_type: NTI134217751, name: null, trace: [], up: null}, "RangeDefect"); + + +} + +function raiseIndexError(i_p0, a_p1, b_p2) { + var Temporary1; + + if ((b_p2 < a_p1)) { + Temporary1 = [105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]; + } + else { + Temporary1 = ([105,110,100,101,120,32]).concat(HEX24__systemZdollars_u8(i_p0),[32,110,111,116,32,105,110,32],HEX24__systemZdollars_u8(a_p1),[32,46,46,32],HEX24__systemZdollars_u8(b_p2)); + } + + raiseException({message: nimCopy(null, Temporary1, NTI33554449), parent: null, m_type: NTI134217749, name: null, trace: [], up: null}, "IndexDefect"); + + +} + +function addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, start_p2, n_p3) { + var Temporary1; + + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 44; + F.filename = "digitsutils.nim"; + var old_301990096 = (result_p0[result_p0_Idx]).length; + F.line = 45; + if (result_p0[result_p0_Idx].length < (Temporary1 = chckRange(addInt(old_301990096, n_p3), 0, 2147483647), Temporary1)) { for (var i = result_p0[result_p0_Idx].length; i < Temporary1; ++i) result_p0[result_p0_Idx].push(0); } + else {result_p0[result_p0_Idx].length = Temporary1; }; + Label2: { + F.line = 47; + var iHEX60gensym4_301990110 = 0; + F.line = 128; + F.filename = "iterators_1.nim"; + var i_654311685 = 0; + Label3: { + F.line = 129; + Label4: while (true) { + if (!(i_654311685 < n_p3)) break Label4; + F.line = 50; + F.filename = "digitsutils.nim"; + iHEX60gensym4_301990110 = i_654311685; + F.line = 47; + result_p0[result_p0_Idx][chckIndx(addInt(old_301990096, iHEX60gensym4_301990110), 0, (result_p0[result_p0_Idx]).length - 1)] = x_p1.charCodeAt(chckIndx(addInt(start_p2, iHEX60gensym4_301990110), 0, (x_p1).length - 1)); + F.line = 131; + F.filename = "iterators_1.nim"; + i_654311685 = addInt(i_654311685, 1); + } + }; + }; + framePtr = F.prev; + + +} + +function addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 56; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, 0, ((x_p1) == null ? 0 : (x_p1).length)); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 112; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, ((x_p1) + "")); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u241(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 116; + F.filename = "digitsutils.nim"; + addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, BigInt(x_p1)); + framePtr = F.prev; + + +} + +function HEX24__systemZdollars_u8(x_p0) { + var result_369098762 = [[]]; + + var F = {procname: "dollars.$", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/dollars.nim", line: 0}; + framePtr = F; + F.line = 18; + F.filename = "dollars.nim"; + addInt__stdZprivateZdigitsutils_u241(result_369098762, 0, x_p0); + framePtr = F.prev; + + return result_369098762[0]; + +} + +function auxWriteStackTrace__system_u2084(f_p0) { + var result_33556518 = [[]]; + + var it_33556526 = f_p0; + var i_33556527 = 0; + var total_33556528 = 0; + var tempFrames_33556529 = arrayConstr(64, {Field0: null, Field1: 0, Field2: null}, NTI33555836); + Label1: { + Label2: while (true) { + if (!(!((it_33556526 == null)) && (i_33556527 <= 63))) break Label2; + tempFrames_33556529[i_33556527].Field0 = it_33556526.procname; + tempFrames_33556529[i_33556527].Field1 = it_33556526.line; + tempFrames_33556529[i_33556527].Field2 = it_33556526.filename; + i_33556527 += 1; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + Label3: { + Label4: while (true) { + if (!!((it_33556526 == null))) break Label4; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + result_33556518[0] = nimCopy(null, [], NTI33554449); + if (!((total_33556528 == i_33556527))) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + result_33556518[0].push.apply(result_33556518[0], HEX24__systemZdollars_u8((total_33556528 - i_33556527)));; + result_33556518[0].push.apply(result_33556518[0], [32,99,97,108,108,115,32,111,109,105,116,116,101,100,41,32,46,46,46,10]);; + } + + Label5: { + var j_33556562 = 0; + var colontmp__654311677 = 0; + colontmp__654311677 = (i_33556527 - 1); + var res_654311679 = colontmp__654311677; + Label6: { + Label7: while (true) { + if (!(0 <= res_654311679)) break Label7; + j_33556562 = res_654311679; + result_33556518[0].push.apply(result_33556518[0], cstrToNimstr(tempFrames_33556529[j_33556562].Field2));; + if ((0 < tempFrames_33556529[j_33556562].Field1)) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, tempFrames_33556529[j_33556562].Field1); + if (false) { + result_33556518[0].push.apply(result_33556518[0], [44,32]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, 0); + } + + result_33556518[0].push.apply(result_33556518[0], [41]);; + } + + result_33556518[0].push.apply(result_33556518[0], [32,97,116,32]);; + add__system_u1942(result_33556518, 0, tempFrames_33556529[j_33556562].Field0); + result_33556518[0].push.apply(result_33556518[0], [10]);; + res_654311679 -= 1; + } + }; + }; + + return result_33556518[0]; + +} + +function rawWriteStackTrace__system_u2180() { + var result_33556613 = []; + + if (!((framePtr == null))) { + result_33556613 = nimCopy(null, ([84,114,97,99,101,98,97,99,107,32,40,109,111,115,116,32,114,101,99,101,110,116,32,99,97,108,108,32,108,97,115,116,41,10]).concat(auxWriteStackTrace__system_u2084(framePtr)), NTI33554449); + } + else { + result_33556613 = nimCopy(null, [78,111,32,115,116,97,99,107,32,116,114,97,99,101,98,97,99,107,32,97,118,97,105,108,97,98,108,101,10], NTI33554449); + } + + + return result_33556613; + +} + +function newSeq__system_u2507(len_p0) { + var result_33556943 = []; + + var F = {procname: "newSeq.newSeq", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system.nim", line: 0}; + framePtr = F; + F.line = 653; + F.filename = "system.nim"; + result_33556943 = new Array(len_p0); for (var i = 0 ; i < len_p0 ; ++i) { result_33556943[i] = null; } framePtr = F.prev; + + return result_33556943; + +} + +function unhandledException(e_p0) { + var buf_33556658 = [[]]; + if (!(((e_p0.message).length == 0))) { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32]);; + buf_33556658[0].push.apply(buf_33556658[0], e_p0.message);; + } + else { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110]);; + } + + buf_33556658[0].push.apply(buf_33556658[0], [32,91]);; + add__system_u1942(buf_33556658, 0, e_p0.name); + buf_33556658[0].push.apply(buf_33556658[0], [93,10]);; + buf_33556658[0].push.apply(buf_33556658[0], rawWriteStackTrace__system_u2180());; + var cbuf_33556659 = toJSStr(buf_33556658[0]); + framePtr = null; + if (typeof(Error) !== "undefined") { + throw new Error(cbuf_33556659); + } + else { + throw cbuf_33556659; + } + + + +} + +function sysFatal__stdZassertions_u44(message_p1) { + var F = {procname: "sysFatal.sysFatal", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/fatal.nim", line: 0}; + framePtr = F; + F.line = 53; + F.filename = "fatal.nim"; + raiseException({message: nimCopy(null, message_p1, NTI33554449), m_type: NTI134217745, parent: null, name: null, trace: [], up: null}, "AssertionDefect"); + framePtr = F.prev; + + +} + +function raiseAssert__stdZassertions_u42(msg_p0) { + var F = {procname: "assertions.raiseAssert", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 36; + F.filename = "assertions.nim"; + sysFatal__stdZassertions_u44(msg_p0); + framePtr = F.prev; + + +} + +function failedAssertImpl__stdZassertions_u84(msg_p0) { + var F = {procname: "assertions.failedAssertImpl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 41; + F.filename = "assertions.nim"; + raiseAssert__stdZassertions_u42(msg_p0); + framePtr = F.prev; + + +} + +function HEX3DHEX3D__jsheaders95examples951_u13(x_p0, y_p1) { + var result_654311441 = false; + + var F = {procname: "==.==", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/comparisons.nim", line: 0}; + framePtr = F; + BeforeRet: { + F.line = 326; + F.filename = "comparisons.nim"; + var sameObject_654311449 = false; + F.line = 327; + sameObject_654311449 = x_p0 === y_p1; + if (sameObject_654311449) { + F.line = 328; + result_654311441 = true; + break BeforeRet; + } + + if (!(((x_p0).length == (y_p1).length))) { + F.line = 331; + result_654311441 = false; + break BeforeRet; + } + + Label1: { + F.line = 333; + var i_654311463 = 0; + F.line = 81; + F.filename = "iterators_1.nim"; + var colontmp__654311690 = 0; + F.line = 333; + F.filename = "comparisons.nim"; + colontmp__654311690 = subInt((x_p0).length, 1); + F.line = 96; + F.filename = "iterators_1.nim"; + var res_654311692 = 0; + Label2: { + F.line = 97; + Label3: while (true) { + if (!(res_654311692 <= colontmp__654311690)) break Label3; + F.line = 333; + F.filename = "comparisons.nim"; + i_654311463 = res_654311692; + if (!((x_p0[chckIndx(i_654311463, 0, (x_p0).length - 1)] == y_p1[chckIndx(i_654311463, 0, (y_p1).length - 1)]))) { + F.line = 335; + result_654311441 = false; + break BeforeRet; + } + + F.line = 102; + F.filename = "iterators_1.nim"; + res_654311692 = addInt(res_654311692, 1); + } + }; + }; + F.line = 337; + F.filename = "comparisons.nim"; + result_654311441 = true; + break BeforeRet; + }; + framePtr = F.prev; + + return result_654311441; + +} + +function HEX3DHEX3D__jsheaders95examples951_u99(x_p0, y_p1) { + var result_654311527 = false; + + var F = {procname: "==.==", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system.nim", line: 0}; + framePtr = F; + BeforeRet: { + if (true) { + if (!((x_p0["Field0"] == y_p1["Field0"]))) { + F.line = 1803; + F.filename = "system.nim"; + result_654311527 = false; + break BeforeRet; + } + + } + + if (true) { + if (!((x_p0["Field1"] == y_p1["Field1"]))) { + F.line = 1803; + result_654311527 = false; + break BeforeRet; + } + + } + + F.line = 1804; + result_654311527 = true; + break BeforeRet; + }; + framePtr = F.prev; + + return result_654311527; + +} + +function HEX3DHEX3D__jsheaders95examples951_u72(x_p0, y_p1) { + var result_654311500 = false; + + var F = {procname: "==.==", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/comparisons.nim", line: 0}; + framePtr = F; + BeforeRet: { + F.line = 326; + F.filename = "comparisons.nim"; + var sameObject_654311508 = false; + F.line = 327; + sameObject_654311508 = x_p0 === y_p1; + if (sameObject_654311508) { + F.line = 328; + result_654311500 = true; + break BeforeRet; + } + + if (!(((x_p0).length == (y_p1).length))) { + F.line = 331; + result_654311500 = false; + break BeforeRet; + } + + Label1: { + F.line = 333; + var i_654311522 = 0; + F.line = 81; + F.filename = "iterators_1.nim"; + var colontmp__654311695 = 0; + F.line = 333; + F.filename = "comparisons.nim"; + colontmp__654311695 = subInt((x_p0).length, 1); + F.line = 96; + F.filename = "iterators_1.nim"; + var res_654311696 = 0; + Label2: { + F.line = 97; + Label3: while (true) { + if (!(res_654311696 <= colontmp__654311695)) break Label3; + F.line = 333; + F.filename = "comparisons.nim"; + i_654311522 = res_654311696; + if (!(HEX3DHEX3D__jsheaders95examples951_u99(x_p0[chckIndx(i_654311522, 0, (x_p0).length - 1)], y_p1[chckIndx(i_654311522, 0, (y_p1).length - 1)]))) { + F.line = 335; + result_654311500 = false; + break BeforeRet; + } + + F.line = 102; + F.filename = "iterators_1.nim"; + res_654311696 = addInt(res_654311696, 1); + } + }; + }; + F.line = 337; + F.filename = "comparisons.nim"; + result_654311500 = true; + break BeforeRet; + }; + framePtr = F.prev; + + return result_654311500; + +} +var F = {procname: "module jsheaders_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim", line: 0}; +framePtr = F; +Label1: { + F.line = 51; + F.filename = "jsheaders.nim"; + var header_654311427 = new Headers(); + F.line = 51; + header_654311427.append("key", "value"); + if (!(header_654311427.has("key"))) { + F.line = 51; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim(13, 5) `header.hasKey(\"key\")` ")); + } + + if (!(HEX3DHEX3D__jsheaders95examples951_u13(Array.from(header_654311427.keys()), ["key"]))) { + F.line = 51; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim(14, 5) `header.keys() == @[\"key\".cstring]` ")); + } + + if (!(HEX3DHEX3D__jsheaders95examples951_u13(Array.from(header_654311427.values()), ["value"]))) { + F.line = 51; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim(15, 5) `header.values() == @[\"value\".cstring]` ")); + } + + if (!((header_654311427.get("key") == "value"))) { + F.line = 51; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim(16, 5) `header[\"key\"] == \"value\".cstring` ")); + } + + F.line = 51; + header_654311427.set("other", "another"); + if (!((header_654311427.get("other") == "another"))) { + F.line = 51; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim(18, 5) `header[\"other\"] == \"another\".cstring` ")); + } + + if (!(HEX3DHEX3D__jsheaders95examples951_u72(Array.from(header_654311427.entries()), [nimCopy(null, {Field0: "key", Field1: "value"}, NTI654311481), nimCopy(null, {Field0: "other", Field1: "another"}, NTI654311481)]))) { + F.line = 51; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim(19, 5) `header.entries() ==\x0A @[(\"key\".cstring, \"value\".cstring), (\"other\".cstring, \"another\".cstring)]` ")); + } + + if (!((JSON.stringify(Array.from(header_654311427.entries())) == "[[\"key\",\"value\"],[\"other\",\"another\"]]"))) { + F.line = 51; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim(20, 5) `header.toCstring() == \"\"\"[[\"key\",\"value\"],[\"other\",\"another\"]]\"\"\".cstring` ")); + } + + F.line = 51; + header_654311427.delete("other"); + if (!(HEX3DHEX3D__jsheaders95examples951_u72(Array.from(header_654311427.entries()), [nimCopy(null, {Field0: "key", Field1: "value"}, NTI654311515)]))) { + F.line = 51; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim(22, 5) `header.entries() == @[(\"key\".cstring, \"value\".cstring)]` ")); + } + + F.line = 51; + (() => { const header = header_654311427; Array.from(header.keys()).forEach((key) => header.delete(key)) })(); + if (!(HEX3DHEX3D__jsheaders95examples951_u72(Array.from(header_654311427.entries()), []))) { + F.line = 51; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim(24, 5) `header.entries() == @[]` ")); + } + + if (!((Array.from(header_654311427.entries()).length == 0))) { + F.line = 51; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim(25, 5) `header.len == 0` ")); + } + +}; +Label2: { + F.line = 51; + var header_654311574 = new Headers(); + F.line = 51; + header_654311574.append("key", "a"); + F.line = 51; + header_654311574.append("key", "b"); + F.line = 51; + header_654311574.append("key", "c"); + if (!((header_654311574.get("key") == "a, b, c"))) { + F.line = 51; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim(32, 5) `header[\"key\"] == \"a, b, c\".cstring` ")); + } + + F.line = 51; + header_654311574.set("key", "value"); + if (!((header_654311574.get("key") == "value"))) { + F.line = 51; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim(34, 5) `header[\"key\"] == \"value\".cstring` ")); + } + +}; +Label3: { + F.line = 51; + var header_654311585 = new Headers(); + F.line = 51; + header_654311585.set("key", "a"); + F.line = 51; + header_654311585.set("key", "b"); + if (!((header_654311585.get("key") == "b"))) { + F.line = 51; + failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim(40, 5) `header[\"key\"] == \"b\".cstring` ")); + } + +}; +framePtr = F.prev; +var F = {procname: "module jsheaders_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsheaders_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsheaders_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; diff --git a/nimcache/runnableExamples/jsheaders_group0_examples.nim b/nimcache/runnableExamples/jsheaders_group0_examples.nim new file mode 100644 index 0000000000000..00ce6a1ee604f --- /dev/null +++ b/nimcache/runnableExamples/jsheaders_group0_examples.nim @@ -0,0 +1,4 @@ +# autogenerated by docgen +# source: /home/runner/work/Nim/Nim/lib/std/jsheaders.nim +# rdoccmd: -r:off +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsheaders_examples_1.nim" diff --git a/nimcache/runnableExamples/jsre_examples_1.nim b/nimcache/runnableExamples/jsre_examples_1.nim new file mode 100644 index 0000000000000..1b6fa1d2caedc --- /dev/null +++ b/nimcache/runnableExamples/jsre_examples_1.nim @@ -0,0 +1,13 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/jsre.nim(56, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/jsre.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/jsre.nim", 56, 3).}: + let jsregex: RegExp = newRegExp(r"bc$", r"i") + assert jsregex in r"abc" + assert jsregex notin r"abcd" + assert "xabc".contains jsregex + diff --git a/nimcache/runnableExamples/jsre_examples_2.nim b/nimcache/runnableExamples/jsre_examples_2.nim new file mode 100644 index 0000000000000..aa6154b4488ad --- /dev/null +++ b/nimcache/runnableExamples/jsre_examples_2.nim @@ -0,0 +1,11 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/jsre.nim(65, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/jsre.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/jsre.nim", 65, 3).}: + let jsregex: RegExp = newRegExp(r"abc", r"i") + assert "abcd".startsWith jsregex + diff --git a/nimcache/runnableExamples/jsre_examples_3.nim b/nimcache/runnableExamples/jsre_examples_3.nim new file mode 100644 index 0000000000000..3cd9876eb73b4 --- /dev/null +++ b/nimcache/runnableExamples/jsre_examples_3.nim @@ -0,0 +1,11 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/jsre.nim(72, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/jsre.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/jsre.nim", 72, 3).}: + let jsregex: RegExp = newRegExp(r"bcd", r"i") + assert "abcd".endsWith jsregex + diff --git a/nimcache/runnableExamples/jsre_examples_4.nim b/nimcache/runnableExamples/jsre_examples_4.nim new file mode 100644 index 0000000000000..d0a17cc8a2dc5 --- /dev/null +++ b/nimcache/runnableExamples/jsre_examples_4.nim @@ -0,0 +1,28 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/js/jsre.nim(78, 1) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/js/jsre.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/js/jsre.nim", 78, 1).}: + let jsregex: RegExp = newRegExp(r"\s+", r"i") + jsregex.compile(r"\w+", r"i") + assert "nim javascript".contains jsregex + assert jsregex.exec(r"nim javascript") == @["nim".cstring] + assert jsregex.toCstring() == r"/\w+/i" + jsregex.compile(r"[0-9]", r"i") + assert "0123456789abcd".contains jsregex + assert $jsregex == "/[0-9]/i" + jsregex.compile(r"abc", r"i") + assert "abcd".startsWith jsregex + assert "dabc".endsWith jsregex + jsregex.compile(r"\d", r"i") + assert "do1ne".split(jsregex) == @["do".cstring, "ne".cstring] + jsregex.compile(r"[lw]", r"i") + assert "hello world".replace(jsregex,"X") == "heXlo world" + jsregex.compile(r"([a-z])\1*", r"g") + assert "abbcccdddd".replace(jsregex, proc (m: varargs[cstring]): cstring = ($m[0] & $(m.len)).cstring) == "a1b2c3d4" + let digitsRegex: RegExp = newRegExp(r"\d") + assert "foo".match(digitsRegex) == @[] + diff --git a/nimcache/runnableExamples/jsre_group0_examples.js b/nimcache/runnableExamples/jsre_group0_examples.js new file mode 100644 index 0000000000000..06a83225642c9 --- /dev/null +++ b/nimcache/runnableExamples/jsre_group0_examples.js @@ -0,0 +1,978 @@ +/* Generated by the Nim Compiler v2.2.1 */ +var framePtr = null; +var excHandler = 0; +var lastJSError = null; +var NTI134217749 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217751 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217741 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217743 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554435 = {size: 0,kind: 31,base: null,node: null,finalizer: null}; +var NTI33555836 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI33555167 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555175 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554450 = {size: 0,kind: 29,base: null,node: null,finalizer: null}; +var NTI33555174 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33555171 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555172 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217745 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554449 = {size: 0,kind: 28,base: null,node: null,finalizer: null}; +var NNI134217745 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217745.node = NNI134217745; +var NNI33555172 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555172.node = NNI33555172; +NTI33555174.base = NTI33555171; +NTI33555175.base = NTI33555171; +var NNI33555171 = {kind: 2, len: 5, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "parent", len: 0, typ: NTI33555174, name: "parent", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}, +{kind: 1, offset: "message", len: 0, typ: NTI33554449, name: "msg", sons: null}, +{kind: 1, offset: "trace", len: 0, typ: NTI33554449, name: "trace", sons: null}, +{kind: 1, offset: "up", len: 0, typ: NTI33555175, name: "up", sons: null}]}; +NTI33555171.node = NNI33555171; +var NNI33555167 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555167.node = NNI33555167; +NTI33555171.base = NTI33555167; +NTI33555172.base = NTI33555171; +NTI134217745.base = NTI33555172; +var NNI33555836 = {kind: 2, len: 3, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "Field0", len: 0, typ: NTI33554450, name: "Field0", sons: null}, +{kind: 1, offset: "Field1", len: 0, typ: NTI33554435, name: "Field1", sons: null}, +{kind: 1, offset: "Field2", len: 0, typ: NTI33554450, name: "Field2", sons: null}]}; +NTI33555836.node = NNI33555836; +var NNI134217743 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217743.node = NNI134217743; +var NNI134217741 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217741.node = NNI134217741; +NTI134217741.base = NTI33555172; +NTI134217743.base = NTI134217741; +var NNI134217751 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217751.node = NNI134217751; +NTI134217751.base = NTI33555172; +var NNI134217749 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217749.node = NNI134217749; +NTI134217749.base = NTI33555172; + +function setConstr() { + var result = {}; + for (var i = 0; i < arguments.length; ++i) { + var x = arguments[i]; + if (typeof(x) == "object") { + for (var j = x[0]; j <= x[1]; ++j) { + result[j] = true; + } + } else { + result[x] = true; + } + } + return result; + + + +} +var ConstSet1 = setConstr(17, 16, 4, 18, 27, 19, 23, 22, 21); + +function nimCopy(dest_p0, src_p1, ti_p2) { + var result_33557321 = null; + + switch (ti_p2.kind) { + case 21: + case 22: + case 23: + case 5: + if (!(isFatPointer__system_u2869(ti_p2))) { + result_33557321 = src_p1; + } + else { + result_33557321 = [src_p1[0], src_p1[1]]; + } + + break; + case 19: + if (dest_p0 === null || dest_p0 === undefined) { + dest_p0 = {}; + } + else { + for (var key in dest_p0) { delete dest_p0[key]; } + } + for (var key in src_p1) { dest_p0[key] = src_p1[key]; } + result_33557321 = dest_p0; + + break; + case 18: + case 17: + if (!((ti_p2.base == null))) { + result_33557321 = nimCopy(dest_p0, src_p1, ti_p2.base); + } + else { + if ((ti_p2.kind == 17)) { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {m_type: ti_p2} : dest_p0; + } + else { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {} : dest_p0; + } + } + nimCopyAux(result_33557321, src_p1, ti_p2.node); + break; + case 4: + case 16: + if(ArrayBuffer.isView(src_p1)) { + if(dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new src_p1.constructor(src_p1); + } else { + dest_p0.set(src_p1, 0); + } + result_33557321 = dest_p0; + } else { + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + } + + break; + case 24: + case 27: + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + + break; + case 28: + if (src_p1 !== null) { + result_33557321 = src_p1.slice(0); + } + + break; + default: + result_33557321 = src_p1; + break; + } + + return result_33557321; + +} + +function arrayConstr(len_p0, value_p1, typ_p2) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; ++i) result[i] = nimCopy(null, value_p1, typ_p2); + return result; + + + +} + +function mnewString(len_p0) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; i++) {result[i] = 0;} + return result; + + + +} + +function addInt(a_p0, b_p1) { + var result = a_p0 + b_p1; + checkOverflowInt(result); + return result; + + + +} + +function chckRange(i_p0, a_p1, b_p2) { + var result_33557361 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557361 = i_p0; + break BeforeRet; + } + else { + raiseRangeError(); + } + + }; + + return result_33557361; + +} + +function chckIndx(i_p0, a_p1, b_p2) { + var result_33557356 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557356 = i_p0; + break BeforeRet; + } + else { + raiseIndexError(i_p0, a_p1, b_p2); + } + + }; + + return result_33557356; + +} + +function cstrToNimstr(c_p0) { + var ln = c_p0.length; + var result = new Array(ln); + var r = 0; + for (var i = 0; i < ln; ++i) { + var ch = c_p0.charCodeAt(i); + + if (ch < 128) { + result[r] = ch; + } + else { + if (ch < 2048) { + result[r] = (ch >> 6) | 192; + } + else { + if (ch < 55296 || ch >= 57344) { + result[r] = (ch >> 12) | 224; + } + else { + ++i; + ch = 65536 + (((ch & 1023) << 10) | (c_p0.charCodeAt(i) & 1023)); + result[r] = (ch >> 18) | 240; + ++r; + result[r] = ((ch >> 12) & 63) | 128; + } + ++r; + result[r] = ((ch >> 6) & 63) | 128; + } + ++r; + result[r] = (ch & 63) | 128; + } + ++r; + } + return result; + + + +} + +function toJSStr(s_p0) { + var result_33556910 = null; + + var res_33556964 = newSeq__system_u2507((s_p0).length); + var i_33556965 = 0; + var j_33556966 = 0; + Label1: { + Label2: while (true) { + if (!(i_33556965 < (s_p0).length)) break Label2; + var c_33556967 = s_p0[i_33556965]; + if ((c_33556967 < 128)) { + res_33556964[j_33556966] = String.fromCharCode(c_33556967); + i_33556965 += 1; + } + else { + var helper_33556993 = newSeq__system_u2507(0); + Label3: { + Label4: while (true) { + if (!true) break Label4; + var code_33556994 = c_33556967.toString(16); + if ((((code_33556994) == null ? 0 : (code_33556994).length) == 1)) { + helper_33556993.push("%0");; + } + else { + helper_33556993.push("%");; + } + + helper_33556993.push(code_33556994);; + i_33556965 += 1; + if ((((s_p0).length <= i_33556965) || (s_p0[i_33556965] < 128))) { + break Label3; + } + + c_33556967 = s_p0[i_33556965]; + } + }; +++excHandler; + try { + res_33556964[j_33556966] = decodeURIComponent(helper_33556993.join("")); +--excHandler; +} catch (EXCEPTION) { + var prevJSError = lastJSError; + lastJSError = EXCEPTION; + --excHandler; + res_33556964[j_33556966] = helper_33556993.join(""); + lastJSError = prevJSError; + } finally { + } + } + + j_33556966 += 1; + } + }; + if (res_33556964.length < j_33556966) { for (var i = res_33556964.length ; i < j_33556966 ; ++i) res_33556964.push(null); } + else { res_33556964.length = j_33556966; }; + result_33556910 = res_33556964.join(""); + + return result_33556910; + +} + +function raiseException(e_p0, ename_p1) { + e_p0.name = ename_p1; + if ((excHandler == 0)) { + unhandledException(e_p0); + } + + e_p0.trace = nimCopy(null, rawWriteStackTrace__system_u2180(), NTI33554449); + throw e_p0; + + +} + +function makeNimstrLit(c_p0) { + var result = []; + for (var i = 0; i < c_p0.length; ++i) { + result[i] = c_p0.charCodeAt(i); + } + return result; + + + +} + +function subInt(a_p0, b_p1) { + var result = a_p0 - b_p1; + checkOverflowInt(result); + return result; + + + +} + +function eqStrings(a_p0, b_p1) { + if (a_p0 == b_p1) return true; + if (a_p0 === null && b_p1.length == 0) return true; + if (b_p1 === null && a_p0.length == 0) return true; + if ((!a_p0) || (!b_p1)) return false; + var alen = a_p0.length; + if (alen != b_p1.length) return false; + for (var i = 0; i < alen; ++i) + if (a_p0[i] != b_p1[i]) return false; + return true; + + + +} +var F = {procname: "module jsre", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsre.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsre", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsre.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function contains__jsZjsre_u51(pattern_p0, self_p1) { + var result_671088694 = false; + + var F = {procname: "jsre.contains", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsre.nim", line: 0}; + framePtr = F; + F.line = 61; + F.filename = "jsre.nim"; + result_671088694 = self_p1.test(pattern_p0); + framePtr = F.prev; + + return result_671088694; + +} + +function isFatPointer__system_u2869(ti_p0) { + var result_33557303 = false; + + BeforeRet: { + result_33557303 = !((ConstSet1[ti_p0.base.kind] != undefined)); + break BeforeRet; + }; + + return result_33557303; + +} + +function nimCopyAux(dest_p0, src_p1, n_p2) { + switch (n_p2.kind) { + case 0: + break; + case 1: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + + break; + case 2: + for (var i = 0; i < n_p2.sons.length; i++) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i]); + } + + break; + case 3: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + for (var i = 0; i < n_p2.sons.length; ++i) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i][1]); + } + + break; + } + + +} + +function add__system_u1942(x_p0, x_p0_Idx, y_p1) { + if (x_p0[x_p0_Idx] === null) { x_p0[x_p0_Idx] = []; } + var off = x_p0[x_p0_Idx].length; + x_p0[x_p0_Idx].length += y_p1.length; + for (var i = 0; i < y_p1.length; ++i) { + x_p0[x_p0_Idx][off+i] = y_p1.charCodeAt(i); + } + + + +} + +function raiseOverflow() { + raiseException({message: [111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119], parent: null, m_type: NTI134217743, name: null, trace: [], up: null}, "OverflowDefect"); + + +} + +function checkOverflowInt(a_p0) { + if (a_p0 > 2147483647 || a_p0 < -2147483648) raiseOverflow(); + + + +} + +function raiseRangeError() { + raiseException({message: [118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101], parent: null, m_type: NTI134217751, name: null, trace: [], up: null}, "RangeDefect"); + + +} + +function raiseIndexError(i_p0, a_p1, b_p2) { + var Temporary1; + + if ((b_p2 < a_p1)) { + Temporary1 = [105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]; + } + else { + Temporary1 = ([105,110,100,101,120,32]).concat(HEX24__systemZdollars_u8(i_p0),[32,110,111,116,32,105,110,32],HEX24__systemZdollars_u8(a_p1),[32,46,46,32],HEX24__systemZdollars_u8(b_p2)); + } + + raiseException({message: nimCopy(null, Temporary1, NTI33554449), parent: null, m_type: NTI134217749, name: null, trace: [], up: null}, "IndexDefect"); + + +} + +function addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, start_p2, n_p3) { + var Temporary1; + + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 44; + F.filename = "digitsutils.nim"; + var old_301990096 = (result_p0[result_p0_Idx]).length; + F.line = 45; + if (result_p0[result_p0_Idx].length < (Temporary1 = chckRange(addInt(old_301990096, n_p3), 0, 2147483647), Temporary1)) { for (var i = result_p0[result_p0_Idx].length; i < Temporary1; ++i) result_p0[result_p0_Idx].push(0); } + else {result_p0[result_p0_Idx].length = Temporary1; }; + Label2: { + F.line = 47; + var iHEX60gensym4_301990110 = 0; + F.line = 128; + F.filename = "iterators_1.nim"; + var i_654311454 = 0; + Label3: { + F.line = 129; + Label4: while (true) { + if (!(i_654311454 < n_p3)) break Label4; + F.line = 50; + F.filename = "digitsutils.nim"; + iHEX60gensym4_301990110 = i_654311454; + F.line = 47; + result_p0[result_p0_Idx][chckIndx(addInt(old_301990096, iHEX60gensym4_301990110), 0, (result_p0[result_p0_Idx]).length - 1)] = x_p1.charCodeAt(chckIndx(addInt(start_p2, iHEX60gensym4_301990110), 0, (x_p1).length - 1)); + F.line = 131; + F.filename = "iterators_1.nim"; + i_654311454 = addInt(i_654311454, 1); + } + }; + }; + framePtr = F.prev; + + +} + +function addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 56; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, 0, ((x_p1) == null ? 0 : (x_p1).length)); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 112; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, ((x_p1) + "")); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u241(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 116; + F.filename = "digitsutils.nim"; + addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, BigInt(x_p1)); + framePtr = F.prev; + + +} + +function HEX24__systemZdollars_u8(x_p0) { + var result_369098762 = [[]]; + + var F = {procname: "dollars.$", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/dollars.nim", line: 0}; + framePtr = F; + F.line = 18; + F.filename = "dollars.nim"; + addInt__stdZprivateZdigitsutils_u241(result_369098762, 0, x_p0); + framePtr = F.prev; + + return result_369098762[0]; + +} + +function auxWriteStackTrace__system_u2084(f_p0) { + var result_33556518 = [[]]; + + var it_33556526 = f_p0; + var i_33556527 = 0; + var total_33556528 = 0; + var tempFrames_33556529 = arrayConstr(64, {Field0: null, Field1: 0, Field2: null}, NTI33555836); + Label1: { + Label2: while (true) { + if (!(!((it_33556526 == null)) && (i_33556527 <= 63))) break Label2; + tempFrames_33556529[i_33556527].Field0 = it_33556526.procname; + tempFrames_33556529[i_33556527].Field1 = it_33556526.line; + tempFrames_33556529[i_33556527].Field2 = it_33556526.filename; + i_33556527 += 1; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + Label3: { + Label4: while (true) { + if (!!((it_33556526 == null))) break Label4; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + result_33556518[0] = nimCopy(null, [], NTI33554449); + if (!((total_33556528 == i_33556527))) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + result_33556518[0].push.apply(result_33556518[0], HEX24__systemZdollars_u8((total_33556528 - i_33556527)));; + result_33556518[0].push.apply(result_33556518[0], [32,99,97,108,108,115,32,111,109,105,116,116,101,100,41,32,46,46,46,10]);; + } + + Label5: { + var j_33556562 = 0; + var colontmp__654311446 = 0; + colontmp__654311446 = (i_33556527 - 1); + var res_654311448 = colontmp__654311446; + Label6: { + Label7: while (true) { + if (!(0 <= res_654311448)) break Label7; + j_33556562 = res_654311448; + result_33556518[0].push.apply(result_33556518[0], cstrToNimstr(tempFrames_33556529[j_33556562].Field2));; + if ((0 < tempFrames_33556529[j_33556562].Field1)) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, tempFrames_33556529[j_33556562].Field1); + if (false) { + result_33556518[0].push.apply(result_33556518[0], [44,32]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, 0); + } + + result_33556518[0].push.apply(result_33556518[0], [41]);; + } + + result_33556518[0].push.apply(result_33556518[0], [32,97,116,32]);; + add__system_u1942(result_33556518, 0, tempFrames_33556529[j_33556562].Field0); + result_33556518[0].push.apply(result_33556518[0], [10]);; + res_654311448 -= 1; + } + }; + }; + + return result_33556518[0]; + +} + +function rawWriteStackTrace__system_u2180() { + var result_33556613 = []; + + if (!((framePtr == null))) { + result_33556613 = nimCopy(null, ([84,114,97,99,101,98,97,99,107,32,40,109,111,115,116,32,114,101,99,101,110,116,32,99,97,108,108,32,108,97,115,116,41,10]).concat(auxWriteStackTrace__system_u2084(framePtr)), NTI33554449); + } + else { + result_33556613 = nimCopy(null, [78,111,32,115,116,97,99,107,32,116,114,97,99,101,98,97,99,107,32,97,118,97,105,108,97,98,108,101,10], NTI33554449); + } + + + return result_33556613; + +} + +function newSeq__system_u2507(len_p0) { + var result_33556943 = []; + + var F = {procname: "newSeq.newSeq", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system.nim", line: 0}; + framePtr = F; + F.line = 653; + F.filename = "system.nim"; + result_33556943 = new Array(len_p0); for (var i = 0 ; i < len_p0 ; ++i) { result_33556943[i] = null; } framePtr = F.prev; + + return result_33556943; + +} + +function unhandledException(e_p0) { + var buf_33556658 = [[]]; + if (!(((e_p0.message).length == 0))) { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32]);; + buf_33556658[0].push.apply(buf_33556658[0], e_p0.message);; + } + else { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110]);; + } + + buf_33556658[0].push.apply(buf_33556658[0], [32,91]);; + add__system_u1942(buf_33556658, 0, e_p0.name); + buf_33556658[0].push.apply(buf_33556658[0], [93,10]);; + buf_33556658[0].push.apply(buf_33556658[0], rawWriteStackTrace__system_u2180());; + var cbuf_33556659 = toJSStr(buf_33556658[0]); + framePtr = null; + if (typeof(Error) !== "undefined") { + throw new Error(cbuf_33556659); + } + else { + throw cbuf_33556659; + } + + + +} + +function sysFatal__stdZassertions_u44(message_p1) { + var F = {procname: "sysFatal.sysFatal", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/fatal.nim", line: 0}; + framePtr = F; + F.line = 53; + F.filename = "fatal.nim"; + raiseException({message: nimCopy(null, message_p1, NTI33554449), m_type: NTI134217745, parent: null, name: null, trace: [], up: null}, "AssertionDefect"); + framePtr = F.prev; + + +} + +function raiseAssert__stdZassertions_u42(msg_p0) { + var F = {procname: "assertions.raiseAssert", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 36; + F.filename = "assertions.nim"; + sysFatal__stdZassertions_u44(msg_p0); + framePtr = F.prev; + + +} + +function failedAssertImpl__stdZassertions_u84(msg_p0) { + var F = {procname: "assertions.failedAssertImpl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 41; + F.filename = "assertions.nim"; + raiseAssert__stdZassertions_u42(msg_p0); + framePtr = F.prev; + + +} +var F = {procname: "module jsre_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_1.nim", line: 0}; +framePtr = F; +F.line = 56; +F.filename = "jsre.nim"; +var jsregex_654311427 = new RegExp("bc$", "i"); +if (!(contains__jsZjsre_u51("abc", jsregex_654311427))) { +F.line = 56; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_1.nim(10, 3) `jsregex in r\"abc\"` ")); +} + +if (!(!(contains__jsZjsre_u51("abcd", jsregex_654311427)))) { +F.line = 56; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_1.nim(11, 3) `jsregex notin r\"abcd\"` ")); +} + +if (!(contains__jsZjsre_u51("xabc", jsregex_654311427))) { +F.line = 56; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_1.nim(12, 3) `\"xabc\".contains jsregex` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsre_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_1.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function startsWith__jsZjsre_u55(pattern_p0, self_p1) { + var result_671088698 = false; + + var F = {procname: "jsre.startsWith", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsre.nim", line: 0}; + framePtr = F; + F.line = 64; + F.filename = "jsre.nim"; + result_671088698 = contains__jsZjsre_u51(pattern_p0, new RegExp(toJSStr(([94]).concat(cstrToNimstr(self_p1.source))), self_p1.flags)); + framePtr = F.prev; + + return result_671088698; + +} +var F = {procname: "module jsre_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_2.nim", line: 0}; +framePtr = F; +F.line = 65; +F.filename = "jsre.nim"; +var jsregex_687865859 = new RegExp("abc", "i"); +if (!(startsWith__jsZjsre_u55("abcd", jsregex_687865859))) { +F.line = 65; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_2.nim(10, 3) `\"abcd\".startsWith jsregex` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsre_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_2.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function endsWith__jsZjsre_u75(pattern_p0, self_p1) { + var result_671088718 = false; + + var F = {procname: "jsre.endsWith", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsre.nim", line: 0}; + framePtr = F; + F.line = 71; + F.filename = "jsre.nim"; + result_671088718 = contains__jsZjsre_u51(pattern_p0, new RegExp(toJSStr((cstrToNimstr(self_p1.source)).concat([36])), self_p1.flags)); + framePtr = F.prev; + + return result_671088718; + +} +var F = {procname: "module jsre_examples_3", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_3.nim", line: 0}; +framePtr = F; +F.line = 72; +F.filename = "jsre.nim"; +var jsregex_704643075 = new RegExp("bcd", "i"); +if (!(endsWith__jsZjsre_u75("abcd", jsregex_704643075))) { +F.line = 72; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_3.nim(10, 3) `\"abcd\".endsWith jsregex` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsre_examples_3", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_3.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function HEX3DHEX3D__jsre95examples954_u13(x_p0, y_p1) { + var result_721420305 = false; + + var F = {procname: "==.==", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/comparisons.nim", line: 0}; + framePtr = F; + BeforeRet: { + F.line = 326; + F.filename = "comparisons.nim"; + var sameObject_721420313 = false; + F.line = 327; + sameObject_721420313 = x_p0 === y_p1; + if (sameObject_721420313) { + F.line = 328; + result_721420305 = true; + break BeforeRet; + } + + if (!(((x_p0).length == (y_p1).length))) { + F.line = 331; + result_721420305 = false; + break BeforeRet; + } + + Label1: { + F.line = 333; + var i_721420327 = 0; + F.line = 81; + F.filename = "iterators_1.nim"; + var colontmp__721420466 = 0; + F.line = 333; + F.filename = "comparisons.nim"; + colontmp__721420466 = subInt((x_p0).length, 1); + F.line = 96; + F.filename = "iterators_1.nim"; + var res_721420468 = 0; + Label2: { + F.line = 97; + Label3: while (true) { + if (!(res_721420468 <= colontmp__721420466)) break Label3; + F.line = 333; + F.filename = "comparisons.nim"; + i_721420327 = res_721420468; + if (!((x_p0[chckIndx(i_721420327, 0, (x_p0).length - 1)] == y_p1[chckIndx(i_721420327, 0, (y_p1).length - 1)]))) { + F.line = 335; + result_721420305 = false; + break BeforeRet; + } + + F.line = 102; + F.filename = "iterators_1.nim"; + res_721420468 = addInt(res_721420468, 1); + } + }; + }; + F.line = 337; + F.filename = "comparisons.nim"; + result_721420305 = true; + break BeforeRet; + }; + framePtr = F.prev; + + return result_721420305; + +} + +function HEX24__jsZjsre_u48(self_p0) { + var result_671088690 = []; + + var F = {procname: "jsre.$", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsre.nim", line: 0}; + framePtr = F; + F.line = 52; + F.filename = "jsre.nim"; + result_671088690 = nimCopy(null, cstrToNimstr(self_p0.toString()), NTI33554449); + framePtr = F.prev; + + return result_671088690; + +} + var Temporary2; + +function HEX3Aanonymous__jsre95examples954_u88(m_p0) { + var result_721420378 = null; + + var F = {procname: "jsre_examples_4.:anonymous", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_4.nim", line: 0}; + framePtr = F; + F.line = 25; + F.filename = "jsre_examples_4.nim"; + result_721420378 = toJSStr((cstrToNimstr(m_p0[chckIndx(0, 0, (m_p0).length - 1)])).concat(HEX24__systemZdollars_u8((m_p0).length))); + framePtr = F.prev; + + return result_721420378; + +} +var F = {procname: "module jsre_examples_4", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_4.nim", line: 0}; +framePtr = F; +F.line = 78; +F.filename = "jsre.nim"; +var jsregex_721420291 = new RegExp("\\s+", "i"); +F.line = 78; +jsregex_721420291.compile("\\w+", "i"); +if (!(contains__jsZjsre_u51("nim javascript", jsregex_721420291))) { +F.line = 78; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_4.nim(11, 3) `\"nim javascript\".contains jsregex` ")); +} + +if (!(HEX3DHEX3D__jsre95examples954_u13((jsregex_721420291.exec("nim javascript") || []), ["nim"]))) { +F.line = 78; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_4.nim(12, 3) `jsregex.exec(r\"nim javascript\") == @[\"nim\".cstring]` ")); +} + +if (!((jsregex_721420291.toString() == "/\\w+/i"))) { +F.line = 78; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_4.nim(13, 3) `jsregex.toCstring() == r\"/\\w+/i\"` ")); +} + +F.line = 78; +jsregex_721420291.compile("[0-9]", "i"); +if (!(contains__jsZjsre_u51("0123456789abcd", jsregex_721420291))) { +F.line = 78; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_4.nim(15, 3) `\"0123456789abcd\".contains jsregex` ")); +} + +if (!(eqStrings(HEX24__jsZjsre_u48(jsregex_721420291), [47,91,48,45,57,93,47,105]))) { +F.line = 78; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_4.nim(16, 3) `$jsregex == \"/[0-9]/i\"` ")); +} + +F.line = 78; +jsregex_721420291.compile("abc", "i"); +if (!(startsWith__jsZjsre_u55("abcd", jsregex_721420291))) { +F.line = 78; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_4.nim(18, 3) `\"abcd\".startsWith jsregex` ")); +} + +if (!(endsWith__jsZjsre_u75("dabc", jsregex_721420291))) { +F.line = 78; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_4.nim(19, 3) `\"dabc\".endsWith jsregex` ")); +} + +F.line = 78; +jsregex_721420291.compile("\\d", "i"); +if (!(HEX3DHEX3D__jsre95examples954_u13(("do1ne".split(jsregex_721420291) || []), ["do", "ne"]))) { +F.line = 78; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_4.nim(21, 3) `\"do1ne\".split(jsregex) == @[\"do\".cstring, \"ne\".cstring]` ")); +} + +F.line = 78; +jsregex_721420291.compile("[lw]", "i"); +if (!(("hello world".replace(jsregex_721420291, "X") == "heXlo world"))) { +F.line = 78; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_4.nim(23, 3) `\"hello world\".replace(jsregex, \"X\") == \"heXlo world\"` ")); +} + +F.line = 78; +jsregex_721420291.compile("([a-z])\\1*", "g"); + Temporary2 = HEX3Aanonymous__jsre95examples954_u88.bind(null); Temporary2.ClP_0 = HEX3Aanonymous__jsre95examples954_u88; Temporary2.ClE_0 = null; +if (!(("abbcccdddd".replace(jsregex_721420291, Temporary2) == "a1b2c3d4"))) { +F.line = 78; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_4.nim(25, 3) `\"abbcccdddd\".replace(jsregex, proc (m: varargs[cstring]): cstring =\x0A ($m[0] & $(m.len)).cstring) ==\x0A \"a1b2c3d4\"` ")); +} + +F.line = 78; +var digitsRegex_721420388 = new RegExp("\\d"); +if (!(HEX3DHEX3D__jsre95examples954_u13(("foo".match(digitsRegex_721420388) || []), []))) { +F.line = 78; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_4.nim(27, 3) `\"foo\".match(digitsRegex) == @[]` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsre_examples_4", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_4.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsre_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsre_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; diff --git a/nimcache/runnableExamples/jsre_group0_examples.nim b/nimcache/runnableExamples/jsre_group0_examples.nim new file mode 100644 index 0000000000000..c08256acb3ad0 --- /dev/null +++ b/nimcache/runnableExamples/jsre_group0_examples.nim @@ -0,0 +1,7 @@ +# autogenerated by docgen +# source: /home/runner/work/Nim/Nim/lib/js/jsre.nim +# rdoccmd: +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_1.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_2.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_3.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsre_examples_4.nim" diff --git a/nimcache/runnableExamples/jsutils_examples_1.nim b/nimcache/runnableExamples/jsutils_examples_1.nim new file mode 100644 index 0000000000000..82a93f743ff0a --- /dev/null +++ b/nimcache/runnableExamples/jsutils_examples_1.nim @@ -0,0 +1,14 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/private/jsutils.nim(27, 5) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", 27, 5).}: + import std/[jsffi, jsbigints] + assert jsTypeOf(1.toJs) == "number" + assert jsTypeOf(false.toJs) == "boolean" + assert [1].toJs.jsTypeOf == "object" # note the difference with `getProtoName` + assert big"1".toJs.jsTypeOf == "bigint" + diff --git a/nimcache/runnableExamples/jsutils_examples_2.nim b/nimcache/runnableExamples/jsutils_examples_2.nim new file mode 100644 index 0000000000000..8556aec888fc8 --- /dev/null +++ b/nimcache/runnableExamples/jsutils_examples_2.nim @@ -0,0 +1,13 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/private/jsutils.nim(35, 5) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", 35, 5).}: + import std/jsffi + let a = array[2, float64].default + assert jsConstructorName(a) == "Float64Array" + assert jsConstructorName(a.toJs) == "Float64Array" + diff --git a/nimcache/runnableExamples/jsutils_examples_3.nim b/nimcache/runnableExamples/jsutils_examples_3.nim new file mode 100644 index 0000000000000..7637c27c6ea2e --- /dev/null +++ b/nimcache/runnableExamples/jsutils_examples_3.nim @@ -0,0 +1,19 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/private/jsutils.nim(49, 5) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", 49, 5).}: + import std/[jsffi, jsbigints] + type A = ref object + assert 1.toJs.getProtoName == "[object Number]" + assert "a".toJs.getProtoName == "[object String]" + assert big"1".toJs.getProtoName == "[object BigInt]" + assert false.toJs.getProtoName == "[object Boolean]" + assert (a: 1).toJs.getProtoName == "[object Object]" + assert A.default.toJs.getProtoName == "[object Null]" + assert [1].toJs.getProtoName == "[object Int32Array]" # implementation defined + assert @[1].toJs.getProtoName == "[object Array]" # ditto + diff --git a/nimcache/runnableExamples/jsutils_examples_4.nim b/nimcache/runnableExamples/jsutils_examples_4.nim new file mode 100644 index 0000000000000..2689c19683e44 --- /dev/null +++ b/nimcache/runnableExamples/jsutils_examples_4.nim @@ -0,0 +1,11 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/private/jsutils.nim(64, 3) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", 64, 3).}: + let a {.importjs: "Number.MAX_SAFE_INTEGER".}: int64 + assert a == maxSafeInteger + diff --git a/nimcache/runnableExamples/jsutils_examples_5.nim b/nimcache/runnableExamples/jsutils_examples_5.nim new file mode 100644 index 0000000000000..e1e9e5b159ac4 --- /dev/null +++ b/nimcache/runnableExamples/jsutils_examples_5.nim @@ -0,0 +1,14 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/private/jsutils.nim(69, 5) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", 69, 5).}: + import std/jsffi + assert 1.isInteger + assert not 1.5.isInteger + assert 1.toJs.isInteger + assert not 1.5.toJs.isInteger + diff --git a/nimcache/runnableExamples/jsutils_examples_6.nim b/nimcache/runnableExamples/jsutils_examples_6.nim new file mode 100644 index 0000000000000..9bc189cf1e82a --- /dev/null +++ b/nimcache/runnableExamples/jsutils_examples_6.nim @@ -0,0 +1,16 @@ +#[ +autogenerated by docgen +loc: /home/runner/work/Nim/Nim/lib/std/private/jsutils.nim(77, 5) +rdoccmd: +]# +import std/assertions +import "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim" +{.line: ("/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", 77, 5).}: + import std/jsffi + assert not "123".toJs.isSafeInteger + assert 123.isSafeInteger + assert 123.toJs.isSafeInteger + when false: + assert 9007199254740991.toJs.isSafeInteger + assert not 9007199254740992.toJs.isSafeInteger + diff --git a/nimcache/runnableExamples/jsutils_group0_examples.js b/nimcache/runnableExamples/jsutils_group0_examples.js new file mode 100644 index 0000000000000..f5b9daebb48e6 --- /dev/null +++ b/nimcache/runnableExamples/jsutils_group0_examples.js @@ -0,0 +1,947 @@ +/* Generated by the Nim Compiler v2.2.1 */ +var framePtr = null; +var excHandler = 0; +var lastJSError = null; +var NTI134217749 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217751 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217741 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217743 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554435 = {size: 0,kind: 31,base: null,node: null,finalizer: null}; +var NTI33555836 = {size: 0, kind: 18, base: null, node: null, finalizer: null}; +var NTI33555167 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555175 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33554450 = {size: 0,kind: 29,base: null,node: null,finalizer: null}; +var NTI33555174 = {size: 0, kind: 22, base: null, node: null, finalizer: null}; +var NTI33555171 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33555172 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI134217745 = {size: 0, kind: 17, base: null, node: null, finalizer: null}; +var NTI33554449 = {size: 0,kind: 28,base: null,node: null,finalizer: null}; +var NNI134217745 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217745.node = NNI134217745; +var NNI33555172 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555172.node = NNI33555172; +NTI33555174.base = NTI33555171; +NTI33555175.base = NTI33555171; +var NNI33555171 = {kind: 2, len: 5, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "parent", len: 0, typ: NTI33555174, name: "parent", sons: null}, +{kind: 1, offset: "name", len: 0, typ: NTI33554450, name: "name", sons: null}, +{kind: 1, offset: "message", len: 0, typ: NTI33554449, name: "msg", sons: null}, +{kind: 1, offset: "trace", len: 0, typ: NTI33554449, name: "trace", sons: null}, +{kind: 1, offset: "up", len: 0, typ: NTI33555175, name: "up", sons: null}]}; +NTI33555171.node = NNI33555171; +var NNI33555167 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI33555167.node = NNI33555167; +NTI33555171.base = NTI33555167; +NTI33555172.base = NTI33555171; +NTI134217745.base = NTI33555172; +var NNI33555836 = {kind: 2, len: 3, offset: 0, typ: null, name: null, sons: [{kind: 1, offset: "Field0", len: 0, typ: NTI33554450, name: "Field0", sons: null}, +{kind: 1, offset: "Field1", len: 0, typ: NTI33554435, name: "Field1", sons: null}, +{kind: 1, offset: "Field2", len: 0, typ: NTI33554450, name: "Field2", sons: null}]}; +NTI33555836.node = NNI33555836; +var NNI134217743 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217743.node = NNI134217743; +var NNI134217741 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217741.node = NNI134217741; +NTI134217741.base = NTI33555172; +NTI134217743.base = NTI134217741; +var NNI134217751 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217751.node = NNI134217751; +NTI134217751.base = NTI33555172; +var NNI134217749 = {kind: 2, len: 0, offset: 0, typ: null, name: null, sons: []}; +NTI134217749.node = NNI134217749; +NTI134217749.base = NTI33555172; + +function setConstr() { + var result = {}; + for (var i = 0; i < arguments.length; ++i) { + var x = arguments[i]; + if (typeof(x) == "object") { + for (var j = x[0]; j <= x[1]; ++j) { + result[j] = true; + } + } else { + result[x] = true; + } + } + return result; + + + +} +var ConstSet1 = setConstr(17, 16, 4, 18, 27, 19, 23, 22, 21); + +function nimCopy(dest_p0, src_p1, ti_p2) { + var result_33557321 = null; + + switch (ti_p2.kind) { + case 21: + case 22: + case 23: + case 5: + if (!(isFatPointer__system_u2869(ti_p2))) { + result_33557321 = src_p1; + } + else { + result_33557321 = [src_p1[0], src_p1[1]]; + } + + break; + case 19: + if (dest_p0 === null || dest_p0 === undefined) { + dest_p0 = {}; + } + else { + for (var key in dest_p0) { delete dest_p0[key]; } + } + for (var key in src_p1) { dest_p0[key] = src_p1[key]; } + result_33557321 = dest_p0; + + break; + case 18: + case 17: + if (!((ti_p2.base == null))) { + result_33557321 = nimCopy(dest_p0, src_p1, ti_p2.base); + } + else { + if ((ti_p2.kind == 17)) { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {m_type: ti_p2} : dest_p0; + } + else { + result_33557321 = (dest_p0 === null || dest_p0 === undefined) ? {} : dest_p0; + } + } + nimCopyAux(result_33557321, src_p1, ti_p2.node); + break; + case 4: + case 16: + if(ArrayBuffer.isView(src_p1)) { + if(dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new src_p1.constructor(src_p1); + } else { + dest_p0.set(src_p1, 0); + } + result_33557321 = dest_p0; + } else { + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + } + + break; + case 24: + case 27: + if (src_p1 === null) { + result_33557321 = null; + } + else { + if (dest_p0 === null || dest_p0 === undefined || dest_p0.length != src_p1.length) { + dest_p0 = new Array(src_p1.length); + } + result_33557321 = dest_p0; + for (var i = 0; i < src_p1.length; ++i) { + result_33557321[i] = nimCopy(result_33557321[i], src_p1[i], ti_p2.base); + } + } + + break; + case 28: + if (src_p1 !== null) { + result_33557321 = src_p1.slice(0); + } + + break; + default: + result_33557321 = src_p1; + break; + } + + return result_33557321; + +} + +function arrayConstr(len_p0, value_p1, typ_p2) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; ++i) result[i] = nimCopy(null, value_p1, typ_p2); + return result; + + + +} + +function mnewString(len_p0) { + var result = new Array(len_p0); + for (var i = 0; i < len_p0; i++) {result[i] = 0;} + return result; + + + +} + +function addInt(a_p0, b_p1) { + var result = a_p0 + b_p1; + checkOverflowInt(result); + return result; + + + +} + +function chckRange(i_p0, a_p1, b_p2) { + var result_33557361 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557361 = i_p0; + break BeforeRet; + } + else { + raiseRangeError(); + } + + }; + + return result_33557361; + +} + +function chckIndx(i_p0, a_p1, b_p2) { + var result_33557356 = 0; + + BeforeRet: { + if (((a_p1 <= i_p0) && (i_p0 <= b_p2))) { + result_33557356 = i_p0; + break BeforeRet; + } + else { + raiseIndexError(i_p0, a_p1, b_p2); + } + + }; + + return result_33557356; + +} + +function cstrToNimstr(c_p0) { + var ln = c_p0.length; + var result = new Array(ln); + var r = 0; + for (var i = 0; i < ln; ++i) { + var ch = c_p0.charCodeAt(i); + + if (ch < 128) { + result[r] = ch; + } + else { + if (ch < 2048) { + result[r] = (ch >> 6) | 192; + } + else { + if (ch < 55296 || ch >= 57344) { + result[r] = (ch >> 12) | 224; + } + else { + ++i; + ch = 65536 + (((ch & 1023) << 10) | (c_p0.charCodeAt(i) & 1023)); + result[r] = (ch >> 18) | 240; + ++r; + result[r] = ((ch >> 12) & 63) | 128; + } + ++r; + result[r] = ((ch >> 6) & 63) | 128; + } + ++r; + result[r] = (ch & 63) | 128; + } + ++r; + } + return result; + + + +} + +function toJSStr(s_p0) { + var result_33556910 = null; + + var res_33556964 = newSeq__system_u2507((s_p0).length); + var i_33556965 = 0; + var j_33556966 = 0; + Label1: { + Label2: while (true) { + if (!(i_33556965 < (s_p0).length)) break Label2; + var c_33556967 = s_p0[i_33556965]; + if ((c_33556967 < 128)) { + res_33556964[j_33556966] = String.fromCharCode(c_33556967); + i_33556965 += 1; + } + else { + var helper_33556993 = newSeq__system_u2507(0); + Label3: { + Label4: while (true) { + if (!true) break Label4; + var code_33556994 = c_33556967.toString(16); + if ((((code_33556994) == null ? 0 : (code_33556994).length) == 1)) { + helper_33556993.push("%0");; + } + else { + helper_33556993.push("%");; + } + + helper_33556993.push(code_33556994);; + i_33556965 += 1; + if ((((s_p0).length <= i_33556965) || (s_p0[i_33556965] < 128))) { + break Label3; + } + + c_33556967 = s_p0[i_33556965]; + } + }; +++excHandler; + try { + res_33556964[j_33556966] = decodeURIComponent(helper_33556993.join("")); +--excHandler; +} catch (EXCEPTION) { + var prevJSError = lastJSError; + lastJSError = EXCEPTION; + --excHandler; + res_33556964[j_33556966] = helper_33556993.join(""); + lastJSError = prevJSError; + } finally { + } + } + + j_33556966 += 1; + } + }; + if (res_33556964.length < j_33556966) { for (var i = res_33556964.length ; i < j_33556966 ; ++i) res_33556964.push(null); } + else { res_33556964.length = j_33556966; }; + result_33556910 = res_33556964.join(""); + + return result_33556910; + +} + +function raiseException(e_p0, ename_p1) { + e_p0.name = ename_p1; + if ((excHandler == 0)) { + unhandledException(e_p0); + } + + e_p0.trace = nimCopy(null, rawWriteStackTrace__system_u2180(), NTI33554449); + throw e_p0; + + +} + +function makeNimstrLit(c_p0) { + var result = []; + for (var i = 0; i < c_p0.length; ++i) { + result[i] = c_p0.charCodeAt(i); + } + return result; + + + +} +var F = {procname: "module jsbigints", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsbigints", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/jsbigints.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module macros", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/core/macros.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module macros", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/core/macros.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module hashes", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/hashes.nim", line: 0}; +framePtr = F; +F.line = 218; +F.filename = "hashes.nim"; +var objectID_754974898 = [0]; +framePtr = F.prev; +var F = {procname: "module hashes", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/hashes.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops_utils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/bitops_utils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops_utils", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/bitops_utils.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module countbits_impl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/countbits_impl.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module countbits_impl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/countbits_impl.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/bitops.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module bitops", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/bitops.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module fenv", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/fenv.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module fenv", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/fenv.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module math", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/math.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module math", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/math.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module algorithm", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/algorithm.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module algorithm", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/algorithm.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module outparams", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/outparams.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module outparams", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/outparams.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module tables", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/collections/tables.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module tables", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/pure/collections/tables.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsffi", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsffi.nim", line: 0}; +framePtr = F; +F.line = 45; +F.filename = "jsffi.nim"; +F.line = 46; +framePtr = F.prev; +var F = {procname: "module jsffi", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/js/jsffi.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function isFatPointer__system_u2869(ti_p0) { + var result_33557303 = false; + + BeforeRet: { + result_33557303 = !((ConstSet1[ti_p0.base.kind] != undefined)); + break BeforeRet; + }; + + return result_33557303; + +} + +function nimCopyAux(dest_p0, src_p1, n_p2) { + switch (n_p2.kind) { + case 0: + break; + case 1: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + + break; + case 2: + for (var i = 0; i < n_p2.sons.length; i++) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i]); + } + + break; + case 3: + dest_p0[n_p2.offset] = nimCopy(dest_p0[n_p2.offset], src_p1[n_p2.offset], n_p2.typ); + for (var i = 0; i < n_p2.sons.length; ++i) { + nimCopyAux(dest_p0, src_p1, n_p2.sons[i][1]); + } + + break; + } + + +} + +function add__system_u1942(x_p0, x_p0_Idx, y_p1) { + if (x_p0[x_p0_Idx] === null) { x_p0[x_p0_Idx] = []; } + var off = x_p0[x_p0_Idx].length; + x_p0[x_p0_Idx].length += y_p1.length; + for (var i = 0; i < y_p1.length; ++i) { + x_p0[x_p0_Idx][off+i] = y_p1.charCodeAt(i); + } + + + +} + +function raiseOverflow() { + raiseException({message: [111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119], parent: null, m_type: NTI134217743, name: null, trace: [], up: null}, "OverflowDefect"); + + +} + +function checkOverflowInt(a_p0) { + if (a_p0 > 2147483647 || a_p0 < -2147483648) raiseOverflow(); + + + +} + +function raiseRangeError() { + raiseException({message: [118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101], parent: null, m_type: NTI134217751, name: null, trace: [], up: null}, "RangeDefect"); + + +} + +function raiseIndexError(i_p0, a_p1, b_p2) { + var Temporary1; + + if ((b_p2 < a_p1)) { + Temporary1 = [105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]; + } + else { + Temporary1 = ([105,110,100,101,120,32]).concat(HEX24__systemZdollars_u8(i_p0),[32,110,111,116,32,105,110,32],HEX24__systemZdollars_u8(a_p1),[32,46,46,32],HEX24__systemZdollars_u8(b_p2)); + } + + raiseException({message: nimCopy(null, Temporary1, NTI33554449), parent: null, m_type: NTI134217749, name: null, trace: [], up: null}, "IndexDefect"); + + +} + +function addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, start_p2, n_p3) { + var Temporary1; + + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 44; + F.filename = "digitsutils.nim"; + var old_301990096 = (result_p0[result_p0_Idx]).length; + F.line = 45; + if (result_p0[result_p0_Idx].length < (Temporary1 = chckRange(addInt(old_301990096, n_p3), 0, 2147483647), Temporary1)) { for (var i = result_p0[result_p0_Idx].length; i < Temporary1; ++i) result_p0[result_p0_Idx].push(0); } + else {result_p0[result_p0_Idx].length = Temporary1; }; + Label2: { + F.line = 47; + var iHEX60gensym4_301990110 = 0; + F.line = 128; + F.filename = "iterators_1.nim"; + var i_654311488 = 0; + Label3: { + F.line = 129; + Label4: while (true) { + if (!(i_654311488 < n_p3)) break Label4; + F.line = 50; + F.filename = "digitsutils.nim"; + iHEX60gensym4_301990110 = i_654311488; + F.line = 47; + result_p0[result_p0_Idx][chckIndx(addInt(old_301990096, iHEX60gensym4_301990110), 0, (result_p0[result_p0_Idx]).length - 1)] = x_p1.charCodeAt(chckIndx(addInt(start_p2, iHEX60gensym4_301990110), 0, (x_p1).length - 1)); + F.line = 131; + F.filename = "iterators_1.nim"; + i_654311488 = addInt(i_654311488, 1); + } + }; + }; + framePtr = F.prev; + + +} + +function addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "addChars.addChars", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 56; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u202(result_p0, result_p0_Idx, x_p1, 0, ((x_p1) == null ? 0 : (x_p1).length)); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 112; + F.filename = "digitsutils.nim"; + addChars__stdZprivateZdigitsutils_u198(result_p0, result_p0_Idx, ((x_p1) + "")); + framePtr = F.prev; + + +} + +function addInt__stdZprivateZdigitsutils_u241(result_p0, result_p0_Idx, x_p1) { + var F = {procname: "digitsutils.addInt", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/digitsutils.nim", line: 0}; + framePtr = F; + F.line = 116; + F.filename = "digitsutils.nim"; + addInt__stdZprivateZdigitsutils_u223(result_p0, result_p0_Idx, BigInt(x_p1)); + framePtr = F.prev; + + +} + +function HEX24__systemZdollars_u8(x_p0) { + var result_369098762 = [[]]; + + var F = {procname: "dollars.$", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/dollars.nim", line: 0}; + framePtr = F; + F.line = 18; + F.filename = "dollars.nim"; + addInt__stdZprivateZdigitsutils_u241(result_369098762, 0, x_p0); + framePtr = F.prev; + + return result_369098762[0]; + +} + +function auxWriteStackTrace__system_u2084(f_p0) { + var result_33556518 = [[]]; + + var it_33556526 = f_p0; + var i_33556527 = 0; + var total_33556528 = 0; + var tempFrames_33556529 = arrayConstr(64, {Field0: null, Field1: 0, Field2: null}, NTI33555836); + Label1: { + Label2: while (true) { + if (!(!((it_33556526 == null)) && (i_33556527 <= 63))) break Label2; + tempFrames_33556529[i_33556527].Field0 = it_33556526.procname; + tempFrames_33556529[i_33556527].Field1 = it_33556526.line; + tempFrames_33556529[i_33556527].Field2 = it_33556526.filename; + i_33556527 += 1; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + Label3: { + Label4: while (true) { + if (!!((it_33556526 == null))) break Label4; + total_33556528 += 1; + it_33556526 = it_33556526.prev; + } + }; + result_33556518[0] = nimCopy(null, [], NTI33554449); + if (!((total_33556528 == i_33556527))) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + result_33556518[0].push.apply(result_33556518[0], HEX24__systemZdollars_u8((total_33556528 - i_33556527)));; + result_33556518[0].push.apply(result_33556518[0], [32,99,97,108,108,115,32,111,109,105,116,116,101,100,41,32,46,46,46,10]);; + } + + Label5: { + var j_33556562 = 0; + var colontmp__654311480 = 0; + colontmp__654311480 = (i_33556527 - 1); + var res_654311482 = colontmp__654311480; + Label6: { + Label7: while (true) { + if (!(0 <= res_654311482)) break Label7; + j_33556562 = res_654311482; + result_33556518[0].push.apply(result_33556518[0], cstrToNimstr(tempFrames_33556529[j_33556562].Field2));; + if ((0 < tempFrames_33556529[j_33556562].Field1)) { + result_33556518[0].push.apply(result_33556518[0], [40]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, tempFrames_33556529[j_33556562].Field1); + if (false) { + result_33556518[0].push.apply(result_33556518[0], [44,32]);; + addInt__stdZprivateZdigitsutils_u241(result_33556518, 0, 0); + } + + result_33556518[0].push.apply(result_33556518[0], [41]);; + } + + result_33556518[0].push.apply(result_33556518[0], [32,97,116,32]);; + add__system_u1942(result_33556518, 0, tempFrames_33556529[j_33556562].Field0); + result_33556518[0].push.apply(result_33556518[0], [10]);; + res_654311482 -= 1; + } + }; + }; + + return result_33556518[0]; + +} + +function rawWriteStackTrace__system_u2180() { + var result_33556613 = []; + + if (!((framePtr == null))) { + result_33556613 = nimCopy(null, ([84,114,97,99,101,98,97,99,107,32,40,109,111,115,116,32,114,101,99,101,110,116,32,99,97,108,108,32,108,97,115,116,41,10]).concat(auxWriteStackTrace__system_u2084(framePtr)), NTI33554449); + } + else { + result_33556613 = nimCopy(null, [78,111,32,115,116,97,99,107,32,116,114,97,99,101,98,97,99,107,32,97,118,97,105,108,97,98,108,101,10], NTI33554449); + } + + + return result_33556613; + +} + +function newSeq__system_u2507(len_p0) { + var result_33556943 = []; + + var F = {procname: "newSeq.newSeq", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system.nim", line: 0}; + framePtr = F; + F.line = 653; + F.filename = "system.nim"; + result_33556943 = new Array(len_p0); for (var i = 0 ; i < len_p0 ; ++i) { result_33556943[i] = null; } framePtr = F.prev; + + return result_33556943; + +} + +function unhandledException(e_p0) { + var buf_33556658 = [[]]; + if (!(((e_p0.message).length == 0))) { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32]);; + buf_33556658[0].push.apply(buf_33556658[0], e_p0.message);; + } + else { + buf_33556658[0].push.apply(buf_33556658[0], [69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110]);; + } + + buf_33556658[0].push.apply(buf_33556658[0], [32,91]);; + add__system_u1942(buf_33556658, 0, e_p0.name); + buf_33556658[0].push.apply(buf_33556658[0], [93,10]);; + buf_33556658[0].push.apply(buf_33556658[0], rawWriteStackTrace__system_u2180());; + var cbuf_33556659 = toJSStr(buf_33556658[0]); + framePtr = null; + if (typeof(Error) !== "undefined") { + throw new Error(cbuf_33556659); + } + else { + throw cbuf_33556659; + } + + + +} + +function sysFatal__stdZassertions_u44(message_p1) { + var F = {procname: "sysFatal.sysFatal", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/system/fatal.nim", line: 0}; + framePtr = F; + F.line = 53; + F.filename = "fatal.nim"; + raiseException({message: nimCopy(null, message_p1, NTI33554449), m_type: NTI134217745, parent: null, name: null, trace: [], up: null}, "AssertionDefect"); + framePtr = F.prev; + + +} + +function raiseAssert__stdZassertions_u42(msg_p0) { + var F = {procname: "assertions.raiseAssert", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 36; + F.filename = "assertions.nim"; + sysFatal__stdZassertions_u44(msg_p0); + framePtr = F.prev; + + +} + +function failedAssertImpl__stdZassertions_u84(msg_p0) { + var F = {procname: "assertions.failedAssertImpl", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/assertions.nim", line: 0}; + framePtr = F; + F.line = 41; + F.filename = "assertions.nim"; + raiseAssert__stdZassertions_u42(msg_p0); + framePtr = F.prev; + + +} +var F = {procname: "module jsutils_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_1.nim", line: 0}; +framePtr = F; +if (!((typeof((1)) == "number"))) { +F.line = 27; +F.filename = "jsutils.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_1.nim(10, 3) `jsTypeOf(1.toJs) == \"number\"` ")); +} + +if (!((typeof((false)) == "boolean"))) { +F.line = 27; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_1.nim(11, 3) `jsTypeOf(false.toJs) == \"boolean\"` ")); +} + +if (!((typeof((new Int32Array([1]))) == "object"))) { +F.line = 27; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_1.nim(12, 3) `[1].toJs.jsTypeOf == \"object\"` ")); +} + +if (!((typeof((BigInt("1"))) == "bigint"))) { +F.line = 27; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_1.nim(13, 3) `big\"1\".toJs.jsTypeOf == \"bigint\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsutils_examples_1", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_1.nim", line: 0}; +framePtr = F; +framePtr = F.prev; + +function jsConstructorName__jsutils95examples952_u10(a_p0) { + var result_922746893 = null; + + var F = {procname: "jsConstructorName.jsConstructorName", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", line: 0}; + framePtr = F; + F.line = 40; + F.filename = "jsutils.nim"; + result_922746893 = a_p0.constructor.name; + framePtr = F.prev; + + return result_922746893; + +} + +function jsConstructorName__jsutils95examples952_u22(a_p0) { + var result_922746905 = null; + + var F = {procname: "jsConstructorName.jsConstructorName", prev: framePtr, filename: "/home/runner/work/Nim/Nim/lib/std/private/jsutils.nim", line: 0}; + framePtr = F; + F.line = 40; + F.filename = "jsutils.nim"; + result_922746905 = a_p0.constructor.name; + framePtr = F.prev; + + return result_922746905; + +} +var F = {procname: "module jsutils_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_2.nim", line: 0}; +framePtr = F; +F.line = 35; +F.filename = "jsutils.nim"; +var a_922746889 = new Float64Array(2); +if (!((jsConstructorName__jsutils95examples952_u10(a_922746889) == "Float64Array"))) { +F.line = 35; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_2.nim(11, 3) `jsConstructorName(a) == \"Float64Array\"` ")); +} + +if (!((jsConstructorName__jsutils95examples952_u22((a_922746889)) == "Float64Array"))) { +F.line = 35; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_2.nim(12, 3) `jsConstructorName(a.toJs) == \"Float64Array\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsutils_examples_2", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_2.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils_examples_3", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_3.nim", line: 0}; +framePtr = F; +if (!((Object.prototype.toString.call((1)) == "[object Number]"))) { +F.line = 49; +F.filename = "jsutils.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_3.nim(11, 3) `1.toJs.getProtoName == \"[object Number]\"` ")); +} + +if (!((Object.prototype.toString.call(("a")) == "[object String]"))) { +F.line = 49; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_3.nim(12, 3) `\"a\".toJs.getProtoName == \"[object String]\"` ")); +} + +if (!((Object.prototype.toString.call((BigInt("1"))) == "[object BigInt]"))) { +F.line = 49; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_3.nim(13, 3) `big\"1\".toJs.getProtoName == \"[object BigInt]\"` ")); +} + +if (!((Object.prototype.toString.call((false)) == "[object Boolean]"))) { +F.line = 49; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_3.nim(14, 3) `false.toJs.getProtoName == \"[object Boolean]\"` ")); +} + +if (!((Object.prototype.toString.call(({Field0: 1})) == "[object Object]"))) { +F.line = 49; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_3.nim(15, 3) `(a: 1).toJs.getProtoName == \"[object Object]\"` ")); +} + +if (!((Object.prototype.toString.call((null)) == "[object Null]"))) { +F.line = 49; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_3.nim(16, 3) `A.default.toJs.getProtoName == \"[object Null]\"` ")); +} + +if (!((Object.prototype.toString.call((new Int32Array([1]))) == "[object Int32Array]"))) { +F.line = 49; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_3.nim(17, 3) `[1].toJs.getProtoName == \"[object Int32Array]\"` ")); +} + +if (!((Object.prototype.toString.call(([1])) == "[object Array]"))) { +F.line = 49; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_3.nim(18, 3) `@[1].toJs.getProtoName == \"[object Array]\"` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsutils_examples_3", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_3.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils_examples_4", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_4.nim", line: 0}; +framePtr = F; +if (!((Number.MAX_SAFE_INTEGER == 9007199254740991n))) { +F.line = 64; +F.filename = "jsutils.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_4.nim(10, 3) `a == maxSafeInteger` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsutils_examples_4", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_4.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils_examples_5", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_5.nim", line: 0}; +framePtr = F; +if (!(Number.isInteger(1))) { +F.line = 69; +F.filename = "jsutils.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_5.nim(10, 3) `1.isInteger` ")); +} + +if (!(!(Number.isInteger(1.5)))) { +F.line = 69; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_5.nim(11, 3) `not 1.5.isInteger` ")); +} + +if (!(Number.isInteger((1)))) { +F.line = 69; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_5.nim(12, 3) `1.toJs.isInteger` ")); +} + +if (!(!(Number.isInteger((1.5))))) { +F.line = 69; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_5.nim(13, 3) `not 1.5.toJs.isInteger` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsutils_examples_5", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_5.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils_examples_6", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_6.nim", line: 0}; +framePtr = F; +if (!(!(Number.isSafeInteger(("123"))))) { +F.line = 77; +F.filename = "jsutils.nim"; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_6.nim(10, 3) `not \"123\".toJs.isSafeInteger` ")); +} + +if (!(Number.isSafeInteger(123))) { +F.line = 77; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_6.nim(11, 3) `123.isSafeInteger` ")); +} + +if (!(Number.isSafeInteger((123)))) { +F.line = 77; +failedAssertImpl__stdZassertions_u84(makeNimstrLit("/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_6.nim(12, 3) `123.toJs.isSafeInteger` ")); +} + +framePtr = F.prev; +var F = {procname: "module jsutils_examples_6", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_6.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; +var F = {procname: "module jsutils_group0_examples", prev: framePtr, filename: "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_group0_examples.nim", line: 0}; +framePtr = F; +framePtr = F.prev; diff --git a/nimcache/runnableExamples/jsutils_group0_examples.nim b/nimcache/runnableExamples/jsutils_group0_examples.nim new file mode 100644 index 0000000000000..0d986c2ec642a --- /dev/null +++ b/nimcache/runnableExamples/jsutils_group0_examples.nim @@ -0,0 +1,9 @@ +# autogenerated by docgen +# source: /home/runner/work/Nim/Nim/lib/std/private/jsutils.nim +# rdoccmd: +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_1.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_2.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_3.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_4.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_5.nim" +import "/home/runner/work/Nim/Nim/doc/html/nimcache/runnableExamples/jsutils_examples_6.nim" diff --git a/nimdoc.out.css b/nimdoc.out.css new file mode 100644 index 0000000000000..0c399e4c19193 --- /dev/null +++ b/nimdoc.out.css @@ -0,0 +1,1036 @@ +/* +Stylesheet for use with Docutils/rst2html. + +See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to +customize this style sheet. + +Modified from Chad Skeeters' rst2html-style +https://bitbucket.org/cskeeters/rst2html-style/ + +Modified by Boyd Greenfield and narimiran +*/ + +:root { + --primary-background: #fff; + --secondary-background: ghostwhite; + --third-background: #e8e8e8; + --info-background: #50c050; + --warning-background: #c0a000; + --error-background: #e04040; + --border: #dde; + --text: #222; + --anchor: #07b; + --anchor-focus: #607c9f; + --input-focus: #1fa0eb; + --strong: #3c3c3c; + --hint: #9A9A9A; + --nim-sprite-base64: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAN4AAAA9CAYAAADCt9ebAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFFmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxNDggNzkuMTY0MDM2LCAyMDE5LzA4LzEzLTAxOjA2OjU3ICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgeG1sbnM6cGhvdG9zaG9wPSJodHRwOi8vbnMuYWRvYmUuY29tL3Bob3Rvc2hvcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RFdnQ9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZUV2ZW50IyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgMjEuMCAoV2luZG93cykiIHhtcDpDcmVhdGVEYXRlPSIyMDE5LTEyLTAzVDAxOjAzOjQ4KzAxOjAwIiB4bXA6TW9kaWZ5RGF0ZT0iMjAxOS0xMi0wM1QwMjoyODo0MSswMTowMCIgeG1wOk1ldGFkYXRhRGF0ZT0iMjAxOS0xMi0wM1QwMjoyODo0MSswMTowMCIgZGM6Zm9ybWF0PSJpbWFnZS9wbmciIHBob3Rvc2hvcDpDb2xvck1vZGU9IjMiIHBob3Rvc2hvcDpJQ0NQcm9maWxlPSJzUkdCIElFQzYxOTY2LTIuMSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDozMzM0ZjAxYS0yMDExLWE1NGQtOTVjNy1iOTgxMDFlMDFhMmEiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MzMzNGYwMWEtMjAxMS1hNTRkLTk1YzctYjk4MTAxZTAxYTJhIiB4bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ9InhtcC5kaWQ6MzMzNGYwMWEtMjAxMS1hNTRkLTk1YzctYjk4MTAxZTAxYTJhIj4gPHhtcE1NOkhpc3Rvcnk+IDxyZGY6U2VxPiA8cmRmOmxpIHN0RXZ0OmFjdGlvbj0iY3JlYXRlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDozMzM0ZjAxYS0yMDExLWE1NGQtOTVjNy1iOTgxMDFlMDFhMmEiIHN0RXZ0OndoZW49IjIwMTktMTItMDNUMDE6MDM6NDgrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyMS4wIChXaW5kb3dzKSIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4PsixkAAAJ5klEQVR4nO2dfbBUZR3HP3vvxVD0zo0ACXxBuQMoQjJ1DfMl0NIhNcuSZqQhfGt6UWtK06xJexkrmywVRTQlHCIdtclC0zBJvYIvvEUgZpc3XyC7RVbKlQu1/fHdbc+uu2fPOfs85+y55/nMnBl2z+5zfnc5v/M8z+8119XVRYroAG4HfgvMT1YUR4MMAa4HLkhakCRoSVqAELwLeBY4C7gF+D6QS1QiR1ROAJ4Dzk9akKQwoXhtwL4GxvHjU8AKoNPz3leAu4HBFq+bAyZZHD9rDAK+BywDDklYlkQxoXhfAtYAEw2MVckQYBHwU6or99nA08BBFq49GngUeBIYaWH8rNEJdAOXA60Jy5I4jSreSOBKYDzwBPCJhiUqcSjwe2BWnc9NLnxuvMFrnwqsAqYBBwBfNzh2FpmNfs9jkhakWcg1aFxZiH5UL3cDnwf+Xue7BwFjgFHAOwuv24tyob3cO0LIshP4EbCn8Pq/wKvA9sLxMvCvOmPsA1yDZnHv/nEv2mM+F0IeR4m8z7lM7tMbUbzj0CxX7YfbAXwaWFJ4PRrNIu9FS9KJyEIZN68CG4DnkRJtLBw7gHHAYuDdNb77EDAjBhkHIk7xKoiqeK3IwjilzuceQJvoZjdQ/AMZaeoZiWYgBXSEwyleBW0Rv3cR9ZUO4LSI48fN2wN+bi5wJNBvUZaBSCaVy48oxpVhwDdMC5ISxpJRh6/DLGEUrxXt29YBQ+2IkwquR76ofZIWxJFegireNLSnm48skFmmDfmiVgJHJyuKI620ADOpbWEcDPwYOZKD7OmyxCTkXL+wzueOiEEWR8poQb60V4A7kLm/yFjgKeALuM1xLfYDbkX+zEGe98cAX0Oui6viF8vR7OS6urragW2UZr21wK+Aiwlu7XPoN3sYOAd4H6WH1SnA0qSEcjQnRT/e1bgnsw16kGPez4/lyCBF48oNwL+TFGSAsgCndI4qFBVvJ0owdZhjL3CnxfHzBo8+YBMyol0CHBijrKbHS/LoA7Yio9sPgJNr/QHekLGR6MffL+KP4SjnHmQxtoXNmbQP+CHyV75hYDzTIWNpWkU8iR5mq71vVsZqXgtcFqNQ/wG2IOtfD8oi6AX+Ujj+isKz8sBrnu+1okyGdmD/wnEgcDClTIdRyJRvI1cvCMciq7At4rj5eoCPAusbHCfLigda/VyKgi+AtyreMGAzykGzQQ/wO+BxSlkCuy1dq8hw5OieUjimYT+x9bHCdWwS1823Ez1EXmhgjKwrXpHzkduuanbCtzGX+NkPPAj8GincNkPjNkIO5dadUjiOB95m+BonopQpm8R58/0JJbHWy2eshVM8sRvdbyurKV4Hmoka2WA/iwwLP6d+QmzSdKC92GzK/W9R+Q3woQbHCELcN991wJcjftcpXolngKm18vFmoVonYcgDv0Qz5pqGREuOTuA8lPYUZbndh0LJNpkUqgZx33xvomim7RG+6xSvnOm1gqQXoyiMoKxFs8VZpFfpQHvQK4HDUPnAsBa9bxGP0tUjF+IYCkxFew+/G3owdq20pgjzt3uPRscs/o43IaOhH2f4ZaAPRyZQP6vgbuCbyGext87F0sgIZFI/N8BnlwBnolovcWAjq/uzwM0+55cBJ0UYN84ZL+rfbnLMM4FfUDv7Z1XlCe8FetETbleNL7+CZrnvMjCVDuTOOA84Hf+96ga0PC8qXY50FQsuMg+41+d8p885R4n7gdt8zo+qvDkmUF4fZQXwEbS+99KDMhlWkw0eALqQglXyDDCdcovf+4lv5jPNXJ9zWc/FDMMdPudGVCreRlTWwVtWbynwYVQQCFSp61Q042WJLUjB1nneuw8tvXo97x1Lugvg+j1Mo9boySLVHtJFWqsthx5GlbSGeN5bigrHdqPl52Zj4qWLXvTQWY4KOX2ccgPMBLRcuy9+0YzhguXN4GuYq2Zc2R/NZg+hfYt3/9ZCepdQthmB4vIWIYOTbWyWzGt2Y0izG1fqjlltxnsdpbPMRMmd3lqTTumqMw7FZY5G5mSHw5dalreiRWYGWjbZ7gYUlFa0xOtIWA4vk1E6zWEoI+FvyYrjSAO1FG8DCmQGKd+DJFsGogWVVFiP/GWbga9Svg9NgtPQvnd04fUNCcriSBF+vqZ5nn9PQ+Xs4q401oI6EP0R+BkyXoAeAtcgBfwidnvkVaMVFTO6n1JoWTfqiONw1MVP8e6l3GVwOPJZXW5VItGGiuduAu5CZdOrMQJ1CHqpIFccS+LxaD/3Hcr7vF0Xw7UdAwQ/xduLGkJ6aUMhVAuwU006B3wM+ZLmozJ5QRhWkGs9yjKw1fhwDsq8eE/F+y+i1CeHIxD1wppupXrA5xyUOjQHMzU3cyjTeS2aaaN2Fzoc1bhch3xspuqBTkDulQVUz1q4mYEbNuewQD3FexGFS1VjOLoRHwOOinj9HAooXY2CSidHHKeSI5GFcRWNdSxqR7VH1iHHeTV24R+X53C8hSCBvPPqnD8B+AOygn6OYAm0ORSGthLl8B0d4DtRmIKsoMsJF1U/Hi1dt6DusIN8PrsIlUdwOAITpDFlC6q3MTbgmHm011qGepOvQSXPipyOCujW6rxqk0dRWYsVFe8PRSn5JxWOoEvdfOGzfnF5tnCRK+bGi33MoB1hL0U5d1H5J5oVD6A5mp8sQS6KSWh5e0jEcR4BPmhKqJA4xTM3XuxjBlW8DuRacDU3y0myNbNTPHPjxT5m0GTN15A/zVFiI+HKYzgc/ydMlrRfgmQWuYn0F91xJEQYxVuDnMcOrQAWJi2EI72ErQviwqLEQpQ+5XBEIqzi3YWLwF+BMiMcjshEqYR1Gdk1KmxBsaR9SQviSDdRFK8fxVU+YliWZmcbcq7vSFoQR/qJWvuxD0WgLDYoSzPzAqowtjVhORwDhEaKru4GPoliGgcyy4Hj0DLT4TBCo9WO88jQ8Bns97lLghvRTOfqqDiMYqrM+HyUYdBtaLykeRmlK12C9rQOh1FM1vd/HqUIzaT5e+LVoh/VxByHShs6HFaw0VjjHhTxP5d0LT+fRnu5q3HuAodlbHW02Q5cDByM+sw1642cRylCx6PeZiuTFScUFxK+f19QovaRS+t4tsasxhvABbZbSfUCV6CM7qtQl6Fm4E1U22UqcAYqvZ42fgJMxH6vdYc5nkBlSW6Pq4fbS6hb6jg0u9yGug7FyS5U1+UcVBbwbFSuMM1sQ1bXK4A9CcviqM0e9H80HdUxCpwIa4McygA/GfgAcCJqmGKKXUixupEv7nHsLc2agWNQ0d9OzC+PHNHIo1XeLCoe8kkqXiUtwKFoWXoEKqk3BpWLaC8cXsV8HT1J+tFTZKvn+DMqFZi1knvtyKg1O2lBHADcCVxEedNSAP4HJcsr0NNWHVUAAAAASUVORK5CYII="); + + --keyword: #5e8f60; + --identifier: #222; + --comment: #484a86; + --operator: #155da4; + --punctuation: black; + --other: black; + --escapeSequence: #c4891b; + --number: #252dbe; + --literal: #a4255b; + --program: #6060c0; + --option: #508000; + --raw-data: #a4255b; + + --clipboard-image-normal: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='color: black' fill='none' viewBox='0 0 24 24' stroke='currentColor'%3E %3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2' /%3E %3C/svg%3E"); + --clipboard-image-selected: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='color: black' viewBox='0 0 20 20' fill='currentColor'%3E %3Cpath d='M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z' /%3E %3Cpath d='M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z' /%3E %3C/svg%3E"); + --clipboard-image: var(--clipboard-image-normal) +} + +[data-theme="dark"] { + --primary-background: #171921; + --secondary-background: #1e202a; + --third-background: #2b2e3b; + --info-background: #008000; + --warning-background: #807000; + --error-background: #c03000; + --border: #0e1014; + --text: #fff; + --anchor: #8be9fd; + --anchor-focus: #8be9fd; + --input-focus: #8be9fd; + --strong: #bd93f9; + --hint: #7A7C85; + --nim-sprite-base64: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAARMAAABMCAYAAABOBlMuAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFFmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxNDggNzkuMTY0MDM2LCAyMDE5LzA4LzEzLTAxOjA2OjU3ICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgeG1sbnM6cGhvdG9zaG9wPSJodHRwOi8vbnMuYWRvYmUuY29tL3Bob3Rvc2hvcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RFdnQ9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZUV2ZW50IyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgMjEuMCAoV2luZG93cykiIHhtcDpDcmVhdGVEYXRlPSIyMDE5LTEyLTAzVDAxOjE4OjIyKzAxOjAwIiB4bXA6TW9kaWZ5RGF0ZT0iMjAxOS0xMi0wM1QwMToyMDoxMCswMTowMCIgeG1wOk1ldGFkYXRhRGF0ZT0iMjAxOS0xMi0wM1QwMToyMDoxMCswMTowMCIgZGM6Zm9ybWF0PSJpbWFnZS9wbmciIHBob3Rvc2hvcDpDb2xvck1vZGU9IjMiIHBob3Rvc2hvcDpJQ0NQcm9maWxlPSJzUkdCIElFQzYxOTY2LTIuMSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDplZGViMzU3MC1iNmZjLWQyNDQtYTExZi0yMjc5YmY4NDNhYTAiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6ZWRlYjM1NzAtYjZmYy1kMjQ0LWExMWYtMjI3OWJmODQzYWEwIiB4bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ9InhtcC5kaWQ6ZWRlYjM1NzAtYjZmYy1kMjQ0LWExMWYtMjI3OWJmODQzYWEwIj4gPHhtcE1NOkhpc3Rvcnk+IDxyZGY6U2VxPiA8cmRmOmxpIHN0RXZ0OmFjdGlvbj0iY3JlYXRlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDplZGViMzU3MC1iNmZjLWQyNDQtYTExZi0yMjc5YmY4NDNhYTAiIHN0RXZ0OndoZW49IjIwMTktMTItMDNUMDE6MTg6MjIrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyMS4wIChXaW5kb3dzKSIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4JZNR8AAAfG0lEQVR4nO2deViTZ7r/7yxkJaxJ2MK+GCBAMCwS1kgUFQSKK4XWWqsz1jpjp3b0tDP1V+eqU391fqfT/mpPPd20drTFDS0KFEVWJSGAEgLIZpAICBJACIRs549Rj1WILAkBfD/XlevySp68z/0S3+/7vPdzLyidTgcLkU2bd+z39/f/q1gshsrKSoJELFCa2iaEuU9K6kb+8uXxv54/fzE8L/eswNT2zCfQpjbAGKS8lPFKSEjIXiaTCSEhIeDj4xNnapsQ5j6rktZGp6UlfxIdzQVzCplmanvmG1hTG2BIAtlc26CgoDfT0tL2e3l5AQCAjY0NkMnk/a9s2k6rrKw8UV8n1JjYTIQ5RlAw14KzmL3xze1vfJyUuMJaq9UCFovFm9qu+YbBxcSPFUYkk8l2Q0NDsvo6ocrQx5+I8Ih4bz6f/0l8fHyKlZXV4/dRKBQwmcwwMpn8A4FAoPgHhH9bV1sxa488wZxoaycnJ/a9e/duCa5fkc3WvAiTI4Ib77p+XdqHG9anbfLy8gAAgLGxMdBpF+bjvzExqJj4scKI0dHRnwQHB++orq7+AgDeMuTxJ2Jl4rqU9PT0EwEBAUQCgTDuGAaDAampqYepVKpHUHDk325Ulw0a266YuFW+Gzdu/MDPz29jfn7+XgA4aOw5ESZP6kvpCXv3vnM8NiaSamVl+fj9BepGNDoGFRN7e/slcXFxO1xcXMDJyWnH7j//H/fi4uJdgutXmgw5z5O8smn7X9euXbvf29sbMBjMhONQKBRYWVlBbGzsbjMzM3JoOG+/sKKwy1h2rd/4elpGRsYuLy+vaDweD2w2Oy1h5ZrCvEunEaeeiVnMiabyl/F2/+X9P+8JDPQHHA5napMWBAYTk6DgSNuEhIS9DAYDAP7tq1i6dOkqOp3OWbNu0wens44emeoxA9lcWwKBYEMkEm2JRKIdHo+3QKFQWJ1Op8ZgMER3d/dVq1evTnFycpr0MSkUCsTExGzH4/Gk1LTME/39/TI0Go1FoVCg1WrVY2NjipGRkcGRkRH5dPwrEZHLXMPCwjJSUlIy3dzcfB+97+rqGhYSEpIOAIiYmBguN3zL77dt3uPh4W5qUxYUBhMTb2/vjeHh4cvR6P/dILK0tITIyEg7BweHr363/Z3Ampqaf1Zcu/zMKiVsyVJvMplsRyKR7IhEor2FhYUbhUJhJCYm2pFIJB6JRAIymQx4PB7QaDRoNBowMzMDJycnwOOn7icjEokQGxu7icFgbLp///7jFY1WqwWlUgkjIyOgUCgO7Ni5Rz48PCwfHh7uGRkZeaBQKOSjo6ODCoVCXlNVKn/6uCsT13FXrVr1emho6BYKhfLMnP7+/omrU9LPX8g+UThloxEMxqJFXjxESAyPQcSEExrLWLNmzW57e/txP/fw8ABHR8cdDAaDt3xF2ru9vb03sVgs0cbGxs/FxWVZUlISj0aj+dna2oKtrS1M5PcwJCgUCry8vODRrs84vPfoH6OjoyCXy6Gvr+/R6+CWrX9s7evrk/b19bWr1Wqli4sLZ8OGDe95eXmxUSjUuAd0cHDwjoqK2sYKXFIhvnldYYTTQpgU4/8+jyASCYDGoCd+ZkYYF8OICYezl8PhuOkbQyAQIDo62s/NzS2np6cHbGxsgEajAYFAAAwGA1gsFia6CE0NgUAABwcHsLe3B61WC2q1eo9WqwWNRgNKpRLUajUQiUSgUCh6zwGHwwGTydzo5+eXBQBnZu8MEJ5keHhYPqyYWMtHR0ZBpVIhYj9FUDONgOUvT12+du3avMDAQJjssdRqNWCxCyrEZdLodDoQi8Ulx44de628NL/V1Pa8iERE8l2dHB2CJvpcq9Nqbt1qKURWj1Njxld0ZGTkAW9v70kLCQC8sEIC8O/HKx8fn2gmk8kHgCk7pRFmzrWyAikASE1tx0Jj2uH0EZHL/N7YtuvT4OBgzmz4OBYSeDweIiMjt2S++vtMP1YYEmmJsCCY8mNOIJtr6+zsHBcZGXmIw+G4mZubG8m0hU9HRwcUFxe/KxQKTyDRsQjznSmJCS9+dVRERMTfQ0NDo2xtbfUGiSFMjtHRUaitrc3Jzc09kHvxVLmp7UFAmC6oZQkvrZLL5RJhReHtiQb5scKIXC7371FRUX90dnYGIpE4JR8Jgn40Gg20t7fXFxYWfnr9+vWjz8sdYi+Osh4vzgUBwZSgtu94V+fs7Hx7YGCgra6u7khLS0u2RCwYeTQgKmYFh8fj/f/g4OAldnZ2prR1wdPd3Q1CofBQSUnJkdLi3N8E93FCY6k+Pj48FxcXjlar1ZSWlh65VvYr4kREmDNg79+/D3FxcW5OTk5uXl5evNbW1tL0jK3ZXV1d1ykUintycvInoaGhdkj+gvGxs7MDPp+/m0AgWMQvS/lyeHhYTqPRPJycnIJSU1NZ3t7eW2g0Gly/fv2oWq1Gij0hzClQ/gHhpLS0tEM8Hm/7I8Ho7++HlpYWsLa2Bg8PDxOb+OKhUCigqakJ7t+/D25ubuDu7g4oFAp0Oh08ePAAvv7666TTWUdzTG0nAsKTYMU3ryuSU18+4+bmFrZo0SIOAICVlRUsXrx4zkakLnRIJBI8CgJ8MtdJp9NBZ2enqL29XWRC8xAQxgUNAHD+3L8KGhoaCp78ABES04JCoX4jJAAAAwMDUFtbe96YpRMQEKbL41DU5ubmko6Ojj2PSgggzD36+/vrb9y4cX425zzw93/8EBjon2is44+NjSkePBjqGRwc7G5v7xBV19w8U5B/3qgrr9+/uWtXUuKKD/TZ9MXh/066/OuFmunO8dGBQ98HBbGSp/t9U6LRaDXK0dHBoeFhuVzeL22/0yFqamopufjLqRJ933ssJi0tLSXV1dWHGAzGbuObOzs8ubqa71vZKpUKOjo6blwpOF8zm/Mu5cVkLlkSaswprAHAaVihgK7O7oSGxltvfXLon3nXK4RHT2cdN4pfKDCAlZyUuMJan02nTmczAaBmunPw4qI3cbnh0/36XICq0+lgcPABp7OrK629vUP5z8++LLh2XXD05L++yxrvC4/F5EZ12WBS8saLS5Ys2U2lUufUY45SqQSlUgkqlQrUavXj19jYGGg0GtBoNKDT6UCn05VotVq1TqfToFAojFar1eh0Og0Wi8XhcDgeGo1+/PhgZmYGOBwOsFgsmJmZ/eY1F+nt7YXa2trs2Z73wdCQBgCMHp1IJpHA09MdPD3dLRIS+OtKisvWvbP7vf2lZdePVFwzbHTwyMiI3hidkZFRUKvUYzOZ48HQkBIA5nWqBAqFAktLC7C0tADmIh88Pz4uMSyUk7hn776DV4tKPn/6d/lNxp1MJqsRCASf8vn8XdMpOjRTVCoVjI2NgUqlAq1WCyMjI9DX1wf379+Hvr6+/Q8ePOgdGRmRKxSKx0WLFAqFXKlUKnQ6nUar1arHq47mxwrD4/F4Eg6HI2GxWDwej7cgkUjWFAqFam5uTjU3N6eRyeQPLSwswNraGqysrIBAIDwWFywW+zja11Qi29LSclIikeSZZPJZBovBAI8XA8HBQR9kZZ3lR8cmvFZSlGe00p8IkwONRkNERBj4+i7a4+XpHv307/IbMakWlciXJbx0nMPh7Jqo0JGh0el0MDo6Cl1dXSCVSkEmk7177969W319fe1DQ0M9KpVKoVarlWq1WjndNhUPG3ApAWDcOxLTLwSDwWAOotFoDBaLxRMIBAsrKysne3t7Xzqd7k2n0/c4OzsDlUoFHA4364IyMDAATU1NxdWikhcq6tXKyhJezljPJZKI2eERS5cZeoWCMD2srCwhPX0tVzk2djiCG//GtfLLUoBxShB0dHTU3Lx580sLC4vtJBLJKMZoNBqQSqUglUqPdnR01PT09DT19/fLHjx40DM0NNQ72933GiSVGgB4JFQK+LfoSAGgnL04yppEIh2xtLS0t7GxcaFSqR7Ozs4fMRgMcHR0nJX8pJs3b54Ui8UXjT7RHIRMIkFK8irfwcEHPwQELUmqvYHUGJkLmJubw8YNa/i9vfffY/px3myQiDTPiEl9nVDDX576jaenZ7SnpyfLUJNrNBqQyWRw+/bt4x0dHTdkMlltV1dXw/XygjkdEv4wB0YOAK0AUM70C8HQ6fSzdDrdm0qlejg6OrLc3Ny2MBiMadWjfR4PHjyAmzdvZs/1v5MxoVAokJK8iicWS95k+nH+s0EiQhqpzQGoVFtYk5a87ba0XQAA34xbpagg/5zoT7s/OGNnZ8eaaYkBuVwOnZ2d5VKpVNTS0lLS2NhYWFVZ3Dujg5qQh6uY+ocvCAiKIPn4+Jz19PSMdnV15VCpVL6Dg4NBViw6nQ5EItHRpqamqzM+2DzHzo4O69amftLQeKsAZrDLgmBY/PyYsCIhfs+SiKUFE5Y8EwqFx11cXDihoaFTjjFAoVAwPDwMHR0dourq6jNCofDHhZqUVnvjmgIAcgAgJyg40mLRokX8kJCQjT4+PussLS1n1JPl7t27UFxcfHguB6mNjY2B7G4naNRTWyygUCjAYDGAx+PB0sICSCSi3vFYLBbCwjjA8vddBQtATKb7d3saBwc7IJPJBpsHjUGDGRYLJBIJLK0sAfucmyIGg4FFi3y8AwNZtycUk5KiS02vvf7WWQaDkejg4DApQwAeh3xDaWnpPoFAcPxFqnP6sEvgGf+A8Bx3d/cvIyIiNi1evHjT8wpNj8fAwACUlZW9P9dD5+/ckcFbf9gd2dcnn9LNAovF4inmZHtXNxdOdBR3+/JlS33pdP29wolEInA4weuiYxOy5vvuTkeHDHb+8c8xvb33Z3R9/N+Df+uIjYk02DwkEsna2trS1d/fNyGeF7uTyw1/7g3R3t4O2OxA/TVghULhcQqFQk1JSfmYSNR/5wD4d6EfgUBwvLS09IhUKhW9qAV5H9YjKQwJi6uvrKw8ERoamhkSEpKp7w7yJEqlEiQSyZmysrJv53qjdaVSCZdyTk+3qFMrAJRHRPLPN95qeifj5fU7mYt8JhyMRqMhMJDFdnF25gDAvBYTpXIMWlpay2fq/8m5mDcIABYGnEcGAGI/VlhBZWX1yZdSkz55OX0dV5+7w9bGGvz8mPrFpK62QskJjf2GTqd7x8bGbpnID4BCoUAmk0lLSkqOiESik2UleS/MakQflYKrXQDQxY1a3tTe3i6KiIjY5OXlxX7e9+rr6wsuXbr0t4ffn9OgMWjghMZQRcLp+8GulRVI/QPC37Wxtnal0ajJtjY2E451ZjiBra31vE9lR2PQQKFQaAAwo98Yi8Xq9fpPd56HO6rlvKWJv/PwcK+JilyCmajWMw6HAzs7+rMFpQOCIn6zHywSFvXm5eUdFAqFZ9Rq9bgHa2trq79w4cK+zz49cAARkmcpL81v/a/Dhz49d+7c3qqqqjyVSjXuOJ1OBxKJpDw3N/fA5V+zax6978cKw/sHhM/raMrnUVdboSy4fPWQSFSjd5yFBQWIRNKEd2IEw1J4JUd88WL+R51d3XrHWVDMnxUTa2tr1zXrNiUGsrmPf7DS4tymCxcu7Kuurs55+kKQSqVN586d23vs+8NHDXUCC5Wzp3/Iy8rKeruysvLM2Nhvo7VVKhXU1tYWnj17du/T7UOdnZ2D7OzsfGGB09raVi4S1RzXl0eFw+EAj8chYjKLVFffyOrq1C8mJBLpWTFRKBRyDofzC4vFWvXk+1ev/CLOzs7eKxAIslQqFeh0Oujp6enKzs7em/XTd7OayTqfKb56sT4rK+sPAoHg5KO/o0KhAKFQmHXy5MkdF3/5+TeZmctXpIXZ29v7zqVcKWNRX1epuXu3U/y8pEw0GmndOZt0dnXVDw0P6/W5oNHoZ30mQ0NDPb29vfvj4+Pf3rR5B/7od188XnEUXr4gDgmL+0NfX5/U19d3d3l5+YGfTnyDtLmcIhXXLsu4UcvfR6PRGGtra9eysrIjYrE45+kt4Fheou/69es/unnz5vm7d+/Wmsre2WRkZGTQ1DYg/JYGiUiTm1ugBAC9IfHPiEmDpFITE7fqJI/H27lmzZpDq5LWtz55t6wUXO3ihMYerK+vz2tpaUFaM0yT8tL81ujYle+TSCTrvEunBU9/voTLd92wYcPHVCqV39XVdXCu7+oYCp1O90Kc50Jk3I5+xVcv1jc3N5d4enpSMzIyvkpK3sh78nORsKg3++yPBS/q1q+hKCm61DSekERGJ3ikp6d/ERsbm1xVVXWwtbX1hRFtFAqFPMLMUyZsDyoQCI7LZDKIiIjwzczM/GpV0vro2TTsRSUqZoX3+vXrP1u9enXi0NAQiESirIdRtggIc5oJ40zq6uryGhoa8ry8vBJCQ0O9USjU94mrN7yWc+EnvaXb5gJMvxCMp6cnl0Kh2Le1tZVXXLs8L1LXefGrWRkZGZ/x+XyeUqkEkUh0vqenZ14HZyG8OEwoJjdrygd37NxTEBkZmWBtbQ3BwcEeKBTq+/UbX3/355Pfzlmn66qk9dGbN29+k8PhbCSRSNDZ2Snb9ae/HCkpKTksEhbN2QTD5NSX+Vu3bj0cHBzsjcFg4O7du1BWVvbNwxB9BIQ5j94I2Fu3bhXW19cDl8sFLBYLHA7Hg0wmf/e77e84ffXlPz6fLSMnQ2paZkJ4eHjmtm3b+B4eHvZkMhlQKBTY29s72dvbfxgUFJT8x7ffP1NRUfHjXErnZ/qFYKKjo7dt3rz5g8DAQPtH/XHa2tpqGhsbC55/BASEuYFeMblz505NTU3NgfDw8PcwGAygUCjw9fW1IJPJn/1130Hv0tLSI4WXL4hny9inYS+Osvbz80tgMpn8jIwMPovFch2vpoiDgwM4ODhwfH19OYsWLeJv3/Hu+cbGxquzXZz5aZYlvMRJT0/fFhkZue3JZmfd3d0gEolOIr4ShPmEXjFpkFRqXlrzSnFnZ+d7Tk5OjzNfXVxcICMjY6ezszNnVdL6vU8HWhmbgKAIkrOzMyc1NTXz0YU4maAuOp0OK1as4EVFRfGEQqHg1dfePHzr1q2rs71S8WOF4f38/BLS09M/iIyM5DxdxLq5uVlcVVU1bgVwBIS5il4xAQCQyWRigUBwJikpKe3JVGQcDgdLly7l2tranti0ecf7IpEoy9hbxX6sMDydTvdevXr1ltjY2F3u7u6AxT73FJ7B3Nwc4uLiwthsdphQKCzZkL7l0/r6+oKbNeVG90+EhMXZL1++fFtycvKHrq6uz4igUqmE5ubmEiTHCWG+8dwrUXD9imz9xtd/jIuLS7N5KpsTjUZDUFCQE4PB+F4oFGYmJW888Mv5k4UTHGpGxC9LYaenp78VEhKyxdHRESgUyoyOh0KhwNraGuLi4qIDAgKi6+rqyjekb/mHMSN6N6RvSdu+ffseNpsdZm09ftuW+vp6EIvFSB9hhHnHpG7rUqm0orW1tdXS0tLj6TIEaDQaaDQaxMfH811dXTl/3Xfw+JUrVz411J01cfWG6IiIiC07d+5McHNzs7ewMGyOFw6HAwcHB6BSqVx3d/fwz7/4rkAgEBwXCoUnHpZonDGrU9J5MTEx27du3Zrm4uKC0beaqq6u/ry+vj7XEPMiIMwmkxKTimuXZe/u+fCkp6fnexPdUfF4PPj7+1szGIydLi4unF1/+kvenTt3RG1tbRXTqfma8lIG39/fP/HVV19NZrFYHpMpzjQTzMzMwNPTE+Pp6Zng6emZ4Ofnl5CesfV8bW1tznQe3/wDwvFeXl7Rvr6+Ca+88kpaUFCQh74GXzqdDrq7u6GpqankRQmdR1hYTNrhUFVVlcXj8d6ysrKy0OfstLS0hPj4eC6Xy+U2NzeDRCI5/sa2XeX37t1rGhwc7BoYGJBN1P+FFbiE5OzszGaxWImvvvrqpoCAAKfp+ERmCpPJBCaTmcnhcDJLS0u/TE59+YxUKhXoi/lg+oVgrKysGJaWlna2trYeaWlpXDabvTMgIGDSfp2KiorzbW1tL0zoPMLCYtJX6uVfs2u++PKowMPDgz+ZIslEIhECAgKAxWJlajSazJ6eHmhra4PW1tZvtmz9o6Czs7O+r6+vfWxsbFir1WosLCzsV6xYkcnj8d7z9vaelmPV0Hh5eYGnp+f2mJiY7UVFRZ/HL0v5tru7+5ZGo1FisVg8Docj4fF4CxsbG1c+nx/m7e39sYeHB7i4uIC5ufmU6r4ODQ1BZWXlifkSrYuA8DRTumIrKytPent78728vCb9HRQKBVgsFhwcHIBOpwObzd4yNja2RaVSwdDQEHR1dcHo6CjQaDRwdXWdsWPV0KBQKPDw8AA7O7udERERO2tra2FgYACoVCo4OTkBjUYDMpkMeDz+8WuqaLVaaGxsbL19+/YzSX8ICPOFqYrJidDQ0AwvLy/e80c/CwaDARKJBI86BdJoNHB3dwe1Wj0nViL6IJPJwGQywdnZGZRKJRAIBDBUx8OBgQEoLS39BtkORpjPTJg1PB61N64pmpqarvb39xvUiLkuJE9CJpPBxsbGYEICANDZ2SlHgtQQ5jtTEhMAgLq6ulyJRFJvDGNeREZGRkAikRSUFuci2cEI85opi0l+7hmBWCzOeV6dToTJcfv27cHr168jxbgR5j1TFhMAgObm5hKZDNl0MAQtLS3Xzpw6hkS8Isx7piUmUqlUIBAIJuyjgzA5Ojs7QSKRINGuCAuCaYmJsKKw68qVK59KJJIu5HFneiiVSigqKjouEolOmtoWBARDMC0xAQC4+MvPJadOnXq3ra1N8yL0dDEkOp0OSktLy/Pz8w8+3d4CAWG+Mm0xAQA4fuy/jl+8ePGju3fvGsqeBY9Wq4XKysrWU6dOvX31yi8mKyyFgGBoZiQmAAD/79D+fadPn96PCMrz0el0UFVV1frtt9+mj9fiAgFhPjNjMQEAyMvLO3Ds2LE/tLS0INmuerh27Vr9999//xoiJAgLEYOEntbVVigB4PNNm3cMpqSkfMRms50McdyFgkqlgqKiovJTp069nZ97BhEShAWJQePYj373xdF1GzbLFQrFx6Ghob766ne8KNy7dw+KiopO5ubmfmTK4tsICMbG4EkxWT99d35l4rre/v7+D0NCQvh0Ot3QU8wL1Go1SKVSTX5+/sH8/PyDSP8bhIWOUTLsLuVklQcFR65pbGzcvnLlyvfc3NwsCASCMaaac+h0OhgaGoLq6uqaCxcu/OV01tGcTw7uM7VZCAhGx2jpug/vxAd58atzoqKitq1cuXKnvb29saabE+h0Oqiurpbm5eUdrK6uPlspuDrvY0hmO4YIhUIBGq1/X2CmNqFQKL3/79HomZ/z82xEowyy9zFr80zGDqPn/hdeviBmL47ad+fOnRsRERGbQkNDo62srIw97azT2dkJxcXFx0tKSo7Mdh8hY4LD4TDPH2U4MFjMc6tLmZmZzaj+Aw6H0/t9PB4PGCxmRudNJBL0ngeZTAI0Gj3jv+1szfM88Hic8cUEAKCmqlQOAN/ELU2qkEgkySwWK3HRokVcBoMxG9MbDZ1OB83NzdDU1FRQW1t7XiAQHJ+ovu18pbr6Rg6L5ZtoM0EhcUPT0tJW8tWRb0vQqIkvgKqqmhnVfrl2TfANXo+gjKlUio4OWc1M5sjOzjnQUH8rbqLPu3t6moaGhmfc+3q25tGHUqmECoEIUKbIrVkcEkONiIh4jcvlvu7s7OxLo9GmVe7QVCgUCujq6oKGhoaCioqKo9XV1WeM3YDMVPDik1gpyas+XrVyeaKXl8czjyANjbcgI/MNmkg49Q4ECPOH3NyC4RUr+M8IcHt7B1y9WlKRl3/5kElKnD1sfXEoJCzueEBAQGJYWFgGk8nk2djYAIFAgLm4pTw6Ogqjo6Mgl8vhxo0b50tLS4/U19fnLvS2FIWXfxEDQNLmLW9ueW1TxtchHDaQyWRTm4VgYkZHR6G+vhF+/NfP+y5e+vVjiVgwZpKVydOwF0dZW1lZOTGZTD6bzU4LCAiIptPp8HTDL1MwOjoKLS0tUFdXd1IsFudIpdKKgYGB7tloJTrX4MUnsVJTEj9etzY10dHRAQAAGm81wcsZW5CVyQInL69gNCGBjwcAGBx8ANnncypOnTr3H9nn/reD55wovvrQpyIHAHFUzIocGo3mQaPRfBwdHVlubm7bXF1dgcFgABqNNvruglwuh7t374JMJoOOjo7P79y5I+ru7m7q7e1tXQi7MzOh8PIv4pCw2DdaWtte37Au7aPIyCWAxWABjUbPif9HCMbjURtKiaQBfvr5zH9evlJ0uLQ4r/nJMXNiZTIRrMAlJAcHB18HBweWo6Mjy8rKajeJRAJLS0uwtLQECwsLoFAogMfjAYvFgpmZ2XNXMyqVCoaHh2FoaAiGh4cfvwYGBqCvrw+6u7vfvnfvXlNvb29rT09Pq0QsUM7S6c4rNqS/lrZ5U+YPRBKR9M7u9xwqBUUvtNAudH766XSLE8PR49ixE78/8tVnX403Zk7fUR46NUUAIPIPCMdTKJTdNjY2QKPRgE6nA51OB1tbWyCRSIDD4YBAIAAejwcCgfDYUajVakGlUoFarQadTvfY79HX1wf9/f0gl8tBLpfDvXv3HvXw+dxQPYYXMj+d+P7Mmzv+5OHr6/OJWq1GBHeB09TcUiKuq/coKS3/eqIx/wPkiIXC3w6YjAAAAABJRU5ErkJggg=="); + + --keyword: #ff79c6; + --identifier: #f8f8f2; + --comment: #6272a4; + --operator: #ff79c6; + --punctuation: #f8f8f2; + --other: #f8f8f2; + --escapeSequence: #bd93f9; + --number: #bd93f9; + --literal: #f1fa8c; + --program: #9090c0; + --option: #90b010; + --raw-data: #8be9fd; + + --clipboard-image-normal: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='color: lightgray' fill='none' viewBox='0 0 24 24' stroke='currentColor'%3E %3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2' /%3E %3C/svg%3E"); + --clipboard-image-selected: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='color: lightgray' viewBox='0 0 20 20' fill='currentColor'%3E %3Cpath d='M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z' /%3E %3Cpath d='M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z' /%3E %3C/svg%3E"); + --clipboard-image: var(--clipboard-image-normal); +} + +@media (prefers-color-scheme: dark) { + [data-theme="auto"] { + --primary-background: #171921; + --secondary-background: #1e202a; + --third-background: #2b2e3b; + --info-background: #008000; + --warning-background: #807000; + --error-background: #c03000; + --border: #0e1014; + --text: #fff; + --anchor: #8be9fd; + --anchor-focus: #8be9fd; + --input-focus: #8be9fd; + --strong: #bd93f9; + --hint: #7A7C85; + --nim-sprite-base64: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAARMAAABMCAYAAABOBlMuAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFFmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxNDggNzkuMTY0MDM2LCAyMDE5LzA4LzEzLTAxOjA2OjU3ICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgeG1sbnM6cGhvdG9zaG9wPSJodHRwOi8vbnMuYWRvYmUuY29tL3Bob3Rvc2hvcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RFdnQ9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZUV2ZW50IyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgMjEuMCAoV2luZG93cykiIHhtcDpDcmVhdGVEYXRlPSIyMDE5LTEyLTAzVDAxOjE4OjIyKzAxOjAwIiB4bXA6TW9kaWZ5RGF0ZT0iMjAxOS0xMi0wM1QwMToyMDoxMCswMTowMCIgeG1wOk1ldGFkYXRhRGF0ZT0iMjAxOS0xMi0wM1QwMToyMDoxMCswMTowMCIgZGM6Zm9ybWF0PSJpbWFnZS9wbmciIHBob3Rvc2hvcDpDb2xvck1vZGU9IjMiIHBob3Rvc2hvcDpJQ0NQcm9maWxlPSJzUkdCIElFQzYxOTY2LTIuMSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDplZGViMzU3MC1iNmZjLWQyNDQtYTExZi0yMjc5YmY4NDNhYTAiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6ZWRlYjM1NzAtYjZmYy1kMjQ0LWExMWYtMjI3OWJmODQzYWEwIiB4bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ9InhtcC5kaWQ6ZWRlYjM1NzAtYjZmYy1kMjQ0LWExMWYtMjI3OWJmODQzYWEwIj4gPHhtcE1NOkhpc3Rvcnk+IDxyZGY6U2VxPiA8cmRmOmxpIHN0RXZ0OmFjdGlvbj0iY3JlYXRlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDplZGViMzU3MC1iNmZjLWQyNDQtYTExZi0yMjc5YmY4NDNhYTAiIHN0RXZ0OndoZW49IjIwMTktMTItMDNUMDE6MTg6MjIrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyMS4wIChXaW5kb3dzKSIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4JZNR8AAAfG0lEQVR4nO2deViTZ7r/7yxkJaxJ2MK+GCBAMCwS1kgUFQSKK4XWWqsz1jpjp3b0tDP1V+eqU391fqfT/mpPPd20drTFDS0KFEVWJSGAEgLIZpAICBJACIRs549Rj1WILAkBfD/XlevySp68z/0S3+/7vPdzLyidTgcLkU2bd+z39/f/q1gshsrKSoJELFCa2iaEuU9K6kb+8uXxv54/fzE8L/eswNT2zCfQpjbAGKS8lPFKSEjIXiaTCSEhIeDj4xNnapsQ5j6rktZGp6UlfxIdzQVzCplmanvmG1hTG2BIAtlc26CgoDfT0tL2e3l5AQCAjY0NkMnk/a9s2k6rrKw8UV8n1JjYTIQ5RlAw14KzmL3xze1vfJyUuMJaq9UCFovFm9qu+YbBxcSPFUYkk8l2Q0NDsvo6ocrQx5+I8Ih4bz6f/0l8fHyKlZXV4/dRKBQwmcwwMpn8A4FAoPgHhH9bV1sxa488wZxoaycnJ/a9e/duCa5fkc3WvAiTI4Ib77p+XdqHG9anbfLy8gAAgLGxMdBpF+bjvzExqJj4scKI0dHRnwQHB++orq7+AgDeMuTxJ2Jl4rqU9PT0EwEBAUQCgTDuGAaDAampqYepVKpHUHDk325Ulw0a266YuFW+Gzdu/MDPz29jfn7+XgA4aOw5ESZP6kvpCXv3vnM8NiaSamVl+fj9BepGNDoGFRN7e/slcXFxO1xcXMDJyWnH7j//H/fi4uJdgutXmgw5z5O8smn7X9euXbvf29sbMBjMhONQKBRYWVlBbGzsbjMzM3JoOG+/sKKwy1h2rd/4elpGRsYuLy+vaDweD2w2Oy1h5ZrCvEunEaeeiVnMiabyl/F2/+X9P+8JDPQHHA5napMWBAYTk6DgSNuEhIS9DAYDAP7tq1i6dOkqOp3OWbNu0wens44emeoxA9lcWwKBYEMkEm2JRKIdHo+3QKFQWJ1Op8ZgMER3d/dVq1evTnFycpr0MSkUCsTExGzH4/Gk1LTME/39/TI0Go1FoVCg1WrVY2NjipGRkcGRkRH5dPwrEZHLXMPCwjJSUlIy3dzcfB+97+rqGhYSEpIOAIiYmBguN3zL77dt3uPh4W5qUxYUBhMTb2/vjeHh4cvR6P/dILK0tITIyEg7BweHr363/Z3Ampqaf1Zcu/zMKiVsyVJvMplsRyKR7IhEor2FhYUbhUJhJCYm2pFIJB6JRAIymQx4PB7QaDRoNBowMzMDJycnwOOn7icjEokQGxu7icFgbLp///7jFY1WqwWlUgkjIyOgUCgO7Ni5Rz48PCwfHh7uGRkZeaBQKOSjo6ODCoVCXlNVKn/6uCsT13FXrVr1emho6BYKhfLMnP7+/omrU9LPX8g+UThloxEMxqJFXjxESAyPQcSEExrLWLNmzW57e/txP/fw8ABHR8cdDAaDt3xF2ru9vb03sVgs0cbGxs/FxWVZUlISj0aj+dna2oKtrS1M5PcwJCgUCry8vODRrs84vPfoH6OjoyCXy6Gvr+/R6+CWrX9s7evrk/b19bWr1Wqli4sLZ8OGDe95eXmxUSjUuAd0cHDwjoqK2sYKXFIhvnldYYTTQpgU4/8+jyASCYDGoCd+ZkYYF8OICYezl8PhuOkbQyAQIDo62s/NzS2np6cHbGxsgEajAYFAAAwGA1gsFia6CE0NgUAABwcHsLe3B61WC2q1eo9WqwWNRgNKpRLUajUQiUSgUCh6zwGHwwGTydzo5+eXBQBnZu8MEJ5keHhYPqyYWMtHR0ZBpVIhYj9FUDONgOUvT12+du3avMDAQJjssdRqNWCxCyrEZdLodDoQi8Ulx44de628NL/V1Pa8iERE8l2dHB2CJvpcq9Nqbt1qKURWj1Njxld0ZGTkAW9v70kLCQC8sEIC8O/HKx8fn2gmk8kHgCk7pRFmzrWyAikASE1tx0Jj2uH0EZHL/N7YtuvT4OBgzmz4OBYSeDweIiMjt2S++vtMP1YYEmmJsCCY8mNOIJtr6+zsHBcZGXmIw+G4mZubG8m0hU9HRwcUFxe/KxQKTyDRsQjznSmJCS9+dVRERMTfQ0NDo2xtbfUGiSFMjtHRUaitrc3Jzc09kHvxVLmp7UFAmC6oZQkvrZLL5RJhReHtiQb5scKIXC7371FRUX90dnYGIpE4JR8Jgn40Gg20t7fXFxYWfnr9+vWjz8sdYi+Osh4vzgUBwZSgtu94V+fs7Hx7YGCgra6u7khLS0u2RCwYeTQgKmYFh8fj/f/g4OAldnZ2prR1wdPd3Q1CofBQSUnJkdLi3N8E93FCY6k+Pj48FxcXjlar1ZSWlh65VvYr4kREmDNg79+/D3FxcW5OTk5uXl5evNbW1tL0jK3ZXV1d1ykUintycvInoaGhdkj+gvGxs7MDPp+/m0AgWMQvS/lyeHhYTqPRPJycnIJSU1NZ3t7eW2g0Gly/fv2oWq1Gij0hzClQ/gHhpLS0tEM8Hm/7I8Ho7++HlpYWsLa2Bg8PDxOb+OKhUCigqakJ7t+/D25ubuDu7g4oFAp0Oh08ePAAvv7666TTWUdzTG0nAsKTYMU3ryuSU18+4+bmFrZo0SIOAICVlRUsXrx4zkakLnRIJBI8CgJ8MtdJp9NBZ2enqL29XWRC8xAQxgUNAHD+3L8KGhoaCp78ABES04JCoX4jJAAAAwMDUFtbe96YpRMQEKbL41DU5ubmko6Ojj2PSgggzD36+/vrb9y4cX425zzw93/8EBjon2is44+NjSkePBjqGRwc7G5v7xBV19w8U5B/3qgrr9+/uWtXUuKKD/TZ9MXh/066/OuFmunO8dGBQ98HBbGSp/t9U6LRaDXK0dHBoeFhuVzeL22/0yFqamopufjLqRJ933ssJi0tLSXV1dWHGAzGbuObOzs8ubqa71vZKpUKOjo6blwpOF8zm/Mu5cVkLlkSaswprAHAaVihgK7O7oSGxltvfXLon3nXK4RHT2cdN4pfKDCAlZyUuMJan02nTmczAaBmunPw4qI3cbnh0/36XICq0+lgcPABp7OrK629vUP5z8++LLh2XXD05L++yxrvC4/F5EZ12WBS8saLS5Ys2U2lUufUY45SqQSlUgkqlQrUavXj19jYGGg0GtBoNKDT6UCn05VotVq1TqfToFAojFar1eh0Og0Wi8XhcDgeGo1+/PhgZmYGOBwOsFgsmJmZ/eY1F+nt7YXa2trs2Z73wdCQBgCMHp1IJpHA09MdPD3dLRIS+OtKisvWvbP7vf2lZdePVFwzbHTwyMiI3hidkZFRUKvUYzOZ48HQkBIA5nWqBAqFAktLC7C0tADmIh88Pz4uMSyUk7hn776DV4tKPn/6d/lNxp1MJqsRCASf8vn8XdMpOjRTVCoVjI2NgUqlAq1WCyMjI9DX1wf379+Hvr6+/Q8ePOgdGRmRKxSKx0WLFAqFXKlUKnQ6nUar1arHq47mxwrD4/F4Eg6HI2GxWDwej7cgkUjWFAqFam5uTjU3N6eRyeQPLSwswNraGqysrIBAIDwWFywW+zja11Qi29LSclIikeSZZPJZBovBAI8XA8HBQR9kZZ3lR8cmvFZSlGe00p8IkwONRkNERBj4+i7a4+XpHv307/IbMakWlciXJbx0nMPh7Jqo0JGh0el0MDo6Cl1dXSCVSkEmk7177969W319fe1DQ0M9KpVKoVarlWq1WjndNhUPG3ApAWDcOxLTLwSDwWAOotFoDBaLxRMIBAsrKysne3t7Xzqd7k2n0/c4OzsDlUoFHA4364IyMDAATU1NxdWikhcq6tXKyhJezljPJZKI2eERS5cZeoWCMD2srCwhPX0tVzk2djiCG//GtfLLUoBxShB0dHTU3Lx580sLC4vtJBLJKMZoNBqQSqUglUqPdnR01PT09DT19/fLHjx40DM0NNQ72933GiSVGgB4JFQK+LfoSAGgnL04yppEIh2xtLS0t7GxcaFSqR7Ozs4fMRgMcHR0nJX8pJs3b54Ui8UXjT7RHIRMIkFK8irfwcEHPwQELUmqvYHUGJkLmJubw8YNa/i9vfffY/px3myQiDTPiEl9nVDDX576jaenZ7SnpyfLUJNrNBqQyWRw+/bt4x0dHTdkMlltV1dXw/XygjkdEv4wB0YOAK0AUM70C8HQ6fSzdDrdm0qlejg6OrLc3Ny2MBiMadWjfR4PHjyAmzdvZs/1v5MxoVAokJK8iicWS95k+nH+s0EiQhqpzQGoVFtYk5a87ba0XQAA34xbpagg/5zoT7s/OGNnZ8eaaYkBuVwOnZ2d5VKpVNTS0lLS2NhYWFVZ3Dujg5qQh6uY+ocvCAiKIPn4+Jz19PSMdnV15VCpVL6Dg4NBViw6nQ5EItHRpqamqzM+2DzHzo4O69amftLQeKsAZrDLgmBY/PyYsCIhfs+SiKUFE5Y8EwqFx11cXDihoaFTjjFAoVAwPDwMHR0dourq6jNCofDHhZqUVnvjmgIAcgAgJyg40mLRokX8kJCQjT4+PussLS1n1JPl7t27UFxcfHguB6mNjY2B7G4naNRTWyygUCjAYDGAx+PB0sICSCSi3vFYLBbCwjjA8vddBQtATKb7d3saBwc7IJPJBpsHjUGDGRYLJBIJLK0sAfucmyIGg4FFi3y8AwNZtycUk5KiS02vvf7WWQaDkejg4DApQwAeh3xDaWnpPoFAcPxFqnP6sEvgGf+A8Bx3d/cvIyIiNi1evHjT8wpNj8fAwACUlZW9P9dD5+/ckcFbf9gd2dcnn9LNAovF4inmZHtXNxdOdBR3+/JlS33pdP29wolEInA4weuiYxOy5vvuTkeHDHb+8c8xvb33Z3R9/N+Df+uIjYk02DwkEsna2trS1d/fNyGeF7uTyw1/7g3R3t4O2OxA/TVghULhcQqFQk1JSfmYSNR/5wD4d6EfgUBwvLS09IhUKhW9qAV5H9YjKQwJi6uvrKw8ERoamhkSEpKp7w7yJEqlEiQSyZmysrJv53qjdaVSCZdyTk+3qFMrAJRHRPLPN95qeifj5fU7mYt8JhyMRqMhMJDFdnF25gDAvBYTpXIMWlpay2fq/8m5mDcIABYGnEcGAGI/VlhBZWX1yZdSkz55OX0dV5+7w9bGGvz8mPrFpK62QskJjf2GTqd7x8bGbpnID4BCoUAmk0lLSkqOiESik2UleS/MakQflYKrXQDQxY1a3tTe3i6KiIjY5OXlxX7e9+rr6wsuXbr0t4ffn9OgMWjghMZQRcLp+8GulRVI/QPC37Wxtnal0ajJtjY2E451ZjiBra31vE9lR2PQQKFQaAAwo98Yi8Xq9fpPd56HO6rlvKWJv/PwcK+JilyCmajWMw6HAzs7+rMFpQOCIn6zHywSFvXm5eUdFAqFZ9Rq9bgHa2trq79w4cK+zz49cAARkmcpL81v/a/Dhz49d+7c3qqqqjyVSjXuOJ1OBxKJpDw3N/fA5V+zax6978cKw/sHhM/raMrnUVdboSy4fPWQSFSjd5yFBQWIRNKEd2IEw1J4JUd88WL+R51d3XrHWVDMnxUTa2tr1zXrNiUGsrmPf7DS4tymCxcu7Kuurs55+kKQSqVN586d23vs+8NHDXUCC5Wzp3/Iy8rKeruysvLM2Nhvo7VVKhXU1tYWnj17du/T7UOdnZ2D7OzsfGGB09raVi4S1RzXl0eFw+EAj8chYjKLVFffyOrq1C8mJBLpWTFRKBRyDofzC4vFWvXk+1ev/CLOzs7eKxAIslQqFeh0Oujp6enKzs7em/XTd7OayTqfKb56sT4rK+sPAoHg5KO/o0KhAKFQmHXy5MkdF3/5+TeZmctXpIXZ29v7zqVcKWNRX1epuXu3U/y8pEw0GmndOZt0dnXVDw0P6/W5oNHoZ30mQ0NDPb29vfvj4+Pf3rR5B/7od188XnEUXr4gDgmL+0NfX5/U19d3d3l5+YGfTnyDtLmcIhXXLsu4UcvfR6PRGGtra9eysrIjYrE45+kt4Fheou/69es/unnz5vm7d+/Wmsre2WRkZGTQ1DYg/JYGiUiTm1ugBAC9IfHPiEmDpFITE7fqJI/H27lmzZpDq5LWtz55t6wUXO3ihMYerK+vz2tpaUFaM0yT8tL81ujYle+TSCTrvEunBU9/voTLd92wYcPHVCqV39XVdXCu7+oYCp1O90Kc50Jk3I5+xVcv1jc3N5d4enpSMzIyvkpK3sh78nORsKg3++yPBS/q1q+hKCm61DSekERGJ3ikp6d/ERsbm1xVVXWwtbX1hRFtFAqFPMLMUyZsDyoQCI7LZDKIiIjwzczM/GpV0vro2TTsRSUqZoX3+vXrP1u9enXi0NAQiESirIdRtggIc5oJ40zq6uryGhoa8ry8vBJCQ0O9USjU94mrN7yWc+EnvaXb5gJMvxCMp6cnl0Kh2Le1tZVXXLs8L1LXefGrWRkZGZ/x+XyeUqkEkUh0vqenZ14HZyG8OEwoJjdrygd37NxTEBkZmWBtbQ3BwcEeKBTq+/UbX3/355Pfzlmn66qk9dGbN29+k8PhbCSRSNDZ2Snb9ae/HCkpKTksEhbN2QTD5NSX+Vu3bj0cHBzsjcFg4O7du1BWVvbNwxB9BIQ5j94I2Fu3bhXW19cDl8sFLBYLHA7Hg0wmf/e77e84ffXlPz6fLSMnQ2paZkJ4eHjmtm3b+B4eHvZkMhlQKBTY29s72dvbfxgUFJT8x7ffP1NRUfHjXErnZ/qFYKKjo7dt3rz5g8DAQPtH/XHa2tpqGhsbC55/BASEuYFeMblz505NTU3NgfDw8PcwGAygUCjw9fW1IJPJn/1130Hv0tLSI4WXL4hny9inYS+Osvbz80tgMpn8jIwMPovFch2vpoiDgwM4ODhwfH19OYsWLeJv3/Hu+cbGxquzXZz5aZYlvMRJT0/fFhkZue3JZmfd3d0gEolOIr4ShPmEXjFpkFRqXlrzSnFnZ+d7Tk5OjzNfXVxcICMjY6ezszNnVdL6vU8HWhmbgKAIkrOzMyc1NTXz0YU4maAuOp0OK1as4EVFRfGEQqHg1dfePHzr1q2rs71S8WOF4f38/BLS09M/iIyM5DxdxLq5uVlcVVU1bgVwBIS5il4xAQCQyWRigUBwJikpKe3JVGQcDgdLly7l2tranti0ecf7IpEoy9hbxX6sMDydTvdevXr1ltjY2F3u7u6AxT73FJ7B3Nwc4uLiwthsdphQKCzZkL7l0/r6+oKbNeVG90+EhMXZL1++fFtycvKHrq6uz4igUqmE5ubmEiTHCWG+8dwrUXD9imz9xtd/jIuLS7N5KpsTjUZDUFCQE4PB+F4oFGYmJW888Mv5k4UTHGpGxC9LYaenp78VEhKyxdHRESgUyoyOh0KhwNraGuLi4qIDAgKi6+rqyjekb/mHMSN6N6RvSdu+ffseNpsdZm09ftuW+vp6EIvFSB9hhHnHpG7rUqm0orW1tdXS0tLj6TIEaDQaaDQaxMfH811dXTl/3Xfw+JUrVz411J01cfWG6IiIiC07d+5McHNzs7ewMGyOFw6HAwcHB6BSqVx3d/fwz7/4rkAgEBwXCoUnHpZonDGrU9J5MTEx27du3Zrm4uKC0beaqq6u/ry+vj7XEPMiIMwmkxKTimuXZe/u+fCkp6fnexPdUfF4PPj7+1szGIydLi4unF1/+kvenTt3RG1tbRXTqfma8lIG39/fP/HVV19NZrFYHpMpzjQTzMzMwNPTE+Pp6Zng6emZ4Ofnl5CesfV8bW1tznQe3/wDwvFeXl7Rvr6+Ca+88kpaUFCQh74GXzqdDrq7u6GpqankRQmdR1hYTNrhUFVVlcXj8d6ysrKy0OfstLS0hPj4eC6Xy+U2NzeDRCI5/sa2XeX37t1rGhwc7BoYGJBN1P+FFbiE5OzszGaxWImvvvrqpoCAAKfp+ERmCpPJBCaTmcnhcDJLS0u/TE59+YxUKhXoi/lg+oVgrKysGJaWlna2trYeaWlpXDabvTMgIGDSfp2KiorzbW1tL0zoPMLCYtJX6uVfs2u++PKowMPDgz+ZIslEIhECAgKAxWJlajSazJ6eHmhra4PW1tZvtmz9o6Czs7O+r6+vfWxsbFir1WosLCzsV6xYkcnj8d7z9vaelmPV0Hh5eYGnp+f2mJiY7UVFRZ/HL0v5tru7+5ZGo1FisVg8Docj4fF4CxsbG1c+nx/m7e39sYeHB7i4uIC5ufmU6r4ODQ1BZWXlifkSrYuA8DRTumIrKytPent78728vCb9HRQKBVgsFhwcHIBOpwObzd4yNja2RaVSwdDQEHR1dcHo6CjQaDRwdXWdsWPV0KBQKPDw8AA7O7udERERO2tra2FgYACoVCo4OTkBjUYDMpkMeDz+8WuqaLVaaGxsbL19+/YzSX8ICPOFqYrJidDQ0AwvLy/e80c/CwaDARKJBI86BdJoNHB3dwe1Wj0nViL6IJPJwGQywdnZGZRKJRAIBDBUx8OBgQEoLS39BtkORpjPTJg1PB61N64pmpqarvb39xvUiLkuJE9CJpPBxsbGYEICANDZ2SlHgtQQ5jtTEhMAgLq6ulyJRFJvDGNeREZGRkAikRSUFuci2cEI85opi0l+7hmBWCzOeV6dToTJcfv27cHr168jxbgR5j1TFhMAgObm5hKZDNl0MAQtLS3Xzpw6hkS8Isx7piUmUqlUIBAIJuyjgzA5Ojs7QSKRINGuCAuCaYmJsKKw68qVK59KJJIu5HFneiiVSigqKjouEolOmtoWBARDMC0xAQC4+MvPJadOnXq3ra1N8yL0dDEkOp0OSktLy/Pz8w8+3d4CAWG+Mm0xAQA4fuy/jl+8ePGju3fvGsqeBY9Wq4XKysrWU6dOvX31yi8mKyyFgGBoZiQmAAD/79D+fadPn96PCMrz0el0UFVV1frtt9+mj9fiAgFhPjNjMQEAyMvLO3Ds2LE/tLS0INmuerh27Vr9999//xoiJAgLEYOEntbVVigB4PNNm3cMpqSkfMRms50McdyFgkqlgqKiovJTp069nZ97BhEShAWJQePYj373xdF1GzbLFQrFx6Ghob766ne8KNy7dw+KiopO5ubmfmTK4tsICMbG4EkxWT99d35l4rre/v7+D0NCQvh0Ot3QU8wL1Go1SKVSTX5+/sH8/PyDSP8bhIWOUTLsLuVklQcFR65pbGzcvnLlyvfc3NwsCASCMaaac+h0OhgaGoLq6uqaCxcu/OV01tGcTw7uM7VZCAhGx2jpug/vxAd58atzoqKitq1cuXKnvb29saabE+h0Oqiurpbm5eUdrK6uPlspuDrvY0hmO4YIhUIBGq1/X2CmNqFQKL3/79HomZ/z82xEowyy9zFr80zGDqPn/hdeviBmL47ad+fOnRsRERGbQkNDo62srIw97azT2dkJxcXFx0tKSo7Mdh8hY4LD4TDPH2U4MFjMc6tLmZmZzaj+Aw6H0/t9PB4PGCxmRudNJBL0ngeZTAI0Gj3jv+1szfM88Hic8cUEAKCmqlQOAN/ELU2qkEgkySwWK3HRokVcBoMxG9MbDZ1OB83NzdDU1FRQW1t7XiAQHJ+ovu18pbr6Rg6L5ZtoM0EhcUPT0tJW8tWRb0vQqIkvgKqqmhnVfrl2TfANXo+gjKlUio4OWc1M5sjOzjnQUH8rbqLPu3t6moaGhmfc+3q25tGHUqmECoEIUKbIrVkcEkONiIh4jcvlvu7s7OxLo9GmVe7QVCgUCujq6oKGhoaCioqKo9XV1WeM3YDMVPDik1gpyas+XrVyeaKXl8czjyANjbcgI/MNmkg49Q4ECPOH3NyC4RUr+M8IcHt7B1y9WlKRl3/5kElKnD1sfXEoJCzueEBAQGJYWFgGk8nk2djYAIFAgLm4pTw6Ogqjo6Mgl8vhxo0b50tLS4/U19fnLvS2FIWXfxEDQNLmLW9ueW1TxtchHDaQyWRTm4VgYkZHR6G+vhF+/NfP+y5e+vVjiVgwZpKVydOwF0dZW1lZOTGZTD6bzU4LCAiIptPp8HTDL1MwOjoKLS0tUFdXd1IsFudIpdKKgYGB7tloJTrX4MUnsVJTEj9etzY10dHRAQAAGm81wcsZW5CVyQInL69gNCGBjwcAGBx8ANnncypOnTr3H9nn/reD55wovvrQpyIHAHFUzIocGo3mQaPRfBwdHVlubm7bXF1dgcFgABqNNvruglwuh7t374JMJoOOjo7P79y5I+ru7m7q7e1tXQi7MzOh8PIv4pCw2DdaWtte37Au7aPIyCWAxWABjUbPif9HCMbjURtKiaQBfvr5zH9evlJ0uLQ4r/nJMXNiZTIRrMAlJAcHB18HBweWo6Mjy8rKajeJRAJLS0uwtLQECwsLoFAogMfjAYvFgpmZ2XNXMyqVCoaHh2FoaAiGh4cfvwYGBqCvrw+6u7vfvnfvXlNvb29rT09Pq0QsUM7S6c4rNqS/lrZ5U+YPRBKR9M7u9xwqBUUvtNAudH766XSLE8PR49ixE78/8tVnX403Zk7fUR46NUUAIPIPCMdTKJTdNjY2QKPRgE6nA51OB1tbWyCRSIDD4YBAIAAejwcCgfDYUajVakGlUoFarQadTvfY79HX1wf9/f0gl8tBLpfDvXv3HvXw+dxQPYYXMj+d+P7Mmzv+5OHr6/OJWq1GBHeB09TcUiKuq/coKS3/eqIx/wPkiIXC3w6YjAAAAABJRU5ErkJggg=="); + + --keyword: #ff79c6; + --identifier: #f8f8f2; + --comment: #6272a4; + --operator: #ff79c6; + --punctuation: #f8f8f2; + --other: #f8f8f2; + --escapeSequence: #bd93f9; + --number: #bd93f9; + --literal: #f1fa8c; + --program: #9090c0; + --option: #90b010; + --raw-data: #8be9fd; + + --clipboard-image-normal: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='color: lightgray' fill='none' viewBox='0 0 24 24' stroke='currentColor'%3E %3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2' /%3E %3C/svg%3E"); + --clipboard-image-selected: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='color: lightgray' viewBox='0 0 20 20' fill='currentColor'%3E %3Cpath d='M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z' /%3E %3Cpath d='M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z' /%3E %3C/svg%3E"); + --clipboard-image: var(--clipboard-image-normal); + } +} + +.theme-select-wrapper { + display: flex; + align-items: center; +} + +html { + font-size: 100%; + -webkit-text-size-adjust: 100%; + -ms-text-size-adjust: 100%; } + +body { + font-family: "Lato", "Helvetica Neue", "HelveticaNeue", Helvetica, Arial, sans-serif; + font-weight: 400; + font-size: 1.125em; + line-height: 1.5; + color: var(--text); + background-color: var(--primary-background); } + +/* Skeleton grid */ +.container { + position: relative; + width: 100%; + max-width: 1050px; + margin: 0 auto; + padding: 0; + box-sizing: border-box; } + +.column, .columns { + width: 100%; + float: left; + box-sizing: border-box; + margin-left: 1%; } + +@media print { + #global-links, .link-seesrc, .theme-switch-wrapper, #searchInputDiv, .search-groupby { + display:none; + } + .columns { + width:100% !important; + } +} + +.column:first-child, .columns:first-child { + margin-left: 0; } + +.container .row { + display: flex; } + +.three.columns { + width: 25.0%; + height: 100vh; + position: sticky; + top: 0px; + overflow-y: auto; + padding: 2px; +} + +.nine.columns { + width: 75.0%; + padding-left: 1.5em; } + +.twelve.columns { + width: 100%; + margin-left: 0; } + +@media screen and (max-width: 860px) { + .three.columns { + display: none; + } + .nine.columns { + width: 98.0%; + } + body { + font-size: 1em; + line-height: 1.35; + } +} + +cite { + font-style: italic !important; } + + +/* Nim search input */ +div#searchInputDiv { + margin-bottom: 1em; +} +input#searchInput { + width: 80%; +} + +/* + * Some custom formatting for input forms. + * This also fixes input form colors on Firefox with a dark system theme on Linux. + */ +input { + -moz-appearance: none; + background-color: var(--secondary-background); + color: var(--text); + border: 1px solid var(--border); + font-family: "Lato", "Helvetica Neue", "HelveticaNeue", Helvetica, Arial, sans-serif; + font-size: 0.9em; + padding: 6px; +} + +input:focus { + border: 1px solid var(--input-focus); + box-shadow: 0 0 3px var(--input-focus); +} + +select { + -moz-appearance: none; + background-color: var(--secondary-background); + color: var(--text); + border: 1px solid var(--border); + font-family: "Lato", "Helvetica Neue", "HelveticaNeue", Helvetica, Arial, sans-serif; + font-size: 0.9em; + padding: 6px; +} + +select:focus { + border: 1px solid var(--input-focus); + box-shadow: 0 0 3px var(--input-focus); +} + +/* Docgen styles */ + +:target { + border: 2px solid #B5651D; + border-style: dotted; +} + +/* Links */ +a { + color: var(--anchor); + text-decoration: none; +} + +a span.Identifier { + text-decoration: underline; + text-decoration-color: #aab; +} + +a.reference-toplevel { + font-weight: bold; +} + +a.nimdoc { + word-spacing: 0.3em; +} + +a.toc-backref { + text-decoration: none; + color: var(--text); +} + +a.link-seesrc { + color: #607c9f; + font-size: 0.9em; + font-style: italic; +} + +a:hover, a:focus { + color: var(--anchor-focus); + text-decoration: underline; +} + +a:hover span.Identifier { + color: var(--anchor); +} + + +sub, sup { + position: relative; + font-size: 75%; + line-height: 0; + vertical-align: baseline; } + +sup { + top: -0.5em; } + +sub { + bottom: -0.25em; } + +img { + width: auto; + height: auto; + max-width: 100%; + vertical-align: middle; + border: 0; + -ms-interpolation-mode: bicubic; } + +@media print { + * { + color: black !important; + text-shadow: none !important; + background: transparent !important; + box-shadow: none !important; } + + a, a:visited { + text-decoration: underline; } + + a[href]:after { + content: " (" attr(href) ")"; } + + abbr[title]:after { + content: " (" attr(title) ")"; } + + .ir a:after, + a[href^="javascript:"]:after, + a[href^="#"]:after { + content: ""; } + + pre, blockquote { + border: 1px solid #999; + page-break-inside: avoid; } + + thead { + display: table-header-group; } + + tr, img { + page-break-inside: avoid; } + + img { + max-width: 100% !important; } + + @page { + margin: 0.5cm; } + + h1 { + page-break-before: always; } + + h1.title { + page-break-before: avoid; } + + p, h2, h3 { + orphans: 3; + widows: 3; } + + h2, h3 { + page-break-after: avoid; } +} + + +p { + margin-top: 0.5em; + margin-bottom: 0.5em; } + +small { + font-size: 85%; } + +strong { + font-weight: 600; + font-size: 0.95em; + color: var(--strong); } + +em { + font-style: italic; } + +h1 { + font-size: 1.8em; + font-weight: 400; + padding-bottom: .25em; + border-bottom: 6px solid var(--third-background); + margin-top: 2.5em; + margin-bottom: 1em; + line-height: 1.2em; } + +h1.title { + padding-bottom: 1em; + border-bottom: 0px; + font-size: 2.5em; + text-align: center; + font-weight: 900; + margin-top: 0.75em; + margin-bottom: 0em; } + +h2 { + font-size: 1.3em; + margin-top: 2em; } + +h2.subtitle { + margin-top: 0em; + text-align: center; } + +h3 { + font-size: 1.125em; + font-style: italic; + margin-top: 1.5em; } + +h4 { + font-size: 1.125em; + margin-top: 1em; } + +h5 { + font-size: 1.125em; + margin-top: 0.75em; } + +h6 { + font-size: 1.1em; } + + +ul, ol { + padding: 0; + margin-top: 0.5em; + margin-left: 0.75em; } + +ul ul, ul ol, ol ol, ol ul { + margin-bottom: 0; + margin-left: 1.25em; } + +ul.simple > li { + list-style-type: circle; } + +ul.simple-boot li { + list-style-type: none; + margin-left: 0em; + margin-bottom: 0.5em; } + +ol.simple > li, ul.simple > li { + margin-bottom: 0.2em; + margin-left: 0.4em } + +ul.simple.simple-toc > li { + margin-top: 1em; } + +ul.simple-toc { + list-style: none; + font-size: 0.9em; + margin-left: -0.3em; + margin-top: 1em; } + +ul.simple-toc > li { + list-style-type: none; } + +ul.simple-toc-section { + list-style-type: circle; + margin-left: 0.8em; + color: #6c9aae; } + +ul.nested-toc-section { + list-style-type: circle; + margin-left: -0.75em; + color: var(--text); } + +ul.nested-toc-section > li { + margin-left: 1.25em; } + + +ol.arabic { + list-style: decimal; } + +ol.loweralpha { + list-style: lower-alpha; } + +ol.upperalpha { + list-style: upper-alpha; } + +ol.lowerroman { + list-style: lower-roman; } + +ol.upperroman { + list-style: upper-roman; } + +ul.auto-toc { + list-style-type: none; } + + +dl { + margin-bottom: 1.5em; } + +dt { + margin-bottom: -0.5em; + margin-left: 0.0em; } + +dd { + margin-left: 2.0em; + margin-bottom: 3.0em; + margin-top: 0.5em; } + + +hr { + margin: 2em 0; + border: 0; + border-top: 1px solid #aaa; } + +hr.footnote { + width: 25%; + border-top: 0.15em solid #999; + margin-bottom: 0.15em; + margin-top: 0.15em; +} +div.footnote-group { + margin-left: 1em; +} +div.footnote-label { + display: inline-block; + min-width: 1.7em; +} + +div.option-list { + border: 0.1em solid var(--border); +} +div.option-list-item { + padding-left: 12em; + padding-right: 0; + padding-bottom: 0.3em; + padding-top: 0.3em; +} +div.odd { + background-color: var(--secondary-background); +} +div.option-list-label { + margin-left: -11.5em; + margin-right: 0em; + min-width: 11.5em; + display: inline-block; + vertical-align: top; +} +div.option-list-description { + width: calc(100% - 1em); + padding-left: 1em; + padding-right: 0; + display: inline-block; +} + +blockquote { + font-size: 0.9em; + font-style: italic; + padding-left: 0.5em; + margin-left: 0; + border-left: 5px solid #bbc; +} + +blockquote.markdown-quote { + font-size: 0.9rem; /* use rem to avoid recursion */ + font-style: normal; +} + +.pre, span.tok { + font-family: "Source Code Pro", Monaco, Menlo, Consolas, "Courier New", monospace; + font-weight: 500; + font-size: 0.85em; + color: var(--text); + background-color: var(--third-background); + padding-left: 3px; + padding-right: 3px; + border-radius: 4px; +} + +span.tok { + border: 1px solid #808080; + padding-bottom: 0.1em; + margin-right: 0.2em; +} + +.copyToClipBoard { + position: relative; +} + +pre { + font-family: "Source Code Pro", Monaco, Menlo, Consolas, "Courier New", monospace; + color: var(--text); + font-weight: 500; + display: inline-block; + box-sizing: border-box; + min-width: 100%; + padding: 0.5em; + margin-top: 0.5em; + margin-bottom: 0.5em; + font-size: 0.85em; + white-space: pre !important; + overflow-y: hidden; + overflow-x: visible; + background-color: var(--secondary-background); + border: 1px solid var(--border); + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} + +.copyToClipBoardBtn { + visibility: hidden; + position: absolute; + width: 24px; + border-radius: 4px; + background-image: var(--clipboard-image); + right: 5px; + top: 13px; + background-color: var(--secondary-background); + padding: 11px; + border: 0; +} + +.copyToClipBoard:hover .copyToClipBoardBtn { + visibility: visible; +} + +.pre-scrollable { + max-height: 340px; + overflow-y: scroll; } + + +/* Nim line-numbered tables */ +.line-nums-table { + width: 100%; + table-layout: fixed; } + +table.line-nums-table { + border-radius: 4px; + border: 1px solid var(--border); + background-color: var(--secondary-background); + border-collapse: separate; + margin-top: 15px; + margin-bottom: 25px; } + +.line-nums-table tbody { + border: none; } + +.line-nums-table td pre { + border: none; + background-color: transparent; } + +.line-nums-table td.blob-line-nums { + width: 28px; } + +.line-nums-table td.blob-line-nums pre { + color: #b0b0b0; + -webkit-filter: opacity(75%); + filter: opacity(75%); + text-align: right; + border-color: transparent; + background-color: transparent; + padding-left: 0px; + margin-left: 0px; + padding-right: 0px; + margin-right: 0px; } + + +table { + max-width: 100%; + background-color: transparent; + margin-top: 0.5em; + margin-bottom: 1.5em; + border-collapse: collapse; + border-color: var(--third-background); + border-spacing: 0; +} + +table:not(.line-nums-table) { + font-size: 0.9em; +} + +table th, table td { + padding: 0px 0.5em 0px; + border-color: var(--third-background); +} + +table th { + background-color: var(--third-background); + border-color: var(--third-background); + font-weight: bold; } + +table th.docinfo-name { + background-color: transparent; + text-align: right; +} + +table:not(.line-nums-table) tr:hover { + background-color: var(--third-background); } + + +/* rst2html default used to remove borders from tables and images */ +.borderless, table.borderless td, table.borderless th { + border: 0; } + +table.borderless td, table.borderless th { + /* Override padding for "table.docutils td" with "! important". + The right padding separates the table cells. */ + padding: 0 0.5em 0 0 !important; } + +.admonition { + padding: 0.3em; + background-color: var(--secondary-background); + border-left: 0.4em solid #7f7f84; + margin-bottom: 0.5em; + -webkit-box-shadow: 0 5px 8px -6px rgba(0,0,0,.2); + -moz-box-shadow: 0 5px 8px -6px rgba(0,0,0,.2); + box-shadow: 0 5px 8px -6px rgba(0,0,0,.2); +} +.admonition-info { + border-color: var(--info-background); +} +.admonition-info-text { + color: var(--info-background); +} +.admonition-warning { + border-color: var(--warning-background); +} +.admonition-warning-text { + color: var(--warning-background); +} +.admonition-error { + border-color: var(--error-background); +} +.admonition-error-text { + color: var(--error-background); +} + +.first { + /* Override more specific margin styles with "! important". */ + margin-top: 0 !important; } + +.last, .with-subtitle { + margin-bottom: 0 !important; } + +.hidden { + display: none; } + +blockquote.epigraph { + margin: 2em 5em; } + +dl.docutils dd { + margin-bottom: 0.5em; } + +object[type="image/svg+xml"], object[type="application/x-shockwave-flash"] { + overflow: hidden; } + + +div.figure { + margin-left: 2em; + margin-right: 2em; } + +div.footer, div.header { + clear: both; + text-align: center; + color: #666; + font-size: smaller; } + +div.footer { + padding-top: 5em; } + +div.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; } + +div.line-block div.line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; } + +div.topic { + margin: 2em; } + +div.search_results { + background-color: var(--third-background); + margin: 3vh 5vw; + padding: 1em; + border: 1px solid #4d4d4d; + position: fixed; + top: 10px; + isolation: isolate; + max-width: calc(100vw - 6em); + z-index: 1; + max-height: calc(100vh - 6em); + overflow-y: scroll;} + +div#global-links ul { + margin-left: 0; + list-style-type: none; } + +div#global-links > simple-boot { + margin-left: 3em; } + +hr.docutils { + width: 75%; } + +img.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; } + +img.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; } + +img.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; } + +.align-left { + text-align: left; } + +.align-center { + clear: both; + text-align: center; } + +.align-right { + text-align: right; } + +/* reset inner alignment in figures */ +div.align-right { + text-align: inherit; } + +p.attribution { + text-align: right; + margin-left: 50%; } + +p.caption { + font-style: italic; } + +p.credits { + font-style: italic; + font-size: smaller; } + +p.label { + white-space: nowrap; } + +p.rubric { + font-weight: bold; + font-size: larger; + color: maroon; + text-align: center; } + +p.topic-title { + font-weight: bold; } + +pre.address { + margin-bottom: 0; + margin-top: 0; + font: inherit; } + +pre.literal-block, pre.doctest-block, pre.math, pre.code { + margin-left: 2em; + margin-right: 2em; } + +pre.code .ln { + color: grey; } + +/* line numbers */ +pre.code, code { + background-color: #eeeeee; } + +pre.code .comment, code .comment { + color: #5c6576; } + +pre.code .keyword, code .keyword { + color: #3B0D06; + font-weight: bold; } + +pre.code .literal.string, code .literal.string { + color: #0c5404; } + +pre.code .name.builtin, code .name.builtin { + color: #352b84; } + +pre.code .deleted, code .deleted { + background-color: #DEB0A1; } + +pre.code .inserted, code .inserted { + background-color: #A3D289; } + +span.classifier { + font-style: oblique; } + +span.classifier-delimiter { + font-weight: bold; } + +span.problematic { + color: #b30000; } + +span.section-subtitle { + /* font-size relative to parent (h1..h6 element) */ + font-size: 80%; } + +span.DecNumber { + color: var(--number); } + +span.BinNumber { + color: var(--number); } + +span.HexNumber { + color: var(--number); } + +span.OctNumber { + color: var(--number); } + +span.FloatNumber { + color: var(--number); } + +span.Identifier { + color: var(--identifier); } + +span.Keyword { + font-weight: 600; + color: var(--keyword); } + +span.StringLit { + color: var(--literal); } + +span.LongStringLit { + color: var(--literal); } + +span.CharLit { + color: var(--literal); } + +span.EscapeSequence { + color: var(--escapeSequence); } + +span.Operator { + color: var(--operator); } + +span.Punctuation { + color: var(--punctuation); } + +span.Comment, span.LongComment { + font-style: italic; + font-weight: 400; + color: var(--comment); } + +span.RegularExpression { + color: darkviolet; } + +span.TagStart { + color: darkviolet; } + +span.TagEnd { + color: darkviolet; } + +span.Key { + color: #252dbe; } + +span.Value { + color: #252dbe; } + +span.RawData { + color: var(--raw-data); } + +span.Assembler { + color: #252dbe; } + +span.Preprocessor { + color: #252dbe; } + +span.Directive { + color: #252dbe; } + +span.option { + font-weight: bold; + font-family: "Source Code Pro", Monaco, Menlo, Consolas, "Courier New", monospace; + color: var(--option); } + +span.Prompt { + font-weight: bold; + color: red; } + +span.ProgramOutput { + font-weight: bold; + color: #808080; } + +span.program { + font-weight: bold; + color: var(--program); + text-decoration: underline; + text-decoration-color: var(--hint); + text-decoration-thickness: 0.05em; + text-underline-offset: 0.15em; } + +span.Command, span.Rule, span.Hyperlink, +span.Label, span.Reference, span.Other { + color: var(--other); } + +/* Pop type, const, proc, and iterator defs in nim def blocks */ +dt pre > span.Identifier, dt pre > span.Operator { + color: var(--identifier); + font-weight: 700; } + +dt pre > span.Keyword ~ span.Identifier, dt pre > span.Identifier ~ span.Identifier, +dt pre > span.Operator ~ span.Identifier, dt pre > span.Other ~ span.Identifier { + color: var(--identifier); + font-weight: inherit; } + +/* Nim sprite for the footer (taken from main page favicon) */ +.nim-sprite { + display: inline-block; + width: 51px; + height: 14px; + background-position: 0 0; + background-size: 51px 14px; + -webkit-filter: opacity(50%); + filter: opacity(50%); + background-repeat: no-repeat; + background-image: var(--nim-sprite-base64); + margin-bottom: 5px; } + +span.pragmadots { + /* Position: relative frees us up to make the dots + look really nice without fucking up the layout and + causing bulging in the parent container */ + position: relative; + /* 1px down looks slightly nicer */ + top: 1px; + padding: 2px; + background-color: var(--third-background); + border-radius: 4px; + margin: 0 2px; + cursor: pointer; + font-size: 0.8em; } + +span.pragmadots:hover { + background-color: var(--hint); } + +span.pragmawrap { + display: none; } + +span.attachedType { + display: none; + visibility: hidden; } diff --git a/nimgrep.html b/nimgrep.html new file mode 100644 index 0000000000000..00aaa55bca2dd --- /dev/null +++ b/nimgrep.html @@ -0,0 +1,228 @@ + + + + + + + +nimgrep User's manual + + + + + + + + + + + + + + + + +
+
+

nimgrep User's manual

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + + +
+
+ Source   +Edit   + +
+ +

+ +
Author:Andreas Rumpf
Version:1.6.0

Nimgrep is a command line tool for search and replace tasks. It can search for regex or peg patterns and can search whole directories at once. User confirmation for every single replace operation can be requested.

+

Nimgrep has particularly good support for Nim's eccentric style insensitivity (see option -y below). Apart from that it is a generic text manipulation tool.

+ +

Installation

Compile nimgrep with the command:

+

nim c -d:release tools/nimgrep.nim

+

And copy the executable somewhere in your $PATH.

+ +

Command line switches

Usage:
  • To search:
    nimgrep [options] PATTERN [(FILE/DIRECTORY)*/-]
    +
  • +
  • To replace:
    nimgrep [options] PATTERN --replace REPLACEMENT (FILE/DIRECTORY)*/-
    +
  • +
  • To list file names:
    nimgrep [options] --filenames [PATTERN] [(FILE/DIRECTORY)*]
    +
  • +
+

Positional arguments, from left to right:

+
  1. PATTERN is either Regex (default) or Peg if --peg is specified. PATTERN and REPLACEMENT should be skipped when --stdin is specified.
  2. +
  3. REPLACEMENT supports $1, $# notations for captured groups in PATTERN.
    Danger: +--replace mode DOES NOT ask confirmation unless --confirm is specified!
    +
  4. +
  5. Final arguments are a list of paths (FILE/DIRECTORY) or a standalone minus - or not specified (empty):
    • empty, current directory . is assumed (not with --replace)
      Note: +so when no FILE/DIRECTORY/- is specified nimgrep does not read the pipe, but searches files in the current dir instead!
      +
    • +
    • -, read buffer once from stdin: pipe or terminal input; in --replace mode the result is directed to stdout; it's not compatible with --stdin, --filenames, or --confirm
    • +
    +

    For any given DIRECTORY nimgrep searches only its immediate files without traversing subdirectories unless --recursive is specified.

    +
  6. +
+

In replacement mode we require all 3 positional arguments to avoid damaging.

+

Options:

+
  • Mode of operation:
    --find, -f
    find the PATTERN (default)
    +
    --replace, -!
    replace the PATTERN to REPLACEMENT, rewriting the files
    +
    --confirm
    confirm each occurrence/replacement; there is a chance to abort any time without touching the file
    +
    --filenames
    just list filenames. Provide a PATTERN to find it in the filenames (not in the contents of a file) or run with empty pattern to just list all files:
    nimgrep --filenames               # In current dir
    +nimgrep --filenames "" DIRECTORY
    + # Note empty pattern "", lists all files in DIRECTORY
    +
    +
  • +
  • Interprete patterns:
    --peg
    PATTERN and PAT are Peg
    +
    --re
    PATTERN and PAT are regular expressions (default)
    +
    --rex, -x
    use the "extended" syntax for the regular expression so that whitespace is not significant
    +
    --word, -w
    matches should have word boundaries (buggy for pegs!)
    +
    --ignoreCase, -i
    be case-insensitive in PATTERN and PAT
    +
    --ignoreStyle, -y
    be style insensitive in PATTERN and PAT
    +
    Note: +PATTERN and patterns PAT (see below in other options) are all either Regex or Peg simultaneously and options --rex, --word, --ignoreCase, and --ignoreStyle are applied to all of them.
    +
  • +
  • File system walk:
    --recursive, -r
    process directories recursively
    +
    --follow
    follow all symlinks when processing recursively
    +
    --sortTime, -s[:asc|desc]
    order files by the last modification time (default: off): ascending (recent files go last) or descending
    +
  • +
  • Filter files (based on filesystem paths):
    Hint: +Instead of not you can type just n for negative options below.
    +
    --ex[tensions]:EX1|EX2|...
    only search the files with the given extension(s), empty one (--ex) means files with missing extension
    +
    --notex[tensions]:EX1|EX2|...
    exclude files having given extension(s), use empty one to skip files with no extension (like some binary files are)
    +
    --fi[lename]:PAT
    search only files whose name matches pattern PAT
    +
    --notfi[lename]:PAT
    skip files whose name matches pattern PAT
    +
    --di[rname]:PAT
    select files that in their path have a directory name that matches pattern PAT
    +
    --notdi[rname]:PAT
    do not descend into directories whose name (not path) matches pattern PAT
    +
    --dirp[ath]:PAT
    select only files whose whole relative directory path matches pattern PAT
    +
    --notdirp[ath]:PAT
    skip files whose whole relative directory path matches pattern PAT
    +
  • +
  • Filter files (based on file contents):
    --inF[ile]:PAT
    select files containing a (not displayed) match of PAT
    +
    --notinF[ile]:PAT
    skip files containing a match of PAT
    +
    --bin:on|off|only
    process binary files? (detected by 0 in first 1K bytes) (default: on - binary and text files treated the same way)
    +
    --text, -t
    process only text files, the same as --bin:off
    +
  • +
  • Filter matches:
    --inC[ontext]:PAT
    select only matches containing a match of PAT in their surrounding context (multiline with -c, -a, -b)
    +
    --notinC[ontext]:PAT
    skip matches not containing a match of PAT in their surrounding context
    +
  • +
  • Represent results:
    --nocolor
    output will be given without any colors
    +
    --color[:on]
    force color even if output is redirected (default: auto)
    +
    --colorTheme:THEME
    select color THEME from simple (default), bnw (black and white), ack, or gnu (GNU grep)
    +
    --count
    only print counts of matches for files that matched
    +
    --context:N, -c:N
    print N lines of leading context before every match and N lines of trailing context after it (default N: 0)
    +
    --afterContext:N, -a:N
    print N lines of trailing context after every match
    +
    --beforeContext:N, -b:N
    print N lines of leading context before every match
    +
    --group, -g
    group matches by file
    +
    --newLine, -l
    display every matching line starting from a new line
    +
    --cols[:N]
    limit max displayed columns/width of output lines from files by N characters, cropping overflows (default: off)
    +
    --cols:auto, -%
    calculate columns from terminal width for every line
    +
    --onlyAscii, -@
    display only printable ASCII Latin characters 0x20-0x7E substitutions: 0 -> ^@, 1 -> ^A, ... 0x1F -> ^_, 0x7F -> '7F, ..., 0xFF -> 'FF
    +
  • +
  • Miscellaneous:
    --threads:N, -j:N
    speed up search by N additional workers (default: 0, off)
    +
    --stdin
    read PATTERN from stdin (to avoid the shell's confusing quoting rules) and, if --replace given, REPLACEMENT
    +
    --verbose
    be verbose: list every processed file
    +
    --help, -h
    shows this help
    +
    --version, -v
    shows the version
    +
  • +
+ +

Path filter options

Let us assume we have file dirA/dirB/dirC/file.nim. Filesystem path options will match for these parts of the path:

+ + + + + +
optionmatches for
--[not]extensionsnim
--[not]filenamefile.nim
--[not]dirnamedirA and dirB and dirC
--[not]dirpathdirA/dirB/dirC
+

Combining multiple filter options together and negating them

Options for filtering can be provided multiple times so they form a list, which works as:

+
  • positive filters --filename, --dirname, --dirpath, --inContext, --inFile accept files/matches if any pattern from the list is hit
  • +
  • negative filters --notfilename, --notdirname, --notdirpath, --notinContext, --notinFile accept files/matches if no pattern from the list is hit.
  • +
+

In other words the same filtering option repeated many times means logical OR.

+
Important: +Different filtering options are related by logical AND: they all must be true for a match to be accepted. E.g. --filename:F --dirname:D1 --notdirname:D2 means filename(F) AND dirname(D1) AND (NOT dirname(D2)).
+

So negative filtering patterns are effectively related by logical OR also: (NOT PAT1) AND (NOT PAT2) == NOT (PAT1 OR PAT2) in pseudo-code.

+

That means you can always use only 1 such an option with logical OR, e.g. --notdirname:PAT1 --notdirname:PAT2 is fully equivalent to --notdirname:'PAT1|PAT2'.

+
Note: +

If you want logical AND on patterns you should compose 1 appropriate pattern, possibly combined with multi-line mode (?s). E.g. to require that multi-line context of matches has occurrences of both PAT1 and PAT2 use positive lookaheads ((?=PAT)):

+

nimgrep --inContext:'(?s)(?=.*PAT1)(?=.*PAT2)'

+
+ +

Meaning of ^ and $

nimgrep PCRE engine is run in a single-line mode so ^ matches the beginning of whole input file and $ matches the end of file (or whole input string for options like --filename).

+

Add the (?m) modifier to the beginning of your pattern for ^ and $ to match the beginnings and ends of lines.

+ +

Examples

All examples below use default PCRE Regex patterns:

+
  • To search recursively in Nim files using style-insensitive identifiers:

    +

    nimgrep --recursive --ext:'nim|nims' --ignoreStyle
    +# short: -r --ext:'nim|nims' -y

    +
    Note: +we used ' quotes to avoid special treatment of | symbol for shells like Bash
    +
  • +
  • To exclude version control directories (Git, Mercurial=hg, Subversion=svn) from the search:

    +

    nimgrep --notdirname:'^\.git$' --notdirname:'^\.hg$' --notdirname:'^\.svn$'
    +# short: --ndi:'^\.git$' --ndi:'^\.hg$' --ndi:'^\.svn$'

    +
  • +
  • To search only in paths containing the tests sub-directory recursively:

    +

    nimgrep --recursive --dirname:'^tests$'
    +# short: -r --di:'^tests$'
    +# or using --dirpath:
    +nimgrep --recursive --dirpath:'(^|/)tests($|/)'
    +# short: -r --pa:'(^|/)tests($|/)'

    +
  • +
  • Nimgrep can search multi-line, e.g. to find files containing import and then strutils use pattern 'import(.|\n)*?strutils'.
  • +
+

+ +
+
+ + +
+
+ + + + diff --git a/nimgrep.idx b/nimgrep.idx new file mode 100644 index 0000000000000..5299701d6d173 --- /dev/null +++ b/nimgrep.idx @@ -0,0 +1,7 @@ +markupTitle nimgrep User's manual nimgrep.html nimgrep User's manual 0 +heading Installation nimgrep.html#installation Installation 0 +heading Command line switches nimgrep.html#command-line-switches Command line switches 0 +heading Path filter options nimgrep.html#command-line-switches-path-filter-options Path filter options 0 +heading Combining multiple filter options together and negating them nimgrep.html#command-line-switches-combining-multiple-filter-options-together-and-negating-them Combining multiple filter options together and negating them 0 +heading Meaning of ^ and $ nimgrep.html#meaning-of-roof-and-dollar Meaning of ^ and $ 0 +heading Examples nimgrep.html#examples Examples 0 diff --git a/nimhcr.html b/nimhcr.html new file mode 100644 index 0000000000000..7977a6a16622e --- /dev/null +++ b/nimhcr.html @@ -0,0 +1,365 @@ + + + + + + + +nimhcr + + + + + + + + + + + + + + + + +
+
+

nimhcr

+
+ +
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
HcrModuleInitializer = proc () {.nimcall.}
+
+ + + Source   +Edit   + +
+
+
+
HcrProcGetter = proc (libHandle: pointer; procName: cstring): pointer {.nimcall.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc hcrAddEventHandler(isBefore: bool; cb: proc () {.nimcall.}) {.compilerproc,
+    exportc, dynlib, ...raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hcrAddModule(module: cstring) {.compilerproc, exportc, dynlib, ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hcrGeneration(): int {.compilerproc, exportc, dynlib, ...raises: [], tags: [],
+                            forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hcrGetGlobal(module: cstring; name: cstring): pointer {.compilerproc,
+    exportc, dynlib, ...raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hcrGetProc(module: cstring; name: cstring): pointer {.compilerproc,
+    exportc, dynlib, ...raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hcrHasModuleChanged(moduleHash: string): bool {.compilerproc, exportc,
+    dynlib, ...raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hcrInit(moduleList: ptr pointer; main, sys: cstring;
+             datInit: HcrModuleInitializer; handle: pointer; gpa: HcrProcGetter) {.
+    compilerproc, exportc, dynlib, ...raises: [KeyError, Exception, LibraryError], tags: [
+    ReadDirEffect, ReadIOEffect, WriteIOEffect, WriteDirEffect, RootEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hcrMarkGlobals() {.compilerproc, exportc, dynlib, nimcall, ...gcsafe,
+                        raises: [], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hcrPerformCodeReload() {.compilerproc, exportc, dynlib,
+                              ...raises: [KeyError, Exception, LibraryError], tags: [
+    RootEffect, ReadDirEffect, ReadIOEffect, WriteIOEffect, WriteDirEffect],
+                              forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hcrRegisterGlobal(module: cstring; name: cstring; size: Natural;
+                       gcMarker: HcrGcMarkerProc; outPtr: ptr pointer): bool {.
+    compilerproc, exportc, dynlib, ...raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hcrRegisterProc(module: cstring; name: cstring; fn: pointer): pointer {.
+    compilerproc, exportc, dynlib, ...raises: [KeyError, OSError], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hcrReloadNeeded(): bool {.compilerproc, exportc, dynlib,
+                               ...raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/nimhcr.idx b/nimhcr.idx new file mode 100644 index 0000000000000..027a7a4f9cd40 --- /dev/null +++ b/nimhcr.idx @@ -0,0 +1,15 @@ +nimTitle nimhcr nimhcr.html module nimhcr 0 +nim HcrProcGetter nimhcr.html#HcrProcGetter type HcrProcGetter 214 +nim HcrModuleInitializer nimhcr.html#HcrModuleInitializer type HcrModuleInitializer 216 +nim hcrRegisterProc nimhcr.html#hcrRegisterProc,cstring,cstring,pointer proc hcrRegisterProc(module: cstring; name: cstring; fn: pointer): pointer 334 +nim hcrGetProc nimhcr.html#hcrGetProc,cstring,cstring proc hcrGetProc(module: cstring; name: cstring): pointer 356 +nim hcrRegisterGlobal nimhcr.html#hcrRegisterGlobal,cstring,cstring,Natural,HcrGcMarkerProc,ptr.pointer proc hcrRegisterGlobal(module: cstring; name: cstring; size: Natural;\n gcMarker: HcrGcMarkerProc; outPtr: ptr pointer): bool 360 +nim hcrGetGlobal nimhcr.html#hcrGetGlobal,cstring,cstring proc hcrGetGlobal(module: cstring; name: cstring): pointer 388 +nim hcrInit nimhcr.html#hcrInit,ptr.pointer,cstring,cstring,HcrModuleInitializer,pointer,HcrProcGetter proc hcrInit(moduleList: ptr pointer; main, sys: cstring;\n datInit: HcrModuleInitializer; handle: pointer; gpa: HcrProcGetter) 521 +nim hcrHasModuleChanged nimhcr.html#hcrHasModuleChanged,string proc hcrHasModuleChanged(moduleHash: string): bool 539 +nim hcrReloadNeeded nimhcr.html#hcrReloadNeeded proc hcrReloadNeeded(): bool 543 +nim hcrPerformCodeReload nimhcr.html#hcrPerformCodeReload proc hcrPerformCodeReload() 549 +nim hcrAddEventHandler nimhcr.html#hcrAddEventHandler,bool,proc) proc hcrAddEventHandler(isBefore: bool; cb: proc () {.nimcall.}) 605 +nim hcrAddModule nimhcr.html#hcrAddModule,cstring proc hcrAddModule(module: cstring) 609 +nim hcrGeneration nimhcr.html#hcrGeneration proc hcrGeneration(): int 613 +nim hcrMarkGlobals nimhcr.html#hcrMarkGlobals proc hcrMarkGlobals() 616 diff --git a/niminst.html b/niminst.html new file mode 100644 index 0000000000000..0b36c0d2d1dc6 --- /dev/null +++ b/niminst.html @@ -0,0 +1,334 @@ + + + + + + + +niminst User's manual + + + + + + + + + + + + + + + + +
+
+

niminst User's manual

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + + +
+
+ Source   +Edit   + +
+ +

+ +
Author:Andreas Rumpf
Version:2.2.1
+

Introduction

niminst is a tool to generate an installer for a Nim program. Currently it can create an installer for Windows via Inno Setup as well as installation/deinstallation scripts for UNIX. Later versions will support Linux' package management systems.

+

niminst works by reading a configuration file that contains all the information that it needs to generate an installer for the different operating systems.

+ +

Configuration file

niminst uses the Nim parsecfg module to parse the configuration file. Here's an example of how the syntax looks like:

+
# This is a comment.
+; this too.
+
+[Common]
+cc=gcc     # '=' and ':' are the same
+--foo="bar"   # '--cc' and 'cc' are the same, 'bar' and '"bar"' are the same (except for '#')
+macrosym: "#"  # Note that '#' is interpreted as a comment without the quotation
+--verbose
+
+[Windows]
+isConsoleApplication=False ; another comment
+
+[Posix]
+isConsoleApplication=True
+
+key1: "in this string backslash escapes are interpreted\n"
+key2: r"in this string not"
+key3: """triple quotes strings
+are also supported. They may span
+multiple lines."""
+
+--"long option with spaces": r"c:\myfiles\test.txt" 
+
+

The value of a key-value pair can reference user-defined variables via the $variable notation: They can be defined in the command line with the --var:name=value switch. This is useful to not hard-coding the program's version number into the configuration file, for instance.

+

It follows a description of each possible section and how it affects the generated installers.

+ +

Project section

The project section gathers general information about your project. It must contain the following key-value pairs:

+ + + + + + + + + + +
Keydescription
Namethe project's name; this needs to be a single word
DisplayNamethe project's long name; this can contain spaces. If not specified, this is the same as Name.
Versionthe project's version
OSthe OSes to generate C code for; for example: "windows;linux;macosx"
CPUthe CPUs to generate C code for; for example: "i386;amd64;powerpc"
Authorsthe project's authors
Descriptionthe project's description
Appthe application's type: "Console" or "GUI". If "Console", niminst generates a special batch file for Windows to open up the command-line shell.
Licensethe filename of the application's license
+

files key

Many sections support the files key. Listed filenames can be separated by semicolon or the files key can be repeated. Wildcards in filenames are supported. If it is a directory name, all files in the directory are used:

+
[Config]
+Files: "configDir"
+Files: "otherconfig/*.conf;otherconfig/*.cfg"
+ +

Config section

The config section currently only supports the files key. Listed files will be installed into the OS's configuration directory.

+ +

Documentation section

The documentation section supports the files key. Listed files will be installed into the OS's native documentation directory (which might be $appdir/doc).

+

There is a start key which determines whether the Windows installer generates a link to e.g. the index.html of your documentation.

+ +

Other section

The other section currently only supports the files key. Listed files will be installed into the application installation directory ($appdir).

+ +

Lib section

The lib section currently only supports the files key. Listed files will be installed into the OS's native library directory (which might be $appdir/lib).

+ +

Windows section

The windows section supports the files key for Windows-specific files. Listed files will be installed into the application installation directory ($appdir).

+

Other possible options are:

+ + + +
Keydescription
BinPathpaths to add to the Windows %PATH% environment variable. Example: BinPath: r"bin;dist\mingw\bin"
InnoSetupboolean flag whether an Inno Setup installer should be generated for Windows. Example: InnoSetup: "Yes"
+

UnixBin section

The UnixBin section currently only supports the files key. Listed files will be installed into the OS's native bin directory (e.g. /usr/local/bin). The exact location depends on the installation path the user specifies when running the install.sh script.

+ +

Unix section

Possible options are:

+ + + +
Keydescription
InstallScriptboolean flag whether an installation shell script should be generated. Example: InstallScript: "Yes"
UninstallScriptboolean flag whether a de-installation shell script should be generated. Example: UninstallScript: "Yes"
+

InnoSetup section

Possible options are:

+ + + +
Keydescription
pathPath to Inno Setup. Example: path = r"c:\inno setup 5\iscc.exe"
flagsFlags to pass to Inno Setup. Example: flags = "/Q"
+

C_Compiler section

Possible options are:

+ + + +
Keydescription
pathPath to the C compiler.
flagsFlags to pass to the C Compiler. Example: flags = "-w"
+

Real-world example

The installers for the Nim compiler itself are generated by niminst. Have a look at its configuration file:

+
; This config file holds configuration information about the Nim compiler
+; and project.
+
+[Project]
+Name: "Nim"
+Version: "$version"
+Platforms: """
+  windows: i386;amd64
+  linux: i386;hppa;ia64;alpha;amd64;powerpc64;arm;sparc;sparc64;m68k;mips;mipsel;mips64;mips64el;powerpc;powerpc64el;arm64;riscv32;riscv64;loongarch64
+  macosx: i386;amd64;powerpc64;arm64
+  solaris: i386;amd64;sparc;sparc64
+  freebsd: i386;amd64;powerpc64;arm;arm64;riscv64;sparc64;mips;mipsel;mips64;mips64el;powerpc;powerpc64el
+  netbsd: i386;amd64;arm64
+  openbsd: i386;amd64;arm;arm64
+  dragonfly: i386;amd64
+  crossos: amd64
+  haiku: i386;amd64
+  android: i386;arm;arm64
+  nintendoswitch: arm64
+"""
+
+Authors: "Andreas Rumpf"
+Description: """This is the Nim Compiler. Nim is a new statically typed,
+imperative programming language, that supports procedural, functional, object
+oriented and generic programming styles while remaining simple and efficient.
+A special feature that Nim inherited from Lisp is that Nim's abstract
+syntax tree (AST) is part of the specification - this allows a powerful macro
+system which can be used to create domain specific languages.
+
+Nim is a compiled, garbage-collected systems programming language
+which has an excellent productivity/performance ratio. Nim's design
+focuses on the 3E: efficiency, expressiveness, elegance (in the order of
+priority)."""
+
+App: Console
+License: "copying.txt"
+
+[Config]
+Files: "config/*.cfg"
+Files: "config/config.nims"
+
+[Documentation]
+; Files: "doc/*.html"
+; Files: "doc/*.cfg"
+; Files: "doc/*.pdf"
+; Files: "doc/*.ini"
+Files: "doc/html/overview.html"
+Start: "doc/html/overview.html"
+
+
+[Other]
+Files: "copying.txt"
+Files: "koch.nim"
+
+Files: "icons/nim.ico"
+Files: "icons/nim.rc"
+Files: "icons/nim.res"
+Files: "icons/nim_icon.o"
+Files: "icons/koch.ico"
+Files: "icons/koch.rc"
+Files: "icons/koch.res"
+Files: "icons/koch_icon.o"
+
+Files: "compiler"
+Files: "doc"
+Files: "doc/html"
+Files: "tools"
+Files: "tools/debug/nim-gdb.py"
+Files: "nimpretty"
+Files: "testament"
+Files: "nimsuggest"
+Files: "nimsuggest/tests/*.nim"
+Files: "changelogs/*.md"
+Files: "ci/funs.sh"
+
+[Lib]
+Files: "lib"
+
+[Other]
+Files: "examples"
+Files: "dist/nimble"
+Files: "dist/checksums"
+
+Files: "tests"
+
+[Windows]
+Files: "bin/nim.exe"
+Files: "bin/nimgrep.exe"
+Files: "bin/nimsuggest.exe"
+Files: "bin/nimble.exe"
+Files: "bin/vccexe.exe"
+Files: "bin/nimgrab.exe"
+Files: "bin/nimpretty.exe"
+Files: "bin/testament.exe"
+Files: "bin/nim-gdb.bat"
+Files: "bin/atlas.exe"
+
+Files: "koch.exe"
+Files: "finish.exe"
+; Files: "bin/downloader.exe"
+
+; Files: "dist/mingw"
+Files: r"tools\start.bat"
+BinPath: r"bin;dist\mingw\bin;dist"
+
+;           Section | dir | zipFile | size hint (in KB) | url | exe start menu entry
+Download: r"Documentation|doc|docs.zip|13824|https://nim-lang.org/download/docs-${version}.zip|overview.html"
+Download: r"C Compiler (MingW)|dist|mingw.zip|82944|https://nim-lang.org/download/${mingw}.zip"
+Download: r"Support DLLs|bin|nim_dlls.zip|479|https://nim-lang.org/download/dlls.zip"
+Download: r"Aporia Text Editor|dist|aporia.zip|97997|https://nim-lang.org/download/aporia-0.4.0.zip|aporia-0.4.0\bin\aporia.exe"
+; for now only NSIS supports optional downloads
+
+[WinBin]
+Files: "bin/makelink.exe"
+Files: "bin/7zG.exe"
+Files: "bin/*.dll"
+Files: "bin/cacert.pem"
+
+[UnixBin]
+Files: "bin/nim"
+
+
+[Unix]
+InstallScript: "yes"
+UninstallScript: "yes"
+Files: "bin/nim-gdb"
+Files: "build_all.sh"
+
+
+[InnoSetup]
+path = r"c:\Program Files (x86)\Inno Setup 5\iscc.exe"
+flags = "/Q"
+
+[NSIS]
+flags = "/V0"
+
+[C_Compiler]
+path = r""
+flags = "-w"
+
+
+[deb]
+buildDepends: "gcc (>= 4:4.3.2)"
+pkgDepends: "gcc (>= 4:4.3.2)"
+shortDesc: "The Nim Compiler"
+licenses: "bin/nim,MIT;lib/*,MIT;"
+
+[nimble]
+pkgName: "nim"
+pkgFiles: "compiler/*;doc/basicopt.txt;doc/advopt.txt;doc/nimdoc.css;doc/nimdoc.cls"
+
+

+ +
+
+ + +
+
+ + + + diff --git a/niminst.idx b/niminst.idx new file mode 100644 index 0000000000000..f82f8df09e3b4 --- /dev/null +++ b/niminst.idx @@ -0,0 +1,15 @@ +markupTitle niminst User's manual niminst.html niminst User's manual 0 +heading Introduction niminst.html#introduction Introduction 0 +heading Configuration file niminst.html#configuration-file Configuration file 0 +heading Project section niminst.html#configuration-file-project-section Project section 0 +heading nimfiles key niminst.html#configuration-file-nimfiles-key files key 0 +heading Config section niminst.html#configuration-file-config-section Config section 0 +heading Documentation section niminst.html#configuration-file-documentation-section Documentation section 0 +heading Other section niminst.html#configuration-file-other-section Other section 0 +heading Lib section niminst.html#configuration-file-lib-section Lib section 0 +heading Windows section niminst.html#configuration-file-windows-section Windows section 0 +heading UnixBin section niminst.html#configuration-file-unixbin-section UnixBin section 0 +heading Unix section niminst.html#configuration-file-unix-section Unix section 0 +heading InnoSetup section niminst.html#configuration-file-innosetup-section InnoSetup section 0 +heading C_Compiler section niminst.html#configuration-file-c-compiler-section C_Compiler section 0 +heading Real-world example niminst.html#realminusworld-example Real-world example 0 diff --git a/nimprof.html b/nimprof.html new file mode 100644 index 0000000000000..18830def91724 --- /dev/null +++ b/nimprof.html @@ -0,0 +1,153 @@ + + + + + + + +std/nimprof + + + + + + + + + + + + + + + + +
+
+

std/nimprof

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Profiling support for Nim. This is an embedded profiler that requires --profiler:on. You only need to import this module to get a profiling report at program exit. See Embedded Stack Trace Profiler for usage.Timer support for the realtime GC. Based on https://github.com/jckarter/clay/blob/master/compiler/hirestimer.cpp

+ +
+

Procs

+
+
+
+
proc disableProfiling() {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc enableProfiling() {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setSamplingFrequency(intervalInUs: int) {....raises: [], tags: [], forbids: [].}
+
+ + set this to change the sampling frequency. Default value is 5ms. Set it to 0 to disable time based profiling; it uses an imprecise instruction count measure instead then. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/nimprof.idx b/nimprof.idx new file mode 100644 index 0000000000000..a102fdca72870 --- /dev/null +++ b/nimprof.idx @@ -0,0 +1,4 @@ +nimTitle nimprof nimprof.html module std/nimprof 0 +nim setSamplingFrequency nimprof.html#setSamplingFrequency,int proc setSamplingFrequency(intervalInUs: int) 64 +nim disableProfiling nimprof.html#disableProfiling proc disableProfiling() 217 +nim enableProfiling nimprof.html#enableProfiling proc enableProfiling() 222 diff --git a/nimrtl.html b/nimrtl.html new file mode 100644 index 0000000000000..d4f9c25ff2aee --- /dev/null +++ b/nimrtl.html @@ -0,0 +1,101 @@ + + + + + + + +nimrtl + + + + + + + + + + + + + + + + +
+
+

nimrtl

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Main file to generate a DLL from the standard library. The default Nimrtl does not only contain the system module, but these too:

  • parseutils
  • +
  • strutils
  • +
  • parseopt
  • +
  • parsecfg
  • +
  • strtabs
  • +
  • times
  • +
  • os
  • +
  • osproc
  • +
  • unicode
  • +
  • pegs
  • +
  • ropes
  • +
  • cstrutils
  • +
+

+ + +
+
+ + +
+
+ + + + diff --git a/nimrtl.idx b/nimrtl.idx new file mode 100644 index 0000000000000..624956c8987aa --- /dev/null +++ b/nimrtl.idx @@ -0,0 +1 @@ +nimTitle nimrtl nimrtl.html module nimrtl 0 diff --git a/nims.html b/nims.html new file mode 100644 index 0000000000000..3b1c52dfaf02f --- /dev/null +++ b/nims.html @@ -0,0 +1,220 @@ + + + + + + + +NimScript + + + + + + + + + + + + + + + + +
+
+

NimScript

+

Strictly speaking, NimScript is the subset of Nim that can be evaluated by Nim's builtin virtual machine (VM). This VM is used for Nim's compiletime function evaluation features.

+

The nim executable processes the .nims configuration files in the following directories (in this order; later files overwrite previous settings):

+
  1. If environment variable XDG_CONFIG_HOME is defined, $XDG_CONFIG_HOME/nim/config.nims or ~/.config/nim/config.nims (POSIX) or %APPDATA%/nim/config.nims (Windows). This file can be skipped with the --skipUserCfg command line option.
  2. +
  3. $parentDir/config.nims where $parentDir stands for any parent directory of the project file's path. These files can be skipped with the --skipParentCfg command line option.
  4. +
  5. $projectDir/config.nims where $projectDir stands for the project's path. This file can be skipped with the --skipProjCfg command line option.
  6. +
  7. A project can also have a project specific configuration file named $project.nims that resides in the same directory as $project.nim. This file can be skipped with the same --skipProjCfg command line option.
  8. +
+

For available procs and implementation details see nimscript.

+ +

Limitations

NimScript is subject to some limitations caused by the implementation of the VM (virtual machine):

+
  • Nim's FFI (foreign function interface) is not available in NimScript. This means that any stdlib module which relies on importc can not be used in the VM.
  • +
  • ptr operations are are hard to emulate with the symbolic representation the VM uses. They are available and tested extensively but there are bugs left.
  • +
  • var T function arguments rely on ptr operations internally and might also be problematic in some cases.
  • +
  • More than one level of ref is generally not supported (for example, the type ref ref int).
  • +
  • Multimethods are not available.
  • +
  • random.randomize() requires an int64 explicitly passed as argument, you must pass a Seed integer.
  • +
+ +

Standard library modules

At least the following standard library modules are available:

+ +

In addition to the standard Nim syntax (system module), NimScripts support the procs and templates defined in the nimscript module too.

+

See also:

+ + +

NimScript as a configuration file

A command-line switch --FOO is written as switch("FOO") in NimScript. Similarly, command-line --FOO:VAL translates to switch("FOO", "VAL").

+

Here are few examples of using the switch proc:

+

# command-line: --opt:size
+switch("opt", "size")
+# command-line: --define:release or -d:release
+switch("define", "release")
+# command-line: --forceBuild
+switch("forceBuild")
+# command-line: --hint[Conf]:off or --hint:Conf:off
+switch("hint", "[Conf]:off")

+

NimScripts also support -- templates for convenience, which look like command-line switches written as-is in the NimScript file. So the above example can be rewritten as:

+

--opt:size
+--define:release
+--forceBuild

+

Note: In general, the define switches can also be set in NimScripts using switch or --, as shown in above examples. Few define switches such as -d:strip, -d:lto and -d:lto_incremental cannot be set in NimScripts.

+ +

NimScript as a build tool

The task template that the system module defines allows a NimScript file to be used as a build tool. The following example defines a task build that is an alias for the c command:

+

task build, "builds an example":
+  setCommand "c"

+

In fact, as a convention the following tasks should be available:

+ + + + + +
TaskDescription
helpList all the available NimScript tasks along with their docstrings.
buildBuild the project with the required backend (c, cpp or js).
testsRuns the tests belonging to the project.
benchRuns benchmarks belonging to the project.

Look at the module distros for some support of the OS's native package managers.

+ +

Nimble integration

See the Nimble readme for more information.

+ +

Standalone NimScript

NimScript can also be used directly as a portable replacement for Bash and Batch files. Use nim myscript.nims to run myscript.nims. For example, installation of Nimble could be accomplished with this simple script:

+

mode = ScriptMode.Verbose
+
+var id = 0
+while dirExists("nimble" & $id):
+  inc id
+
+exec "git clone https://github.com/nim-lang/nimble.git nimble" & $id
+
+withDir "nimble" & $id & "/src":
+  exec "nim c nimble"
+
+mvFile "nimble" & $id & "/src/nimble".toExe, "bin/nimble".toExe

+

On Unix, you can also use the shebang #!/usr/bin/env nim, as long as your filename ends with .nims:

+

#!/usr/bin/env nim
+mode = ScriptMode.Silent
+
+echo "hello world"

+

Use #!/usr/bin/env -S nim e --hints:off to disable hints and relax the file extension constraint.

+ +

Benefits

+

Cross-Platform

It is a cross-platform scripting language that can run where Nim can run, e.g. you can not run Batch or PowerShell on Linux or Mac, the Bash for Linux might not run on Mac, there are no unit tests tools for Batch, etc.

+

NimScript can detect on which platform, operating system, architecture, and even which Linux distribution is running on, allowing the same script to support a lot of systems.

+

See the following (incomplete) example:

+

import std/distros
+
+# Architectures.
+if defined(amd64):
+  echo "Architecture is x86 64Bits"
+elif defined(i386):
+  echo "Architecture is x86 32Bits"
+elif defined(arm):
+  echo "Architecture is ARM"
+
+# Operating Systems.
+if defined(linux):
+  echo "Operating System is GNU Linux"
+elif defined(windows):
+  echo "Operating System is Microsoft Windows"
+elif defined(macosx):
+  echo "Operating System is Apple OS X"
+
+# Distros.
+if detectOs(Ubuntu):
+  echo "Distro is Ubuntu"
+elif detectOs(ArchLinux):
+  echo "Distro is ArchLinux"
+elif detectOs(Debian):
+  echo "Distro is Debian"

+ +

Uniform Syntax

The syntax, style, and rest of the ecosystem is the same as for compiled Nim, that means there is nothing new to learn, no context switch for developers.

+ +

Powerful Metaprogramming

NimScript can use Nim's templates, macros, types, concepts, effect tracking system, and more, you can create modules that work on compiled Nim and also on interpreted NimScript.

+

func will still check for side effects, debugEcho also works as expected, making it ideal for functional scripting metaprogramming.

+

This is an example of a third party module that uses macros and templates to translate text strings on unmodified NimScript:

+

import nimterlingua
+nimterlingua("translations.cfg")
+echo "cat"  # Run with -d:RU becomes "kot", -d:ES becomes "gato", ...

+

translations.cfg

+

[cat]
+ES = gato
+IT = gatto
+RU = kot
+FR = chat

+ + +

Graceful Fallback

Some features of compiled Nim may not work on NimScript, but often a graceful and seamless fallback degradation is used.

+

See the following NimScript:

+

if likely(true):
+  discard
+elif unlikely(false):
+  discard
+
+proc foo() {.compiletime.} = echo NimVersion
+
+static:
+  echo CompileDate

+

likely(), unlikely(), static: and {.compiletime.} will produce no code at all when run on NimScript, but still no error nor warning is produced and the code just works.

+ +

Evolving Scripting language

NimScript evolves together with Nim, occasionally new features might become available on NimScript, adapted from compiled Nim or added as new features on both.

+ +

Scripting Language with a Package Manager

You can create your own modules to be compatible with NimScript, and check Nimble to search for third party modules that may work on NimScript.

+ +

DevOps Scripting

You can use NimScript to deploy to production, run tests, build projects, do benchmarks, generate documentation, and all kinds of DevOps/SysAdmin specific tasks.

+ + + + + +
+
+ + + + diff --git a/nims.idx b/nims.idx new file mode 100644 index 0000000000000..410aa802c4cea --- /dev/null +++ b/nims.idx @@ -0,0 +1,15 @@ +markupTitle NimScript nims.html NimScript 0 +heading Limitations nims.html#limitations Limitations 0 +heading Standard library modules nims.html#standard-library-modules Standard library modules 0 +heading NimScript as a configuration file nims.html#nimscript-as-a-configuration-file NimScript as a configuration file 0 +heading NimScript as a build tool nims.html#nimscript-as-a-build-tool NimScript as a build tool 0 +heading Nimble integration nims.html#nimble-integration Nimble integration 0 +heading Standalone NimScript nims.html#standalone-nimscript Standalone NimScript 0 +heading Benefits nims.html#benefits Benefits 0 +heading Cross-Platform nims.html#crossminusplatform Cross-Platform 0 +heading Uniform Syntax nims.html#uniform-syntax Uniform Syntax 0 +heading Powerful Metaprogramming nims.html#powerful-metaprogramming Powerful Metaprogramming 0 +heading Graceful Fallback nims.html#graceful-fallback Graceful Fallback 0 +heading Evolving Scripting language nims.html#evolving-scripting-language Evolving Scripting language 0 +heading Scripting Language with a Package Manager nims.html#scripting-language-with-a-package-manager Scripting Language with a Package Manager 0 +heading DevOps Scripting nims.html#devops-scripting DevOps Scripting 0 diff --git a/nimscript.html b/nimscript.html new file mode 100644 index 0000000000000..b9fc7381199d2 --- /dev/null +++ b/nimscript.html @@ -0,0 +1,1254 @@ + + + + + + + +system/nimscript + + + + + + + + + + + + + + + + +
+
+

system/nimscript

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

To learn about scripting in Nim see NimScript

+
+

Types

+
+
+
ScriptMode {.pure.} = enum
+  Silent,                   ## Be silent.
+  Verbose,                  ## Be verbose.
+  Whatif                     ## Do not run commands, instead just echo what
+                             ## would have been done.
+
+ + Controls the behaviour of the script. + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
author: string
+
+ + Nimble support: The package's author. + Source   +Edit   + +
+
+
+
backend: string
+
+ + Nimble support: The package's backend. + Source   +Edit   + +
+
+
+
bin: seq[string] = @[]
+
+ + + Source   +Edit   + +
+
+
+
binDir: string
+
+ + Nimble support: The package's binary directory. + Source   +Edit   + +
+
+
+
description: string
+
+ + Nimble support: The package's description. + Source   +Edit   + +
+
+
+
installDirs: seq[string] = @[]
+
+ + + Source   +Edit   + +
+
+
+
installExt: seq[string] = @[]
+
+ + + Source   +Edit   + +
+
+
+
installFiles: seq[string] = @[]
+
+ + + Source   +Edit   + +
+
+
+
license: string
+
+ + Nimble support: The package's license. + Source   +Edit   + +
+
+
+
mode: ScriptMode
+
+ + Set this to influence how mkDir, rmDir, rmFile etc. behave + Source   +Edit   + +
+
+
+
packageName = ""
+
+ + Nimble support: Set this to the package name. It is usually not required to do that, nims' filename is the default. + Source   +Edit   + +
+
+
+
requiresData: seq[string] = @[]
+
+ + Exposes the list of requirements for read and write accesses. + Source   +Edit   + +
+
+
+
skipDirs: seq[string] = @[]
+
+ + + Source   +Edit   + +
+
+
+
skipExt: seq[string] = @[]
+
+ + + Source   +Edit   + +
+
+
+
skipFiles: seq[string] = @[]
+
+ + + Source   +Edit   + +
+
+
+
srcDir: string
+
+ + Nimble support: The package's source directory. + Source   +Edit   + +
+
+
+
version: string
+
+ + Nimble support: The package's version. + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
buildCPU {.magic: "BuildCPU".}: string = ""
+
+ + The CPU this build is running on. Can be different from system.hostCPU for cross compilations. + Source   +Edit   + +
+
+
+
buildOS {.magic: "BuildOS".}: string = ""
+
+ + The OS this build is running on. Can be different from system.hostOS for cross compilations. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc cd(dir: string) {....raises: [OSError], tags: [], forbids: [].}
+
+ +

Changes the current directory.

+

The change is permanent for the rest of the execution, since this is just a shortcut for os.setCurrentDir() . Use the withDir() template if you want to perform a temporary change only.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc cmpic(a, b: string): int {....raises: [], tags: [], forbids: [].}
+
+ + Compares a and b ignoring case. + Source   +Edit   + +
+
+ +
+
+
+
proc cpDir(from, to: string) {....raises: [OSError],
+                               tags: [ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + Copies the dir from to to. + Source   +Edit   + +
+
+ +
+
+
+
proc cpFile(from, to: string) {....raises: [OSError],
+                                tags: [ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + Copies the file from to to. + Source   +Edit   + +
+
+ +
+
+
+
proc cppDefine(define: string) {....raises: [], tags: [], forbids: [].}
+
+ + tell Nim that define is a C preprocessor #define and so always needs to be mangled. + Source   +Edit   + +
+
+ +
+
+
+
proc delEnv(key: string) {....tags: [WriteIOEffect], raises: [], forbids: [].}
+
+ + Deletes the environment variable named key. + Source   +Edit   + +
+
+ +
+
+
+
proc dirExists(dir: string): bool {....tags: [ReadIOEffect], raises: [],
+                                    forbids: [].}
+
+ + Checks if the directory dir exists. + Source   +Edit   + +
+
+ +
+
+
+
proc exec(command: string) {....raises: [OSError],
+                             tags: [ExecIOEffect, WriteIOEffect], forbids: [].}
+
+ + Executes an external process. If the external process terminates with a non-zero exit code, an OSError exception is raised. The command is executed relative to the current source path.
Note: +If you need a version of exec that returns the exit code and text output of the command, you can use system.gorgeEx.
+ + Source   +Edit   + +
+
+
+
proc exec(command: string; input: string; cache = "") {....raises: [OSError],
+    tags: [ExecIOEffect, WriteIOEffect], forbids: [].}
+
+ + Executes an external process. If the external process terminates with a non-zero exit code, an OSError exception is raised.
Warning: +This version of exec is executed relative to the nimscript module path, which affects how the command resolves relative paths. Thus it is generally better to use gorgeEx directly when you need more control over the execution environment or when working with commands that deal with relative paths.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc exists(key: string): bool {....raises: [], tags: [], forbids: [].}
+
+ + Checks for the existence of a configuration 'key' like 'gcc.options.always'. + Source   +Edit   + +
+
+ +
+
+
+
proc existsEnv(key: string): bool {....tags: [ReadIOEffect], raises: [],
+                                    forbids: [].}
+
+ + Checks for the existence of an environment variable named key. + Source   +Edit   + +
+
+ +
+
+
+
proc fileExists(filename: string): bool {....tags: [ReadIOEffect], raises: [],
+    forbids: [].}
+
+ + Checks if the file exists. + Source   +Edit   + +
+
+ +
+
+
+
proc findExe(bin: string): string {....raises: [], tags: [], forbids: [].}
+
+ + Searches for bin in the current working directory and then in directories listed in the PATH environment variable. Returns "" if the exe cannot be found. + Source   +Edit   + +
+
+ +
+
+
+
proc get(key: string): string {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves a configuration 'key' like 'gcc.options.always'. + Source   +Edit   + +
+
+ +
+
+
+
proc getCommand(): string {....raises: [], tags: [], forbids: [].}
+
+ + Gets the Nim command that the compiler has been invoked with, for example "c", "js", "build", "help". + Source   +Edit   + +
+
+ +
+
+
+
proc getCurrentDir(): string {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the current working directory. + Source   +Edit   + +
+
+ +
+
+
+
proc getEnv(key: string; default = ""): string {....tags: [ReadIOEffect],
+    raises: [], forbids: [].}
+
+ + Retrieves the environment variable of name key. + Source   +Edit   + +
+
+ +
+
+
+
proc hint(name: string; val: bool) {....raises: [], tags: [], forbids: [].}
+
+ + Disables or enables a specific hint. + Source   +Edit   + +
+
+ +
+
+
+
proc listDirs(dir: string): seq[string] {....raises: [OSError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + Lists all the subdirectories (non-recursively) in the directory dir. + Source   +Edit   + +
+
+ +
+
+
+
proc listFiles(dir: string): seq[string] {....raises: [OSError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + Lists all the files (non-recursively) in the directory dir. + Source   +Edit   + +
+
+ +
+
+
+
proc mkDir(dir: string) {....raises: [OSError], tags: [WriteIOEffect], forbids: [].}
+
+ + Creates the directory dir including all necessary subdirectories. If the directory already exists, no error is raised. + Source   +Edit   + +
+
+ +
+
+
+
proc mvDir(from, to: string) {....raises: [OSError],
+                               tags: [ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + Moves the dir from to to. + Source   +Edit   + +
+
+ +
+
+
+
proc mvFile(from, to: string) {....raises: [OSError],
+                                tags: [ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + Moves the file from to to. + Source   +Edit   + +
+
+ +
+
+
+
proc nimcacheDir(): string {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the location of 'nimcache'. + Source   +Edit   + +
+
+ +
+
+
+
proc paramCount(): int {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the number of command line parameters. + Source   +Edit   + +
+
+ +
+
+
+
proc paramStr(i: int): string {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the i'th command line parameter. + Source   +Edit   + +
+
+ +
+
+
+
proc patchFile(package, filename, replacement: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Overrides the location of a given file belonging to the passed package. If the replacement is not an absolute path, the path is interpreted to be local to the Nimscript file that contains the call to patchFile, Nim's --path is not used at all to resolve the filename! The compiler also performs path substitution on replacement.

+

Example:

+

patchFile("stdlib", "asyncdispatch", "patches/replacement")

+ + Source   +Edit   + +
+
+ +
+
+
+
proc projectDir(): string {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the absolute directory of the current project + Source   +Edit   + +
+
+ +
+
+
+
proc projectName(): string {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the name of the current project + Source   +Edit   + +
+
+ +
+
+
+
proc projectPath(): string {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the absolute path of the current project + Source   +Edit   + +
+
+ +
+
+
+
proc put(key, value: string) {....raises: [], tags: [], forbids: [].}
+
+ + Sets a configuration 'key' like 'gcc.options.always' to its value. + Source   +Edit   + +
+
+ +
+
+
+
proc putEnv(key, val: string) {....tags: [WriteIOEffect], raises: [], forbids: [].}
+
+ + Sets the value of the environment variable named key to val. + Source   +Edit   + +
+
+ +
+
+
+
proc readAllFromStdin(): string {....raises: [IOError], tags: [ReadIOEffect],
+                                  forbids: [].}
+
+ + Reads all data from stdin - blocks until EOF which happens when stdin is closed + Source   +Edit   + +
+
+ +
+
+
+
proc readLineFromStdin(): string {....raises: [IOError], tags: [ReadIOEffect],
+                                   forbids: [].}
+
+ + Reads a line of data from stdin - blocks until n or EOF which happens when stdin is closed + Source   +Edit   + +
+
+ +
+
+
+
proc requires(deps: varargs[string]) {....raises: [], tags: [], forbids: [].}
+
+ + Nimble support: Call this to set the list of requirements of your Nimble package. + Source   +Edit   + +
+
+ +
+
+
+
proc rmDir(dir: string; checkDir = false) {....raises: [OSError],
+    tags: [ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + Removes the directory dir. + Source   +Edit   + +
+
+ +
+
+
+
proc rmFile(file: string) {....raises: [OSError],
+                            tags: [ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + Removes the file. + Source   +Edit   + +
+
+ +
+
+
+
proc selfExe(): string {....deprecated: "Deprecated since v1.7; Use getCurrentCompilerExe",
+                         raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v1.7; Use getCurrentCompilerExe +
+ + Returns the currently running nim or nimble executable. + Source   +Edit   + +
+
+ +
+
+
+
proc selfExec(command: string) {....raises: [OSError],
+                                 tags: [ExecIOEffect, WriteIOEffect],
+                                 forbids: [].}
+
+ + Executes an external command with the current nim/nimble executable. Command must not contain the "nim " part. + Source   +Edit   + +
+
+ +
+
+
+
proc setCommand(cmd: string; project = "") {....raises: [], tags: [], forbids: [].}
+
+ + Sets the Nim command that should be continued with after this Nimscript has finished. + Source   +Edit   + +
+
+ +
+
+
+
proc switch(key: string; val = "") {....raises: [], tags: [], forbids: [].}
+
+ + Sets a Nim compiler command line switch, for example switch("checks", "on"). + Source   +Edit   + +
+
+ +
+
+
+
proc thisDir(): string {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the directory of the current nims script file. Its path is obtained via currentSourcePath (although, currently, currentSourcePath resolves symlinks, unlike thisDir). + Source   +Edit   + +
+
+ +
+
+
+
proc toDll(filename: string): string {....raises: [], tags: [], forbids: [].}
+
+ + On Windows adds ".dll" to filename, on Posix produces "lib$filename.so". + Source   +Edit   + +
+
+ +
+
+
+
proc toExe(filename: string): string {....raises: [], tags: [], forbids: [].}
+
+ + On Windows adds ".exe" to filename, else returns filename unmodified. + Source   +Edit   + +
+
+ +
+
+
+
proc warning(name: string; val: bool) {....raises: [], tags: [], forbids: [].}
+
+ + Disables or enables a specific warning. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template `--`(key, val: untyped)
+
+ +

A shortcut for switch Example:

+

--path:somePath # same as switch("path", "somePath")
+--path:"someOtherPath" # same as switch("path", "someOtherPath")
+--hint:"[Conf]:off" # same as switch("hint", "[Conf]:off")

+ + Source   +Edit   + +
+
+
+
template `--`(key: untyped)
+
+ +

A shortcut for switch Example:

+

--listCmd # same as switch("listCmd")

+ + Source   +Edit   + +
+
+ +
+
+
+
template task(name: untyped; description: string; body: untyped): untyped
+
+ +

Defines a task. Hidden tasks are supported via an empty description.

+

Example:

+

task build, "default build is via the C backend":
+  setCommand "c"

+

For a task named foo, this template generates a proc named fooTask. This is useful if you need to call one task in another in your Nimscript.

+

Example:

+

task foo, "foo":        # > nim foo
+  echo "Running foo"    # Running foo
+
+task bar, "bar":        # > nim bar
+  echo "Running bar"    # Running bar
+  fooTask()             # Running foo

+ + Source   +Edit   + +
+
+ +
+
+
+
template withDir(dir: string; body: untyped): untyped
+
+ +

Changes the current directory temporarily.

+

If you need a permanent change, use the cd() proc. Usage example:

+

# inside /some/path/
+withDir "foo":
+  # move to /some/path/foo/
+# back in /some/path/

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/nimscript.idx b/nimscript.idx new file mode 100644 index 0000000000000..c9d1dca4308cd --- /dev/null +++ b/nimscript.idx @@ -0,0 +1,72 @@ +nimTitle nimscript nimscript.html module system/nimscript 0 +nim buildOS nimscript.html#buildOS const buildOS 16 +nim buildCPU nimscript.html#buildCPU const buildCPU 20 +nim getCurrentDir nimscript.html#getCurrentDir proc getCurrentDir(): string 50 +nim paramStr nimscript.html#paramStr,int proc paramStr(i: int): string 59 +nim paramCount nimscript.html#paramCount proc paramCount(): int 63 +nim switch nimscript.html#switch,string,string proc switch(key: string; val = "") 67 +nim warning nimscript.html#warning,string,bool proc warning(name: string; val: bool) 72 +nim hint nimscript.html#hint,string,bool proc hint(name: string; val: bool) 77 +nim patchFile nimscript.html#patchFile,string,string,string proc patchFile(package, filename, replacement: string) 82 +nim getCommand nimscript.html#getCommand proc getCommand(): string 97 +nim setCommand nimscript.html#setCommand,string,string proc setCommand(cmd: string; project = "") 102 +nim cmpic nimscript.html#cmpic,string,string proc cmpic(a, b: string): int 110 +nim getEnv nimscript.html#getEnv,string,string proc getEnv(key: string; default = ""): string 114 +nim existsEnv nimscript.html#existsEnv,string proc existsEnv(key: string): bool 118 +nim putEnv nimscript.html#putEnv,string,string proc putEnv(key, val: string) 122 +nim delEnv nimscript.html#delEnv,string proc delEnv(key: string) 126 +nim fileExists nimscript.html#fileExists,string proc fileExists(filename: string): bool 130 +nim dirExists nimscript.html#dirExists,string proc dirExists(dir: string): bool 134 +nim selfExe nimscript.html#selfExe proc selfExe(): string 139 +nim toExe nimscript.html#toExe,string proc toExe(filename: string): string 143 +nim toDll nimscript.html#toDll,string proc toDll(filename: string): string 147 +nim `--` nimscript.html#--.t,untyped,untyped template `--`(key, val: untyped) 158 +nim `--` nimscript.html#--.t,untyped template `--`(key: untyped) 168 +nim ScriptMode nimscript.html#ScriptMode enum ScriptMode 177 +nim mode nimscript.html#mode var mode 184 +nim listDirs nimscript.html#listDirs,string proc listDirs(dir: string): seq[string] 200 +nim listFiles nimscript.html#listFiles,string proc listFiles(dir: string): seq[string] 205 +nim rmDir nimscript.html#rmDir,string proc rmDir(dir: string; checkDir = false) 210 +nim rmFile nimscript.html#rmFile,string proc rmFile(file: string) 216 +nim mkDir nimscript.html#mkDir,string proc mkDir(dir: string) 222 +nim mvFile nimscript.html#mvFile,string,string proc mvFile(from, to: string) 229 +nim mvDir nimscript.html#mvDir,string,string proc mvDir(from, to: string) 235 +nim cpFile nimscript.html#cpFile,string,string proc cpFile(from, to: string) 241 +nim cpDir nimscript.html#cpDir,string,string proc cpDir(from, to: string) 247 +nim exec nimscript.html#exec,string proc exec(command: string) 253 +nim exec nimscript.html#exec,string,string,string proc exec(command: string; input: string; cache = "") 267 +nim selfExec nimscript.html#selfExec,string proc selfExec(command: string) 283 +nim put nimscript.html#put,string,string proc put(key, value: string) 293 +nim get nimscript.html#get,string proc get(key: string): string 297 +nim exists nimscript.html#exists,string proc exists(key: string): bool 301 +nim nimcacheDir nimscript.html#nimcacheDir proc nimcacheDir(): string 306 +nim projectName nimscript.html#projectName proc projectName(): string 310 +nim projectDir nimscript.html#projectDir proc projectDir(): string 314 +nim projectPath nimscript.html#projectPath proc projectPath(): string 318 +nim thisDir nimscript.html#thisDir proc thisDir(): string 322 +nim cd nimscript.html#cd,string proc cd(dir: string) 328 +nim findExe nimscript.html#findExe,string proc findExe(bin: string): string 338 +nim withDir nimscript.html#withDir.t,string,untyped template withDir(dir: string; body: untyped): untyped 344 +nim cppDefine nimscript.html#cppDefine,string proc cppDefine(define: string) 368 +nim readLineFromStdin nimscript.html#readLineFromStdin proc readLineFromStdin(): string 381 +nim readAllFromStdin nimscript.html#readAllFromStdin proc readAllFromStdin(): string 387 +nim task nimscript.html#task.t,untyped,string,untyped template task(name: untyped; description: string; body: untyped): untyped 395 +nim packageName nimscript.html#packageName var packageName 431 +nim version nimscript.html#version var version 434 +nim author nimscript.html#author var author 435 +nim description nimscript.html#description var description 436 +nim license nimscript.html#license var license 437 +nim srcDir nimscript.html#srcDir var srcDir 438 +nim binDir nimscript.html#binDir var binDir 439 +nim backend nimscript.html#backend var backend 440 +nim skipDirs nimscript.html#skipDirs var skipDirs 442 +nim skipFiles nimscript.html#skipFiles var skipFiles 442 +nim skipExt nimscript.html#skipExt var skipExt 442 +nim installDirs nimscript.html#installDirs var installDirs 442 +nim installFiles nimscript.html#installFiles var installFiles 442 +nim installExt nimscript.html#installExt var installExt 442 +nim bin nimscript.html#bin var bin 442 +nim requiresData nimscript.html#requiresData var requiresData 444 +nim requires nimscript.html#requires,varargs[string] proc requires(deps: varargs[string]) 447 +nimgrp exec nimscript.html#exec-procs-all proc 253 +nimgrp -- nimscript.html#---templates-all template 158 diff --git a/nimsuggest.html b/nimsuggest.html new file mode 100644 index 0000000000000..2e063605ea351 --- /dev/null +++ b/nimsuggest.html @@ -0,0 +1,143 @@ + + + + + + + +Nim IDE Integration Guide + + + + + + + + + + + + + + + + +
+
+

Nim IDE Integration Guide

+
+
+
+ + +
+ +
+ Search: +
+
+ Group by: + +
+ + + +
+
+ Source   +Edit   + +
+ +

+ +
Author:Unknown
Version:2.2.1

Nim differs from many other compilers in that it is really fast, and being so fast makes it suited to provide external queries for text editors about the source code being written. Through the nimsuggest tool, any IDE can query a .nim source file and obtain useful information like definition of symbols or suggestions for completion.

+

This document will guide you through the available options. If you want to look at practical examples of nimsuggest support you can look at the various editor integrations already available.

+ +

Installation

Nimsuggest is part of Nim's core. Build it via:

+

koch nimsuggest

+ +

Nimsuggest invocation

Run it via nimsuggest --stdin --debug myproject.nim. Nimsuggest is a server that takes queries that are related to myproject. There is some support so that you can throw random .nim files which are not part of myproject at Nimsuggest too, but usually the query refer to modules/files that are part of myproject.

+

--stdin means that Nimsuggest reads the query from stdin. This is great for testing things out and playing with it but for an editor communication via sockets is more reasonable so that is the default. It listens to port 6000 by default.

+

Nimsuggest is basically a frontend for the nim compiler so --path flags and config files can be used to specify additional dependencies like nimsuggest --stdin --debug --path:"dependencies" myproject.nim.

+ +

Specifying the location of the query

Nimsuggest then waits for queries to process. A query consists of a cryptic 3 letter "command" def or con or sug or use followed by a location. A query location consists of:

+
file.nim
+
This is the name of the module or include file the query refers to.
+
dirtyfile.nim
+

This is optional.

+

The file parameter is enough for static analysis, but IDEs tend to have unsaved buffers where the user may still be in the middle of typing a line. In such situations the IDE can save the current contents to a temporary file and then use the dirtyfile.nim option to tell Nimsuggest that foobar.nim should be taken from temporary/foobar.nim.

+
+
line
+
An integer with the line you are going to query. For the compiler lines start at 1.
+
col
+
An integer with the column you are going to query. For the compiler columns start at 0.
+
+ +

Definitions

The def Nimsuggest command performs a query about the definition of a specific symbol. If available, Nimsuggest will answer with the type, source file, line/column information and other accessory data if available like a docstring. With this information an IDE can provide the typical Jump to definition where a user puts the cursor on a symbol or uses the mouse to select it and is redirected to the place where the symbol is located.

+

Since Nim is implemented in Nim, one of the nice things of this feature is that any user with an IDE supporting it can quickly jump around the standard library implementation and see exactly what a proc does, learning about the language and seeing real life examples of how to write/implement specific features.

+

Nimsuggest will always answer with a single definition or none if it can't find any valid symbol matching the position of the query.

+ +

Suggestions

The sug Nimsuggest command performs a query about possible completion symbols at some point in the file.

+

The typical usage scenario for this option is to call it after the user has typed the dot character for the object oriented call syntax. Nimsuggest will try to return the suggestions sorted first by scope (from innermost to outermost) and then by item name.

+ +

Invocation context

The con Nimsuggest command is very similar to the suggestions command, but instead of being used after the user has typed a dot character, this one is meant to be used after the user has typed an opening brace to start typing parameters.

+ +

Symbol usages

The use Nimsuggest command lists all usages of the symbol at a position. IDEs can use this to find all the places in the file where the symbol is used and offer the user to rename it in all places at the same time.

+

For this kind of query the IDE will most likely ignore all the type/signature info provided by Nimsuggest and concentrate on the filename, line and column position of the multiple returned answers.

+ +

Parsing nimsuggest output

Nimsuggest output is always returned on single lines separated by tab characters (\t). The values of each column are:

+
  1. Three characters indicating the type of returned answer (e.g. def for definition, sug for suggestion, etc).
  2. +
  3. Type of the symbol. This can be skProc, skLet, and just about any of the enums defined in the module compiler/ast.nim.
  4. +
  5. Fully qualified path of the symbol. If you are querying a symbol defined in the proj.nim file, this would have the form proj.symbolName.
  6. +
  7. Type/signature. For variables and enums this will contain the type of the symbol, for procs, methods and templates this will contain the full unique signature (e.g. proc (File)).
  8. +
  9. Full path to the file containing the symbol.
  10. +
  11. Line where the symbol is located in the file. Lines start to count at 1.
  12. +
  13. Column where the symbol is located in the file. Columns start to count at 0.
  14. +
  15. Docstring for the symbol if available or the empty string. To differentiate the docstring from end of answer, the docstring is always provided enclosed in double quotes, and if the docstring spans multiple lines, all following lines of the docstring will start with a blank space to align visually with the starting quote.

    +

    Also, you won't find raw \n characters breaking the one answer per line format. Instead you will need to parse sequences in the form \xHH, where HH is a hexadecimal value (e.g. newlines generate the sequence \x0A).

    +
  16. +
+

+ +
+
+ + +
+
+ + + + diff --git a/nimsuggest.idx b/nimsuggest.idx new file mode 100644 index 0000000000000..7bb075f296dea --- /dev/null +++ b/nimsuggest.idx @@ -0,0 +1,9 @@ +markupTitle Nim IDE Integration Guide nimsuggest.html Nim IDE Integration Guide 0 +heading Installation nimsuggest.html#installation Installation 0 +heading Nimsuggest invocation nimsuggest.html#nimsuggest-invocation Nimsuggest invocation 0 +heading Specifying the location of the query nimsuggest.html#nimsuggest-invocation-specifying-the-location-of-the-query Specifying the location of the query 0 +heading Definitions nimsuggest.html#nimsuggest-invocation-definitions Definitions 0 +heading Suggestions nimsuggest.html#nimsuggest-invocation-suggestions Suggestions 0 +heading Invocation context nimsuggest.html#nimsuggest-invocation-invocation-context Invocation context 0 +heading Symbol usages nimsuggest.html#nimsuggest-invocation-symbol-usages Symbol usages 0 +heading Parsing nimsuggest output nimsuggest.html#parsing-nimsuggest-output Parsing nimsuggest output 0 diff --git a/nre.html b/nre.html new file mode 100644 index 0000000000000..8b297a1ef4c81 --- /dev/null +++ b/nre.html @@ -0,0 +1,962 @@ + + + + + + + +std/nre + + + + + + + + + + + + + + + + +
+
+

std/nre

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+

What is NRE?

A regular expression library for Nim using PCRE to do the hard work.

+

For documentation on how to write patterns, there exists the official PCRE pattern documentation. You can also search the internet for a wide variety of third-party documentation and tools.

+
Warning: +If you love sequtils.toSeq we have bad news for you. This library doesn't work with it due to documented compiler limitations. As a workaround, use this:
+ +

Example:

+
import std/nre
+# either `import std/nre except toSeq` or fully qualify `sequtils.toSeq`:
+import std/sequtils
+iterator iota(n: int): int =
+  for i in 0..<n: yield i
+assert sequtils.toSeq(iota(3)) == @[0, 1, 2]
Note: +There are also alternative nimble packages such as tinyre and regex.
+ +

Licencing

PCRE has some additional terms that you must agree to in order to use this module.

+ +

Example:

+
import std/nre
+import std/sugar
+let vowels = re"[aeoui]"
+let bounds = collect:
+  for match in "moiga".findIter(vowels): match.matchBounds
+assert bounds == @[1 .. 1, 2 .. 2, 4 .. 4]
+from std/sequtils import toSeq
+let s = sequtils.toSeq("moiga".findIter(vowels))
+  # fully qualified to avoid confusion with nre.toSeq
+assert s.len == 3
+
+let firstVowel = "foo".find(vowels)
+let hasVowel = firstVowel.isSome()
+assert hasVowel
+let matchBounds = firstVowel.get().captureBounds[-1]
+assert matchBounds.a == 1
+
+# as with module `re`, unless specified otherwise, `start` parameter in each
+# proc indicates where the scan starts, but outputs are relative to the start
+# of the input string, not to `start`:
+assert find("uxabc", re"(?<=x|y)ab", start = 1).get.captures[-1] == "ab"
+assert find("uxabc", re"ab", start = 3).isNone

+ +
+

Types

+
+
+
CaptureBounds = distinct RegexMatch
+
+ + + Source   +Edit   + +
+
+
+
Captures = distinct RegexMatch
+
+ + + Source   +Edit   + +
+
+
+
InvalidUnicodeError = ref object of RegexError
+  pos*: int                  ## the location of the invalid unicode in bytes
+
+ + Thrown when matching fails due to invalid unicode in strings + Source   +Edit   + +
+
+
+
Regex = ref RegexDesc
+
+ + Represents the pattern that things are matched against, constructed with re(string). Examples: re"foo", re(r"(*ANYCRLF)(?x)foo # comment".
pattern: string
+
the string that was used to create the pattern. For details on how to write a pattern, please see the official PCRE pattern documentation.
+
captureCount: int
+
the number of captures that the pattern has.
+
captureNameId: Table[string, int]
+
a table from the capture names to their numeric id.
+
+ +

Options

The following options may appear anywhere in the pattern, and they affect the rest of it.

+
  • (?i) - case insensitive
  • +
  • (?m) - multi-line: ^ and $ match the beginning and end of lines, not of the subject string
  • +
  • (?s) - . also matches newline (dotall)
  • +
  • (?U) - expressions are not greedy by default. ? can be added to a qualifier to make it greedy
  • +
  • (?x) - whitespace and comments (#) are ignored (extended)
  • +
  • (?X) - character escapes without special meaning (\w vs. \a) are errors (extra)
  • +
+

One or a combination of these options may appear only at the beginning of the pattern:

+
  • (*UTF8) - treat both the pattern and subject as UTF-8
  • +
  • (*UCP) - Unicode character properties; \w matches я
  • +
  • (*U) - a combination of the two options above
  • +
  • (*FIRSTLINE*) - fails if there is not a match on the first line
  • +
  • (*NO_AUTO_CAPTURE) - turn off auto-capture for groups; (?<name>...) can be used to capture
  • +
  • (*CR) - newlines are separated by \r
  • +
  • (*LF) - newlines are separated by \n (UNIX default)
  • +
  • (*CRLF) - newlines are separated by \r\n (Windows default)
  • +
  • (*ANYCRLF) - newlines are separated by any of the above
  • +
  • (*ANY) - newlines are separated by any of the above and Unicode newlines:

    +

    single characters VT (vertical tab, U+000B), FF (form feed, U+000C), NEL (next line, U+0085), LS (line separator, U+2028), and PS (paragraph separator, U+2029). For the 8-bit library, the last two are recognized only in UTF-8 mode. — man pcre

    +
  • +
  • (*JAVASCRIPT_COMPAT) - JavaScript compatibility
  • +
  • (*NO_STUDY) - turn off studying; study is enabled by default
  • +
+

For more details on the leading option groups, see the Option Setting and the Newline Convention sections of the PCRE syntax manual.

+

Some of these options are not part of PCRE and are converted by nre into PCRE flags. These include NEVER_UTF, ANCHORED, DOLLAR_ENDONLY, FIRSTLINE, NO_AUTO_CAPTURE, JAVASCRIPT_COMPAT, U, NO_STUDY. In other PCRE wrappers, you will need to pass these as separate flags to PCRE.

+ + Source   +Edit   + +
+
+
+
RegexDesc = object
+  pattern*: string
+  ## not nil
+  ## nil
+
+ + + Source   +Edit   + +
+
+
+
RegexError = ref object of CatchableError
+
+ + + Source   +Edit   + +
+
+
+
RegexInternalError = ref object of RegexError
+
+ + Internal error in the module, this probably means that there is a bug + Source   +Edit   + +
+
+
+
RegexMatch = object
+  pattern*: Regex            ## The regex doing the matching.
+                             ## Not nil.
+  str*: string               ## The string that was matched against.
+  ## First item is the bounds of the match
+  ## Other items are the captures
+  ## `a` is inclusive start, `b` is exclusive end
+
+ + Usually seen as OptionRegexMatch, it represents the result of an execution. On failure, it is none, on success, it is some.
pattern: Regex
+
the pattern that is being matched
+
str: string
+
the string that was matched against
+
captures[]: string
+
the string value of whatever was captured at that id. If the value is invalid, then behavior is undefined. If the id is -1, then the whole match is returned. If the given capture was not matched, nil is returned. See examples for match.
+
captureBounds[]: HSlice[int, int]
+
gets the bounds of the given capture according to the same rules as the above. If the capture is not filled, then None is returned. The bounds are both inclusive. See examples for match.
+
match: string
+
the full text of the match.
+
matchBounds: HSlice[int, int]
+
the bounds of the match, as in captureBounds[]
+
(captureBounds|captures).toTable
+
returns a table with each named capture as a key.
+
(captureBounds|captures).toSeq
+
returns all the captures by their number.
+
$: string
+
same as match
+
+ + Source   +Edit   + +
+
+
+
StudyError = ref object of RegexError
+
+ + Thrown when studying the regular expression fails for whatever reason. The message contains the error code. + Source   +Edit   + +
+
+
+
SyntaxError = ref object of RegexError
+  pos*: int                  ## the location of the syntax error in bytes
+  pattern*: string           ## the pattern that caused the problem
+
+ + Thrown when there is a syntax error in the regular expression string passed in + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(pattern: RegexMatch): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(a, b: Regex): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(a, b: RegexMatch): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func `[]`(pattern: CaptureBounds; i: int): HSlice[int, int] {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `[]`(pattern: CaptureBounds; name: string): HSlice[int, int] {.
+    ...raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `[]`(pattern: Captures; i: int): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `[]`(pattern: Captures; name: string): string {....raises: [KeyError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func captureBounds(pattern: RegexMatch): CaptureBounds {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc captureCount(pattern: Regex): int {....raises: [ValueError], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc captureNameId(pattern: Regex): Table[string, int] {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func captures(pattern: RegexMatch): Captures {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func contains(pattern: CaptureBounds; i: int): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func contains(pattern: CaptureBounds; name: string): bool {....raises: [KeyError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func contains(pattern: Captures; i: int): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func contains(pattern: Captures; name: string): bool {....raises: [KeyError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc contains(str: string; pattern: Regex; start = 0; endpos = int.high): bool {.
+    ...raises: [ValueError, RegexInternalError, InvalidUnicodeError], tags: [],
+    forbids: [].}
+
+ + Determine if the string contains the given pattern between the end and start positions: This function is equivalent to isSome(str.find(pattern, start, endpos)). +

Example:

+
assert "abc".contains(re"bc")
+assert not "abc".contains(re"cd")
+assert not "abc".contains(re"a", start = 1)
+ Source   +Edit   + +
+
+ +
+
+
+
proc escapeRe(str: string): string {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ +

Escapes the string so it doesn't match any special characters. Incompatible with the Extra flag (X).

+

Escaped char: \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

+ +

Example:

+
assert escapeRe("fly+wind") == "fly\\+wind"
+assert escapeRe("!") == "\\!"
+assert escapeRe("nim*") == "nim\\*"
+ Source   +Edit   + +
+
+ +
+
+
+
proc find(str: string; pattern: Regex; start = 0; endpos = int.high): Option[
+    RegexMatch] {....raises: [ValueError, RegexInternalError, InvalidUnicodeError],
+                  tags: [], forbids: [].}
+
+ + Finds the given pattern in the string between the end and start positions.
start
+
The start point at which to start matching. |abc is 0; a|bc is 1
+
endpos
+
The maximum index for a match; int.high means the end of the string, otherwise it’s an inclusive upper bound.
+
+ + Source   +Edit   + +
+
+ +
+
+
+
proc findAll(str: string; pattern: Regex; start = 0; endpos = int.high): seq[
+    string] {....raises: [ValueError, RegexInternalError, InvalidUnicodeError],
+              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func match(pattern: RegexMatch): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc match(str: string; pattern: Regex; start = 0; endpos = int.high): Option[
+    RegexMatch] {....raises: [ValueError, RegexInternalError, InvalidUnicodeError],
+                  tags: [], forbids: [].}
+
+ + Like find(...), but anchored to the start of the string. +

Example:

+
assert "foo".match(re"f").isSome
+assert "foo".match(re"o").isNone
+
+assert "abc".match(re"(\w)").get.captures[0] == "a"
+assert "abc".match(re"(?<letter>\w)").get.captures["letter"] == "a"
+assert "abc".match(re"(\w)\w").get.captures[-1] == "ab"
+
+assert "abc".match(re"(\w)").get.captureBounds[0] == 0 .. 0
+assert 0 in "abc".match(re"(\w)").get.captureBounds
+assert "abc".match(re"").get.captureBounds[-1] == 0 .. -1
+assert "abc".match(re"abc").get.captureBounds[-1] == 0 .. 2
+ Source   +Edit   + +
+
+ +
+
+
+
func matchBounds(pattern: RegexMatch): HSlice[int, int] {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc re(pattern: string): Regex {....raises: [KeyError, SyntaxError, StudyError,
+    ValueError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc replace(str: string; pattern: Regex; sub: string): string {.
+    ...raises: [ValueError, RegexInternalError, InvalidUnicodeError, KeyError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc replace(str: string; pattern: Regex;
+             subproc: proc (match: RegexMatch): string): string {.
+    ...raises: [ValueError, RegexInternalError, InvalidUnicodeError, Exception],
+    tags: [RootEffect], forbids: [].}
+
+ +

Replaces each match of Regex in the string with subproc, which should never be or return nil.

+

If subproc is a proc (RegexMatch): string, then it is executed with each match and the return value is the replacement value.

+

If subproc is a proc (string): string, then it is executed with the full text of the match and the return value is the replacement value.

+

If subproc is a string, the syntax is as follows:

+
  • $$ - literal $
  • +
  • $123 - capture number 123
  • +
  • $foo - named capture foo
  • +
  • ${foo} - same as above
  • +
  • $1$# - first and second captures
  • +
  • $# - first capture
  • +
  • $0 - full match
  • +
+

If a given capture is missing, IndexDefect thrown for un-named captures and KeyError for named captures.

+ + Source   +Edit   + +
+
+
+
proc replace(str: string; pattern: Regex; subproc: proc (match: string): string): string {.
+    ...raises: [ValueError, RegexInternalError, InvalidUnicodeError, Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc split(str: string; pattern: Regex; maxSplit = -1; start = 0): seq[string] {.
+    ...raises: [ValueError, RegexInternalError, InvalidUnicodeError], tags: [],
+    forbids: [].}
+
+ +

Splits the string with the given regex. This works according to the rules that Perl and Javascript use.

+

start behaves the same as in find(...).

+ +

Example:

+
# -  If the match is zero-width, then the string is still split:
+assert "123".split(re"") == @["1", "2", "3"]
+
+# -  If the pattern has a capture in it, it is added after the string
+#    split:
+assert "12".split(re"(\d)") == @["", "1", "", "2", ""]
+
+# -  If `maxsplit != -1`, then the string will only be split
+#    `maxsplit - 1` times. This means that there will be `maxsplit`
+#    strings in the output seq.
+assert "1.2.3".split(re"\.", maxsplit = 2) == @["1", "2.3"]
+ Source   +Edit   + +
+
+ +
+
+
+
proc toSeq(pattern: CaptureBounds; default = none(HSlice[int, int])): seq[
+    Option[HSlice[int, int]]] {....raises: [ValueError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc toSeq(pattern: Captures; default: Option[string] = none(string)): seq[
+    Option[string]] {....raises: [ValueError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func toTable(pattern: CaptureBounds): Table[string, HSlice[int, int]] {.
+    ...raises: [KeyError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func toTable(pattern: Captures): Table[string, string] {....raises: [KeyError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator findIter(str: string; pattern: Regex; start = 0; endpos = int.high): RegexMatch {.
+    ...raises: [ValueError, RegexInternalError, InvalidUnicodeError], tags: [],
+    forbids: [].}
+
+ + Works the same as find(...), but finds every non-overlapping match: +

Example:

+
import std/sugar
+assert collect(for a in "2222".findIter(re"22"): a.match) == @["22", "22"]
+ # not @["22", "22", "22"]

Arguments are the same as find(...)

+

Variants:

+
  • proc findAll(...) returns a seq[string]
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
iterator items(pattern: CaptureBounds; default = none(HSlice[int, int])): Option[
+    HSlice[int, int]] {....raises: [ValueError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
iterator items(pattern: Captures; default: Option[string] = none(string)): Option[
+    string] {....raises: [ValueError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/nre.idx b/nre.idx new file mode 100644 index 0000000000000..45a44e7ea7a5b --- /dev/null +++ b/nre.idx @@ -0,0 +1,56 @@ +nimTitle nre nre.html module std/nre 0 +nim RegexDesc nre.html#RegexDesc object RegexDesc 77 +nim Regex nre.html#Regex type Regex 84 +nim RegexMatch nre.html#RegexMatch object RegexMatch 156 +nim Captures nre.html#Captures type Captures 198 +nim CaptureBounds nre.html#CaptureBounds type CaptureBounds 199 +nim RegexError nre.html#RegexError type RegexError 201 +nim RegexInternalError nre.html#RegexInternalError type RegexInternalError 203 +nim InvalidUnicodeError nre.html#InvalidUnicodeError type InvalidUnicodeError 206 +nim SyntaxError nre.html#SyntaxError type SyntaxError 210 +nim StudyError nre.html#StudyError type StudyError 216 +nim captureCount nre.html#captureCount,Regex proc captureCount(pattern: Regex): int 302 +nim captureNameId nre.html#captureNameId,Regex proc captureNameId(pattern: Regex): Table[string, int] 305 +nim captureBounds nre.html#captureBounds,RegexMatch proc captureBounds(pattern: RegexMatch): CaptureBounds 330 +nim captures nre.html#captures,RegexMatch proc captures(pattern: RegexMatch): Captures 332 +nim contains nre.html#contains,CaptureBounds,int proc contains(pattern: CaptureBounds; i: int): bool 334 +nim contains nre.html#contains,Captures,int proc contains(pattern: Captures; i: int): bool 338 +nim `[]` nre.html#[],CaptureBounds,int proc `[]`(pattern: CaptureBounds; i: int): HSlice[int, int] 341 +nim `[]` nre.html#[],Captures,int proc `[]`(pattern: Captures; i: int): string 349 +nim match nre.html#match,RegexMatch proc match(pattern: RegexMatch): string 355 +nim matchBounds nre.html#matchBounds,RegexMatch proc matchBounds(pattern: RegexMatch): HSlice[int, int] 358 +nim contains nre.html#contains,CaptureBounds,string proc contains(pattern: CaptureBounds; name: string): bool 361 +nim contains nre.html#contains,Captures,string proc contains(pattern: Captures; name: string): bool 368 +nim `[]` nre.html#[],CaptureBounds,string proc `[]`(pattern: CaptureBounds; name: string): HSlice[int, int] 375 +nim `[]` nre.html#[],Captures,string proc `[]`(pattern: Captures; name: string): string 381 +nim toTable nre.html#toTable,Captures proc toTable(pattern: Captures): Table[string, string] 392 +nim toTable nre.html#toTable,CaptureBounds proc toTable(pattern: CaptureBounds): Table[string, HSlice[int, int]] 396 +nim items nre.html#items.i,CaptureBounds iterator items(pattern: CaptureBounds; default = none(HSlice[int, int])): Option[\n HSlice[int, int]] 411 +nim items nre.html#items.i,Captures,Option[string] iterator items(pattern: Captures; default: Option[string] = none(string)): Option[string] 415 +nim toSeq nre.html#toSeq,CaptureBounds proc toSeq(pattern: CaptureBounds; default = none(HSlice[int, int])): seq[\n Option[HSlice[int, int]]] 419 +nim toSeq nre.html#toSeq,Captures,Option[string] proc toSeq(pattern: Captures; default: Option[string] = none(string)): seq[\n Option[string]] 424 +nim `$` nre.html#$,RegexMatch proc `$`(pattern: RegexMatch): string 429 +nim `==` nre.html#==,Regex,Regex proc `==`(a, b: Regex): bool 432 +nim `==` nre.html#==,RegexMatch,RegexMatch proc `==`(a, b: RegexMatch): bool 440 +nim re nre.html#re,string proc re(pattern: string): Regex 499 +nim match nre.html#match,string,Regex,int proc match(str: string; pattern: Regex; start = 0; endpos = int.high): Option[\n RegexMatch] 542 +nim findIter nre.html#findIter.i,string,Regex,int iterator findIter(str: string; pattern: Regex; start = 0; endpos = int.high): RegexMatch 559 +nim find nre.html#find,string,Regex,int proc find(str: string; pattern: Regex; start = 0; endpos = int.high): Option[\n RegexMatch] 610 +nim findAll nre.html#findAll,string,Regex,int proc findAll(str: string; pattern: Regex; start = 0; endpos = int.high): seq[string] 623 +nim contains nre.html#contains,string,Regex,int proc contains(str: string; pattern: Regex; start = 0; endpos = int.high): bool 628 +nim split nre.html#split,string,Regex,int,int proc split(str: string; pattern: Regex; maxSplit = -1; start = 0): seq[string] 639 +nim replace nre.html#replace,string,Regex,proc(RegexMatch) proc replace(str: string; pattern: Regex; subproc: proc (match: RegexMatch): string): string 718 +nim replace nre.html#replace,string,Regex,proc(string) proc replace(str: string; pattern: Regex; subproc: proc (match: string): string): string 743 +nim replace nre.html#replace,string,Regex,string proc replace(str: string; pattern: Regex; sub: string): string 747 +nim escapeRe nre.html#escapeRe,string proc escapeRe(str: string): string 752 +heading What is NRE? nre.html#what-is-nreqmark What is NRE? 0 +heading Licencing nre.html#what-is-nreqmark-licencing Licencing 0 +heading Options nre.html#licencing-options Options 0 +nimgrp totable nre.html#toTable-procs-all proc 392 +nimgrp replace nre.html#replace-procs-all proc 718 +nimgrp == nre.html#==-procs-all proc 432 +nimgrp contains nre.html#contains-procs-all proc 334 +nimgrp [] nre.html#[]-procs-all proc 341 +nimgrp toseq nre.html#toSeq-procs-all proc 419 +nimgrp match nre.html#match-procs-all proc 355 +nimgrp items nre.html#items-iterators-all iterator 411 diff --git a/ntpath.html b/ntpath.html new file mode 100644 index 0000000000000..cc3563b2f4b21 --- /dev/null +++ b/ntpath.html @@ -0,0 +1,128 @@ + + + + + + + +std/private/ntpath + + + + + + + + + + + + + + + + +
+
+

std/private/ntpath

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ strutils +
+
+
+

Procs

+
+
+
+
func splitDrive(p: string): tuple[drive, path: string] {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Splits a Windows path into a drive and path part. The drive can be e.g. C:. It can also be a UNC path (\\server\drive\path).

+

The equivalent splitDrive for POSIX systems always returns empty drive. Therefore this proc is only necessary on DOS-like file systems (together with Nim's doslikeFileSystem conditional variable).

+

This proc's use case is to extract path such that it can be manipulated like a POSIX path.

+ +

Example:

+
doAssert splitDrive("C:") == ("C:", "")
+doAssert splitDrive(r"C:\") == (r"C:", r"\")
+doAssert splitDrive(r"\\server\drive\foo\bar") == (r"\\server\drive", r"\foo\bar")
+doAssert splitDrive(r"\\?\UNC\server\share\dir") == (r"\\?\UNC\server\share", r"\dir")
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/ntpath.idx b/ntpath.idx new file mode 100644 index 0000000000000..9a801892f30b3 --- /dev/null +++ b/ntpath.idx @@ -0,0 +1,2 @@ +nimTitle ntpath ntpath.html module std/private/ntpath 0 +nim splitDrive ntpath.html#splitDrive,string proc splitDrive(p: string): tuple[drive, path: string] 15 diff --git a/objectdollar.html b/objectdollar.html new file mode 100644 index 0000000000000..b8c3f2115669c --- /dev/null +++ b/objectdollar.html @@ -0,0 +1,124 @@ + + + + + + + +std/objectdollar + + + + + + + + + + + + + + + + +
+
+

std/objectdollar

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a generic $ operator to convert objects to strings.

+
+

Imports

+
+ miscdollars +
+
+
+

Procs

+
+
+
+
proc `$`[T: object](x: T): string
+
+ + Generic $ operator for objects with similar output to $ for named tuples. +

Example:

+
type Foo = object
+  a, b: int
+let x = Foo(a: 23, b: 45)
+assert $x == "(a: 23, b: 45)"
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/objectdollar.idx b/objectdollar.idx new file mode 100644 index 0000000000000..f11711e2aa244 --- /dev/null +++ b/objectdollar.idx @@ -0,0 +1,2 @@ +nimTitle objectdollar objectdollar.html module std/objectdollar 0 +nim `$` objectdollar.html#$,T proc `$`[T: object](x: T): string 5 diff --git a/odbcsql.html b/odbcsql.html new file mode 100644 index 0000000000000..746aa396248c8 --- /dev/null +++ b/odbcsql.html @@ -0,0 +1,6121 @@ + + + + + + + +src/db_connector/odbcsql + + + + + + + + + + + + + + + + +
+
+

src/db_connector/odbcsql

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

+
+

Types

+
+
+
PSQL_DATE_STRUCT = ptr SQL_DATE_STRUCT
+
+ + + +
+
+
+
PSQL_TIME_STRUCT = ptr SQL_TIME_STRUCT
+
+ + + +
+
+ +
+
PSQLCHAR = cstring
+
+ + + +
+
+
+
PSQLDOUBLE = ptr TSqlDouble
+
+ + + +
+
+
+
PSQLFLOAT = ptr TSqlFloat
+
+ + + +
+
+
+
PSQLHANDLE = ptr SqlHandle
+
+ + + +
+
+
+
PSQLINTEGER = ptr TSqlInteger
+
+ + + +
+
+
+
PSQLREAL = ptr TSqlReal
+
+ + + +
+
+
+
PSQLSMALLINT = ptr TSqlSmallInt
+
+ + + +
+
+
+
PSQLUINTEGER = ptr SqlUInteger
+
+ + + +
+
+
+
PSQLUSMALLINT = ptr SqlUSmallInt
+
+ + + +
+
+
+
SQL_DATE_STRUCT {.final, pure.} = object
+  Year*: TSqlSmallInt
+  Month*: SqlUSmallInt
+  Day*: SqlUSmallInt
+
+ + + +
+
+
+
SQL_TIME_STRUCT {.final, pure.} = object
+  Hour*: SqlUSmallInt
+  Minute*: SqlUSmallInt
+  Second*: SqlUSmallInt
+
+ + + +
+
+
+
SQL_TIMESTAMP_STRUCT {.final, pure.} = object
+  Year*: SqlUSmallInt
+  Month*: SqlUSmallInt
+  Day*: SqlUSmallInt
+  Hour*: SqlUSmallInt
+  Minute*: SqlUSmallInt
+  Second*: SqlUSmallInt
+  Fraction*: SqlUInteger
+
+ + + +
+
+
+
SqlHandle = pointer
+
+ + + +
+
+
+
SqlHDBC = SqlHandle
+
+ + + +
+
+
+
SqlHDesc = SqlHandle
+
+ + + +
+
+
+
SqlHEnv = SqlHandle
+
+ + + +
+
+
+
SqlHStmt = SqlHandle
+
+ + + +
+
+
+
SqlHWND = pointer
+
+ + + +
+
+
+
SqlPointer = pointer
+
+ + + +
+
+
+
SqlUInteger = int32
+
+ + + +
+
+
+
SqlUSmallInt = int16
+
+ + + +
+
+
+
TSqlChar = char
+
+ + + +
+
+
+
TSqlDouble = cdouble
+
+ + + +
+
+
+
TSqlFloat = cdouble
+
+ + + +
+
+
+
TSqlInteger = int32
+
+ + + +
+
+
+
TSqlLen = int
+
+ + + +
+
+
+
TSqlReal = cfloat
+
+ + + +
+
+
+
TSqlSmallInt = int16
+
+ + + +
+
+
+
TSqlULen = uint
+
+ + + +
+
+ +
+
+
+

Consts

+
+
+
ODBC_ADD_DSN = 1
+
+ + + +
+
+
+
ODBC_ADD_SYS_DSN = 4
+
+ + + +
+
+
+
ODBC_CONFIG_DSN = 2
+
+ + + +
+
+
+
ODBC_CONFIG_SYS_DSN = 5
+
+ + + +
+
+
+
ODBC_REMOVE_DSN = 3
+
+ + + +
+
+
+
ODBC_REMOVE_SYS_DSN = 6
+
+ + + +
+
+
+
SQL_ACCESS_MODE = 101
+
+ + + +
+
+
+
SQL_ACTIVE_CONNECTIONS = 0
+
+ + + +
+
+
+
SQL_ACTIVE_ENVIRONMENTS = 116
+
+ + + +
+
+
+
SQL_ACTIVE_STATEMENTS = 1
+
+ + + +
+
+
+
SQL_ADD = 4
+
+ + + +
+
+
+
SQL_ALL_TYPES = 0
+
+ + + +
+
+
+
SQL_API_SQLDESCRIBEPARAM = 58
+
+ + + +
+
+
+
SQL_ARD_TYPE = -99
+
+ + + +
+
+
+
SQL_ASYNC_ENABLE = 4
+
+ + + +
+
+
+
SQL_ASYNC_MODE = 10021
+
+ + + +
+
+
+
SQL_ATTR_ACCESS_MODE = 101
+
+ + + +
+
+
+
SQL_ATTR_APP_PARAM_DESC = 10011
+
+ + + +
+
+
+
SQL_ATTR_APP_ROW_DESC = 10010
+
+ + + +
+
+
+
SQL_ATTR_AUTO_IPD = 10001
+
+ + + +
+
+
+
SQL_ATTR_AUTOCOMMIT = 102
+
+ + + +
+
+
+
SQL_ATTR_CONCURRENCY = 7
+
+ + + +
+
+
+
SQL_ATTR_CONNECTION_DEAD = 1209
+
+ + + +
+
+
+
SQL_ATTR_CONNECTION_TIMEOUT = 113
+
+ + + +
+
+
+
SQL_ATTR_CURRENT_CATALOG = 109
+
+ + + +
+
+
+
SQL_ATTR_CURSOR_SCROLLABLE = -1
+
+ + + +
+
+
+
SQL_ATTR_CURSOR_SENSITIVITY = -2
+
+ + + +
+
+
+
SQL_ATTR_CURSOR_TYPE = 6
+
+ + + +
+
+
+
SQL_ATTR_DISCONNECT_BEHAVIOR = 114
+
+ + + +
+
+
+
SQL_ATTR_ENLIST_IN_DTC = 1207
+
+ + + +
+
+
+
SQL_ATTR_ENLIST_IN_XA = 1208
+
+ + + +
+
+
+
SQL_ATTR_FETCH_BOOKMARK_PTR = 16
+
+ + + +
+
+
+
SQL_ATTR_IMP_PARAM_DESC = 10013
+
+ + + +
+
+
+
SQL_ATTR_IMP_ROW_DESC = 10012
+
+ + + +
+
+
+
SQL_ATTR_LOGIN_TIMEOUT = 103
+
+ + + +
+
+
+
SQL_ATTR_MAX_ROWS = 1
+
+ + + +
+
+
+
SQL_ATTR_METADATA_ID = 10014
+
+ + + +
+
+
+
SQL_ATTR_ODBC_CURSORS = 110
+
+ + + +
+
+
+
SQL_ATTR_ODBC_VERSION = 200
+
+ + + +
+
+
+
SQL_ATTR_OUTPUT_NTS = 10001
+
+ + + +
+
+
+
SQL_ATTR_PACKET_SIZE = 112
+
+ + + +
+
+
+
SQL_ATTR_QUIET_MODE = 111
+
+ + + +
+
+
+
SQL_ATTR_ROW_ARRAY_SIZE = 27
+
+ + + +
+
+
+
SQL_ATTR_ROW_NUMBER = 14
+
+ + + +
+
+
+
SQL_ATTR_ROW_STATUS_PTR = 25
+
+ + + +
+
+
+
SQL_ATTR_ROWS_FETCHED_PTR = 26
+
+ + + +
+
+
+
SQL_ATTR_TRACE = 104
+
+ + + +
+
+
+
SQL_ATTR_TRACEFILE = 105
+
+ + + +
+
+
+
SQL_ATTR_TRANSLATE_LIB = 106
+
+ + + +
+
+
+
SQL_ATTR_TRANSLATE_OPTION = 107
+
+ + + +
+
+
+
SQL_ATTR_TXN_ISOLATION = 108
+
+ + + +
+
+
+
SQL_ATTR_USE_BOOKMARKS = 12
+
+ + + +
+
+
+
SQL_AUTOCOMMIT = 102
+
+ + + +
+
+
+
SQL_AUTOCOMMIT_DEFAULT = 1
+
+ + + +
+
+
+
SQL_AUTOCOMMIT_OFF = 0
+
+ + + +
+
+
+
SQL_AUTOCOMMIT_ON = 1
+
+ + + +
+
+
+
SQL_BATCH_ROW_COUNT = 120
+
+ + + +
+
+
+
SQL_BATCH_SUPPORT = 121
+
+ + + +
+
+
+
SQL_BEST_ROWID = 1
+
+ + + +
+
+
+
SQL_BIGINT = -5
+
+ + + +
+
+
+
SQL_BINARY = -2
+
+ + + +
+
+
+
SQL_BIND_TYPE = 5
+
+ + + +
+
+
+
SQL_BIT = -7
+
+ + + +
+
+
+
SQL_BOOKMARK_PERSISTENCE = 82
+
+ + + +
+
+
+
SQL_BP_CLOSE = 0x00000001
+
+ + + +
+
+
+
SQL_BP_DELETE = 0x00000002
+
+ + + +
+
+
+
SQL_BP_DROP = 0x00000004
+
+ + + +
+
+
+
SQL_BP_OTHER_HSTMT = 0x00000020
+
+ + + +
+
+
+
SQL_BP_SCROLL = 0x00000040
+
+ + + +
+
+
+
SQL_BP_TRANSACTION = 0x00000008
+
+ + + +
+
+
+
SQL_BP_UPDATE = 0x00000010
+
+ + + +
+
+
+
SQL_C_BINARY = -2
+
+ + + +
+
+
+
SQL_C_BIT = -7
+
+ + + +
+
+
+
SQL_C_BOOKMARK = -18
+
+ + + +
+
+
+
SQL_C_CHAR = 1
+
+ + + +
+
+
+
SQL_C_DATE = 9
+
+ + + +
+
+
+
SQL_C_DEFAULT = 99
+
+ + + +
+
+
+
SQL_C_DOUBLE = 8
+
+ + + +
+
+
+
SQL_C_FLOAT = 7
+
+ + + +
+
+
+
SQL_C_GUID = -11
+
+ + + +
+
+
+
SQL_C_INTERVAL_DAY = 103
+
+ + + +
+
+
+
SQL_C_INTERVAL_DAY_TO_HOUR = 108
+
+ + + +
+
+
+
SQL_C_INTERVAL_DAY_TO_MINUTE = 109
+
+ + + +
+
+
+
SQL_C_INTERVAL_DAY_TO_SECOND = 110
+
+ + + +
+
+
+
SQL_C_INTERVAL_HOUR = 104
+
+ + + +
+
+
+
SQL_C_INTERVAL_HOUR_TO_MINUTE = 111
+
+ + + +
+
+
+
SQL_C_INTERVAL_HOUR_TO_SECOND = 112
+
+ + + +
+
+
+
SQL_C_INTERVAL_MINUTE = 105
+
+ + + +
+
+
+
SQL_C_INTERVAL_MINUTE_TO_SECOND = 113
+
+ + + +
+
+
+
SQL_C_INTERVAL_MONTH = 102
+
+ + + +
+
+
+
SQL_C_INTERVAL_SECOND = 106
+
+ + + +
+
+
+
SQL_C_INTERVAL_YEAR = 101
+
+ + + +
+
+
+
SQL_C_INTERVAL_YEAR_TO_MONTH = 107
+
+ + + +
+
+
+
SQL_C_LONG = 4
+
+ + + +
+
+
+
SQL_C_NUMERIC = 2
+
+ + + +
+
+
+
SQL_C_SBIGINT = -25
+
+ + + +
+
+
+
SQL_C_SHORT = 5
+
+ + + +
+
+
+
SQL_C_SLONG = -16
+
+ + + +
+
+
+
SQL_C_SSHORT = -15
+
+ + + +
+
+
+
SQL_C_STINYINT = -26
+
+ + + +
+
+
+
SQL_C_TIME = 10
+
+ + + +
+
+
+
SQL_C_TIMESTAMP = 11
+
+ + + +
+
+
+
SQL_C_TINYINT = -6
+
+ + + +
+
+
+
SQL_C_TYPE_DATE = 91
+
+ + + +
+
+
+
SQL_C_TYPE_TIME = 92
+
+ + + +
+
+
+
SQL_C_TYPE_TIMESTAMP = 93
+
+ + + +
+
+
+
SQL_C_UBIGINT = -27
+
+ + + +
+
+
+
SQL_C_ULONG = -18
+
+ + + +
+
+
+
SQL_C_USHORT = -17
+
+ + + +
+
+
+
SQL_C_UTINYINT = -28
+
+ + + +
+
+
+
SQL_C_VARBOOKMARK = -2
+
+ + + +
+
+
+
SQL_CA1_ABSOLUTE = 2
+
+ + + +
+
+
+
SQL_CA1_BOOKMARK = 8
+
+ + + +
+
+
+
SQL_CA1_BULK_ADD = 0x00010000
+
+ + + +
+
+
+
SQL_CA1_BULK_DELETE_BY_BOOKMARK = 0x00040000
+
+ + + +
+
+
+
SQL_CA1_BULK_FETCH_BY_BOOKMARK = 0x00080000
+
+ + + +
+
+
+
SQL_CA1_BULK_UPDATE_BY_BOOKMARK = 0x00020000
+
+ + + +
+
+
+
SQL_CA1_LOCK_EXCLUSIVE = 0x00000080
+
+ + + +
+
+
+
SQL_CA1_LOCK_NO_CHANGE = 0x00000040
+
+ + + +
+
+
+
SQL_CA1_LOCK_UNLOCK = 0x00000100
+
+ + + +
+
+
+
SQL_CA1_NEXT = 1
+
+ + + +
+
+
+
SQL_CA1_POS_DELETE = 0x00000800
+
+ + + +
+
+
+
SQL_CA1_POS_POSITION = 0x00000200
+
+ + + +
+
+
+
SQL_CA1_POS_REFRESH = 0x00001000
+
+ + + +
+
+
+
SQL_CA1_POS_UPDATE = 0x00000400
+
+ + + +
+
+
+
SQL_CA1_POSITIONED_DELETE = 0x00004000
+
+ + + +
+
+
+
SQL_CA1_POSITIONED_UPDATE = 0x00002000
+
+ + + +
+
+
+
SQL_CA1_RELATIVE = 4
+
+ + + +
+
+
+
SQL_CA1_SELECT_FOR_UPDATE = 0x00008000
+
+ + + +
+
+
+
SQL_CA2_CRC_APPROXIMATE = 0x00002000
+
+ + + +
+
+
+
SQL_CA2_CRC_EXACT = 0x00001000
+
+ + + +
+
+
+
SQL_CA2_LOCK_CONCURRENCY = 2
+
+ + + +
+
+
+
SQL_CA2_MAX_ROWS_AFFECTS_ALL = 3968
+
+ + + +
+
+
+
SQL_CA2_MAX_ROWS_CATALOG = 0x00000800
+
+ + + +
+
+
+
SQL_CA2_MAX_ROWS_DELETE = 0x00000200
+
+ + + +
+
+
+
SQL_CA2_MAX_ROWS_INSERT = 0x00000100
+
+ + + +
+
+
+
SQL_CA2_MAX_ROWS_SELECT = 0x00000080
+
+ + + +
+
+
+
SQL_CA2_MAX_ROWS_UPDATE = 0x00000400
+
+ + + +
+
+ + + +
+
SQL_CA2_SENSITIVITY_ADDITIONS = 0x00000010
+
+ + + +
+
+
+
SQL_CA2_SENSITIVITY_DELETIONS = 0x00000020
+
+ + + +
+
+
+
SQL_CA2_SENSITIVITY_UPDATES = 0x00000040
+
+ + + +
+
+
+
SQL_CA2_SIMULATE_NON_UNIQUE = 0x00004000
+
+ + + +
+
+
+
SQL_CA2_SIMULATE_TRY_UNIQUE = 0x00008000
+
+ + + +
+
+
+
SQL_CA2_SIMULATE_UNIQUE = 0x00010000
+
+ + + +
+
+
+
SQL_CATALOG_LOCATION = 114
+
+ + + +
+
+
+
SQL_CATALOG_NAME = 10003
+
+ + + +
+
+
+
SQL_CATALOG_NAME_SEPARATOR = 41
+
+ + + +
+
+
+
SQL_CATALOG_TERM = 42
+
+ + + +
+
+
+
SQL_CATALOG_USAGE = 92
+
+ + + +
+
+
+
SQL_CHAR = 1
+
+ + + +
+
+
+
SQL_CLOSE = 0
+
+ + + +
+
+
+
SQL_CODE_DATE = 1
+
+ + + +
+
+
+
SQL_CODE_DAY = 3
+
+ + + +
+
+
+
SQL_CODE_DAY_TO_HOUR = 8
+
+ + + +
+
+
+
SQL_CODE_DAY_TO_MINUTE = 9
+
+ + + +
+
+
+
SQL_CODE_DAY_TO_SECOND = 10
+
+ + + +
+
+
+
SQL_CODE_HOUR = 4
+
+ + + +
+
+
+
SQL_CODE_HOUR_TO_MINUTE = 11
+
+ + + +
+
+
+
SQL_CODE_HOUR_TO_SECOND = 12
+
+ + + +
+
+
+
SQL_CODE_MINUTE = 5
+
+ + + +
+
+
+
SQL_CODE_MINUTE_TO_SECOND = 13
+
+ + + +
+
+
+
SQL_CODE_MONTH = 2
+
+ + + +
+
+
+
SQL_CODE_SECOND = 6
+
+ + + +
+
+
+
SQL_CODE_TIME = 2
+
+ + + +
+
+
+
SQL_CODE_TIMESTAMP = 3
+
+ + + +
+
+
+
SQL_CODE_YEAR = 1
+
+ + + +
+
+
+
SQL_CODE_YEAR_TO_MONTH = 7
+
+ + + +
+
+
+
SQL_COLATT_OPT_MAX = 18
+
+ + + +
+
+
+
SQL_COLLATION_SEQ = 10004
+
+ + + +
+
+
+
SQL_COLUMN_ALIAS = 87
+
+ + + +
+
+
+
SQL_COLUMN_AUTO_INCREMENT = 11
+
+ + + +
+
+
+
SQL_COLUMN_CASE_SENSITIVE = 12
+
+ + + +
+
+
+
SQL_COLUMN_COUNT = 0
+
+ + + +
+
+
+
SQL_COLUMN_DISPLAY_SIZE = 6
+
+ + + +
+
+
+
SQL_COLUMN_DRIVER_START = 1000
+
+ + + +
+
+
+
SQL_COLUMN_LABEL = 18
+
+ + + +
+
+
+
SQL_COLUMN_LENGTH = 3
+
+ + + +
+
+
+
SQL_COLUMN_MONEY = 9
+
+ + + +
+
+
+
SQL_COLUMN_NAME = 1
+
+ + + +
+
+
+
SQL_COLUMN_NULLABLE = 7
+
+ + + +
+
+
+
SQL_COLUMN_OWNER_NAME = 16
+
+ + + +
+
+
+
SQL_COLUMN_PRECISION = 4
+
+ + + +
+
+
+
SQL_COLUMN_QUALIFIER_NAME = 17
+
+ + + +
+
+
+
SQL_COLUMN_SCALE = 5
+
+ + + +
+
+
+
SQL_COLUMN_SEARCHABLE = 13
+
+ + + +
+
+
+
SQL_COLUMN_TABLE_NAME = 15
+
+ + + +
+
+
+
SQL_COLUMN_TYPE = 2
+
+ + + +
+
+
+
SQL_COLUMN_TYPE_NAME = 14
+
+ + + +
+
+
+
SQL_COLUMN_UNSIGNED = 8
+
+ + + +
+
+
+
SQL_COLUMN_UPDATABLE = 10
+
+ + + +
+
+
+
SQL_COMMIT = 0
+
+ + + +
+
+
+
SQL_CONCUR_DEFAULT = 1
+
+ + + +
+
+
+
SQL_CONCUR_LOCK = 2
+
+ + + +
+
+
+
SQL_CONCUR_READ_ONLY = 1
+
+ + + +
+
+
+
SQL_CONCUR_ROWVER = 3
+
+ + + +
+
+
+
SQL_CONCUR_VALUES = 4
+
+ + + +
+
+
+
SQL_CONCURRENCY = 7
+
+ + + +
+
+
+
SQL_CUR_DEFAULT = 2
+
+ + + +
+
+
+
SQL_CUR_USE_DRIVER = 2
+
+ + + +
+
+
+
SQL_CUR_USE_IF_NEEDED = 0
+
+ + + +
+
+
+
SQL_CUR_USE_ODBC = 1
+
+ + + +
+
+
+
SQL_CURRENT_QUALIFIER = 109
+
+ + + +
+
+
+
SQL_CURSOR_DYNAMIC = 2
+
+ + + +
+
+
+
SQL_CURSOR_FORWARD_ONLY = 0
+
+ + + +
+
+
+
SQL_CURSOR_KEYSET_DRIVEN = 1
+
+ + + +
+
+
+
SQL_CURSOR_SENSITIVITY = 10001
+
+ + + +
+
+
+
SQL_CURSOR_STATIC = 3
+
+ + + +
+
+
+
SQL_CURSOR_TYPE = 6
+
+ + + +
+
+
+
SQL_CURSOR_TYPE_DEFAULT = 0
+
+ + + +
+
+
+
SQL_DATA_AT_EXEC = -2
+
+ + + +
+
+
+
SQL_DATA_SOURCE_NAME = 2
+
+ + + +
+
+
+
SQL_DATA_SOURCE_READ_ONLY = 25
+
+ + + +
+
+
+
SQL_DATABASE_NAME = 2
+
+ + + +
+
+
+
SQL_DATE = 9
+
+ + + +
+
+
+
SQL_DATE_LEN = 10
+
+ + + +
+
+
+
SQL_DATETIME = 9
+
+ + + +
+
+
+
SQL_DATETIME_LITERALS = 119
+
+ + + +
+
+
+
SQL_DBMS_NAME = 17
+
+ + + +
+
+
+
SQL_DBMS_VERSION = 18
+
+ + + +
+
+
+
SQL_DECIMAL = 3
+
+ + + +
+
+
+
SQL_DEFAULT = 99
+
+ + + +
+
+
+
SQL_DELETE = 3
+
+ + + +
+
+
+
SQL_DELETE_BY_BOOKMARK = 6
+
+ + + +
+
+
+
SQL_DESC_ALLOC_TYPE = 1099
+
+ + + +
+
+
+
SQL_DESC_ARRAY_SIZE = 20
+
+ + + +
+
+
+
SQL_DESC_ARRAY_STATUS_PTR = 21
+
+ + + +
+
+
+
SQL_DESC_AUTO_UNIQUE_VALUE = 11
+
+ + + +
+
+
+
SQL_DESC_BASE_COLUMN_NAME = 22
+
+ + + +
+
+
+
SQL_DESC_BASE_TABLE_NAME = 23
+
+ + + +
+
+
+
SQL_DESC_BIND_OFFSET_PTR = 24
+
+ + + +
+
+
+
SQL_DESC_BIND_TYPE = 25
+
+ + + +
+
+
+
SQL_DESC_CASE_SENSITIVE = 12
+
+ + + +
+
+
+
SQL_DESC_CATALOG_NAME = 17
+
+ + + +
+
+
+
SQL_DESC_CONCISE_TYPE = 2
+
+ + + +
+
+
+
SQL_DESC_COUNT = 1001
+
+ + + +
+
+
+
SQL_DESC_DATA_PTR = 1010
+
+ + + +
+
+
+
SQL_DESC_DATETIME_INTERVAL_CODE = 1007
+
+ + + +
+
+ +
+
SQL_DESC_DISPLAY_SIZE = 6
+
+ + + +
+
+
+
SQL_DESC_FIXED_PREC_SCALE = 9
+
+ + + +
+
+
+
SQL_DESC_INDICATOR_PTR = 1009
+
+ + + +
+
+
+
SQL_DESC_LABEL = 18
+
+ + + +
+
+
+
SQL_DESC_LENGTH = 1003
+
+ + + +
+
+
+
SQL_DESC_LITERAL_PREFIX = 27
+
+ + + +
+
+
+
SQL_DESC_LITERAL_SUFFIX = 28
+
+ + + +
+
+
+
SQL_DESC_LOCAL_TYPE_NAME = 29
+
+ + + +
+
+
+
SQL_DESC_MAXIMUM_SCALE = 30
+
+ + + +
+
+
+
SQL_DESC_MINIMUM_SCALE = 31
+
+ + + +
+
+
+
SQL_DESC_NAME = 1011
+
+ + + +
+
+
+
SQL_DESC_NULLABLE = 1008
+
+ + + +
+
+
+
SQL_DESC_NUM_PREC_RADIX = 32
+
+ + + +
+
+
+
SQL_DESC_OCTET_LENGTH = 1013
+
+ + + +
+
+
+
SQL_DESC_OCTET_LENGTH_PTR = 1004
+
+ + + +
+
+
+
SQL_DESC_PARAMETER_TYPE = 33
+
+ + + +
+
+
+
SQL_DESC_PRECISION = 1005
+
+ + + +
+
+
+
SQL_DESC_ROWS_PROCESSED_PTR = 34
+
+ + + +
+
+
+
SQL_DESC_SCALE = 1006
+
+ + + +
+
+
+
SQL_DESC_SCHEMA_NAME = 16
+
+ + + +
+
+
+
SQL_DESC_SEARCHABLE = 13
+
+ + + +
+
+
+
SQL_DESC_TABLE_NAME = 15
+
+ + + +
+
+
+
SQL_DESC_TYPE = 1002
+
+ + + +
+
+
+
SQL_DESC_TYPE_NAME = 14
+
+ + + +
+
+
+
SQL_DESC_UNNAMED = 1012
+
+ + + +
+
+
+
SQL_DESC_UNSIGNED = 8
+
+ + + +
+
+
+
SQL_DESC_UPDATABLE = 10
+
+ + + +
+
+
+
SQL_DESCRIBE_PARAMETER = 10002
+
+ + + +
+
+
+
SQL_DIAG_ALTER_TABLE = 4
+
+ + + +
+
+
+
SQL_DIAG_CLASS_ORIGIN = 8
+
+ + + +
+
+
+
SQL_DIAG_CONNECTION_NAME = 10
+
+ + + +
+
+
+
SQL_DIAG_CREATE_INDEX = -1
+
+ + + +
+
+
+
SQL_DIAG_CREATE_TABLE = 77
+
+ + + +
+
+
+
SQL_DIAG_CREATE_VIEW = 84
+
+ + + +
+
+
+
SQL_DIAG_DELETE_WHERE = 19
+
+ + + +
+
+
+
SQL_DIAG_DROP_INDEX = -2
+
+ + + +
+
+
+
SQL_DIAG_DROP_TABLE = 32
+
+ + + +
+
+
+
SQL_DIAG_DROP_VIEW = 36
+
+ + + +
+
+
+
SQL_DIAG_DYNAMIC_DELETE_CURSOR = 38
+
+ + + +
+
+
+
SQL_DIAG_DYNAMIC_FUNCTION = 7
+
+ + + +
+
+
+
SQL_DIAG_DYNAMIC_FUNCTION_CODE = 12
+
+ + + +
+
+
+
SQL_DIAG_DYNAMIC_UPDATE_CURSOR = 81
+
+ + + +
+
+
+
SQL_DIAG_GRANT = 48
+
+ + + +
+
+
+
SQL_DIAG_INSERT = 50
+
+ + + +
+
+
+
SQL_DIAG_MESSAGE_TEXT = 6
+
+ + + +
+
+
+
SQL_DIAG_NATIVE = 5
+
+ + + +
+
+
+
SQL_DIAG_NUMBER = 2
+
+ + + +
+
+
+
SQL_DIAG_RETURNCODE = 1
+
+ + + +
+
+
+
SQL_DIAG_REVOKE = 59
+
+ + + +
+
+
+
SQL_DIAG_ROW_COUNT = 3
+
+ + + +
+
+
+
SQL_DIAG_SELECT_CURSOR = 85
+
+ + + +
+
+
+
SQL_DIAG_SERVER_NAME = 11
+
+ + + +
+
+
+
SQL_DIAG_SQLSTATE = 4
+
+ + + +
+
+
+
SQL_DIAG_SUBCLASS_ORIGIN = 9
+
+ + + +
+
+
+
SQL_DIAG_UNKNOWN_STATEMENT = 0
+
+ + + +
+
+
+
SQL_DIAG_UPDATE_WHERE = 82
+
+ + + +
+
+
+
SQL_DOUBLE = 8
+
+ + + +
+
+
+
SQL_DRIVER_COMPLETE = 1
+
+ + + +
+
+
+
SQL_DRIVER_COMPLETE_REQUIRED = 3
+
+ + + +
+
+
+
SQL_DRIVER_HDBC = 3
+
+ + + +
+
+
+
SQL_DRIVER_HENV = 4
+
+ + + +
+
+
+
SQL_DRIVER_HSTMT = 5
+
+ + + +
+
+
+
SQL_DRIVER_NAME = 6
+
+ + + +
+
+
+
SQL_DRIVER_NOPROMPT = 0
+
+ + + +
+
+
+
SQL_DRIVER_ODBC_VER = 77
+
+ + + +
+
+
+
SQL_DRIVER_PROMPT = 2
+
+ + + +
+
+
+
SQL_DRIVER_VER = 7
+
+ + + +
+
+
+
SQL_DROP = 1
+
+ + + +
+
+
+
SQL_DYNAMIC_CURSOR_ATTRIBUTES1 = 144
+
+ + + +
+
+
+
SQL_DYNAMIC_CURSOR_ATTRIBUTES2 = 145
+
+ + + +
+
+
+
SQL_ENSURE = 1
+
+ + + +
+
+
+
SQL_ERROR = -1
+
+ + + +
+
+
+
SQL_FALSE = 0
+
+ + + +
+
+
+
SQL_FETCH_ABSOLUTE = 5
+
+ + + +
+
+
+
SQL_FETCH_BOOKMARK = 8
+
+ + + +
+
+
+
SQL_FETCH_BY_BOOKMARK = 7
+
+ + + +
+
+
+
SQL_FETCH_DIRECTION = 8
+
+ + + +
+
+
+
SQL_FETCH_FIRST = 2
+
+ + + +
+
+
+
SQL_FETCH_FIRST_SYSTEM = 32
+
+ + + +
+
+
+
SQL_FETCH_FIRST_USER = 31
+
+ + + +
+
+
+
SQL_FETCH_LAST = 3
+
+ + + +
+
+
+
SQL_FETCH_NEXT = 1
+
+ + + +
+
+
+
SQL_FETCH_PRIOR = 4
+
+ + + +
+
+
+
SQL_FETCH_RELATIVE = 6
+
+ + + +
+
+
+
SQL_FLOAT = 6
+
+ + + +
+
+ + +
+
SQL_GET_BOOKMARK = 13
+
+ + + +
+
+
+
SQL_GUID = -11
+
+ + + +
+
+
+
SQL_HANDLE_DBC = 2
+
+ + + +
+
+
+
SQL_HANDLE_DESC = 4
+
+ + + +
+
+
+
SQL_HANDLE_ENV = 1
+
+ + + +
+
+
+
SQL_HANDLE_STMT = 3
+
+ + + +
+
+
+
SQL_INDEX_ALL = 1
+
+ + + +
+
+
+
SQL_INDEX_CLUSTERED = 1
+
+ + + +
+
+
+
SQL_INDEX_HASHED = 2
+
+ + + +
+
+
+
SQL_INDEX_KEYWORDS = 148
+
+ + + +
+
+
+
SQL_INDEX_OTHER = 3
+
+ + + +
+
+
+
SQL_INDEX_UNIQUE = 0
+
+ + + +
+
+
+
SQL_INFO_SCHEMA_VIEWS = 149
+
+ + + +
+
+
+
SQL_INSENSITIVE = 1
+
+ + + +
+
+
+
SQL_INTEGER = 4
+
+ + + +
+
+
+
SQL_INTERVAL = 10
+
+ + + +
+
+
+
SQL_INTERVAL_DAY = 103
+
+ + + +
+
+
+
SQL_INTERVAL_DAY_TO_HOUR = 108
+
+ + + +
+
+
+
SQL_INTERVAL_DAY_TO_MINUTE = 109
+
+ + + +
+
+
+
SQL_INTERVAL_DAY_TO_SECOND = 110
+
+ + + +
+
+
+
SQL_INTERVAL_HOUR = 104
+
+ + + +
+
+
+
SQL_INTERVAL_HOUR_TO_MINUTE = 111
+
+ + + +
+
+
+
SQL_INTERVAL_HOUR_TO_SECOND = 112
+
+ + + +
+
+
+
SQL_INTERVAL_MINUTE = 105
+
+ + + +
+
+
+
SQL_INTERVAL_MINUTE_TO_SECOND = 113
+
+ + + +
+
+
+
SQL_INTERVAL_MONTH = 102
+
+ + + +
+
+
+
SQL_INTERVAL_SECOND = 106
+
+ + + +
+
+
+
SQL_INTERVAL_YEAR = 101
+
+ + + +
+
+
+
SQL_INTERVAL_YEAR_TO_MONTH = 107
+
+ + + +
+
+
+
SQL_INVALID_HANDLE = -2
+
+ + + +
+
+
+
SQL_IS_INTEGER = -6
+
+ + + +
+
+
+
SQL_IS_POINTER = -4
+
+ + + +
+
+
+
SQL_IS_SMALLINT = -8
+
+ + + +
+
+
+
SQL_IS_UINTEGER = -5
+
+ + + +
+
+
+
SQL_IS_USMALLINT = -7
+
+ + + +
+
+
+
SQL_KEYSET_CURSOR_ATTRIBUTES1 = 150
+
+ + + +
+
+
+
SQL_KEYSET_CURSOR_ATTRIBUTES2 = 151
+
+ + + +
+
+
+
SQL_KEYSET_SIZE = 8
+
+ + + +
+
+
+
SQL_LOCK_EXCLUSIVE = 1
+
+ + + +
+
+
+
SQL_LOCK_NO_CHANGE = 0
+
+ + + +
+
+
+
SQL_LOCK_UNLOCK = 2
+
+ + + +
+
+
+
SQL_LOGIN_TIMEOUT = 103
+
+ + + +
+
+
+
SQL_LONGVARBINARY = -4
+
+ + + +
+
+
+
SQL_LONGVARCHAR = -1
+
+ + + +
+
+
+
SQL_MAX_DSN_LENGTH = 32
+
+ + + +
+
+
+
SQL_MAX_IDENTIFIER_LEN = 10005
+
+ + + +
+
+
+
SQL_MAX_LENGTH = 3
+
+ + + +
+
+
+
SQL_MAX_MESSAGE_LENGTH = 512
+
+ + + +
+
+
+
SQL_MAX_OPTION_STRING_LENGTH = 256
+
+ + + +
+
+
+
SQL_MAX_ROWS = 1
+
+ + + +
+
+
+
SQL_MAXIMUM_IDENTIFIER_LENGTH = 10005
+
+ + + +
+
+
+
SQL_MODE_DEFAULT = 0
+
+ + + +
+
+
+
SQL_MODE_READ_ONLY = 1
+
+ + + +
+
+
+
SQL_MODE_READ_WRITE = 0
+
+ + + +
+
+
+
SQL_NAME_LEN = 128
+
+ + + +
+
+
+
SQL_NEED_DATA = 99
+
+ + + +
+
+
+
SQL_NO_DATA = 100
+
+ + + +
+
+
+
SQL_NO_NULLS = 0
+
+ + + +
+
+
+
SQL_NO_TOTAL = -4
+
+ + + +
+
+
+
SQL_NONSCROLLABLE = 0
+
+ + + +
+
+
+
SQL_NOSCAN = 2
+
+ + + +
+
+
+
SQL_NTS = -3
+
+ + + +
+
+
+
SQL_NULL_DATA = -1
+
+ + + +
+
+
+
SQL_NULL_HANDLE = nil
+
+ + + +
+
+
+
SQL_NULL_HDBC = nil
+
+ + + +
+
+
+
SQL_NULL_HDESC = nil
+
+ + + +
+
+
+
SQL_NULL_HENV = nil
+
+ + + +
+
+
+
SQL_NULL_HSTMT = nil
+
+ + + +
+
+
+
SQL_NULLABLE = 1
+
+ + + +
+
+
+
SQL_NULLABLE_UNKNOWN = 2
+
+ + + +
+
+
+
SQL_NUMERIC = 2
+
+ + + +
+
+
+
SQL_ODBC_CURSORS = 110
+
+ + + +
+
+
+
SQL_ODBC_VER = 10
+
+ + + +
+
+
+
SQL_OJ_CAPABILITIES = 115
+
+ + + +
+
+
+
SQL_OPT_TRACE = 104
+
+ + + +
+
+
+
SQL_OPT_TRACEFILE = 105
+
+ + + +
+
+
+
SQL_OUTER_JOIN_CAPABILITIES = 115
+
+ + + +
+
+
+
SQL_OV_ODBC2 = 2
+
+ + + +
+
+
+
SQL_OV_ODBC3 = 3
+
+ + + +
+
+
+
SQL_PACKET_SIZE = 112
+
+ + + +
+
+
+
SQL_PARAM_INPUT = 1
+
+ + + +
+
+
+
SQL_PARAM_INPUT_OUTPUT = 2
+
+ + + +
+
+
+
SQL_PARAM_OUTPUT = 4
+
+ + + +
+
+
+
SQL_PARAM_TYPE_UNKNOWN = 0
+
+ + + +
+
+
+
SQL_POSITION = 0
+
+ + + +
+
+
+
SQL_QUERY_TIMEOUT = 0
+
+ + + +
+
+
+
SQL_QUICK = 0
+
+ + + +
+
+
+
SQL_QUIET_MODE = 111
+
+ + + +
+
+
+
SQL_REAL = 7
+
+ + + +
+
+
+
SQL_REFRESH = 1
+
+ + + +
+
+
+
SQL_RESET_PARAMS = 3
+
+ + + +
+
+
+
SQL_RESULT_COL = 3
+
+ + + +
+
+
+
SQL_RETRIEVE_DATA = 11
+
+ + + +
+
+
+
SQL_RETURN_VALUE = 5
+
+ + + +
+
+
+
SQL_ROLLBACK = 1
+
+ + + +
+
+
+
SQL_ROW_ADDED = 4
+
+ + + +
+
+
+
SQL_ROW_DELETED = 1
+
+ + + +
+
+
+
SQL_ROW_ERROR = 5
+
+ + + +
+
+
+
SQL_ROW_IDENTIFIER = 1
+
+ + + +
+
+
+
SQL_ROW_IGNORE = 1
+
+ + + +
+
+
+
SQL_ROW_NOROW = 3
+
+ + + +
+
+
+
SQL_ROW_NUMBER = 14
+
+ + + +
+
+
+
SQL_ROW_PROCEED = 0
+
+ + + +
+
+
+
SQL_ROW_SUCCESS = 0
+
+ + + +
+
+
+
SQL_ROW_SUCCESS_WITH_INFO = 6
+
+ + + +
+
+
+
SQL_ROW_UPDATED = 2
+
+ + + +
+
+
+
SQL_ROWSET_SIZE = 9
+
+ + + +
+
+
+
SQL_ROWVER = 2
+
+ + + +
+
+
+
SQL_SCCO_LOCK = 2
+
+ + + +
+
+
+
SQL_SCCO_OPT_ROWVER = 4
+
+ + + +
+
+
+
SQL_SCCO_OPT_VALUES = 8
+
+ + + +
+
+
+
SQL_SCCO_READ_ONLY = 1
+
+ + + +
+
+
+
SQL_SCOPE_CURROW = 0
+
+ + + +
+
+
+
SQL_SCOPE_SESSION = 2
+
+ + + +
+
+
+
SQL_SCOPE_TRANSACTION = 1
+
+ + + +
+
+
+
SQL_SCROLL_CONCURRENCY = 43
+
+ + + +
+
+
+
SQL_SCROLL_OPTIONS = 44
+
+ + + +
+
+
+
SQL_SCROLLABLE = 1
+
+ + + +
+
+
+
SQL_SENSITIVE = 2
+
+ + + +
+
+
+
SQL_SERVER_NAME = 13
+
+ + + +
+
+
+
SQL_SETPOS_MAX_OPTION_VALUE = 4
+
+ + + +
+
+
+
SQL_SIGNED_OFFSET = -20
+
+ + + +
+
+
+
SQL_SIMULATE_CURSOR = 10
+
+ + + +
+
+
+
SQL_SMALLINT = 5
+
+ + + +
+
+
+
SQL_SO_DYNAMIC = 0x00000004
+
+ + + +
+
+
+
SQL_SO_FORWARD_ONLY = 0x00000001
+
+ + + +
+
+
+
SQL_SO_KEYSET_DRIVEN = 0x00000002
+
+ + + +
+
+
+
SQL_SO_MIXED = 0x00000008
+
+ + + +
+
+
+
SQL_SO_STATIC = 0x00000010
+
+ + + +
+
+
+
SQL_SQL_CONFORMANCE = 118
+
+ + + +
+
+
+
SQL_SS_ADDITIONS = 1
+
+ + + +
+
+
+
SQL_SS_DELETIONS = 2
+
+ + + +
+
+
+
SQL_SS_UPDATES = 4
+
+ + + +
+
+
+
SQL_STATIC_CURSOR_ATTRIBUTES1 = 167
+
+ + + +
+
+
+
SQL_STATIC_CURSOR_ATTRIBUTES2 = 168
+
+ + + +
+
+
+
SQL_STATIC_SENSITIVITY = 83
+
+ + + +
+
+
+
SQL_STILL_EXECUTING = 2
+
+ + + +
+
+
+
SQL_SUCCESS = 0
+
+ + + +
+
+
+
SQL_SUCCESS_WITH_INFO = 1
+
+ + + +
+
+
+
SQL_TABLE_STAT = 0
+
+ + + +
+
+
+
SQL_TC_ALL = 2
+
+ + + +
+
+
+
SQL_TC_DDL_COMMIT = 3
+
+ + + +
+
+
+
SQL_TC_DDL_IGNORE = 4
+
+ + + +
+
+
+
SQL_TC_DML = 1
+
+ + + +
+
+
+
SQL_TC_NONE = 0
+
+ + + +
+
+
+
SQL_TIME = 10
+
+ + + +
+
+
+
SQL_TIME_LEN = 8
+
+ + + +
+
+
+
SQL_TIMESTAMP = 11
+
+ + + +
+
+
+
SQL_TIMESTAMP_LEN = 19
+
+ + + +
+
+
+
SQL_TINYINT = -6
+
+ + + +
+
+
+
SQL_TRANSACTION_CAPABLE = 46
+
+ + + +
+
+ + + + +
+
SQL_TRANSACTION_SERIALIZABLE = 8
+
+ + + +
+
+
+
SQL_TRANSLATE_DLL = 106
+
+ + + +
+
+
+
SQL_TRANSLATE_OPTION = 107
+
+ + + +
+
+
+
SQL_TRUE = 1
+
+ + + +
+
+
+
SQL_TXN_CAPABLE = 46
+
+ + + +
+
+
+
SQL_TXN_ISOLATION = 108
+
+ + + +
+
+
+
SQL_TXN_ISOLATION_OPTION = 72
+
+ + + +
+
+
+
SQL_TXN_READ_COMMITTED = 2
+
+ + + +
+
+
+
SQL_TXN_READ_UNCOMMITTED = 1
+
+ + + +
+
+
+
SQL_TXN_REPEATABLE_READ = 4
+
+ + + +
+
+
+
SQL_TXN_SERIALIZABLE = 8
+
+ + + +
+
+
+
SQL_TYPE_DATE = 91
+
+ + + +
+
+
+
SQL_TYPE_NULL = 0
+
+ + + +
+
+
+
SQL_TYPE_TIME = 92
+
+ + + +
+
+
+
SQL_TYPE_TIMESTAMP = 93
+
+ + + +
+
+
+
SQL_UB_DEFAULT = 0
+
+ + + +
+
+
+
SQL_UB_FIXED = 1
+
+ + + +
+
+
+
SQL_UB_OFF = 0
+
+ + + +
+
+
+
SQL_UB_ON = 1
+
+ + + +
+
+
+
SQL_UB_VARIABLE = 2
+
+ + + +
+
+
+
SQL_UNBIND = 2
+
+ + + +
+
+
+
SQL_UNICODE = -8
+
+ + + +
+
+
+
SQL_UNICODE_CHAR = -8
+
+ + + +
+
+
+
SQL_UNICODE_LONGVARCHAR = -10
+
+ + + +
+
+
+
SQL_UNICODE_VARCHAR = -9
+
+ + + +
+
+
+
SQL_UNKNOWN_TYPE = 0
+
+ + + +
+
+
+
SQL_UNSIGNED_OFFSET = -22
+
+ + + +
+
+
+
SQL_UNSPECIFIED = 0
+
+ + + +
+
+
+
SQL_UPDATE = 2
+
+ + + +
+
+
+
SQL_UPDATE_BY_BOOKMARK = 5
+
+ + + +
+
+
+
SQL_USE_BOOKMARKS = 12
+
+ + + +
+
+
+
SQL_USER_NAME = 47
+
+ + + +
+
+
+
SQL_VARBINARY = -3
+
+ + + +
+
+
+
SQL_VARCHAR = 12
+
+ + + +
+
+
+
SQL_WCHAR = -8
+
+ + + +
+
+
+
SQL_WLONGVARCHAR = -10
+
+ + + +
+
+
+
SQL_WVARCHAR = -9
+
+ + + +
+
+
+
SQL_XOPEN_CLI_YEAR = 10000
+
+ + + +
+
+ +
+
+
+

Procs

+
+
+
+
proc SQLAllocHandle(HandleType: TSqlSmallInt; InputHandle: SqlHandle;
+                    OutputHandlePtr: var SqlHandle): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLBindCol(StatementHandle: SqlHStmt; ColumnNumber: SqlUSmallInt;
+                TargetType: TSqlSmallInt; TargetValue: SqlPointer;
+                BufferLength: TSqlLen; StrLen_or_Ind: PSQLINTEGER): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLBindParameter(hstmt: SqlHStmt; ipar: SqlUSmallInt;
+                      fParamType: TSqlSmallInt; fCType: TSqlSmallInt;
+                      fSqlType: TSqlSmallInt; cbColDef: TSqlULen;
+                      ibScale: TSqlSmallInt; rgbValue: SqlPointer;
+                      cbValueMax: TSqlLen; pcbValue: var TSqlLen): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLBrowseConnect(hdbc: SqlHDBC; szConnStrIn: PSQLCHAR;
+                      cbConnStrIn: TSqlSmallInt; szConnStrOut: PSQLCHAR;
+                      cbConnStrOutMax: TSqlSmallInt;
+                      cbConnStrOut: var TSqlSmallInt): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLBulkOperations(StatementHandle: SqlHStmt; Operation: SqlUSmallInt): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLCloseCursor(StatementHandle: SqlHStmt): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLColAttribute(StatementHandle: SqlHStmt; ColumnNumber: SqlUSmallInt;
+                     FieldIdentifier: SqlUSmallInt;
+                     CharacterAttribute: PSQLCHAR; BufferLength: TSqlSmallInt;
+                     StringLength: PSQLSMALLINT; NumericAttribute: TSqlLen): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLColumns(hstmt: SqlHStmt; szTableQualifier: PSQLCHAR;
+                cbTableQualifier: TSqlSmallInt; szTableOwner: PSQLCHAR;
+                cbTableOwner: TSqlSmallInt; szTableName: PSQLCHAR;
+                cbTableName: TSqlSmallInt; szColumnName: PSQLCHAR;
+                cbColumnName: TSqlSmallInt): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLConnect(ConnectionHandle: SqlHDBC; ServerName: PSQLCHAR;
+                NameLength1: TSqlSmallInt; UserName: PSQLCHAR;
+                NameLength2: TSqlSmallInt; Authentication: PSQLCHAR;
+                NameLength3: TSqlSmallInt): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLDataSources(EnvironmentHandle: SqlHEnv; Direction: SqlUSmallInt;
+                    ServerName: PSQLCHAR; BufferLength1: TSqlSmallInt;
+                    NameLength1: PSQLSMALLINT; Description: PSQLCHAR;
+                    BufferLength2: TSqlSmallInt; NameLength2: PSQLSMALLINT): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLDescribeCol(StatementHandle: SqlHStmt; ColumnNumber: SqlUSmallInt;
+                    ColumnName: PSQLCHAR; BufferLength: TSqlSmallInt;
+                    NameLength: var TSqlSmallInt; DataType: var TSqlSmallInt;
+                    ColumnSize: var TSqlULen; DecimalDigits: var TSqlSmallInt;
+                    Nullable: var TSqlSmallInt): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLDisconnect(ConnectionHandle: SqlHDBC): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLDriverConnect(hdbc: SqlHDBC; hwnd: SqlHWND; szCsin: cstring;
+                      szCLen: TSqlSmallInt; szCsout: cstring;
+                      cbCSMax: TSqlSmallInt; cbCsOut: var TSqlSmallInt;
+                      f: SqlUSmallInt): TSqlSmallInt {.dynlib: odbclib, importc,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLDrivers(EnvironmentHandle: SqlHEnv; Direction: SqlUSmallInt;
+                DriverDescription: PSQLCHAR; BufferLength1: TSqlSmallInt;
+                DescriptionLength1: PSQLSMALLINT; DriverAttributes: PSQLCHAR;
+                BufferLength2: TSqlSmallInt; AttributesLength2: PSQLSMALLINT): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLEndTran(HandleType: TSqlSmallInt; Handle: SqlHandle;
+                CompletionType: TSqlSmallInt): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLErr(henv: SqlHEnv; hdbc: SqlHDBC; hstmt: SqlHStmt;
+            szSqlState, pfNativeError, szErrorMsg: PSQLCHAR;
+            cbErrorMsgMax: TSqlSmallInt; pcbErrorMsg: PSQLSMALLINT): TSqlSmallInt {.
+    dynlib: odbclib, importc: "SQLError", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLExecDirect(StatementHandle: SqlHStmt; StatementText: PSQLCHAR;
+                   TextLength: TSqlInteger): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLExecDirectW(StatementHandle: SqlHStmt; StatementText: WideCString;
+                    TextLength: TSqlInteger): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLExecute(StatementHandle: SqlHStmt): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLExtendedFetch(hstmt: SqlHStmt; fFetchType: SqlUSmallInt; irow: TSqlLen;
+                      pcrow: var TSqlULen; rgfRowStatus: PSQLUSMALLINT): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLFetch(StatementHandle: SqlHStmt): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLFetchScroll(StatementHandle: SqlHStmt; FetchOrientation: TSqlSmallInt;
+                    FetchOffset: TSqlLen): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLFreeHandle(HandleType: TSqlSmallInt; Handle: SqlHandle): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLFreeStmt(StatementHandle: SqlHStmt; Option: SqlUSmallInt): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLGetCursorName(StatementHandle: SqlHStmt; CursorName: PSQLCHAR;
+                      BufferLength: TSqlSmallInt; NameLength: PSQLSMALLINT): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLGetData(StatementHandle: SqlHStmt; ColumnNumber: SqlUSmallInt;
+                TargetType: TSqlSmallInt; TargetValue: SqlPointer;
+                BufferLength: TSqlLen; StrLen_or_Ind: ptr TSqlLen): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLGetDiagField(HandleType: TSqlSmallInt; Handle: SqlHandle;
+                     RecNumber: TSqlSmallInt; DiagIdentifier: TSqlSmallInt;
+                     DiagInfoPtr: SqlPointer; BufferLength: TSqlSmallInt;
+                     StringLengthPtr: var TSqlSmallInt): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLGetDiagRec(HandleType: TSqlSmallInt; Handle: SqlHandle;
+                   RecNumber: TSqlSmallInt; Sqlstate: PSQLCHAR;
+                   NativeError: var TSqlInteger; MessageText: PSQLCHAR;
+                   BufferLength: TSqlSmallInt; TextLength: var TSqlSmallInt): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLGetEnvAttr(EnvironmentHandle: SqlHEnv; Attribute: TSqlInteger;
+                   Value: SqlPointer; BufferLength: TSqlInteger;
+                   StringLength: PSQLINTEGER): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLGetInfo(ConnectionHandle: SqlHDBC; InfoType: SqlUSmallInt;
+                InfoValue: SqlPointer; BufferLength: TSqlSmallInt;
+                StringLength: PSQLSMALLINT): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLGetStmtAttr(StatementHandle: SqlHStmt; Attribute: TSqlInteger;
+                    Value: SqlPointer; BufferLength: TSqlInteger;
+                    StringLength: PSQLINTEGER): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLNumResultCols(StatementHandle: SqlHStmt; ColumnCount: var TSqlSmallInt): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLPrepare(StatementHandle: SqlHStmt; StatementText: PSQLCHAR;
+                TextLength: TSqlInteger): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLPrepareW(StatementHandle: SqlHStmt; StatementText: WideCString;
+                 TextLength: TSqlInteger): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLPrimaryKeys(hstmt: SqlHStmt; CatalogName: PSQLCHAR;
+                    NameLength1: TSqlSmallInt; SchemaName: PSQLCHAR;
+                    NameLength2: TSqlSmallInt; TableName: PSQLCHAR;
+                    NameLength3: TSqlSmallInt): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLProcedureColumns(hstmt: SqlHStmt; CatalogName: PSQLCHAR;
+                         NameLength1: TSqlSmallInt; SchemaName: PSQLCHAR;
+                         NameLength2: TSqlSmallInt; ProcName: PSQLCHAR;
+                         NameLength3: TSqlSmallInt; ColumnName: PSQLCHAR;
+                         NameLength4: TSqlSmallInt): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLProcedures(hstmt: SqlHStmt; szTableQualifier: PSQLCHAR;
+                   cbTableQualifier: TSqlSmallInt; szTableOwner: PSQLCHAR;
+                   cbTableOwner: TSqlSmallInt; szTableName: PSQLCHAR;
+                   cbTableName: TSqlSmallInt): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLPutData(StatementHandle: SqlHStmt; Data: SqlPointer;
+                StrLen_or_Ind: TSqlLen): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLRowCount(StatementHandle: SqlHStmt; RowCount: var TSqlLen): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLSetConnectAttr(ConnectionHandle: SqlHDBC; Attribute: TSqlInteger;
+                       Value: SqlPointer; StringLength: TSqlInteger): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLSetCursorName(StatementHandle: SqlHStmt; CursorName: PSQLCHAR;
+                      NameLength: TSqlSmallInt): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLSetEnvAttr(EnvironmentHandle: SqlHEnv; Attribute: TSqlInteger;
+                   Value: SqlPointer; StringLength: TSqlInteger): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLSetPos(hstmt: SqlHStmt; irow: SqlUSmallInt; fOption: SqlUSmallInt;
+               fLock: SqlUSmallInt): TSqlSmallInt {.dynlib: odbclib, importc,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLSetStmtAttr(StatementHandle: SqlHStmt; Attribute: TSqlInteger;
+                    Value: SqlPointer; StringLength: TSqlInteger): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLSpecialColumns(StatementHandle: SqlHStmt; IdentifierType: SqlUSmallInt;
+                       CatalogName: PSQLCHAR; NameLength1: TSqlSmallInt;
+                       SchemaName: PSQLCHAR; NameLength2: TSqlSmallInt;
+                       TableName: PSQLCHAR; NameLength3: TSqlSmallInt;
+                       Scope: SqlUSmallInt; Nullable: SqlUSmallInt): TSqlSmallInt {.
+    dynlib: odbclib, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLStatistics(hstmt: SqlHStmt; CatalogName: PSQLCHAR;
+                   NameLength1: TSqlSmallInt; SchemaName: PSQLCHAR;
+                   NameLength2: TSqlSmallInt; TableName: PSQLCHAR;
+                   NameLength3: TSqlSmallInt; Unique: SqlUSmallInt;
+                   Reserved: SqlUSmallInt): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc SQLTables(hstmt: SqlHStmt; szTableQualifier: PSQLCHAR;
+               cbTableQualifier: TSqlSmallInt; szTableOwner: PSQLCHAR;
+               cbTableOwner: TSqlSmallInt; szTableName: PSQLCHAR;
+               cbTableName: TSqlSmallInt; szTableType: PSQLCHAR;
+               cbTableType: TSqlSmallInt): TSqlSmallInt {.dynlib: odbclib,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/oids.html b/oids.html new file mode 100644 index 0000000000000..fa680631d0978 --- /dev/null +++ b/oids.html @@ -0,0 +1,253 @@ + + + + + + + +std/oids + + + + + + + + + + + + + + + + +
+
+

std/oids

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Nim OID support. 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 calls initRand() for the first call of genOid.

+

+ +
+

Types

+
+
+
Oid = object
+
+ + An OID. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(oid: Oid): string {....raises: [], tags: [], forbids: [].}
+
+ + Converts an OID to a string. + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(oid1: Oid; oid2: Oid): bool {.inline, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + Compares two OIDs for equality. + Source   +Edit   + +
+
+ +
+
+
+
proc generatedTime(oid: Oid): Time {....raises: [], tags: [], forbids: [].}
+
+ + Returns the generated timestamp of the OID. + Source   +Edit   + +
+
+ +
+
+
+
proc genOid(): Oid {....raises: [], tags: [TimeEffect], forbids: [].}
+
+ + Generates a new OID. +

Example:

+
doAssert ($genOid()).len == 24
+

Example: cmd: -r:off

+
echo $genOid() # for example, "5fc7f546ddbbc84800006aaf"
+ Source   +Edit   + +
+
+ +
+
+
+
proc hash(oid: Oid): Hash {....raises: [], tags: [], forbids: [].}
+
+ + Generates the hash of an OID for use in hashtables. + Source   +Edit   + +
+
+ +
+
+
+
proc hexbyte(hex: char): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc parseOid(str: cstring): Oid {....raises: [], tags: [], forbids: [].}
+
+ + Parses an OID. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/oids.idx b/oids.idx new file mode 100644 index 0000000000000..6022c9af8ec0c --- /dev/null +++ b/oids.idx @@ -0,0 +1,9 @@ +nimTitle oids oids.html module std/oids 0 +nim Oid oids.html#Oid object Oid 24 +nim `==` oids.html#==,Oid,Oid proc `==`(oid1: Oid; oid2: Oid): bool 29 +nim hash oids.html#hash,Oid proc hash(oid: Oid): Hash 34 +nim hexbyte oids.html#hexbyte,char proc hexbyte(hex: char): int 42 +nim parseOid oids.html#parseOid,cstring proc parseOid(str: cstring): Oid 45 +nim `$` oids.html#$,Oid proc `$`(oid: Oid): string 53 +nim genOid oids.html#genOid proc genOid(): Oid 86 +nim generatedTime oids.html#generatedTime,Oid proc generatedTime(oid: Oid): Time 94 diff --git a/openssl.html b/openssl.html new file mode 100644 index 0000000000000..7af66457beade --- /dev/null +++ b/openssl.html @@ -0,0 +1,4934 @@ + + + + + + + +std/openssl + + + + + + + + + + + + + + + + +
+
+

std/openssl

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

OpenSSL wrapper. Supports OpenSSL >= 1.1.0 dynamically (as default) or statically linked using --dynlibOverride:ssl.

+

-d:sslVersion=1.2.3 can be used to force an SSL version. This version must be included in the library name. -d:useOpenssl3 may be set for OpenSSL 3 instead.

+

There is also limited support for OpenSSL 1.0.x which may require -d:openssl10.

+

Build and test examples:

+

./bin/nim c -d:ssl -p:. -r tests/stdlib/tssl.nim
+./bin/nim c -d:ssl --threads:on -p:. -r tests/stdlib/thttpclient_ssl.nim
+./bin/nim c -d:ssl -p:. -r tests/untestable/tssl.nim
+./bin/nim c -d:ssl -p:. --dynlibOverride:ssl --passl:-lcrypto --passl:-lssl -r tests/untestable/tssl.nim
+./bin/nim r --putenv:NIM_TESTAMENT_REMOTE_NETWORKING:1 -d:ssl -p:testament/lib --threads:on tests/untestable/thttpclient_ssl_remotenetwork.nim

+

+ +
+

Types

+
+
+
BIO = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
DES_cblock = array[0 .. 7, int8]
+
+ + + Source   +Edit   + +
+
+
+
des_key_schedule = array[1 .. 16, des_ks_struct]
+
+ + + Source   +Edit   + +
+
+
+
des_ks_struct {.final.} = object
+  ks*: DES_cblock
+  weak_key*: cint
+
+ + + Source   +Edit   + +
+
+
+
ENGINE = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
EVP_MD = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
EVP_MD_CTX = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
EVP_PKEY = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
EVP_PKEY_CTX = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
MD5_CTX = object
+
+ + + Source   +Edit   + +
+
+
+
MD5_LONG = cuint
+
+ + + Source   +Edit   + +
+
+
+
PaddingType = enum
+  RSA_PKCS1_PADDING = 1, RSA_SSLV23_PADDING = 2, RSA_NO_PADDING = 3,
+  RSA_PKCS1_OAEP_PADDING = 4, RSA_X931_PADDING = 5, RSA_PKCS1_PSS_PADDING = 6
+
+ + + Source   +Edit   + +
+
+
+
PASN1_cInt = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
PASN1_UTCTIME = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
PBIO_METHOD = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
PDES_cblock = ptr DES_cblock
+
+ + + Source   +Edit   + +
+
+
+
pem_password_cb = proc (buf: cstring; size, rwflag: cint; userdata: pointer): cint {.
+    cdecl.}
+
+ + + Source   +Edit   + +
+
+
+
PFunction = proc () {.cdecl.}
+
+ + + Source   +Edit   + +
+
+
+
PPasswdCb = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
PRSA = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
PskClientCallback = proc (ssl: SslPtr; hint: cstring; identity: cstring;
+                          max_identity_len: cuint; psk: ptr uint8;
+                          max_psk_len: cuint): cuint {.cdecl.}
+
+ + + Source   +Edit   + +
+
+
+
PskServerCallback = proc (ssl: SslPtr; identity: cstring; psk: ptr uint8;
+                          max_psk_len: cint): cuint {.cdecl.}
+
+ + + Source   +Edit   + +
+
+
+
PSSL_METHOD = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
PSslPtr = ptr SslPtr
+
+ + + Source   +Edit   + +
+
+
+
PSTACK = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
PX509 = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
PX509_NAME = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
PX509_OBJECT = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
PX509_STORE = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
SslCtx = SslPtr
+
+ + + Source   +Edit   + +
+
+
+
SslPtr = ptr SslStruct
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
DLLSSLName = "(libssl-1_1-x64|ssleay64|libssl64).dll"
+
+ + + Source   +Edit   + +
+
+
+
DLLUtilName = "(libcrypto-1_1-x64|libeay64).dll"
+
+ + + Source   +Edit   + +
+
+
+
EVP_MAX_MD_SIZE = 36
+
+ + + Source   +Edit   + +
+
+
+
EVP_PKEY_RSA = 6
+
+ + + Source   +Edit   + +
+
+
+
MD5_CBLOCK = 64
+
+ + + Source   +Edit   + +
+
+
+
MD5_DIGEST_LENGTH = 16
+
+ + + Source   +Edit   + +
+
+
+
MD5_LBLOCK = 16
+
+ + + Source   +Edit   + +
+
+
+
OPENSSL_DES_DECRYPT = 0
+
+ + + Source   +Edit   + +
+
+
+
OPENSSL_DES_ENCRYPT = 1
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS = 11
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_EXTRA_CHAIN_CERT = 14
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_GET_CLIENT_CERT_REQUEST = 9
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_GET_FLAGS = 13
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_GET_MAX_CERT_LIST = 50
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_GET_NUM_RENEGOTIATIONS = 10
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_GET_READ_AHEAD = 40
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_GET_SESS_CACHE_MODE = 45
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_GET_SESS_CACHE_SIZE = 43
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_GET_SESSION_REUSED = 8
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_GET_TOTAL_RENEGOTIATIONS = 12
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_MODE = 33
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_NEED_TMP_RSA = 1
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_OPTIONS = 32
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SESS_ACCEPT = 24
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SESS_ACCEPT_GOOD = 25
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SESS_ACCEPT_RENEGOTIATE = 26
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SESS_CACHE_FULL = 31
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SESS_CB_HIT = 28
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SESS_CONNECT = 21
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SESS_CONNECT_GOOD = 22
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SESS_CONNECT_RENEGOTIATE = 23
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SESS_HIT = 27
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SESS_MISSES = 29
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SESS_NUMBER = 20
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SESS_TIMEOUTS = 30
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SET_ECDH_AUTO = 94
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SET_MAX_CERT_LIST = 51
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SET_MSG_CALLBACK = 15
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SET_MSG_CALLBACK_ARG = 16
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SET_MTU = 17
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SET_READ_AHEAD = 41
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SET_SESS_CACHE_MODE = 44
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SET_SESS_CACHE_SIZE = 42
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SET_TMP_DH = 3
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SET_TMP_DH_CB = 6
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SET_TMP_ECDH = 4
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SET_TMP_ECDH_CB = 7
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SET_TMP_RSA = 2
+
+ + + Source   +Edit   + +
+
+
+
SSL_CTRL_SET_TMP_RSA_CB = 5
+
+ + + Source   +Edit   + +
+
+
+
SSL_ERROR_NONE = 0
+
+ + + Source   +Edit   + +
+
+
+
SSL_ERROR_SSL = 1
+
+ + + Source   +Edit   + +
+
+
+
SSL_ERROR_SYSCALL = 5
+
+ + + Source   +Edit   + +
+
+
+
SSL_ERROR_WANT_ACCEPT = 8
+
+ + + Source   +Edit   + +
+
+
+
SSL_ERROR_WANT_CONNECT = 7
+
+ + + Source   +Edit   + +
+
+
+
SSL_ERROR_WANT_READ = 2
+
+ + + Source   +Edit   + +
+
+
+
SSL_ERROR_WANT_WRITE = 3
+
+ + + Source   +Edit   + +
+
+
+
SSL_ERROR_WANT_X509_LOOKUP = 4
+
+ + + Source   +Edit   + +
+
+
+
SSL_ERROR_ZERO_RETURN = 6
+
+ + + Source   +Edit   + +
+
+
+
SSL_FILETYPE_ASN1 = 2
+
+ + + Source   +Edit   + +
+
+
+
SSL_FILETYPE_PEM = 1
+
+ + + Source   +Edit   + +
+
+
+
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER = 2
+
+ + + Source   +Edit   + +
+
+
+
SSL_MODE_AUTO_RETRY = 4
+
+ + + Source   +Edit   + +
+
+
+
SSL_MODE_ENABLE_PARTIAL_WRITE = 1
+
+ + + Source   +Edit   + +
+
+
+
SSL_MODE_NO_AUTO_CHAIN = 8
+
+ + + Source   +Edit   + +
+
+
+
SSL_OP_ALL = 0x000FFFFF
+
+ + + Source   +Edit   + +
+
+
+
SSL_OP_NO_SSLv2 = 0x01000000
+
+ + + Source   +Edit   + +
+
+
+
SSL_OP_NO_SSLv3 = 0x02000000
+
+ + + Source   +Edit   + +
+
+
+
SSL_OP_NO_TLSv1 = 0x04000000
+
+ + + Source   +Edit   + +
+
+
+
SSL_OP_NO_TLSv1_1 = 0x08000000
+
+ + + Source   +Edit   + +
+
+
+
SSL_RECEIVED_SHUTDOWN = 2
+
+ + + Source   +Edit   + +
+
+
+
SSL_SENT_SHUTDOWN = 1
+
+ + + Source   +Edit   + +
+
+
+
SSL_ST_ACCEPT = 0x00002000
+
+ + + Source   +Edit   + +
+
+
+
SSL_ST_CONNECT = 0x00001000
+
+ + + Source   +Edit   + +
+
+
+
SSL_ST_INIT = 12288
+
+ + + Source   +Edit   + +
+
+
+
SSL_TLSEXT_ERR_ALERT_FATAL = 2
+
+ + + Source   +Edit   + +
+
+
+
SSL_TLSEXT_ERR_ALERT_WARNING = 1
+
+ + + Source   +Edit   + +
+
+
+
SSL_TLSEXT_ERR_NOACK = 3
+
+ + + Source   +Edit   + +
+
+
+
SSL_TLSEXT_ERR_OK = 0
+
+ + + Source   +Edit   + +
+
+
+
SSL_VERIFY_NONE = 0x00000000
+
+ + + Source   +Edit   + +
+
+
+
SSL_VERIFY_PEER = 0x00000001
+
+ + + Source   +Edit   + +
+
+
+
TLSEXT_NAMETYPE_host_name = 0
+
+ + + Source   +Edit   + +
+
+
+
useOpenssl3 {.booldefine.} = false
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH = 31
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_AKID_SKID_MISMATCH = 30
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_APPLICATION_VERIFICATION = 50
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_CERT_CHAIN_TOO_LONG = 22
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_CERT_HAS_EXPIRED = 10
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_CERT_NOT_YET_VALID = 9
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_CERT_REJECTED = 28
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_CERT_REVOKED = 23
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_CERT_SIGNATURE_FAILURE = 7
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_CERT_UNTRUSTED = 27
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_CRL_HAS_EXPIRED = 12
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_CRL_NOT_YET_VALID = 11
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_CRL_SIGNATURE_FAILURE = 8
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT = 18
+
+ + + Source   +Edit   + +
+
+ + + + +
+
X509_V_ERR_INVALID_CA = 24
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_INVALID_PURPOSE = 26
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_KEYUSAGE_NO_CERTSIGN = 32
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_OUT_OF_MEM = 17
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_PATH_LENGTH_EXCEEDED = 25
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN = 19
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_SUBJECT_ISSUER_MISMATCH = 29
+
+ + + Source   +Edit   + +
+
+ + + +
+
X509_V_ERR_UNABLE_TO_GET_CRL = 3
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER = 33
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT = 2
+
+ + + Source   +Edit   + +
+
+ + +
+
X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION = 34
+
+ + + Source   +Edit   + +
+
+
+
X509_V_ILLEGAL = 1
+
+ + + Source   +Edit   + +
+
+
+
X509_V_OK = 0
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc BIO_ctrl(bio: BIO; cmd: cint; larg: int; arg: cstring): int {.cdecl,
+    dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc BIO_do_connect(bio: BIO): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc BIO_do_handshake(bio: BIO): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc BIO_free(b: BIO): cint {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc BIO_get_ssl(bio: BIO; ssl: ptr SslPtr): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc BIO_new_mem_buf(data: pointer; len: cint): BIO {.cdecl,
+    dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc BIO_new_ssl_connect(ctx: SslCtx): BIO {.cdecl, dynlib: DLLSSLName, importc,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc BIO_read(b: BIO; data: cstring; length: cint): cint {.cdecl,
+    dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc BIO_set_conn_hostname(bio: BIO; name: cstring): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc BIO_write(b: BIO; data: cstring; length: cint): cint {.cdecl,
+    dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bioCtrlPending(b: BIO): cint {.cdecl, dynlib: DLLUtilName,
+                                    importc: "BIO_ctrl_pending", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bioFreeAll(b: BIO) {.cdecl, dynlib: DLLUtilName, importc: "BIO_free_all",
+                          ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bioNew(b: PBIO_METHOD): BIO {.cdecl, dynlib: DLLUtilName,
+                                   importc: "BIO_new", ...raises: [], tags: [],
+                                   forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bioRead(b: BIO; Buf: cstring; length: cint): cint {.cdecl,
+    dynlib: DLLUtilName, importc: "BIO_read", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bioSMem(): PBIO_METHOD {.cdecl, dynlib: DLLUtilName, importc: "BIO_s_mem",
+                              ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bioWrite(b: BIO; Buf: cstring; length: cint): cint {.cdecl,
+    dynlib: DLLUtilName, importc: "BIO_write", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc CRYPTO_malloc_init() {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc d2i_X509(b: string): PX509 {....raises: [Exception], tags: [], forbids: [].}
+
+ + decode DER/BER bytestring into X.509 certificate struct + Source   +Edit   + +
+
+
+
proc d2i_X509(px: ptr PX509; i: ptr ptr uint8; len: cint): PX509 {.cdecl,
+    dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ERR_error_string(e: culong; buf: cstring): cstring {.cdecl,
+    dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ERR_get_error(): culong {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ERR_load_BIO_strings() {....raises: [Exception], tags: [RootEffect],
+                              forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ERR_peek_last_error(): culong {.cdecl, dynlib: DLLUtilName, importc,
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ERR_print_errors_fp(fp: File) {.cdecl, dynlib: DLLUtilName, importc,
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ErrClearError() {.cdecl, dynlib: DLLUtilName, importc: "ERR_clear_error",
+                       ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ErrFreeStrings() {.cdecl, dynlib: DLLUtilName, importc: "ERR_free_strings",
+                        ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ErrRemoveState(pid: cint) {.cdecl, dynlib: DLLUtilName,
+                                 importc: "ERR_remove_state", ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_DigestFinal_ex(ctx: EVP_MD_CTX; buffer: pointer; size: ptr cuint): cint {.
+    cdecl, dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_DigestInit_ex(ctx: EVP_MD_CTX; typ: EVP_MD; engine: SslPtr = nil): cint {.
+    cdecl, dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_DigestSignFinal(ctx: EVP_MD_CTX; data: pointer; len: ptr csize_t): cint {.
+    cdecl, dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_DigestSignInit(ctx: EVP_MD_CTX; pctx: ptr EVP_PKEY_CTX; typ: EVP_MD;
+                        e: ENGINE; pkey: EVP_PKEY): cint {.cdecl,
+    dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_DigestUpdate(ctx: EVP_MD_CTX; data: pointer; len: cuint): cint {.cdecl,
+    dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_dss(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                         tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_dss1(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                          tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_ecdsa(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                           tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_md2(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                         tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_md4(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                         tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_md5(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                         tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_MD_CTX_cleanup(ctx: EVP_MD_CTX): cint {.cdecl,
+    importc: "EVP_MD_CTX_cleanup", dynlib: DLLUtilName, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_MD_CTX_create(): EVP_MD_CTX {.cdecl, importc: "EVP_MD_CTX_new",
+                                       dynlib: DLLUtilName, ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_MD_CTX_destroy(ctx: EVP_MD_CTX) {.cdecl, importc: "EVP_MD_CTX_free",
+    dynlib: DLLUtilName, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_md_null(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                             tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_MD_size(md: EVP_MD): cint {.cdecl, dynlib: DLLUtilName, importc,
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_mdc2(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                          tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_PKEY_CTX_free(pkeyCtx: EVP_PKEY_CTX) {.cdecl, dynlib: DLLUtilName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_PKEY_CTX_new(pkey: EVP_PKEY; e: ENGINE): EVP_PKEY_CTX {.cdecl,
+    dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_PKEY_free(p: EVP_PKEY) {.cdecl, dynlib: DLLUtilName, importc,
+                                  ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_PKEY_sign_init(c: EVP_PKEY_CTX): cint {.cdecl, dynlib: DLLUtilName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_ripemd160(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_sha(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                         tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_sha1(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                          tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_sha224(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                            tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_sha256(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                            tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_sha384(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                            tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_sha512(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                            tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc EVP_whirlpool(): EVP_MD {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getOpenSSLVersion(): culong {....raises: [Exception], tags: [RootEffect],
+                                   forbids: [].}
+
+ + Return OpenSSL version as unsigned long or 0 if not available + Source   +Edit   + +
+
+ +
+
+
+
proc HMAC(evp_md: EVP_MD; key: pointer; key_len: cint; d: cstring; n: csize_t;
+          md: cstring; md_len: ptr cuint): cstring {.cdecl, dynlib: DLLUtilName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc i2d_X509(cert: PX509): string {....raises: [Exception], tags: [], forbids: [].}
+
+ + encode cert to DER string + Source   +Edit   + +
+
+
+
proc i2d_X509(cert: PX509; o: ptr ptr uint8): cint {.cdecl, dynlib: DLLUtilName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc md5(d: ptr uint8; n: csize_t; md: ptr uint8): ptr uint8 {.importc: "MD5",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc md5_File(file: string): string {....raises: [IOError, Exception],
+                                      tags: [ReadIOEffect], forbids: [].}
+
+ + Generate MD5 hash for a file. Result is a 32 character + Source   +Edit   + +
+
+ +
+
+
+
proc md5_Final(md: cstring; c: var MD5_CTX): cint {.importc: "MD5_Final",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc md5_Init(c: var MD5_CTX): cint {.importc: "MD5_Init", ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc md5_Str(str: string): string {....raises: [], tags: [], forbids: [].}
+
+ + Generate MD5 hash for a string. Result is a 32 character hex string with lowercase characters + Source   +Edit   + +
+
+ +
+
+
+
proc md5_Transform(c: var MD5_CTX; b: ptr uint8) {.importc: "MD5_Transform",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc md5_Update(c: var MD5_CTX; data: pointer; len: csize_t): cint {.
+    importc: "MD5_Update", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc OpenSSL_add_all_algorithms() {....raises: [LibraryError, Exception],
+                                    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc OPENSSL_config(configName: cstring) {.cdecl, dynlib: DLLUtilName, importc,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc OPENSSL_sk_num(stack: PSTACK): int {.cdecl, dynlib: DLLSSLName, importc,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc OPENSSL_sk_value(stack: PSTACK; index: int): pointer {.cdecl,
+    dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc PEM_read_bio_PrivateKey(bp: BIO; x: ptr EVP_PKEY; cb: pointer; u: pointer): EVP_PKEY {.
+    cdecl, dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc PEM_read_bio_RSA_PUBKEY(bp: BIO; x: ptr PRSA; pw: pem_password_cb;
+                             u: pointer): PRSA {.cdecl, dynlib: DLLUtilName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc PEM_read_bio_RSAPrivateKey(bp: BIO; x: ptr PRSA; cb: pem_password_cb;
+                                u: pointer): PRSA {.cdecl, dynlib: DLLUtilName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc PEM_read_bio_RSAPublicKey(bp: BIO; x: ptr PRSA; cb: pem_password_cb;
+                               u: pointer): PRSA {.cdecl, dynlib: DLLUtilName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc PEM_read_RSA_PUBKEY(fp: pointer; x: ptr PRSA; cb: pem_password_cb;
+                         u: pointer): PRSA {.cdecl, dynlib: DLLUtilName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc PEM_read_RSAPrivateKey(fp: pointer; x: ptr PRSA; cb: pem_password_cb;
+                            u: pointer): PRSA {.cdecl, dynlib: DLLUtilName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc PEM_read_RSAPublicKey(fp: pointer; x: ptr PRSA; cb: pem_password_cb;
+                           u: pointer): PRSA {.cdecl, dynlib: DLLUtilName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc RSA_free(rsa: PRSA) {.cdecl, dynlib: DLLUtilName, importc, ...raises: [],
+                           tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc RSA_private_decrypt(flen: cint; fr: ptr uint8; to: ptr uint8; rsa: PRSA;
+                         padding: PaddingType): cint {.cdecl,
+    dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc RSA_private_encrypt(flen: cint; fr: ptr uint8; to: ptr uint8; rsa: PRSA;
+                         padding: PaddingType): cint {.cdecl,
+    dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc RSA_public_decrypt(flen: cint; fr: ptr uint8; to: ptr uint8; rsa: PRSA;
+                        padding: PaddingType): cint {.cdecl,
+    dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc RSA_public_encrypt(flen: cint; fr: ptr uint8; to: ptr uint8; rsa: PRSA;
+                        padding: PaddingType): cint {.cdecl,
+    dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc RSA_size(rsa: PRSA): cint {.cdecl, dynlib: DLLUtilName, importc,
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc RSA_verify(kind: cint; origMsg: pointer; origMsgLen: cuint;
+                signature: pointer; signatureLen: cuint; rsa: PRSA): cint {.
+    cdecl, dynlib: DLLUtilName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_accept(ssl: SslPtr): cint {.cdecl, dynlib: DLLSSLName, importc,
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_connect(ssl: SslPtr): cint {.cdecl, dynlib: DLLSSLName, importc,
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_ctrl(ssl: SslPtr; cmd: cint; larg: int; parg: pointer): int {.cdecl,
+    dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_check_private_key(ctx: SslCtx): cint {.cdecl, dynlib: DLLSSLName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_ctrl(ctx: SslCtx; cmd: cint; larg: clong; parg: pointer): clong {.
+    cdecl, dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_free(arg0: SslCtx) {.cdecl, dynlib: DLLSSLName, importc,
+                                  ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_get_ex_data(ssl: SslCtx; idx: cint): pointer {.cdecl,
+    dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_get_ex_new_index(argl: clong; argp: pointer; new_func: pointer;
+                              dup_func: pointer; free_func: pointer): cint {.
+    cdecl, dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_load_verify_locations(ctx: SslCtx; CAfile: cstring; CApath: cstring): cint {.
+    cdecl, dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_new(meth: PSSL_METHOD): SslCtx {.cdecl, dynlib: DLLSSLName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_set_alpn_protos(ctx: SslCtx; protos: cstring; protos_len: cuint): cint {.
+    cdecl, dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_set_alpn_select_cb(ctx: SslCtx; cb: proc (ssl: SslPtr;
+    out_proto: ptr cstring; outlen: cstring; in_proto: cstring; inlen: cuint;
+    arg: pointer): cint {.cdecl.}; arg: pointer): cint {.cdecl,
+    dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_set_cipher_list(s: SslCtx; ciphers: cstring): cint {.cdecl,
+    dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_set_ciphersuites(ctx: SslCtx; str: cstring): cint {.
+    ...raises: [LibraryError, Exception], tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_set_ecdh_auto(ctx: SslCtx; onoff: cint): cint {.inline,
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ +

Set automatic curve selection.

+

On OpenSSL >= 1.1.0 this is on by default and cannot be disabled.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_set_ex_data(ssl: SslCtx; idx: cint; arg: pointer): cint {.cdecl,
+    dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_set_next_proto_select_cb(ctx: SslCtx; cb: proc (s: SslPtr;
+    out_proto: cstring; outlen: cstring; in_proto: cstring; inlen: cuint;
+    arg: pointer): cint {.cdecl.}; arg: pointer) {.cdecl, dynlib: DLLSSLName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_set_next_protos_advertised_cb(ctx: SslCtx; cb: proc (ssl: SslPtr;
+    out_proto: ptr cstring; outlen: ptr cuint; arg: pointer): cint {.cdecl.};
+    arg: pointer) {.cdecl, dynlib: DLLSSLName, importc, ...raises: [], tags: [],
+                    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_set_psk_client_callback(ctx: SslCtx; callback: PskClientCallback) {.
+    cdecl, dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + Set callback called when OpenSSL needs PSK (for client). + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_set_psk_server_callback(ctx: SslCtx; callback: PskServerCallback) {.
+    cdecl, dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + Set callback called when OpenSSL needs PSK (for server). + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_set_session_id_context(context: SslCtx; sid_ctx: string;
+                                    sid_ctx_len: int) {.cdecl,
+    dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_set_tlsext_servername_arg(ctx: SslCtx; arg: pointer): int {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Set the pointer to be used in the callback registered to SSL_CTX_set_tlsext_servername_callback. + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_set_tlsext_servername_callback(ctx: SslCtx;
+    cb: proc (ssl: SslPtr; cb_id: int; arg: pointer): int {.cdecl.}): int {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Set the callback to be used on listening SSL connections when the client hello is received.

+

The callback should return one of:

+
  • SSL_TLSEXT_ERR_OK
  • +
  • SSL_TLSEXT_ERR_ALERT_WARNING
  • +
  • SSL_TLSEXT_ERR_ALERT_FATAL
  • +
  • SSL_TLSEXT_ERR_NOACK
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_set_verify(s: SslCtx; mode: int;
+                        cb: proc (a: int; b: pointer): int {.cdecl.}) {.cdecl,
+    dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_use_certificate_chain_file(ctx: SslCtx; filename: cstring): cint {.
+    stdcall, dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_use_certificate_file(ctx: SslCtx; filename: cstring; typ: cint): cint {.
+    stdcall, dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_use_PrivateKey_file(ctx: SslCtx; filename: cstring; typ: cint): cint {.
+    cdecl, dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_CTX_use_psk_identity_hint(ctx: SslCtx; hint: cstring): cint {.cdecl,
+    dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + Set PSK identity hint to use. + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_free(ssl: SslPtr) {.cdecl, dynlib: DLLSSLName, importc, ...raises: [],
+                             tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_get0_alpn_selected(ssl: SslPtr; data: ptr cstring; len: ptr cuint) {.
+    cdecl, dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_get0_next_proto_negotiated(s: SslPtr; data: ptr cstring; len: ptr cuint) {.
+    cdecl, dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_get0_verified_chain(ssl: SslPtr): PSTACK {.cdecl, dynlib: DLLSSLName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_get_error(s: SslPtr; ret_code: cint): cint {.cdecl, dynlib: DLLSSLName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_get_peer_certificate(ssl: SslCtx): PX509 {....raises: [LibraryError],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_get_psk_identity(ssl: SslPtr): cstring {.cdecl, dynlib: DLLSSLName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + Get PSK identity. + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_get_servername(ssl: SslPtr; typ: cint = TLSEXT_NAMETYPE_host_name): cstring {.
+    cdecl, dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + Retrieve the server name requested in the client hello. This can be used in the callback set in SSL_CTX_set_tlsext_servername_callback to implement virtual hosting. May return nil. + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_get_shutdown(ssl: SslPtr): cint {.cdecl, dynlib: DLLSSLName,
+    importc: "SSL_get_shutdown", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_get_SSL_CTX(ssl: SslPtr): SslCtx {.cdecl, dynlib: DLLSSLName, importc,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_get_verify_result(ssl: SslPtr): int {.cdecl, dynlib: DLLSSLName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_in_init(ssl: SslPtr): cint {....raises: [LibraryError, Exception],
+                                      tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_library_init(): cint {.discardable, ...raises: [LibraryError, Exception],
+                                tags: [RootEffect], forbids: [].}
+
+ + Initialize SSL using OPENSSL_init_ssl for OpenSSL >= 1.1.0 otherwise SSL_library_init + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_load_error_strings() {....raises: [LibraryError, Exception],
+                                tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_new(context: SslCtx): SslPtr {.cdecl, dynlib: DLLSSLName, importc,
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_pending(ssl: SslPtr): cint {.cdecl, dynlib: DLLSSLName, importc,
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_read(ssl: SslPtr; buf: pointer; num: int): cint {.cdecl,
+    dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_select_next_proto(out_proto: ptr cstring; outlen: cstring;
+                           server: cstring; server_len: cuint; client: cstring;
+                           client_len: cuint): cint {.cdecl, dynlib: DLLSSLName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_set_alpn_protos(ssl: SslPtr; protos: cstring; protos_len: cuint): cint {.
+    cdecl, dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_set_fd(ssl: SslPtr; fd: SocketHandle): cint {.cdecl,
+    dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_set_shutdown(ssl: SslPtr; mode: cint) {.cdecl, dynlib: DLLSSLName,
+    importc: "SSL_set_shutdown", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_set_SSL_CTX(ssl: SslPtr; ctx: SslCtx): SslCtx {.cdecl,
+    dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_set_tlsext_host_name(ssl: SslPtr; name: cstring): int {....raises: [],
+    tags: [], forbids: [].}
+
+ + Set the SNI server name extension to be used in a client hello. Returns 1 if SNI was set, 0 if current SSL configuration doesn't support SNI. + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_shutdown(ssl: SslPtr): cint {.cdecl, dynlib: DLLSSLName, importc,
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSL_write(ssl: SslPtr; buf: cstring; num: int): cint {.cdecl,
+    dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSLCTXSetMode(ctx: SslCtx; mode: int): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sslDoHandshake(ssl: SslPtr): cint {.cdecl, dynlib: DLLSSLName,
+    importc: "SSL_do_handshake", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sslPeek(ssl: SslPtr; buf: cstring; num: cint): cint {.cdecl,
+    dynlib: DLLSSLName, importc: "SSL_peek", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sslRead(ssl: SslPtr; buf: cstring; num: cint): cint {.cdecl,
+    dynlib: DLLSSLName, importc: "SSL_read", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sslSetAcceptState(s: SslPtr) {.cdecl, dynlib: DLLSSLName,
+                                    importc: "SSL_set_accept_state", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sslSetBio(ssl: SslPtr; rbio, wbio: BIO) {.cdecl, dynlib: DLLSSLName,
+    importc: "SSL_set_bio", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sslSetConnectState(s: SslPtr) {.cdecl, dynlib: DLLSSLName,
+                                     importc: "SSL_set_connect_state",
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSLv2_method(): PSSL_METHOD {....raises: [LibraryError], tags: [RootEffect],
+                                   forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSLv3_method(): PSSL_METHOD {....raises: [LibraryError], tags: [RootEffect],
+                                   forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSLv23_client_method(): PSSL_METHOD {....raises: [LibraryError],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SSLv23_method(): PSSL_METHOD {....raises: [LibraryError], tags: [RootEffect],
+                                    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sslWrite(ssl: SslPtr; buf: cstring; num: cint): cint {.cdecl,
+    dynlib: DLLSSLName, importc: "SSL_write", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc TLS_client_method(): PSSL_METHOD {....raises: [LibraryError],
+                                        tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc TLS_method(): PSSL_METHOD {....raises: [LibraryError], tags: [RootEffect],
+                                 forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc TLS_server_method(): PSSL_METHOD {....raises: [LibraryError],
+                                        tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc TLSv1_method(): PSSL_METHOD {.cdecl, dynlib: DLLSSLName, importc,
+                                   ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_check_host(cert: PX509; name: cstring; namelen: cint; flags: cuint;
+                     peername: cstring): cint {.cdecl, dynlib: DLLSSLName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_free(cert: PX509) {.cdecl, dynlib: DLLSSLName, importc, ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_get_issuer_name(a: PX509): PX509_NAME {.cdecl, dynlib: DLLUtilName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_get_subject_name(a: PX509): PX509_NAME {.cdecl, dynlib: DLLSSLName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_NAME_get_text_by_NID(subject: cstring; NID: cint; buf: cstring;
+                               size: cint): cint {.cdecl, dynlib: DLLSSLName,
+    importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_NAME_oneline(a: PX509_NAME; buf: cstring; size: cint): cstring {.
+    cdecl, dynlib: DLLSSLName, importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_OBJECT_free(a: PX509_OBJECT) {.importc, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_OBJECT_new(): PX509_OBJECT {.importc, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_STORE_add_cert(ctx: PX509_STORE; x: PX509): cint {.importc,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_STORE_free(v: PX509_STORE) {.importc, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_STORE_lock(ctx: PX509_STORE): cint {.importc, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_STORE_new(): PX509_STORE {.importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_STORE_set_flags(ctx: PX509_STORE; flags: culong): cint {.importc,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_STORE_set_purpose(ctx: PX509_STORE; purpose: cint): cint {.importc,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_STORE_set_trust(ctx: PX509_STORE; trust: cint): cint {.importc,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_STORE_unlock(ctx: PX509_STORE): cint {.importc, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc X509_STORE_up_ref(v: PX509_STORE): cint {.importc, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/options.html b/options.html new file mode 100644 index 0000000000000..e059e126990f0 --- /dev/null +++ b/options.html @@ -0,0 +1,601 @@ + + + + + + + +std/options + + + + + + + + + + + + + + + + +
+
+

std/options

+
+ +
+ Source   +Edit   + +
+ +

This module implements types which encapsulate an optional value.

+

A value of type Option[T] either contains a value x (represented as some(x)) or is empty (none(T)).

+

This can be useful when you have a value that can be present or not. The absence of a value is often represented by nil, but that is not always available, nor is it always a good solution.

+ +

Basic usage

Let's start with an example: a procedure that finds the index of a character in a string.

+ +

Example:

+
import std/options
+proc find(haystack: string, needle: char): Option[int] =
+  for i, c in haystack:
+    if c == needle:
+      return some(i)
+  return none(int)  # This line is actually optional,
+                    # because the default is empty
+
+let found = "abc".find('c')
+assert found.isSome and found.get() == 2
The get operation demonstrated above returns the underlying value, or raises UnpackDefect if there is no value. Note that UnpackDefect inherits from system.Defect and should therefore never be caught. Instead, rely on checking if the option contains a value with the isSome and isNone procs. +

Pattern matching

Note: +This requires the fusion package.
+

fusion/matching supports pattern matching on Options, with the Some(<pattern>) and None() patterns.

+

{.experimental: "caseStmtMacros".}
+
+import fusion/matching
+
+case some(42)
+of Some(@a):
+  assert a == 42
+of None():
+  assert false
+
+assertMatch(some(some(none(int))), Some(Some(None())))

+

+ +
+

Types

+
+
+
Option[T] = object
+  when T is SomePointer:
+  else:
+
+ + An optional type that may or may not contain a value of type T. When T is a a pointer type (ptr, pointer, ref, proc or iterator {.closure.}), none(T) is represented as nil. + Source   +Edit   + +
+
+
+
UnpackDefect = object of Defect
+
+ + + Source   +Edit   + +
+
+
+
UnpackError {....deprecated: "See corresponding Defect".} = UnpackDefect
+
+
+ Deprecated: See corresponding Defect +
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`[T](self: Option[T]): string
+
+ + Get the string representation of the Option. +

Example:

+
assert $some(42) == "some(42)"
+assert $none(int) == "none(int)"
+ Source   +Edit   + +
+
+ +
+
+
+
proc `==`[T](a, b: Option[T]): bool {.inline.}
+
+ + Returns true if both Options are none, or if they are both some and have equal values. +

Example:

+
let
+  a = some(42)
+  b = none(int)
+  c = some(42)
+  d = none(int)
+
+assert a == c
+assert b == d
+assert not (a == b)
+ Source   +Edit   + +
+
+ +
+
+
+
proc filter[T](self: Option[T]; callback: proc (input: T): bool): Option[T] {.
+    inline, effectsOf: callback.}
+
+ +

Applies a callback to the value of the Option.

+

If the callback returns true, the option is returned as some. If it returns false, it is returned as none.

+

See also:

+ + +

Example:

+
proc isEven(x: int): bool =
+  x mod 2 == 0
+
+assert some(42).filter(isEven) == some(42)
+assert none(int).filter(isEven) == none(int)
+assert some(-11).filter(isEven) == none(int)
+ Source   +Edit   + +
+
+ +
+
+
+
proc flatMap[T, R](self: Option[T]; callback: proc (input: T): Option[R]): Option[
+    R] {.inline, effectsOf: callback.}
+
+ +

Applies a callback function to the value of the Option and returns the new value.

+

If the Option has no value, none(R) will be returned.

+

This is similar to map, with the difference that the callback returns an Option, not a raw value. This allows multiple procs with a signature of A -> Option[B] to be chained together.

+

See also:

+ + +

Example:

+
proc doublePositives(x: int): Option[int] =
+  if x > 0:
+    some(2 * x)
+  else:
+    none(int)
+
+assert some(42).flatMap(doublePositives) == some(84)
+assert none(int).flatMap(doublePositives) == none(int)
+assert some(-11).flatMap(doublePositives) == none(int)
+ Source   +Edit   + +
+
+ +
+
+
+
proc flatten[T](self: Option[Option[T]]): Option[T] {.inline.}
+
+ +

Remove one level of structure in a nested Option.

+

See also:

+ + +

Example:

+
assert flatten(some(some(42))) == some(42)
+assert flatten(none(Option[int])) == none(int)
+ Source   +Edit   + +
+
+ +
+
+
+
proc get[T](self: Option[T]): lent T {.inline.}
+
+ +

Returns the content of an Option. If it has no value, an UnpackDefect exception is raised.

+

See also:

+ + +

Example:

+
assert some(42).get == 42
+doAssertRaises(UnpackDefect):
+  echo none(string).get
+ Source   +Edit   + +
+
+
+
proc get[T](self: Option[T]; otherwise: T): T {.inline.}
+
+ + Returns the content of the Option or otherwise if the Option has no value. +

Example:

+
assert some(42).get(9999) == 42
+assert none(int).get(9999) == 9999
+ Source   +Edit   + +
+
+
+
proc get[T](self: var Option[T]): var T {.inline.}
+
+ + Returns the content of the var Option mutably. If it has no value, an UnpackDefect exception is raised. +

Example:

+
var
+  a = some(42)
+  b = none(string)
+inc(a.get)
+assert a.get == 43
+doAssertRaises(UnpackDefect):
+  echo b.get
+ Source   +Edit   + +
+
+ +
+
+
+
proc isNone[T](self: Option[T]): bool {.inline.}
+
+ +

Checks if an Option is empty.

+

See also:

+ + +

Example:

+
assert not some(42).isNone
+assert none(string).isNone
+ Source   +Edit   + +
+
+ +
+
+
+
proc isSome[T](self: Option[T]): bool {.inline.}
+
+ +

Checks if an Option contains a value.

+

See also:

+ + +

Example:

+
assert some(42).isSome
+assert not none(string).isSome
+ Source   +Edit   + +
+
+ +
+
+
+
proc map[T, R](self: Option[T]; callback: proc (input: T): R): Option[R] {.
+    inline, effectsOf: callback.}
+
+ +

Applies a callback function to the value of the Option and returns an Option containing the new value.

+

If the Option has no value, none(R) will be returned.

+

See also:

+ + +

Example:

+
proc isEven(x: int): bool =
+  x mod 2 == 0
+
+assert some(42).map(isEven) == some(true)
+assert none(int).map(isEven) == none(bool)
+ Source   +Edit   + +
+
+
+
proc map[T](self: Option[T]; callback: proc (input: T)) {.inline,
+    effectsOf: callback.}
+
+ +

Applies a callback function to the value of the Option, if it has one.

+

See also:

+
  • map proc for a version with a callback which returns a value
  • +
+ +

Example:

+
var d = 0
+proc saveDouble(x: int) =
+  d = 2 * x
+
+none(int).map(saveDouble)
+assert d == 0
+some(42).map(saveDouble)
+assert d == 84
+ Source   +Edit   + +
+
+ +
+
+
+
proc none(T: typedesc): Option[T] {.inline.}
+
+ +

Returns an Option for this type that has no value.

+

See also:

+ + +

Example:

+
assert none(int).isNone
+ Source   +Edit   + +
+
+
+
proc none[T](): Option[T] {.inline.}
+
+ + Alias for none(T). + Source   +Edit   + +
+
+ +
+
+
+
proc option[T](val: sink T): Option[T] {.inline.}
+
+ +

Can be used to convert a pointer type (ptr, pointer, ref or proc) to an option type. It converts nil to none(T). When T is no pointer type, this is equivalent to some(val).

+

See also:

+ + +

Example:

+
type
+  Foo = ref object
+    a: int
+    b: string
+
+assert option[Foo](nil).isNone
+assert option(42).isSome
+ Source   +Edit   + +
+
+ +
+
+
+
proc some[T](val: sink T): Option[T] {.inline.}
+
+ +

Returns an Option that has the value val.

+

See also:

+ + +

Example:

+
let a = some("abc")
+
+assert a.isSome
+assert a.get == "abc"
+ Source   +Edit   + +
+
+ +
+
+
+
proc unsafeGet[T](self: Option[T]): lent T {.inline.}
+
+ +

Returns the value of a some. The behavior is undefined for none.

+

Note: Use this only when you are absolutely sure the value is present (e.g. after checking with isSome). Generally, using the get proc is preferred.

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/options.idx b/options.idx new file mode 100644 index 0000000000000..a5920cd40275f --- /dev/null +++ b/options.idx @@ -0,0 +1,26 @@ +nimTitle options options.html module std/options 0 +nim Option options.html#Option object Option 91 +nim UnpackDefect options.html#UnpackDefect object UnpackDefect 101 +nim UnpackError options.html#UnpackError type UnpackError 102 +nim option options.html#option,sinkT proc option[T](val: sink T): Option[T] 104 +nim some options.html#some,sinkT proc some[T](val: sink T): Option[T] 125 +nim none options.html#none,typedesc proc none(T: typedesc): Option[T] 144 +nim none options.html#none proc none[T](): Option[T] 157 +nim isSome options.html#isSome,Option[T] proc isSome[T](self: Option[T]): bool 161 +nim isNone options.html#isNone,Option[T] proc isNone[T](self: Option[T]): bool 176 +nim get options.html#get,Option[T] proc get[T](self: Option[T]): lent T 191 +nim get options.html#get,Option[T],T proc get[T](self: Option[T]; otherwise: T): T 206 +nim get options.html#get,Option[T]_2 proc get[T](self: var Option[T]): var T 218 +nim map options.html#map,Option[T],proc(T) proc map[T](self: Option[T]; callback: proc (input: T)) 234 +nim map options.html#map,Option[T],proc(T)_2 proc map[T, R](self: Option[T]; callback: proc (input: T): R): Option[R] 253 +nim flatten options.html#flatten,Option[Option[T]] proc flatten[T](self: Option[Option[T]]): Option[T] 275 +nim flatMap options.html#flatMap,Option[T],proc(T) proc flatMap[T, R](self: Option[T]; callback: proc (input: T): Option[R]): Option[R] 289 +nim filter options.html#filter,Option[T],proc(T) proc filter[T](self: Option[T]; callback: proc (input: T): bool): Option[T] 315 +nim `==` options.html#==,Option[T],Option[T] proc `==`[T](a, b: Option[T]): bool 336 +nim `$` options.html#$,Option[T] proc `$`[T](self: Option[T]): string 355 +nim unsafeGet options.html#unsafeGet,Option[T] proc unsafeGet[T](self: Option[T]): lent T 374 +heading Basic usage options.html#basic-usage Basic usage 0 +heading Pattern matching options.html#pattern-matching Pattern matching 0 +nimgrp none options.html#none-procs-all proc 144 +nimgrp map options.html#map-procs-all proc 234 +nimgrp get options.html#get-procs-all proc 191 diff --git a/os.html b/os.html new file mode 100644 index 0000000000000..6361ceedc4a9a --- /dev/null +++ b/os.html @@ -0,0 +1,978 @@ + + + + + + + +std/os + + + + + + + + + + + + + + + + +
+
+

std/os

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module contains basic operating system facilities like retrieving environment variables, working with directories, running shell commands, etc. +

Example:

+
import std/os
+let myFile = "/path/to/my/file.nim"
+assert splitPath(myFile) == (head: "/path/to/my", tail: "file.nim")
+when defined(posix):
+  assert parentDir(myFile) == "/path/to/my"
+assert splitFile(myFile) == (dir: "/path/to/my", name: "file", ext: ".nim")
+assert myFile.changeFileExt("c") == "/path/to/my/file.c"
See also: +

+ +
+

Types

+
+
+
DeviceId = Dev
+
+ + + Source   +Edit   + +
+
+
+
FileId = Ino
+
+ + + Source   +Edit   + +
+
+
+
FileInfo = object
+  id*: tuple[device: DeviceId, file: FileId] ## Device and file id.
+  kind*: PathComponent       ## Kind of file object - directory, symlink, etc.
+  size*: BiggestInt          ## Size of file.
+  permissions*: set[FilePermission] ## File permissions
+  linkCount*: BiggestInt     ## Number of hard links the file object has.
+  lastAccessTime*: times.Time ## Time file was last accessed.
+  lastWriteTime*: times.Time ## Time file was last modified/written to.
+  creationTime*: times.Time  ## Time file was created. Not supported on all systems!
+  blockSize*: int            ## Preferred I/O block size for this object.
+                             ## In some filesystems, this may vary from file to file.
+  isSpecial*: bool           ## Is file special? (on Unix some "files"
+                             ## can be special=non-regular like FIFOs,
+                             ## devices); for directories `isSpecial`
+                             ## is always `false`, for symlinks it is
+                             ## the same as for the link's target.
+
+ +

Contains information associated with a file object.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
ExeExts = [""]
+
+ + Platform specific file extension for executables. On Windows ["exe", "cmd", "bat"], on Posix [""]. + Source   +Edit   + +
+
+
+
invalidFilenameChars = {'/', '\\', ':', '*', '?', '\"', '<', '>', '|', '^',
+                        '\x00'}
+
+ + +Characters that may produce invalid filenames across Linux, Windows and Mac. You can check if your filename contains any of these chars and strip them for safety. Mac bans ':', Linux bans '/', Windows bans all others. + Source   +Edit   + +
+
+
+
invalidFilenames = ["CON", "PRN", "AUX", "NUL", "COM0", "COM1", "COM2", "COM3",
+                    "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT0",
+                    "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7",
+                    "LPT8", "LPT9"]
+
+ + +Filenames that may be invalid across Linux, Windows, Mac, etc. You can check if your filename match these and rename it for safety (Currently all invalid filenames are from Windows only). + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+ +
+
+
proc exclFilePermissions(filename: string; permissions: set[FilePermission]) {.
+    ...gcsafe, extern: "nos$1", tags: [ReadDirEffect, WriteDirEffect],
+    raises: [OSError], forbids: [].}
+
+ +

A convenience proc for:

+

setFilePermissions(filename, getFilePermissions(filename)-permissions)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc execShellCmd(command: string): int {....gcsafe, extern: "nos$1",
+    tags: [ExecIOEffect], raises: [], forbids: [].}
+
+ +

Executes a shell command.

+

Command has the form 'program args' where args are the command line arguments given to program. The proc returns the error code of the shell when it has finished (zero if there is no error). The proc does not return until the process has finished.

+

To execute a program without having a shell involved, use osproc.execProcess proc.

+

Examples:

+

discard execShellCmd("ls -la")

+ + Source   +Edit   + +
+
+ +
+
+
+
proc exitStatusLikeShell(status: cint): cint {....raises: [], tags: [], forbids: [].}
+
+ + Converts exit code from c_system into a shell exit code. + Source   +Edit   + +
+
+ +
+
+
+
proc expandFilename(filename: string): string {....gcsafe, extern: "nos$1",
+    tags: [ReadDirEffect], raises: [OSError], forbids: [].}
+
+ +

Returns the full (absolute) path of an existing file filename.

+

Raises OSError in case of an error. Follows symlinks.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc expandTilde(path: string): string {....tags: [ReadEnvEffect, ReadIOEffect],
+    raises: [], forbids: [].}
+
+ +

Expands ~ or a path starting with ~/ to a full path, replacing ~ with appdirs: getHomeDir() (otherwise returns path unmodified).

+

Windows: this is still supported despite the Windows platform not having this convention; also, both ~/ and ~\ are handled.

+

See also:

+ + +

Example:

+
assert expandTilde("~" / "appname.cfg") == getHomeDir() / "appname.cfg"
+assert expandTilde("~/foo/bar") == getHomeDir() / "foo/bar"
+assert expandTilde("/foo/bar") == "/foo/bar"
+ Source   +Edit   + +
+
+ +
+
+
+
proc fileNewer(a, b: string): bool {....gcsafe, extern: "nos$1", raises: [OSError],
+                                     tags: [], forbids: [].}
+
+ +

Returns true if the file a is newer than file b, i.e. if a's modification time is later than b's.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc findExe(exe: string; followSymlinks: bool = true;
+             extensions: openArray[string] = ExeExts): string {.
+    ...tags: [ReadDirEffect, ReadEnvEffect, ReadIOEffect], raises: [OSError],
+    forbids: [].}
+
+ +

Searches for exe in the current working directory and then in directories listed in the PATH environment variable.

+

Returns "" if the exe cannot be found. exe is added the ExeExts file extensions if it has none.

+

If the system supports symlinks it also resolves them until it meets the actual file. This behavior can be disabled if desired by setting followSymlinks = false.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getAppDir(): string {....gcsafe, extern: "nos$1", tags: [ReadIOEffect],
+                           raises: [], forbids: [].}
+
+ +

Returns the directory of the application's executable.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getAppFilename(): string {....gcsafe, extern: "nos$1", tags: [ReadIOEffect],
+                                raises: [], forbids: [].}
+
+ +

Returns the filename of the application's executable. This proc will resolve symlinks.

+

Returns empty string when name is unavailable

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getCreationTime(file: string): times.Time {....gcsafe, extern: "nos$1",
+    raises: [OSError], tags: [], forbids: [].}
+
+ +

Returns the file's creation time.

+

Note: Under POSIX OS's, the returned time may actually be the time at which the file's attribute's were last modified. See here for details.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getCurrentCompilerExe(): string {.compileTime, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ +

Returns the path of the currently running Nim compiler or nimble executable.

+

Can be used to retrieve the currently executing Nim compiler from a Nim or nimscript program, or the nimble binary inside a nimble program (likewise with other binaries built from compiler API).

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getCurrentProcessId(): int {....raises: [], tags: [], forbids: [].}
+
+ +

Return current process ID.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getFileInfo(file: File): FileInfo {....raises: [IOError, OSError], tags: [],
+    forbids: [].}
+
+ +

Retrieves file information for the file object.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc getFileInfo(handle: FileHandle): FileInfo {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ +

Retrieves file information for the file object represented by the given handle.

+

If the information cannot be retrieved, such as when the file handle is invalid, OSError is raised.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc getFileInfo(path: string; followSymlink = true): FileInfo {.
+    ...raises: [OSError], tags: [], forbids: [].}
+
+ +

Retrieves file information for the file object pointed to by path.

+

Due to intrinsic differences between operating systems, the information contained by the returned FileInfo object will be slightly different across platforms, and in some cases, incomplete or inaccurate.

+

When followSymlink is true (default), symlinks are followed and the information retrieved is information related to the symlink's target. Otherwise, information on the symlink itself is retrieved (however, field isSpecial is still determined from the target on Unix).

+

If the information cannot be retrieved, such as when the path doesn't exist, or when permission restrictions prevent the program from retrieving file information, OSError is raised.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getFileSize(file: string): BiggestInt {....gcsafe, extern: "nos$1",
+    tags: [ReadIOEffect], raises: [OSError], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getLastAccessTime(file: string): times.Time {....gcsafe, extern: "nos$1",
+    raises: [OSError], tags: [], forbids: [].}
+
+ +

Returns the file's last read or write access time.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getLastModificationTime(file: string): times.Time {....gcsafe,
+    extern: "nos$1", raises: [OSError], tags: [], forbids: [].}
+
+ +

Returns the file's last modification time.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inclFilePermissions(filename: string; permissions: set[FilePermission]) {.
+    ...gcsafe, extern: "nos$1", tags: [ReadDirEffect, WriteDirEffect],
+    raises: [OSError], forbids: [].}
+
+ +

A convenience proc for:

+

setFilePermissions(filename, getFilePermissions(filename)+permissions)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc isAdmin(): bool {....raises: [], tags: [], forbids: [].}
+
+ + Returns whether the caller's process is a member of the Administrators local group (on Windows) or a root (on POSIX), via geteuid() == 0. + Source   +Edit   + +
+
+ +
+
+
+
proc isHidden(path: string): bool {....raises: [], tags: [], forbids: [].}
+
+ +

Determines whether path is hidden or not, using this reference.

+

On Windows: returns true if it exists and its "hidden" attribute is set.

+

On posix: returns true if lastPathPart(path) starts with . and is not . or ...

+

Note: paths are not normalized to determine isHidden.

+ +

Example:

+
when defined(posix):
+  assert ".foo".isHidden
+  assert not ".foo/bar".isHidden
+  assert not ".".isHidden
+  assert not "..".isHidden
+  assert not "".isHidden
+  assert ".foo/".isHidden
+ Source   +Edit   + +
+
+ +
+
+
+
func isValidFilename(filename: string; maxLen = 259.Positive): bool {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Returns true if filename is valid for crossplatform use.

+

This is useful if you want to copy or save files across Windows, Linux, Mac, etc. It uses invalidFilenameChars, invalidFilenames and maxLen to verify the specified filename.

+

See also:

+ +
Warning: +This only checks filenames, not whole paths (because basically you can mount anything as a path on Linux).
+ +

Example:

+
assert not isValidFilename(" foo")     # Leading white space
+assert not isValidFilename("foo ")     # Trailing white space
+assert not isValidFilename("foo.")     # Ends with dot
+assert not isValidFilename("con.txt")  # "CON" is invalid (Windows)
+assert not isValidFilename("OwO:UwU")  # ":" is invalid (Mac)
+assert not isValidFilename("aux.bat")  # "AUX" is invalid (Windows)
+assert not isValidFilename("")         # Empty string
+assert not isValidFilename("foo/")     # Filename is empty
+ Source   +Edit   + +
+
+ +
+
+
+
proc quoteShell(s: string): string {.noSideEffect, ...gcsafe, extern: "nosp$1",
+                                     raises: [], tags: [], forbids: [].}
+
+ +

Quote s, so it can be safely passed to shell.

+

When on Windows, it calls quoteShellWindows proc. Otherwise, calls quoteShellPosix proc.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc quoteShellCommand(args: openArray[string]): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + Concatenates and quotes shell arguments args. +

Example:

+
when defined(posix):
+  assert quoteShellCommand(["aaa", "", "c d"]) == "aaa '' 'c d'"
+when defined(windows):
+  assert quoteShellCommand(["aaa", "", "c d"]) == "aaa \"\" \"c d\""
+ Source   +Edit   + +
+
+ +
+
+
+
proc quoteShellPosix(s: string): string {.noSideEffect, ...gcsafe,
+    extern: "nosp$1", raises: [], tags: [], forbids: [].}
+
+ + Quote s, so it can be safely passed to POSIX shell. + Source   +Edit   + +
+
+ +
+
+
+
proc quoteShellWindows(s: string): string {.noSideEffect, ...gcsafe,
+    extern: "nosp$1", raises: [], tags: [], forbids: [].}
+
+ +

Quote s, so it can be safely passed to Windows API.

+

Based on Python's subprocess.list2cmdline. See this link for more details.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc sameFileContent(path1, path2: string): bool {....gcsafe, extern: "nos$1",
+    tags: [ReadIOEffect], raises: [IOError, OSError], forbids: [].}
+
+ +

Returns true if both pathname arguments refer to files with identical binary content.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setLastModificationTime(file: string; t: times.Time) {....raises: [OSError],
+    tags: [], forbids: [].}
+
+ + Sets the file's last modification time. OSError is raised in case of an error. + Source   +Edit   + +
+
+ +
+
+
+
proc sleep(milsecs: int) {....gcsafe, extern: "nos$1", tags: [TimeEffect],
+                           raises: [], forbids: [].}
+
+ + Sleeps milsecs milliseconds. A negative milsecs causes sleep to return immediately. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template existsDir(args: varargs[untyped]): untyped {.
+    ...deprecated: "use dirExists".}
+
+
+ Deprecated: use dirExists +
+ + + Source   +Edit   + +
+
+ +
+
+
+
template existsFile(args: varargs[untyped]): untyped {.
+    ...deprecated: "use fileExists".}
+
+
+ Deprecated: use fileExists +
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/os.idx b/os.idx new file mode 100644 index 0000000000000..8d77cbe7911b1 --- /dev/null +++ b/os.idx @@ -0,0 +1,42 @@ +nimTitle os os.html module std/os 0 +nim invalidFilenameChars os.html#invalidFilenameChars const invalidFilenameChars 64 +nim invalidFilenames os.html#invalidFilenames const invalidFilenames 68 +nim expandTilde os.html#expandTilde,string proc expandTilde(path: string): string 112 +nim quoteShellWindows os.html#quoteShellWindows,string proc quoteShellWindows(s: string): string 141 +nim quoteShellPosix os.html#quoteShellPosix,string proc quoteShellPosix(s: string): string 174 +nim quoteShell os.html#quoteShell,string proc quoteShell(s: string): string 186 +nim quoteShellCommand os.html#quoteShellCommand,openArray[string] proc quoteShellCommand(args: openArray[string]): string 196 +nim ExeExts os.html#ExeExts const ExeExts 220 +nim findExe os.html#findExe,string,bool,openArray[string] proc findExe(exe: string; followSymlinks: bool = true;\n extensions: openArray[string] = ExeExts): string 224 +nim getLastModificationTime os.html#getLastModificationTime,string proc getLastModificationTime(file: string): times.Time 282 +nim getLastAccessTime os.html#getLastAccessTime,string proc getLastAccessTime(file: string): times.Time 300 +nim getCreationTime os.html#getCreationTime,string proc getCreationTime(file: string): times.Time 318 +nim fileNewer os.html#fileNewer,string,string proc fileNewer(a, b: string): bool 340 +nim isAdmin os.html#isAdmin proc isAdmin(): bool 358 +nim exitStatusLikeShell os.html#exitStatusLikeShell,cint proc exitStatusLikeShell(status: cint): cint 390 +nim execShellCmd os.html#execShellCmd,string proc execShellCmd(command: string): int 401 +nim expandFilename os.html#expandFilename,string proc expandFilename(filename: string): string 419 +nim getCurrentCompilerExe os.html#getCurrentCompilerExe proc getCurrentCompilerExe(): string 455 +nim createHardlink os.html#createHardlink,string,string proc createHardlink(src, dest: string) 463 +nim inclFilePermissions os.html#inclFilePermissions,string,set[FilePermission] proc inclFilePermissions(filename: string; permissions: set[FilePermission]) 481 +nim exclFilePermissions os.html#exclFilePermissions,string,set[FilePermission] proc exclFilePermissions(filename: string; permissions: set[FilePermission]) 490 +nim getAppFilename os.html#getAppFilename proc getAppFilename(): string 627 +nim getAppDir os.html#getAppDir proc getAppDir(): string 686 +nim sleep os.html#sleep,int proc sleep(milsecs: int) 693 +nim getFileSize os.html#getFileSize,string proc getFileSize(file: string): BiggestInt 706 +nim DeviceId os.html#DeviceId type DeviceId 728 +nim FileId os.html#FileId type FileId 729 +nim FileInfo os.html#FileInfo object FileInfo 732 +nim getFileInfo os.html#getFileInfo,FileHandle proc getFileInfo(handle: FileHandle): FileInfo 829 +nim getFileInfo os.html#getFileInfo,File proc getFileInfo(file: File): FileInfo 855 +nim getFileInfo os.html#getFileInfo,string proc getFileInfo(path: string; followSymlink = true): FileInfo 865 +nim sameFileContent os.html#sameFileContent,string,string proc sameFileContent(path1, path2: string): bool 904 +nim isHidden os.html#isHidden,string proc isHidden(path: string): bool 937 +nim getCurrentProcessId os.html#getCurrentProcessId proc getCurrentProcessId(): int 964 +nim setLastModificationTime os.html#setLastModificationTime,string, proc setLastModificationTime(file: string; t: times.Time) 976 +nim isValidFilename os.html#isValidFilename,string proc isValidFilename(filename: string; maxLen = 259.Positive): bool 994 +nim existsFile os.html#existsFile.t,varargs[untyped] template existsFile(args: varargs[untyped]): untyped 1029 +nim existsDir os.html#existsDir.t,varargs[untyped] template existsDir(args: varargs[untyped]): untyped 1031 +idx shell command os.html#shell-command_1 Module os 0 +idx absolute os.html#absolute_1 Module os 0 +nimgrp getfileinfo os.html#getFileInfo-procs-all proc 829 diff --git a/osappdirs.html b/osappdirs.html new file mode 100644 index 0000000000000..fb17fbc094a5b --- /dev/null +++ b/osappdirs.html @@ -0,0 +1,267 @@ + + + + + + + +std/private/osappdirs + + + + + + + + + + + + + + + + +
+
+

std/private/osappdirs

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc getCacheDir(): string {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ +

Returns the cache directory of the current user for applications.

+

This makes use of the following environment variables:

+
  • On Windows: getEnv("LOCALAPPDATA")
  • +
  • On macOS: getEnv("XDG_CACHE_HOME", getEnv("HOME") / "Library/Caches")
  • +
  • On other platforms: getEnv("XDG_CACHE_HOME", getEnv("HOME") / ".cache")
  • +
+

See also:

+ + + Source   +Edit   + +
+
+
+
proc getCacheDir(app: string): string {....raises: [], tags: [ReadEnvEffect],
+                                        forbids: [].}
+
+ + Returns the cache directory for an application app.
  • On Windows, this uses: getCacheDir() / app / "cache"
  • +
  • On other platforms, this uses: getCacheDir() / app
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
proc getConfigDir(): string {....gcsafe, extern: "nos$1",
+                              tags: [ReadEnvEffect, ReadIOEffect], raises: [],
+                              forbids: [].}
+
+ +

Returns the config directory of the current user for applications.

+

On non-Windows OSs, this proc conforms to the XDG Base Directory spec. Thus, this proc returns the value of the XDG_CONFIG_HOME environment variable if it is set, otherwise it returns the default configuration directory ("~/.config/").

+

An OS-dependent trailing slash is always present at the end of the returned string: \\ on Windows and / on all other OSs.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getDataDir(): string {....gcsafe, extern: "nos$1",
+                            tags: [ReadEnvEffect, ReadIOEffect], raises: [],
+                            forbids: [].}
+
+ +

Returns the data directory of the current user for applications.

+

On non-Windows OSs, this proc conforms to the XDG Base Directory spec. Thus, this proc returns the value of the XDG_DATA_HOME environment variable if it is set, otherwise it returns the default configuration directory ("~/.local/share" or "~/Library/Application Support" on macOS).

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getHomeDir(): string {....gcsafe, extern: "nos$1",
+                            tags: [ReadEnvEffect, ReadIOEffect], raises: [],
+                            forbids: [].}
+
+ +

Returns the home directory of the current user.

+

This proc is wrapped by the paths: expandTilde proc for the convenience of processing paths coming from user configuration files.

+

See also:

+ + +

Example:

+
import std/os
+assert getHomeDir() == expandTilde("~")
+ Source   +Edit   + +
+
+ +
+
+
+
proc getTempDir(): string {....gcsafe, extern: "nos$1",
+                            tags: [ReadEnvEffect, ReadIOEffect], raises: [],
+                            forbids: [].}
+
+ +

Returns the temporary directory of the current user for applications to save temporary files in.

+

On Windows, it calls GetTempPath. On Posix based platforms, it will check TMPDIR, TEMP, TMP and TEMPDIR environment variables in order. On all platforms, /tmp will be returned if the procs fails.

+

You can override this implementation by adding -d:tempDir=mytempname to your compiler invocation.

+

Note: This proc does not check whether the returned path exists.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/osappdirs.idx b/osappdirs.idx new file mode 100644 index 0000000000000..5a2a060955eb0 --- /dev/null +++ b/osappdirs.idx @@ -0,0 +1,8 @@ +nimTitle osappdirs osappdirs.html module std/private/osappdirs 0 +nim getHomeDir osappdirs.html#getHomeDir proc getHomeDir(): string 7 +nim getDataDir osappdirs.html#getDataDir proc getDataDir(): string 28 +nim getConfigDir osappdirs.html#getConfigDir proc getConfigDir(): string 52 +nim getCacheDir osappdirs.html#getCacheDir proc getCacheDir(): string 77 +nim getCacheDir osappdirs.html#getCacheDir,string proc getCacheDir(app: string): string 102 +nim getTempDir osappdirs.html#getTempDir proc getTempDir(): string 136 +nimgrp getcachedir osappdirs.html#getCacheDir-procs-all proc 77 diff --git a/oscommon.html b/oscommon.html new file mode 100644 index 0000000000000..f5293391cd6fb --- /dev/null +++ b/oscommon.html @@ -0,0 +1,307 @@ + + + + + + + +std/private/oscommon + + + + + + + + + + + + + + + + +
+
+

std/private/oscommon

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
PathComponent = enum
+  pcFile,                   ## path refers to a file
+  pcLinkToFile,             ## path refers to a symbolic link to a file
+  pcDir,                    ## path refers to a directory
+  pcLinkToDir                ## path refers to a symbolic link to a directory
+
+ +

Enumeration specifying a path component.

+

See also:

+ + + Source   +Edit   + +
+
+
+
ReadDirEffect = object of ReadIOEffect
+
+ + Effect that denotes a read operation from the directory structure. + Source   +Edit   + +
+
+
+
WriteDirEffect = object of WriteIOEffect
+
+ + Effect that denotes a write operation to the directory structure. + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
maxSymlinkLen = 1024
+
+ + + Source   +Edit   + +
+
+
+
weirdTarget = false
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc dirExists(dir: string): bool {....gcsafe, extern: "nos$1",
+                                    tags: [ReadDirEffect], sideEffect,
+                                    ...raises: [], forbids: [].}
+
+ +

Returns true if the directory dir exists. If dir is a file, false is returned. Follows symlinks.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fileExists(filename: string): bool {....gcsafe, extern: "nos$1",
+    tags: [ReadDirEffect], sideEffect, ...raises: [], forbids: [].}
+
+ +

Returns true if filename exists and is a regular file or symlink.

+

Directories, device files, named pipes and sockets return false.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getSymlinkFileKind(path: string): tuple[pc: PathComponent, isSpecial: bool] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc symlinkExists(link: string): bool {....gcsafe, extern: "nos$1",
+    tags: [ReadDirEffect], sideEffect, ...raises: [], forbids: [].}
+
+ +

Returns true if the symlink link exists. Will return true regardless of whether the link points to a directory or file.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc tryMoveFSObject(source, dest: string; isDir: bool): bool {.
+    ...raises: [OSError], tags: [], forbids: [].}
+
+ +

Moves a file (or directory if isDir is true) from source to dest.

+

Returns false in case of EXDEV error or AccessDeniedError on Windows (if isDir is true). In case of other errors OSError is raised. Returns true in case of success.

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/oscommon.idx b/oscommon.idx new file mode 100644 index 0000000000000..0a28e1a43821e --- /dev/null +++ b/oscommon.idx @@ -0,0 +1,15 @@ +nimTitle oscommon oscommon.html module std/private/oscommon 0 +nim weirdTarget oscommon.html#weirdTarget const weirdTarget 10 +nim ReadDirEffect oscommon.html#ReadDirEffect object ReadDirEffect 14 +nim WriteDirEffect oscommon.html#WriteDirEffect object WriteDirEffect 17 +nim pcFile oscommon.html#pcFile PathComponent.pcFile 70 +nim pcLinkToFile oscommon.html#pcLinkToFile PathComponent.pcLinkToFile 70 +nim pcDir oscommon.html#pcDir PathComponent.pcDir 70 +nim pcLinkToDir oscommon.html#pcLinkToDir PathComponent.pcLinkToDir 70 +nim PathComponent oscommon.html#PathComponent enum PathComponent 70 +nim getSymlinkFileKind oscommon.html#getSymlinkFileKind,string proc getSymlinkFileKind(path: string): tuple[pc: PathComponent, isSpecial: bool] 82 +nim tryMoveFSObject oscommon.html#tryMoveFSObject,string,string,bool proc tryMoveFSObject(source, dest: string; isDir: bool): bool 94 +nim maxSymlinkLen oscommon.html#maxSymlinkLen const maxSymlinkLen 119 +nim fileExists oscommon.html#fileExists,string proc fileExists(filename: string): bool 121 +nim dirExists oscommon.html#dirExists,string proc dirExists(dir: string): bool 139 +nim symlinkExists oscommon.html#symlinkExists,string proc symlinkExists(link: string): bool 156 diff --git a/osdirs.html b/osdirs.html new file mode 100644 index 0000000000000..707e6dc14db2f --- /dev/null +++ b/osdirs.html @@ -0,0 +1,521 @@ + + + + + + + +std/private/osdirs + + + + + + + + + + + + + + + + +
+
+

std/private/osdirs

+
+ +
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc copyDir(source, dest: string; skipSpecial = false) {....gcsafe,
+    extern: "nos$1", tags: [ReadDirEffect, WriteIOEffect, ReadIOEffect], gcsafe,
+    raises: [OSError, IOError], forbids: [].}
+
+ +

Copies a directory from source to dest.

+

On non-Windows OSes, symlinks are copied as symlinks. On Windows, symlinks are skipped.

+

If skipSpecial is true, then (besides all directories) only regular files (without special "file" objects like FIFOs, device files, etc) will be copied on Unix.

+

If this fails, OSError is raised.

+

On the Windows platform this proc will copy the attributes from source into dest.

+

On other platforms created files and directories will inherit the default permissions of a newly created file/directory for the user. Use copyDirWithPermissions proc to preserve attributes recursively on these platforms.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc copyDirWithPermissions(source, dest: string; ignorePermissionErrors = true;
+                            skipSpecial = false) {....gcsafe, extern: "nos$1",
+    tags: [ReadDirEffect, WriteIOEffect, ReadIOEffect], gcsafe,
+    raises: [OSError, IOError, Exception], forbids: [].}
+
+ +

Copies a directory from source to dest preserving file permissions.

+

On non-Windows OSes, symlinks are copied as symlinks. On Windows, symlinks are skipped.

+

If skipSpecial is true, then (besides all directories) only regular files (without special "file" objects like FIFOs, device files, etc) will be copied on Unix.

+

If this fails, OSError is raised. This is a wrapper proc around copyDir and osfiles: copyFileWithPermissions procs on non-Windows platforms.

+

On Windows this proc is just a wrapper for copyDir proc since that proc already copies attributes.

+

On non-Windows systems permissions are copied after the file or directory itself has been copied, which won't happen atomically and could lead to a race condition. If ignorePermissionErrors is true (default), errors while reading/setting file attributes will be ignored, otherwise will raise OSError.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createDir(dir: string) {....gcsafe, extern: "nos$1",
+                              tags: [WriteDirEffect, ReadDirEffect],
+                              raises: [OSError, IOError], forbids: [].}
+
+ +

Creates the directory dir.

+

The directory may contain several subdirectories that do not exist yet. The full path is created. If this fails, OSError is raised.

+

It does not fail if the directory already exists because for most usages this does not indicate an error.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc existsOrCreateDir(dir: string): bool {....gcsafe, extern: "nos$1",
+    tags: [WriteDirEffect, ReadDirEffect], raises: [OSError, IOError],
+    forbids: [].}
+
+ +

Checks if a directory dir exists, and creates it otherwise.

+

Does not create parent directories (raises OSError if parent directories do not exist). Returns true if the directory already exists, and false otherwise.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc moveDir(source, dest: string) {....tags: [ReadIOEffect, WriteIOEffect],
+                                     raises: [OSError, IOError], forbids: [].}
+
+ +

Moves a directory from source to dest.

+

Symlinks are not followed: if source contains symlinks, they themself are moved, not their target.

+

If this fails, OSError is raised.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc removeDir(dir: string; checkDir = false) {....gcsafe, extern: "nos$1",
+    tags: [WriteDirEffect, ReadDirEffect], gcsafe, raises: [OSError],
+    forbids: [].}
+
+ +

Removes the directory dir including all subdirectories and files in dir (recursively).

+

If this fails, OSError is raised. This does not fail if the directory never existed in the first place, unless checkDir = true.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setCurrentDir(newDir: string) {.inline, ...tags: [], raises: [OSError],
+                                     forbids: [].}
+
+ +

Sets the current working directory; OSError is raised if newDir cannot been set.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator walkDir(dir: string; relative = false; checkDir = false;
+                 skipSpecial = false): tuple[kind: PathComponent, path: string] {.
+    ...tags: [ReadDirEffect], raises: [OSError], forbids: [].}
+
+ +

Walks over the directory dir and yields for each directory or file in dir. The component type and full path for each item are returned.

+

Walking is not recursive.

+
  • If relative is true (default: false) the resulting path is shortened to be relative to dir, otherwise the full path is returned.
  • +
  • If checkDir is true, OSError is raised when dir doesn't exist.
  • +
  • If skipSpecial is true, then (besides all directories) only regular files (without special "file" objects like FIFOs, device files, etc) will be yielded on Unix.
  • +
+

Example:

+

This directory structure:

+
dirA / dirB / fileB1.txt
+     / dirC
+     / fileA1.txt
+     / fileA2.txt
+

and this code:

+ +

Example: cmd: -r:off

+
import std/[strutils, sugar]
+# note: order is not guaranteed
+# this also works at compile time
+assert collect(for k in walkDir("dirA"): k.path).join(" ") ==
+                      "dirA/dirB dirA/dirC dirA/fileA2.txt dirA/fileA1.txt"
See also: + + Source   +Edit   + +
+
+ +
+
+
+
iterator walkDirRec(dir: string; yieldFilter = {pcFile}; followFilter = {pcDir};
+                    relative = false; checkDir = false; skipSpecial = false): string {.
+    ...tags: [ReadDirEffect], raises: [OSError], forbids: [].}
+
+ +

Recursively walks over the directory dir and yields for each file or directory in dir.

+

Options relative, checkdir, skipSpecial are explained in walkDir iterator description.

+
Warning: +Modifying the directory structure while the iterator is traversing may result in undefined behavior!
+

Walking is recursive. followFilter controls the behaviour of the iterator:

+ + + + + +
yieldFiltermeaning
pcFileyield real files (default)
pcLinkToFileyield symbolic links to files
pcDiryield real directories
pcLinkToDiryield symbolic links to directories
+ + +
followFiltermeaning
pcDirfollow real directories (default)
pcLinkToDirfollow symbolic links to directories

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator walkDirs(pattern: string): string {....tags: [ReadDirEffect], raises: [],
+    forbids: [].}
+
+ +

Iterate over all the directories that match the pattern.

+

On POSIX this uses the glob call. pattern is OS dependent, but at least the "*.ext" notation is supported.

+

See also:

+ + +

Example:

+
import std/os
+import std/sequtils
+let paths = toSeq(walkDirs("lib/pure/*")) # works on Windows too
+assert "lib/pure/concurrency".unixToNativePath in paths
+ Source   +Edit   + +
+
+ +
+
+
+
iterator walkFiles(pattern: string): string {....tags: [ReadDirEffect], raises: [],
+    forbids: [].}
+
+ +

Iterate over all the files that match the pattern.

+

On POSIX this uses the glob call. pattern is OS dependent, but at least the "*.ext" notation is supported.

+

See also:

+ + +

Example:

+
import std/os
+import std/sequtils
+assert "lib/pure/os.nim".unixToNativePath in toSeq(walkFiles("lib/pure/*.nim")) # works on Windows too
+ Source   +Edit   + +
+
+ +
+
+
+
iterator walkPattern(pattern: string): string {....tags: [ReadDirEffect],
+    raises: [], forbids: [].}
+
+ +

Iterate over all the files and directories that match the pattern.

+

On POSIX this uses the glob call. pattern is OS dependent, but at least the "*.ext" notation is supported.

+

See also:

+ + +

Example:

+
import std/os
+import std/sequtils
+let paths = toSeq(walkPattern("lib/pure/*")) # works on Windows too
+assert "lib/pure/concurrency".unixToNativePath in paths
+assert "lib/pure/os.nim".unixToNativePath in paths
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/osdirs.idx b/osdirs.idx new file mode 100644 index 0000000000000..bd4ff7598ce77 --- /dev/null +++ b/osdirs.idx @@ -0,0 +1,19 @@ +nimTitle osdirs osdirs.html module std/private/osdirs 0 +nim walkPattern osdirs.html#walkPattern.i,string iterator walkPattern(pattern: string): string 98 +nim walkFiles osdirs.html#walkFiles.i,string iterator walkFiles(pattern: string): string 118 +nim walkDirs osdirs.html#walkDirs.i,string iterator walkDirs(pattern: string): string 136 +nim walkDir osdirs.html#walkDir.i,string iterator walkDir(dir: string; relative = false; checkDir = false; skipSpecial = false): tuple[\n kind: PathComponent, path: string] 159 +nim walkDirRec osdirs.html#walkDirRec.i,string iterator walkDirRec(dir: string; yieldFilter = {pcFile}; followFilter = {pcDir};\n relative = false; checkDir = false; skipSpecial = false): string 273 +nim removeDir osdirs.html#removeDir,string proc removeDir(dir: string; checkDir = false) 339 +nim existsOrCreateDir osdirs.html#existsOrCreateDir,string proc existsOrCreateDir(dir: string): bool 405 +nim createDir osdirs.html#createDir,string proc createDir(dir: string) 424 +nim copyDir osdirs.html#copyDir,string,string proc copyDir(source, dest: string; skipSpecial = false) 449 +nim copyDirWithPermissions osdirs.html#copyDirWithPermissions,string,string proc copyDirWithPermissions(source, dest: string; ignorePermissionErrors = true;\n skipSpecial = false) 487 +nim moveDir osdirs.html#moveDir,string,string proc moveDir(source, dest: string) 537 +nim setCurrentDir osdirs.html#setCurrentDir,string proc setCurrentDir(newDir: string) 557 +idx current working directory osdirs.html#current-working-directory_1 Module osdirs 0 +idx directory osdirs.html#directory_1 Module osdirs 0 +idx directory osdirs.html#directory_2 Module osdirs 0 +idx glob osdirs.html#glob_1 Module osdirs 0 +idx glob osdirs.html#glob_2 Module osdirs 0 +idx glob osdirs.html#glob_3 Module osdirs 0 diff --git a/oserrors.html b/oserrors.html new file mode 100644 index 0000000000000..ab10549798a92 --- /dev/null +++ b/oserrors.html @@ -0,0 +1,254 @@ + + + + + + + +std/oserrors + + + + + + + + + + + + + + + + +
+
+

std/oserrors

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

The std/oserrors module implements OS error reporting.

+
+

Types

+
+
+
OSErrorCode = distinct int32
+
+ + Specifies an OS Error Code. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(err: OSErrorCode): string {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(err1, err2: OSErrorCode): bool {.borrow, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newOSError(errorCode: OSErrorCode; additionalInfo = ""): owned(ref OSError) {.
+    noinline, ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new OSError exception.

+

The errorCode will determine the message, osErrorMsg proc will be used to get this message.

+

The error code can be retrieved using the osLastError proc.

+

If the error code is 0 or an error message could not be retrieved, the message unknown OS error will be used.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc osErrorMsg(errorCode: OSErrorCode): string {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Converts an OS error code into a human readable string.

+

The error code can be retrieved using the osLastError proc.

+

If conversion fails, or errorCode is 0 then "" will be returned.

+

See also:

+ + +

Example:

+
when defined(linux):
+  assert osErrorMsg(OSErrorCode(0)) == ""
+  assert osErrorMsg(OSErrorCode(1)) == "Operation not permitted"
+  assert osErrorMsg(OSErrorCode(2)) == "No such file or directory"
+ Source   +Edit   + +
+
+ +
+
+
+
proc osLastError(): OSErrorCode {.sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Retrieves the last operating system error code.

+

This procedure is useful in the event when an OS call fails. In that case this procedure will return the error code describing the reason why the OS call failed. The OSErrorMsg procedure can then be used to convert this code into a string.

+
Warning: +The behaviour of this procedure varies between Windows and POSIX systems. On Windows some OS calls can reset the error code to 0 causing this procedure to return 0. It is therefore advised to call this procedure immediately after an OS call fails. On POSIX systems this is not a problem.
+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc raiseOSError(errorCode: OSErrorCode; additionalInfo = "") {.noinline,
+    ...raises: [OSError], tags: [], forbids: [].}
+
+ +

Raises an OSError exception.

+

Read the description of the newOSError proc to learn how the exception object is created.

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/oserrors.idx b/oserrors.idx new file mode 100644 index 0000000000000..c535fbdcf56bf --- /dev/null +++ b/oserrors.idx @@ -0,0 +1,8 @@ +nimTitle oserrors oserrors.html module std/oserrors 0 +nim OSErrorCode oserrors.html#OSErrorCode type OSErrorCode 14 +nim `==` oserrors.html#==,OSErrorCode,OSErrorCode proc `==`(err1, err2: OSErrorCode): bool 27 +nim `$` oserrors.html#$,OSErrorCode proc `$`(err: OSErrorCode): string 28 +nim osErrorMsg oserrors.html#osErrorMsg,OSErrorCode proc osErrorMsg(errorCode: OSErrorCode): string 30 +nim newOSError oserrors.html#newOSError,OSErrorCode,string proc newOSError(errorCode: OSErrorCode; additionalInfo = ""): owned(ref OSError) 61 +nim raiseOSError oserrors.html#raiseOSError,OSErrorCode,string proc raiseOSError(errorCode: OSErrorCode; additionalInfo = "") 87 +nim osLastError oserrors.html#osLastError proc osLastError(): OSErrorCode 95 diff --git a/osfiles.html b/osfiles.html new file mode 100644 index 0000000000000..a0dd69e9692a4 --- /dev/null +++ b/osfiles.html @@ -0,0 +1,416 @@ + + + + + + + +std/private/osfiles + + + + + + + + + + + + + + + + +
+
+

std/private/osfiles

+
+ +
+ Source   +Edit   + +
+ +

+ +
+

Types

+
+
+
CopyFlag = enum
+  cfSymlinkAsIs,            ## Copy symlinks as symlinks
+  cfSymlinkFollow,          ## Copy the files symlinks point to
+  cfSymlinkIgnore            ## Ignore symlinks
+
+ + Copy options. + Source   +Edit   + +
+
+
+
FilePermission = enum
+  fpUserExec,               ## execute access for the file owner
+  fpUserWrite,              ## write access for the file owner
+  fpUserRead,               ## read access for the file owner
+  fpGroupExec,              ## execute access for the group
+  fpGroupWrite,             ## write access for the group
+  fpGroupRead,              ## read access for the group
+  fpOthersExec,             ## execute access for others
+  fpOthersWrite,            ## write access for others
+  fpOthersRead               ## read access for others
+
+ +

File access permission, modelled after UNIX.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc copyFile(source, dest: string; options = {cfSymlinkFollow};
+              bufferSize = 16384) {....gcsafe, extern: "nos$1", tags: [
+    ReadDirEffect, ReadIOEffect, WriteIOEffect], raises: [OSError, IOError],
+                                    forbids: [].}
+
+ +

Copies a file from source to dest, where dest.parentDir must exist.

+

On non-Windows OSes, options specify the way file is copied; by default, if source is a symlink, copies the file symlink points to. options is ignored on Windows: symlinks are skipped.

+

If this fails, OSError is raised.

+

On the Windows platform this proc will copy the source file's attributes into dest.

+

On other platforms you need to use getFilePermissions and setFilePermissions procs to copy them by hand (or use the convenience copyFileWithPermissions proc), otherwise dest will inherit the default permissions of a newly created file for the user.

+

If dest already exists, the file attributes will be preserved and the content overwritten.

+

On OSX, copyfile C api will be used (available since OSX 10.5) unless -d:nimLegacyCopyFile is used.

+

copyFile allows to specify bufferSize to improve I/O performance.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc copyFileToDir(source, dir: string; options = {cfSymlinkFollow};
+                   bufferSize = 16384) {....raises: [ValueError, OSError, IOError],
+    tags: [ReadDirEffect, ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ +

Copies a file source into directory dir, which must exist.

+

On non-Windows OSes, options specify the way file is copied; by default, if source is a symlink, copies the file symlink points to. options is ignored on Windows: symlinks are skipped.

+

copyFileToDir allows to specify bufferSize to improve I/O performance.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc copyFileWithPermissions(source, dest: string;
+                             ignorePermissionErrors = true;
+                             options = {cfSymlinkFollow}) {.
+    ...raises: [OSError, IOError, Exception],
+    tags: [ReadDirEffect, ReadIOEffect, WriteIOEffect, WriteDirEffect],
+    forbids: [].}
+
+ +

Copies a file from source to dest preserving file permissions.

+

On non-Windows OSes, options specify the way file is copied; by default, if source is a symlink, copies the file symlink points to. options is ignored on Windows: symlinks are skipped.

+

This is a wrapper proc around copyFile, getFilePermissions and setFilePermissions procs on non-Windows platforms.

+

On Windows this proc is just a wrapper for copyFile proc since that proc already copies attributes.

+

On non-Windows systems permissions are copied after the file itself has been copied, which won't happen atomically and could lead to a race condition. If ignorePermissionErrors is true (default), errors while reading/setting file attributes will be ignored, otherwise will raise OSError.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getFilePermissions(filename: string): set[FilePermission] {....gcsafe,
+    extern: "nos$1", tags: [ReadDirEffect], raises: [OSError], forbids: [].}
+
+ +

Retrieves file permissions for filename.

+

OSError is raised in case of an error. On Windows, only the readonly flag is checked, every other permission is available in any case.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc moveFile(source, dest: string) {....gcsafe, extern: "nos$1", tags: [
+    ReadDirEffect, ReadIOEffect, WriteIOEffect], raises: [OSError, IOError,
+    Exception, Exception], forbids: [].}
+
+ +

Moves a file from source to dest.

+

Symlinks are not followed: if source is a symlink, it is itself moved, not its target.

+

If this fails, OSError is raised. If dest already exists, it will be overwritten.

+

Can be used to rename files.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc removeFile(file: string) {....gcsafe, extern: "nos$1", tags: [WriteDirEffect],
+                                raises: [OSError], forbids: [].}
+
+ +

Removes the file.

+

If this fails, OSError is raised. This does not fail if the file never existed in the first place.

+

On Windows, ignores the read-only attribute.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setFilePermissions(filename: string; permissions: set[FilePermission];
+                        followSymlinks = true) {....gcsafe, extern: "nos$1",
+    tags: [ReadDirEffect, WriteDirEffect], raises: [OSError], forbids: [].}
+
+ +

Sets the file permissions for filename.

+

If followSymlinks set to true (default) and filename points to a symlink, permissions are set to the file symlink points to. followSymlinks set to false is a noop on Windows and some POSIX systems (including Linux) on which lchmod is either unavailable or always fails, given that symlinks permissions there are not observed.

+

OSError is raised in case of an error. On Windows, only the readonly flag is changed, depending on fpUserWrite permission.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc tryRemoveFile(file: string): bool {....gcsafe, extern: "nos$1",
+    tags: [WriteDirEffect], raises: [], forbids: [].}
+
+ +

Removes the file.

+

If this fails, returns false. This does not fail if the file never existed in the first place.

+

On Windows, ignores the read-only attribute.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/osfiles.idx b/osfiles.idx new file mode 100644 index 0000000000000..e2ff5f7de1dd6 --- /dev/null +++ b/osfiles.idx @@ -0,0 +1,24 @@ +nimTitle osfiles osfiles.html module std/private/osfiles 0 +nim fpUserExec osfiles.html#fpUserExec FilePermission.fpUserExec 44 +nim fpUserWrite osfiles.html#fpUserWrite FilePermission.fpUserWrite 44 +nim fpUserRead osfiles.html#fpUserRead FilePermission.fpUserRead 44 +nim fpGroupExec osfiles.html#fpGroupExec FilePermission.fpGroupExec 44 +nim fpGroupWrite osfiles.html#fpGroupWrite FilePermission.fpGroupWrite 44 +nim fpGroupRead osfiles.html#fpGroupRead FilePermission.fpGroupRead 44 +nim fpOthersExec osfiles.html#fpOthersExec FilePermission.fpOthersExec 44 +nim fpOthersWrite osfiles.html#fpOthersWrite FilePermission.fpOthersWrite 44 +nim fpOthersRead osfiles.html#fpOthersRead FilePermission.fpOthersRead 44 +nim FilePermission osfiles.html#FilePermission enum FilePermission 44 +nim getFilePermissions osfiles.html#getFilePermissions,string proc getFilePermissions(filename: string): set[FilePermission] 60 +nim setFilePermissions osfiles.html#setFilePermissions,string,set[FilePermission] proc setFilePermissions(filename: string; permissions: set[FilePermission];\n followSymlinks = true) 95 +nim cfSymlinkAsIs osfiles.html#cfSymlinkAsIs CopyFlag.cfSymlinkAsIs 169 +nim cfSymlinkFollow osfiles.html#cfSymlinkFollow CopyFlag.cfSymlinkFollow 169 +nim cfSymlinkIgnore osfiles.html#cfSymlinkIgnore CopyFlag.cfSymlinkIgnore 169 +nim CopyFlag osfiles.html#CopyFlag enum CopyFlag 169 +nim copyFile osfiles.html#copyFile,string,string,int proc copyFile(source, dest: string; options = {cfSymlinkFollow}; bufferSize = 16384) 176 +nim copyFileToDir osfiles.html#copyFileToDir,string,string,int proc copyFileToDir(source, dir: string; options = {cfSymlinkFollow};\n bufferSize = 16384) 270 +nim copyFileWithPermissions osfiles.html#copyFileWithPermissions,string,string proc copyFileWithPermissions(source, dest: string; ignorePermissionErrors = true;\n options = {cfSymlinkFollow}) 288 +nim tryRemoveFile osfiles.html#tryRemoveFile,string proc tryRemoveFile(file: string): bool 341 +nim removeFile osfiles.html#removeFile,string proc removeFile(file: string) 370 +nim moveFile osfiles.html#moveFile,string,string proc moveFile(source, dest: string) 387 +idx rename files osfiles.html#rename-files_1 Module osfiles 0 diff --git a/ospaths2.html b/ospaths2.html new file mode 100644 index 0000000000000..3f6d7b44fe25a --- /dev/null +++ b/ospaths2.html @@ -0,0 +1,940 @@ + + + + + + + +std/private/ospaths2 + + + + + + + + + + + + + + + + +
+
+

std/private/ospaths2

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+
+
+
proc `/`(head, tail: string): string {.noSideEffect, inline, ...raises: [],
+                                       tags: [], forbids: [].}
+
+ +

The same as joinPath(head, tail) proc.

+

See also:

+ + +

Example:

+
when defined(posix):
+  assert "usr" / "" == "usr"
+  assert "" / "lib" == "lib"
+  assert "" / "/lib" == "/lib"
+  assert "usr/" / "/lib/" == "usr/lib/"
+  assert "usr" / "lib" / "../bin" == "usr/bin"
+ Source   +Edit   + +
+
+ +
+
+
+
proc `/../`(head, tail: string): string {.noSideEffect, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

The same as parentDir(head) / tail, unless there is no parent directory. Then head / tail is performed instead.

+

See also:

+ + +

Example:

+
when defined(posix):
+  assert "a/b/c" /../ "d/e" == "a/b/d/e"
+  assert "a" /../ "d/e" == "a/d/e"
+ Source   +Edit   + +
+
+ +
+
+
+
proc absolutePath(path: string; root = getCurrentDir()): string {.
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ +

Returns the absolute path of path, rooted at root (which must be absolute; default: current directory). If path is absolute, return it, ignoring root.

+

See also:

+ + +

Example:

+
assert absolutePath("a") == getCurrentDir() / "a"
+ Source   +Edit   + +
+
+ +
+
+
+
proc addFileExt(filename, ext: string): string {.noSideEffect, ...gcsafe,
+    extern: "nos$1", raises: [], tags: [], forbids: [].}
+
+ +

Adds the file extension ext to filename, unless filename already has an extension.

+

Ext should be given without the leading '.', because some filesystems may use a different character. (Although I know of none such beast.)

+

See also:

+ + +

Example:

+
assert addFileExt("foo.bar", "baz") == "foo.bar"
+assert addFileExt("foo.bar", "") == "foo.bar"
+assert addFileExt("foo", "baz") == "foo.baz"
+ Source   +Edit   + +
+
+ +
+
+
+
proc changeFileExt(filename, ext: string): string {.noSideEffect, ...gcsafe,
+    extern: "nos$1", raises: [], tags: [], forbids: [].}
+
+ +

Changes the file extension to ext.

+

If the filename has no extension, ext will be added. If ext == "" then any extension is removed.

+

Ext should be given without the leading '.', because some filesystems may use a different character. (Although I know of none such beast.)

+

See also:

+ + +

Example:

+
assert changeFileExt("foo.bar", "baz") == "foo.baz"
+assert changeFileExt("foo.bar", "") == "foo"
+assert changeFileExt("foo", "baz") == "foo.baz"
+ Source   +Edit   + +
+
+ +
+
+
+
proc cmpPaths(pathA, pathB: string): int {.noSideEffect, ...gcsafe,
+    extern: "nos$1", raises: [], tags: [], forbids: [].}
+
+ +

Compares two paths.

+

On a case-sensitive filesystem this is done case-sensitively otherwise case-insensitively. Returns:

+

0 if pathA == pathB
< 0 if pathA < pathB
> 0 if pathA > pathB

+

Example:

+
when defined(macosx):
+  assert cmpPaths("foo", "Foo") == 0
+elif defined(posix):
+  assert cmpPaths("foo", "Foo") > 0
+ Source   +Edit   + +
+
+ +
+
+
+
proc extractFilename(path: string): string {.noSideEffect, ...gcsafe,
+    extern: "nos$1", raises: [], tags: [], forbids: [].}
+
+ +

Extracts the filename of a given path.

+

This is the same as name & ext from splitFile(path) proc.

+

See also:

+ + +

Example:

+
assert extractFilename("foo/bar/") == ""
+assert extractFilename("foo/bar") == "bar"
+assert extractFilename("foo/bar.baz") == "bar.baz"
+ Source   +Edit   + +
+
+ +
+
+
+
proc getCurrentDir(): string {....gcsafe, extern: "nos$1", tags: [],
+                               raises: [OSError], forbids: [].}
+
+ +

Returns the current working directory i.e. where the built binary is run.

+

So the path returned by this proc is determined at run time.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isAbsolute(path: string): bool {....gcsafe, noSideEffect, ...extern: "nos$1",
+                                      raises: [], tags: [], forbids: [].}
+
+ +

Checks whether a given path is absolute.

+

On Windows, network paths are considered absolute too.

+ +

Example:

+
assert not "".isAbsolute
+assert not ".".isAbsolute
+when defined(posix):
+  assert "/".isAbsolute
+  assert not "a/".isAbsolute
+  assert "/a/".isAbsolute
+ Source   +Edit   + +
+
+ +
+
+
+
proc isRelativeTo(path: string; base: string): bool {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + Returns true if path is relative to base. +

Example:

+
doAssert isRelativeTo("./foo//bar", "foo")
+doAssert isRelativeTo("foo/bar", ".")
+doAssert isRelativeTo("/foo/bar.nim", "/foo/bar.nim")
+doAssert not isRelativeTo("foo/bar.nims", "foo/bar.nim")
+ Source   +Edit   + +
+
+ +
+
+
+
proc isRootDir(path: string): bool {.noSideEffect, ...gcsafe, extern: "nos$1",
+                                     raises: [], tags: [], forbids: [].}
+
+ + Checks whether a given path is a root directory. +

Example:

+
assert isRootDir("")
+assert isRootDir(".")
+assert isRootDir("/")
+assert isRootDir("a")
+assert not isRootDir("/a")
+assert not isRootDir("a/b/c")
+ Source   +Edit   + +
+
+ +
+
+
+
proc joinPath(head, tail: string): string {.noSideEffect, ...gcsafe,
+    extern: "nos$1", raises: [], tags: [], forbids: [].}
+
+ +

Joins two directory names to one.

+

returns normalized path concatenation of head and tail, preserving whether or not tail has a trailing slash (or, if tail if empty, whether head has one).

+

See also:

+ + +

Example:

+
when defined(posix):
+  assert joinPath("usr", "lib") == "usr/lib"
+  assert joinPath("usr", "lib/") == "usr/lib/"
+  assert joinPath("usr", "") == "usr"
+  assert joinPath("usr/", "") == "usr/"
+  assert joinPath("", "") == ""
+  assert joinPath("", "lib") == "lib"
+  assert joinPath("", "/lib") == "/lib"
+  assert joinPath("usr/", "/lib") == "usr/lib"
+  assert joinPath("usr/lib", "../bin") == "usr/bin"
+ Source   +Edit   + +
+
+
+
proc joinPath(parts: varargs[string]): string {.noSideEffect, ...gcsafe,
+    extern: "nos$1OpenArray", raises: [], tags: [], forbids: [].}
+
+ +

The same as joinPath(head, tail) proc, but works with any number of directory parts.

+

You need to pass at least one element or the proc will assert in debug builds and crash on release builds.

+

See also:

+ + +

Example:

+
when defined(posix):
+  assert joinPath("a") == "a"
+  assert joinPath("a", "b", "c") == "a/b/c"
+  assert joinPath("usr/lib", "../../var", "log") == "var/log"
+ Source   +Edit   + +
+
+ +
+
+
+
proc lastPathPart(path: string): string {.noSideEffect, ...gcsafe, extern: "nos$1",
+    raises: [], tags: [], forbids: [].}
+
+ +

Like extractFilename proc, but ignores trailing dir separator; aka: baseName in some other languages.

+

See also:

+ + +

Example:

+
assert lastPathPart("foo/bar/") == "bar"
+assert lastPathPart("foo/bar") == "bar"
+ Source   +Edit   + +
+
+ +
+
+
+
proc normalizedPath(path: string): string {....gcsafe, extern: "nos$1", tags: [],
+    raises: [], forbids: [].}
+
+ +

Returns a normalized path for the current OS.

+

See also:

+ + +

Example:

+
when defined(posix):
+  assert normalizedPath("a///b//..//c///d") == "a/c/d"
+ Source   +Edit   + +
+
+ +
+
+
+
proc normalizeExe(file: var string) {....raises: [], tags: [], forbids: [].}
+
+ + on posix, prepends ./ if file doesn't contain / and is not "", ".", "..". +

Example:

+
import std/sugar
+when defined(posix):
+  doAssert "foo".dup(normalizeExe) == "./foo"
+  doAssert "foo/../bar".dup(normalizeExe) == "foo/../bar"
+doAssert "".dup(normalizeExe) == ""
+ Source   +Edit   + +
+
+ +
+
+
+
proc normalizePath(path: var string) {....gcsafe, extern: "nos$1", tags: [],
+                                       raises: [], forbids: [].}
+
+ +

Normalize a path.

+

Consecutive directory separators are collapsed, including an initial double slash.

+

On relative paths, double dot (..) sequences are collapsed if possible. On absolute paths they are always collapsed.

+
Warning: +URL-encoded and Unicode attempts at directory traversal are not detected. Triple dot is not handled.
+

See also:

+ + +

Example:

+
when defined(posix):
+  var a = "a///b//..//c///d"
+  a.normalizePath()
+  assert a == "a/c/d"
+ Source   +Edit   + +
+
+ +
+
+
+
proc normalizePathEnd(path: string; trailingSep = false): string {....raises: [],
+    tags: [], forbids: [].}
+
+ + outplace overload +

Example:

+
when defined(posix):
+  assert normalizePathEnd("/lib//.//", trailingSep = true) == "/lib/"
+  assert normalizePathEnd("lib/./.", trailingSep = false) == "lib"
+  assert normalizePathEnd(".//./.", trailingSep = false) == "."
+  assert normalizePathEnd("", trailingSep = true) == "" # not / !
+  assert normalizePathEnd("/", trailingSep = false) == "/" # not "" !
+ Source   +Edit   + +
+
+
+
proc normalizePathEnd(path: var string; trailingSep = false) {....raises: [],
+    tags: [], forbids: [].}
+
+ + Ensures path has exactly 0 or 1 trailing DirSep, depending on trailingSep, and taking care of edge cases: it preservers whether a path is absolute or relative, and makes sure trailing sep is DirSep, not AltSep. Trailing /. are compressed, see examples. + Source   +Edit   + +
+
+ +
+
+
+
proc parentDir(path: string): string {.noSideEffect, ...gcsafe, extern: "nos$1",
+                                       raises: [], tags: [], forbids: [].}
+
+ +

Returns the parent directory of path.

+

This is similar to splitPath(path).head when path doesn't end in a dir separator, but also takes care of path normalizations. The remainder can be obtained with lastPathPart(path) proc.

+

See also:

+ + +

Example:

+
assert parentDir("") == ""
+when defined(posix):
+  assert parentDir("/usr/local/bin") == "/usr/local"
+  assert parentDir("foo/bar//") == "foo"
+  assert parentDir("//foo//bar//.") == "/foo"
+  assert parentDir("./foo") == "."
+  assert parentDir("/./foo//./") == "/"
+  assert parentDir("a//./") == "."
+  assert parentDir("a/b/c/..") == "a"
+ Source   +Edit   + +
+
+ +
+
+
+
proc relativePath(path, base: string; sep = DirSep): string {....gcsafe,
+    extern: "nos$1", raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ +

Converts path to a path relative to base.

+

The sep (default: osseps: DirSep) is used for the path normalizations, this can be useful to ensure the relative path only contains '/' so that it can be used for URL constructions.

+

On Windows, if a root of path and a root of base are different, returns path as is because it is impossible to make a relative path. That means an absolute path can be returned.

+

See also:

+ + +

Example:

+
assert relativePath("/Users/me/bar/z.nim", "/Users/other/bad", '/') == "../../me/bar/z.nim"
+assert relativePath("/Users/me/bar/z.nim", "/Users/other", '/') == "../me/bar/z.nim"
+when not doslikeFileSystem: # On Windows, UNC-paths start with `//`
+  assert relativePath("/Users///me/bar//z.nim", "//Users/", '/') == "me/bar/z.nim"
+assert relativePath("/Users/me/bar/z.nim", "/Users/me", '/') == "bar/z.nim"
+assert relativePath("", "/users/moo", '/') == ""
+assert relativePath("foo", ".", '/') == "foo"
+assert relativePath("foo", "foo", '/') == "."
+ Source   +Edit   + +
+
+ +
+
+
+
proc sameFile(path1, path2: string): bool {....gcsafe, extern: "nos$1",
+    tags: [ReadDirEffect], raises: [OSError], forbids: [].}
+
+ +

Returns true if both pathname arguments refer to the same physical file or directory.

+

Raises OSError if any of the files does not exist or information about it can not be obtained.

+

This proc will return true if given two alternative hard-linked or sym-linked paths to the same file or directory.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc searchExtPos(path: string): int {....raises: [], tags: [], forbids: [].}
+
+ +

Returns index of the '.' char in path if it signifies the beginning of the file extension. Returns -1 otherwise.

+

See also:

+ + +

Example:

+
assert searchExtPos("a/b/c") == -1
+assert searchExtPos("c.nim") == 1
+assert searchExtPos("a/b/c.nim") == 5
+assert searchExtPos("a.b.c.nim") == 5
+assert searchExtPos(".nim") == -1
+assert searchExtPos("..nim") == -1
+assert searchExtPos("a..nim") == 2
+ Source   +Edit   + +
+
+ +
+
+
+
proc splitFile(path: string): tuple[dir, name, ext: string] {.noSideEffect,
+    ...gcsafe, extern: "nos$1", raises: [], tags: [], forbids: [].}
+
+ +

Splits a filename into (dir, name, extension) tuple.

+

dir does not end in osseps: DirSep unless it's /. extension includes the leading dot.

+

If path has no extension, ext is the empty string. If path has no directory component, dir is the empty string. If path has no filename component, name and ext are empty strings.

+

See also:

+ + +

Example:

+
var (dir, name, ext) = splitFile("usr/local/nimc.html")
+assert dir == "usr/local"
+assert name == "nimc"
+assert ext == ".html"
+(dir, name, ext) = splitFile("/usr/local/os")
+assert dir == "/usr/local"
+assert name == "os"
+assert ext == ""
+(dir, name, ext) = splitFile("/usr/local/")
+assert dir == "/usr/local"
+assert name == ""
+assert ext == ""
+(dir, name, ext) = splitFile("/tmp.txt")
+assert dir == "/"
+assert name == "tmp"
+assert ext == ".txt"
+ Source   +Edit   + +
+
+ +
+
+
+
proc splitPath(path: string): tuple[head, tail: string] {.noSideEffect, ...gcsafe,
+    extern: "nos$1", raises: [], tags: [], forbids: [].}
+
+ +

Splits a directory into (head, tail) tuple, so that head / tail == path (except for edge cases like "/usr").

+

See also:

+ + +

Example:

+
assert splitPath("usr/local/bin") == ("usr/local", "bin")
+assert splitPath("usr/local/bin/") == ("usr/local/bin", "")
+assert splitPath("/bin/") == ("/bin", "")
+when (NimMajor, NimMinor) <= (1, 0):
+  assert splitPath("/bin") == ("", "bin")
+else:
+  assert splitPath("/bin") == ("/", "bin")
+assert splitPath("bin") == ("", "bin")
+assert splitPath("") == ("", "")
+ Source   +Edit   + +
+
+ +
+
+
+
proc tailDir(path: string): string {.noSideEffect, ...gcsafe, extern: "nos$1",
+                                     raises: [], tags: [], forbids: [].}
+
+ +

Returns the tail part of path.

+

See also:

+ + +

Example:

+
assert tailDir("/bin") == "bin"
+assert tailDir("bin") == ""
+assert tailDir("bin/") == ""
+assert tailDir("/usr/local/bin") == "usr/local/bin"
+assert tailDir("//usr//local//bin//") == "usr//local//bin//"
+assert tailDir("./usr/local/bin") == "usr/local/bin"
+assert tailDir("usr/local/bin") == "local/bin"
+ Source   +Edit   + +
+
+ +
+
+
+
proc unixToNativePath(path: string; drive = ""): string {.noSideEffect, ...gcsafe,
+    extern: "nos$1", raises: [], tags: [], forbids: [].}
+
+ +

Converts an UNIX-like path to a native one.

+

On an UNIX system this does nothing. Else it converts '/', '.', '..' to the appropriate things.

+

On systems with a concept of "drives", drive is used to determine which drive label to use during absolute path conversion. drive defaults to the drive of the current working directory, and is ignored on systems that do not have a concept of "drives".

+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator parentDirs(path: string; fromRoot = false; inclusive = true): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Walks over all parent directories of a given path.

+

If fromRoot is true (default: false), the traversal will start from the file system root directory. If inclusive is true (default), the original argument will be included in the traversal.

+

Relative paths won't be expanded by this iterator. Instead, it will traverse only the directories appearing in the relative path.

+

See also:

+ + +

Example:

+
let g = "a/b/c"
+
+for p in g.parentDirs:
+  echo p
+  # a/b/c
+  # a/b
+  # a
+
+for p in g.parentDirs(fromRoot=true):
+  echo p
+  # a/
+  # a/b/
+  # a/b/c
+
+for p in g.parentDirs(inclusive=false):
+  echo p
+  # a/b
+  # a
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/ospaths2.idx b/ospaths2.idx new file mode 100644 index 0000000000000..be52a458a1084 --- /dev/null +++ b/ospaths2.idx @@ -0,0 +1,33 @@ +nimTitle ospaths2 ospaths2.html module std/private/ospaths2 0 +nim normalizePathEnd ospaths2.html#normalizePathEnd,string proc normalizePathEnd(path: var string; trailingSep = false) 48 +nim normalizePathEnd ospaths2.html#normalizePathEnd,string_2 proc normalizePathEnd(path: string; trailingSep = false): string 71 +nim joinPath ospaths2.html#joinPath,string,string proc joinPath(head, tail: string): string 92 +nim joinPath ospaths2.html#joinPath,varargs[string] proc joinPath(parts: varargs[string]): string 136 +nim `/` ospaths2.html#/,string,string proc `/`(head, tail: string): string 162 +nim splitPath ospaths2.html#splitPath,string proc splitPath(path: string): tuple[head, tail: string] 185 +nim isAbsolute ospaths2.html#isAbsolute,string proc isAbsolute(path: string): bool 234 +nim relativePath ospaths2.html#relativePath,string,string proc relativePath(path, base: string; sep = DirSep): string 293 +nim isRelativeTo ospaths2.html#isRelativeTo,string,string proc isRelativeTo(path: string; base: string): bool 383 +nim parentDir ospaths2.html#parentDir,string proc parentDir(path: string): string 402 +nim tailDir ospaths2.html#tailDir,string proc tailDir(path: string): string 447 +nim isRootDir ospaths2.html#isRootDir,string proc isRootDir(path: string): bool 476 +nim parentDirs ospaths2.html#parentDirs.i,string iterator parentDirs(path: string; fromRoot = false; inclusive = true): string 492 +nim `/../` ospaths2.html#/../,string,string proc `/../`(head, tail: string): string 546 +nim searchExtPos ospaths2.html#searchExtPos,string proc searchExtPos(path: string): int 572 +nim splitFile ospaths2.html#splitFile,string proc splitFile(path: string): tuple[dir, name, ext: string] 610 +nim extractFilename ospaths2.html#extractFilename,string proc extractFilename(path: string): string 669 +nim lastPathPart ospaths2.html#lastPathPart,string proc lastPathPart(path: string): string 691 +nim changeFileExt ospaths2.html#changeFileExt,string,string proc changeFileExt(filename, ext: string): string 709 +nim addFileExt ospaths2.html#addFileExt,string,string proc addFileExt(filename, ext: string): string 735 +nim cmpPaths ospaths2.html#cmpPaths,string,string proc cmpPaths(pathA, pathB: string): int 759 +nim unixToNativePath ospaths2.html#unixToNativePath,string,string proc unixToNativePath(path: string; drive = ""): string 786 +nim getCurrentDir ospaths2.html#getCurrentDir proc getCurrentDir(): string 844 +nim absolutePath ospaths2.html#absolutePath,string proc absolutePath(path: string; root = getCurrentDir()): string 892 +nim normalizePath ospaths2.html#normalizePath,string proc normalizePath(path: var string) 913 +nim normalizedPath ospaths2.html#normalizedPath,string proc normalizedPath(path: string): string 964 +nim normalizeExe ospaths2.html#normalizeExe,string proc normalizeExe(file: var string) 975 +nim sameFile ospaths2.html#sameFile,string,string proc sameFile(path1, path2: string): bool 987 +idx baseName ospaths2.html#basename_1 Module ospaths2 0 +idx current working directory ospaths2.html#current-working-directory_1 Module ospaths2 0 +nimgrp normalizepathend ospaths2.html#normalizePathEnd-procs-all proc 48 +nimgrp joinpath ospaths2.html#joinPath-procs-all proc 92 diff --git a/osproc.html b/osproc.html new file mode 100644 index 0000000000000..576d352464208 --- /dev/null +++ b/osproc.html @@ -0,0 +1,867 @@ + + + + + + + +std/osproc + + + + + + + + + + + + + + + + +
+
+

std/osproc

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements an advanced facility for executing OS processes and process communication.

+

See also:

+ +

+ +
+

Types

+
+
+
Process = ref ProcessObj
+
+ + Represents an operating system process. + Source   +Edit   + +
+
+
+
ProcessOption = enum
+  poEchoCmd,                ## Echo the command before execution.
+  poUsePath, ## Asks system to search for executable using PATH environment
+              ## variable.
+              ## On Windows, this is the default.
+  poEvalCommand, ## Pass `command` directly to the shell, without quoting.
+                  ## Use it only if `command` comes from trusted source.
+  poStdErrToStdOut,         ## Merge stdout and stderr to the stdout stream.
+  poParentStreams,          ## Use the parent's streams.
+  poInteractive, ## Optimize the buffer handling for responsiveness for
+                  ## UI applications. Currently this only affects
+                  ## Windows: Named pipes are used so that you can peek
+                  ## at the process' output streams.
+  poDaemon                   ## Windows: The program creates no Window.
+                             ## Unix: Start the program as a daemon. This is still
+                             ## work in progress!
+
+ + Options that can be passed to startProcess proc. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc close(p: Process) {....gcsafe, extern: "nosp$1", raises: [IOError, OSError],
+                         tags: [WriteIOEffect], forbids: [].}
+
+ + When the process has finished executing, cleanup related handles.
Warning: +If the process has not finished executing, this will forcibly terminate the process. Doing so may result in zombie processes and pty leaks.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc countProcessors(): int {....gcsafe, extern: "nosp$1", raises: [], tags: [],
+                              forbids: [].}
+
+ + Returns the number of the processors/cores the machine has. Returns 0 if it cannot be detected. It is implemented just calling cpuinfo.countProcessors. + Source   +Edit   + +
+
+ +
+
+
+
proc errorHandle(p: Process): FileHandle {....gcsafe, extern: "nosp$1", raises: [],
+    tags: [], forbids: [].}
+
+ + Returns p's error file handle for reading from.
Warning: +The returned FileHandle should not be closed manually as it is closed when closing the Process p.
+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc errorStream(p: Process): Stream {....gcsafe, extern: "nosp$1", tags: [],
+                                       raises: [OSError], forbids: [].}
+
+ +

Returns p's error stream for reading from.

+

You cannot perform peek/write/setOption operations to this stream. Use peekableErrorStream proc if you need to peek stream.

+
Warning: +The returned Stream should not be closed manually as it is closed when closing the Process p.
+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc execCmd(command: string): int {....gcsafe, extern: "nosp$1", tags: [
+    ExecIOEffect, ReadIOEffect, RootEffect], raises: [], forbids: [].}
+
+ +

Executes command and returns its error code.

+

Standard input, output, error streams are inherited from the calling process. This operation is also often called system.

+

See also:

+ +

Example:

+

let errC = execCmd("nim c -r mytestfile.nim")

+ + Source   +Edit   + +
+
+ +
+
+
+
proc execCmdEx(command: string;
+               options: set[ProcessOption] = {poStdErrToStdOut, poUsePath};
+               env: StringTableRef = nil; workingDir = ""; input = ""): tuple[
+    output: string, exitCode: int] {....raises: [OSError, IOError], tags: [
+    ExecIOEffect, ReadIOEffect, RootEffect], gcsafe, forbids: [].}
+
+ +

A convenience proc that runs the command, and returns its output and exitCode. env and workingDir params behave as for startProcess. If input.len > 0, it is passed as stdin.

+

Note: this could block if input.len is greater than your OS's maximum pipe buffer size.

+

See also:

+ +

Example:

+

var result = execCmdEx("nim r --hints:off -", options = {}, input = "echo 3*4")
+import std/[strutils, strtabs]
+stripLineEnd(result[0]) ## portable way to remove trailing newline, if any
+doAssert result == ("12", 0)
+doAssert execCmdEx("ls --nonexistent").exitCode != 0
+when defined(posix):
+  assert execCmdEx("echo $FO", env = newStringTable({"FO": "B"})) == ("B\n", 0)
+  assert execCmdEx("echo $PWD", workingDir = "/") == ("/\n", 0)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc execProcess(command: string; workingDir: string = "";
+                 args: openArray[string] = []; env: StringTableRef = nil;
+    options: set[ProcessOption] = {poStdErrToStdOut, poUsePath, poEvalCommand}): string {.
+    ...gcsafe, extern: "nosp$1", raises: [OSError, IOError],
+    tags: [ExecIOEffect, ReadIOEffect, RootEffect], forbids: [].}
+
+ + A convenience procedure that executes command with startProcess and returns its output as a string.
Warning: +This function uses poEvalCommand by default for backwards compatibility. Make sure to pass options explicitly.
+

See also:

+ +

Example:

+

let outp = execProcess("nim", args=["c", "-r", "mytestfile.nim"], options={poUsePath})
+let outp_shell = execProcess("nim c -r mytestfile.nim")
+# Note: outp may have an interleave of text from the nim compile
+# and any output from mytestfile when it runs

+ + Source   +Edit   + +
+
+ +
+
+
+
proc execProcesses(cmds: openArray[string];
+                   options = {poStdErrToStdOut, poParentStreams};
+                   n = countProcessors(); beforeRunEvent: proc (idx: int) = nil;
+                   afterRunEvent: proc (idx: int; p: Process) = nil): int {.
+    ...gcsafe, extern: "nosp$1", raises: [ValueError, OSError, IOError],
+    tags: [ExecIOEffect, TimeEffect, ReadEnvEffect, RootEffect],
+    effectsOf: [beforeRunEvent, afterRunEvent], ...forbids: [].}
+
+ +

Executes the commands cmds in parallel. Creates n processes that execute in parallel.

+

The highest (absolute) return value of all processes is returned. Runs beforeRunEvent before running each command.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc hasData(p: Process): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inputHandle(p: Process): FileHandle {....gcsafe, raises: [], extern: "nosp$1",
+    tags: [], forbids: [].}
+
+ + Returns p's input file handle for writing to.
Warning: +The returned FileHandle should not be closed manually as it is closed when closing the Process p.
+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inputStream(p: Process): Stream {....gcsafe, extern: "nosp$1", tags: [],
+                                       raises: [OSError], forbids: [].}
+
+ + Returns p's input stream for writing to.
Warning: +The returned Stream should not be closed manually as it is closed when closing the Process p.
+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc kill(p: Process) {....gcsafe, extern: "nosp$1", tags: [], raises: [OSError],
+                        forbids: [].}
+
+ +

Kill the process p.

+

On Posix OSes the procedure sends SIGKILL to the process. On Windows kill is simply an alias for terminate().

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc outputHandle(p: Process): FileHandle {....gcsafe, extern: "nosp$1",
+    raises: [], tags: [], forbids: [].}
+
+ + Returns p's output file handle for reading from.
Warning: +The returned FileHandle should not be closed manually as it is closed when closing the Process p.
+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc outputStream(p: Process): Stream {....gcsafe, extern: "nosp$1",
+                                        raises: [IOError, OSError], tags: [],
+                                        forbids: [].}
+
+ +

Returns p's output stream for reading from.

+

You cannot perform peek/write/setOption operations to this stream. Use peekableOutputStream proc if you need to peek stream.

+
Warning: +The returned Stream should not be closed manually as it is closed when closing the Process p.
+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc peekableErrorStream(p: Process): Stream {....gcsafe, extern: "nosp$1",
+    tags: [], raises: [OSError], forbids: [].}
+
+ +

Returns p's error stream for reading from.

+

You can run peek operation to returned stream.

+
Warning: +The returned Stream should not be closed manually as it is closed when closing the Process p.
+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc peekableOutputStream(p: Process): Stream {....gcsafe, extern: "nosp$1",
+    tags: [], raises: [OSError], forbids: [].}
+
+ +

Returns p's output stream for reading from.

+

You can peek returned stream.

+
Warning: +The returned Stream should not be closed manually as it is closed when closing the Process p.
+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc peekExitCode(p: Process): int {....gcsafe, extern: "nosp$1",
+                                     raises: [OSError], tags: [], forbids: [].}
+
+ +

Return -1 if the process is still running. Otherwise the process' exit code.

+

On posix, if the process has exited because of a signal, 128 + signal number will be returned.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc processID(p: Process): int {....gcsafe, extern: "nosp$1", raises: [],
+                                  tags: [], forbids: [].}
+
+ +

Returns p's process ID.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc readLines(p: Process): (seq[string], int) {.
+    ...raises: [OSError, IOError, ValueError], tags: [ReadIOEffect, TimeEffect],
+    forbids: [].}
+
+ +

Convenience function for working with startProcess to read data from a background process.

+

See also:

+ +

Example:

+

const opts = {poUsePath, poDaemon, poStdErrToStdOut}
+var ps: seq[Process]
+for prog in ["a", "b"]: # run 2 progs in parallel
+  ps.add startProcess("nim", "", ["r", prog], nil, opts)
+for p in ps:
+  let (lines, exCode) = p.readLines
+  if exCode != 0:
+    for line in lines: echo line
+  p.close

+ + Source   +Edit   + +
+
+ +
+
+
+
proc resume(p: Process) {....gcsafe, extern: "nosp$1", tags: [], raises: [OSError],
+                          forbids: [].}
+
+ +

Resumes the process p.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc running(p: Process): bool {....gcsafe, extern: "nosp$1", raises: [OSError],
+                                 tags: [], forbids: [].}
+
+ + Returns true if the process p is still running. Returns immediately. + Source   +Edit   + +
+
+ +
+
+
+
proc startProcess(command: string; workingDir: string = "";
+                  args: openArray[string] = []; env: StringTableRef = nil;
+                  options: set[ProcessOption] = {poStdErrToStdOut}): owned(
+    Process) {....gcsafe, extern: "nosp$1", raises: [OSError, IOError],
+               tags: [ExecIOEffect, ReadEnvEffect, RootEffect], forbids: [].}
+
+ +

Starts a process. Command is the executable file, workingDir is the process's working directory. If workingDir == "" the current directory is used (default). args are the command line arguments that are passed to the process. On many operating systems, the first command line argument is the name of the executable. args should not contain this argument! env is the environment that will be passed to the process. If env == nil (default) the environment is inherited of the parent process. options are additional flags that may be passed to startProcess. See the documentation of ProcessOption for the meaning of these flags.

+

You need to close the process when done.

+

Note that you can't pass any args if you use the option poEvalCommand, which invokes the system shell to run the specified command. In this situation you have to concatenate manually the contents of args to command carefully escaping/quoting any special characters, since it will be passed as is to the system shell. Each system/shell may feature different escaping rules, so try to avoid this kind of shell invocation if possible as it leads to non portable software.

+

Return value: The newly created process object. Nil is never returned, but OSError is raised in case of an error.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc suspend(p: Process) {....gcsafe, extern: "nosp$1", tags: [],
+                           raises: [OSError], forbids: [].}
+
+ +

Suspends the process p.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc terminate(p: Process) {....gcsafe, extern: "nosp$1", tags: [],
+                             raises: [OSError], forbids: [].}
+
+ +

Stop the process p.

+

On Posix OSes the procedure sends SIGTERM to the process. On Windows the Win32 API function TerminateProcess() is called to stop the process.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc waitForExit(p: Process; timeout: int = -1): int {....gcsafe, extern: "nosp$1",
+    raises: [OSError, ValueError], tags: [TimeEffect], forbids: [].}
+
+ + Waits for the process to finish and returns p's error code.
Warning: +Be careful when using waitForExit for processes created without poParentStreams because they may fill output buffers, causing deadlock.
+

On posix, if the process has exited because of a signal, 128 + signal number will be returned.

+
Warning: +When working with timeout parameters, remember that the value is typically expressed in milliseconds, and ensure that the correct unit of time is used to avoid unexpected behavior.
+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator lines(p: Process; keepNewLines = false): string {.
+    ...raises: [OSError, IOError, ValueError], tags: [ReadIOEffect, TimeEffect],
+    forbids: [].}
+
+ +

Convenience iterator for working with startProcess to read data from a background process.

+

See also:

+ +

Example:

+

const opts = {poUsePath, poDaemon, poStdErrToStdOut}
+var ps: seq[Process]
+for prog in ["a", "b"]: # run 2 progs in parallel
+  ps.add startProcess("nim", "", ["r", prog], nil, opts)
+for p in ps:
+  var i = 0
+  for line in p.lines:
+    echo line
+    i.inc
+    if i > 100: break
+  p.close

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/osproc.idx b/osproc.idx new file mode 100644 index 0000000000000..1eca6379872b2 --- /dev/null +++ b/osproc.idx @@ -0,0 +1,37 @@ +nimTitle osproc osproc.html module std/osproc 0 +nim poEchoCmd osproc.html#poEchoCmd ProcessOption.poEchoCmd 41 +nim poUsePath osproc.html#poUsePath ProcessOption.poUsePath 41 +nim poEvalCommand osproc.html#poEvalCommand ProcessOption.poEvalCommand 41 +nim poStdErrToStdOut osproc.html#poStdErrToStdOut ProcessOption.poStdErrToStdOut 41 +nim poParentStreams osproc.html#poParentStreams ProcessOption.poParentStreams 41 +nim poInteractive osproc.html#poInteractive ProcessOption.poInteractive 41 +nim poDaemon osproc.html#poDaemon ProcessOption.poDaemon 41 +nim ProcessOption osproc.html#ProcessOption enum ProcessOption 41 +nim Process osproc.html#Process type Process 73 +nim execProcess osproc.html#execProcess,string,string,openArray[string],StringTableRef,set[ProcessOption] proc execProcess(command: string; workingDir: string = "";\n args: openArray[string] = []; env: StringTableRef = nil; options: set[\n ProcessOption] = {poStdErrToStdOut, poUsePath, poEvalCommand}): string 76 +nim execCmd osproc.html#execCmd,string proc execCmd(command: string): int 101 +nim startProcess osproc.html#startProcess,string,string,openArray[string],StringTableRef,set[ProcessOption] proc startProcess(command: string; workingDir: string = "";\n args: openArray[string] = []; env: StringTableRef = nil;\n options: set[ProcessOption] = {poStdErrToStdOut}): owned(Process) 120 +nim close osproc.html#close,Process proc close(p: Process) 155 +nim suspend osproc.html#suspend,Process proc suspend(p: Process) 162 +nim resume osproc.html#resume,Process proc resume(p: Process) 171 +nim terminate osproc.html#terminate,Process proc terminate(p: Process) 179 +nim kill osproc.html#kill,Process proc kill(p: Process) 192 +nim running osproc.html#running,Process proc running(p: Process): bool 204 +nim processID osproc.html#processID,Process proc processID(p: Process): int 207 +nim waitForExit osproc.html#waitForExit,Process,int proc waitForExit(p: Process; timeout: int = -1): int 214 +nim peekExitCode osproc.html#peekExitCode,Process proc peekExitCode(p: Process): int 228 +nim inputStream osproc.html#inputStream,Process proc inputStream(p: Process): Stream 234 +nim outputStream osproc.html#outputStream,Process proc outputStream(p: Process): Stream 244 +nim errorStream osproc.html#errorStream,Process proc errorStream(p: Process): Stream 258 +nim peekableOutputStream osproc.html#peekableOutputStream,Process proc peekableOutputStream(p: Process): Stream 272 +nim peekableErrorStream osproc.html#peekableErrorStream,Process proc peekableErrorStream(p: Process): Stream 284 +nim inputHandle osproc.html#inputHandle,Process proc inputHandle(p: Process): FileHandle 296 +nim outputHandle osproc.html#outputHandle,Process proc outputHandle(p: Process): FileHandle 308 +nim errorHandle osproc.html#errorHandle,Process proc errorHandle(p: Process): FileHandle 320 +nim countProcessors osproc.html#countProcessors proc countProcessors(): int 332 +nim execProcesses osproc.html#execProcesses,openArray[string],proc(int),proc(int,Process) proc execProcesses(cmds: openArray[string];\n options = {poStdErrToStdOut, poParentStreams};\n n = countProcessors(); beforeRunEvent: proc (idx: int) = nil;\n afterRunEvent: proc (idx: int; p: Process) = nil): int 341 +nim lines osproc.html#lines.i,Process iterator lines(p: Process; keepNewLines = false): string 460 +nim readLines osproc.html#readLines,Process proc readLines(p: Process): (seq[string], int) 489 +nim hasData osproc.html#hasData,Process proc hasData(p: Process): bool 1512 +nim execCmdEx osproc.html#execCmdEx,string,set[ProcessOption],StringTableRef,string,string proc execCmdEx(command: string;\n options: set[ProcessOption] = {poStdErrToStdOut, poUsePath};\n env: StringTableRef = nil; workingDir = ""; input = ""): tuple[\n output: string, exitCode: int] 1522 +idx system osproc.html#system_1 Module osproc 0 diff --git a/osseps.html b/osseps.html new file mode 100644 index 0000000000000..e90a913c81f50 --- /dev/null +++ b/osseps.html @@ -0,0 +1,218 @@ + + + + + + + +std/private/osseps + + + + + + + + + + + + + + + + +
+
+

std/private/osseps

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
+

Consts

+
+
+
AltSep = '/'
+
+ + An alternative character used by the operating system to separate pathname components, or the same as DirSep if only one separator character exists. This is set to '/' on Windows systems where DirSep is a backslash ('\\'). + Source   +Edit   + +
+
+
+
CurDir = '.'
+
+ +

The constant character used by the operating system to refer to the current directory.

+

For example: '.' for POSIX or ':' for the classic Macintosh.

+ + Source   +Edit   + +
+
+
+
DirSep = '/'
+
+ + The character used by the operating system to separate pathname components, for example: '/' for POSIX, ':' for the classic Macintosh, and '\\' on Windows. + Source   +Edit   + +
+
+
+
doslikeFileSystem = false
+
+ + + Source   +Edit   + +
+
+
+
DynlibFormat = "lib$1.so"
+
+ + The format string to turn a filename into a DLL file (also called shared object on some operating systems). + Source   +Edit   + +
+
+
+
ExeExt = ""
+
+ + The file extension of native executables. For example: "" for POSIX, "exe" on Windows (without a dot). + Source   +Edit   + +
+
+
+
ExtSep = '.'
+
+ + The character which separates the base filename from the extension; for example, the '.' in os.nim. + Source   +Edit   + +
+
+
+
FileSystemCaseSensitive = true
+
+ + True if the file system is case sensitive, false otherwise. Used by ospaths2: cmpPaths proc to compare filenames properly. + Source   +Edit   + +
+
+
+
ParDir = ".."
+
+ +

The constant string used by the operating system to refer to the parent directory.

+

For example: ".." for POSIX or "::" for the classic Macintosh.

+ + Source   +Edit   + +
+
+
+
PathSep = ':'
+
+ + The character conventionally used by the operating system to separate search path components (as in PATH), such as ':' for POSIX or ';' for Windows. + Source   +Edit   + +
+
+
+
ScriptExt = ""
+
+ + The file extension of a script file. For example: "" for POSIX, "bat" on Windows. + Source   +Edit   + +
+
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/osseps.idx b/osseps.idx new file mode 100644 index 0000000000000..65f4bd01782a9 --- /dev/null +++ b/osseps.idx @@ -0,0 +1,14 @@ +nimTitle osseps osseps.html module std/private/osseps 0 +nim doslikeFileSystem osseps.html#doslikeFileSystem const doslikeFileSystem 9 +nim CurDir osseps.html#CurDir const CurDir 12 +nim ParDir osseps.html#ParDir const ParDir 21 +nim DirSep osseps.html#DirSep const DirSep 29 +nim AltSep osseps.html#AltSep const AltSep 38 +nim PathSep osseps.html#PathSep const PathSep 46 +nim FileSystemCaseSensitive osseps.html#FileSystemCaseSensitive const FileSystemCaseSensitive 55 +nim ExeExt osseps.html#ExeExt const ExeExt 62 +nim ScriptExt osseps.html#ScriptExt const ScriptExt 72 +nim DynlibFormat osseps.html#DynlibFormat const DynlibFormat 78 +nim ExtSep osseps.html#ExtSep const ExtSep 91 +idx DLL osseps.html#dll_1 Module osseps 0 +idx shared object osseps.html#shared-object_1 Module osseps 0 diff --git a/ossymlinks.html b/ossymlinks.html new file mode 100644 index 0000000000000..2c746830135c9 --- /dev/null +++ b/ossymlinks.html @@ -0,0 +1,148 @@ + + + + + + + +std/private/ossymlinks + + + + + + + + + + + + + + + + +
+
+

std/private/ossymlinks

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+ +
+

Procs

+
+ + + +
+
+ +
+
+ + +
+
+ + + + diff --git a/ossymlinks.idx b/ossymlinks.idx new file mode 100644 index 0000000000000..cebf33068db6a --- /dev/null +++ b/ossymlinks.idx @@ -0,0 +1,3 @@ +nimTitle ossymlinks ossymlinks.html module std/private/ossymlinks 0 +nim createSymlink ossymlinks.html#createSymlink,string,string proc createSymlink(src, dest: string) 36 +nim expandSymlink ossymlinks.html#expandSymlink,string proc expandSymlink(symlinkPath: string): string 59 diff --git a/outparams.html b/outparams.html new file mode 100644 index 0000000000000..d8ed912dde7e4 --- /dev/null +++ b/outparams.html @@ -0,0 +1,122 @@ + + + + + + + +std/outparams + + + + + + + + + + + + + + + + +
+
+

std/outparams

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

outParamsAt macro for easy writing code that works with both 2.0 and 1.x.

+
+

Imports

+
+ macros +
+
+
+

Macros

+
+
+
+
macro outParamsAt(positions: static openArray[int]; n: untyped): untyped
+
+ + Use this macro to annotate out parameters in a portable way. +

Example:

+
proc p(x: var int) {.outParamsAt: [1].} =
+  discard "x is really an 'out int' if the Nim compiler supports 'out' parameters"
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/outparams.idx b/outparams.idx new file mode 100644 index 0000000000000..954bdb2694084 --- /dev/null +++ b/outparams.idx @@ -0,0 +1,2 @@ +nimTitle outparams outparams.html module std/outparams 0 +nim outParamsAt outparams.html#outParamsAt.m,staticopenArray[int],untyped macro outParamsAt(positions: static openArray[int]; n: untyped): untyped 14 diff --git a/overview.html b/overview.html new file mode 100644 index 0000000000000..0cd266084ff12 --- /dev/null +++ b/overview.html @@ -0,0 +1,55 @@ + + + + + + + +Nim Documentation Overview + + + + + + + + + + + + + + + + +
+
+

Nim Documentation Overview

+ + +
Author:Andreas Rumpf
Version:2.2.1
The documentation consists of several documents:
  • Tutorial (part I)
    The Nim tutorial part one deals with the basics.

  • +
  • Tutorial (part II)
    The Nim tutorial part two deals with the advanced language constructs.

  • +
  • Tutorial (part III)
    The Nim tutorial part three about Nim's macro system.

  • +
  • Language Manual
    The Nim manual is a draft that will evolve into a proper specification.

  • +
  • Library documentation
    This document describes Nim's standard library.

  • +
  • Compiler user guide
    The user guide lists command line arguments, special features of the compiler, etc.

  • +
  • Tools documentation
    Description of some tools that come with the standard distribution.

  • +
  • Memory management
    Additional documentation about Nim's memory management strategies
    and how to operate them in a realtime setting.

  • +
  • Source code filters
    The Nim compiler supports source code filters as a simple yet powerful builtin templating system.

  • +
  • Internal documentation
    The internal documentation describes how the compiler is implemented. Read this if you want to hack the compiler.

  • +
  • Index
    The generated index. Index + (Ctrl+F) == Joy

  • +
+ + + + +
+
+ + + + diff --git a/overview.idx b/overview.idx new file mode 100644 index 0000000000000..fd550610a8ecd --- /dev/null +++ b/overview.idx @@ -0,0 +1 @@ +markupTitle Nim Documentation Overview overview.html Nim Documentation Overview 0 diff --git a/packaging.html b/packaging.html new file mode 100644 index 0000000000000..70a81f10239ef --- /dev/null +++ b/packaging.html @@ -0,0 +1,98 @@ + + + + + + + +Packaging Nim + + + + + + + + + + + + + + + + +
+
+

Packaging Nim

+

This page provide hints on distributing Nim using OS packages.

+

See distros for tools to detect Linux distribution at runtime.

+

See here for how to compile reproducible builds.

+ +

Supported architectures

Nim runs on a wide variety of platforms. Support on amd64 and i386 is tested regularly, while less popular platforms are tested by the community.

+
  • amd64
  • +
  • arm64 (aka aarch64)
  • +
  • armel
  • +
  • armhf
  • +
  • i386
  • +
  • m68k
  • +
  • mips64el
  • +
  • mipsel
  • +
  • powerpc
  • +
  • ppc64
  • +
  • ppc64el (aka ppc64le)
  • +
  • riscv64
  • +
+

The following platforms are seldomly tested:

+
  • alpha
  • +
  • hppa
  • +
  • ia64
  • +
  • mips
  • +
  • s390x
  • +
  • sparc64
  • +
+ +

Packaging for Linux

See https://github.com/nim-lang/Nim/labels/Installation for installation-related bugs.

+

Build Nim from the released tarball at https://nim-lang.org/install_unix.html It is different from the GitHub sources as it contains Nimble, C sources & other tools.

+

The Debian package ships bash and ksh completion and manpages that can be reused.

+

Hints on the build process:

+

# build from C sources and then using koch
+make -j   # supports parallel build
+# alternatively: ./build.sh --os $os_type --cpu $cpu_arch
+./bin/nim c -d:release koch
+./koch boot -d:release
+
+# optionally generate docs into doc/html
+./koch docs
+
+./koch tools
+
+# extract files to be really installed
+./install.sh <tempdir>
+
+# also include the tools
+for fn in nimble nimsuggest nimgrep; do cp ./bin/$fn <tempdir>/nim/bin/; done

+

What to install:

+
  • The expected stdlib location is /usr/lib/nim/lib, previously it was just /usr/lib/nim
  • +
  • nimdoc.css and nimdoc.cls from the doc folder should go into /usr/lib/nim/doc/
  • +
  • tools/debug/nim-gdb.py should go into /usr/lib/nim/tools/
  • +
  • tools/dochack/dochack.js should be installed to /usr/lib/nim/tools/dochack/
  • +
  • Global configuration files under /etc/nim
  • +
  • Optionally: manpages, documentation, shell completion
  • +
  • When installing documentation, .idx files are not required
  • +
  • The "compiler" directory contains compiler sources and should not be part of the compiler binary package
  • +
+ + + + +
+
+ + + + diff --git a/packaging.idx b/packaging.idx new file mode 100644 index 0000000000000..22f9d13e37e64 --- /dev/null +++ b/packaging.idx @@ -0,0 +1,3 @@ +markupTitle Packaging Nim packaging.html Packaging Nim 0 +heading Supported architectures packaging.html#supported-architectures Supported architectures 0 +heading Packaging for Linux packaging.html#packaging-for-linux Packaging for Linux 0 diff --git a/packedsets.html b/packedsets.html new file mode 100644 index 0000000000000..4606037bd32cf --- /dev/null +++ b/packedsets.html @@ -0,0 +1,811 @@ + + + + + + + +std/packedsets + + + + + + + + + + + + + + + + +
+
+

std/packedsets

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

The packedsets module implements an efficient Ordinal set implemented as a sparse bit set.

+

Supports any Ordinal type.

+ +

See also

+

+ +
+

Types

+
+
+
PackedSet[A] = object
+
+ + An efficient set of Ordinal types implemented as a sparse bit set. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`[A](s: PackedSet[A]): string
+
+ + Converts s to a string. +

Example:

+
let a = [1, 2, 3].toPackedSet
+assert $a == "{1, 2, 3}"
+ Source   +Edit   + +
+
+ +
+
+
+
proc `*`[A](s1, s2: PackedSet[A]): PackedSet[A] {.inline.}
+
+ + Alias for intersection(s1, s2). + Source   +Edit   + +
+
+ +
+
+
+
proc `+`[A](s1, s2: PackedSet[A]): PackedSet[A] {.inline.}
+
+ + Alias for union(s1, s2). + Source   +Edit   + +
+
+ +
+
+
+
proc `-`[A](s1, s2: PackedSet[A]): PackedSet[A] {.inline.}
+
+ + Alias for difference(s1, s2). + Source   +Edit   + +
+
+ +
+
+
+
proc `<`[A](s1, s2: PackedSet[A]): bool
+
+ +

Returns true if s1 is a proper subset of s2.

+

A strict or proper subset s1 has all of its elements in s2, but s2 has more elements than s1.

+ +

Example:

+
let
+  a = [1].toPackedSet
+  b = [1, 2].toPackedSet
+  c = [1, 3].toPackedSet
+assert a < b
+assert not (b < b)
+assert not (c < b)
+ Source   +Edit   + +
+
+ +
+
+
+
proc `<=`[A](s1, s2: PackedSet[A]): bool
+
+ +

Returns true if s1 is a subset of s2.

+

A subset s1 has all of its elements in s2, but s2 doesn't necessarily have more elements than s1. That is, s1 can be equal to s2.

+ +

Example:

+
let
+  a = [1].toPackedSet
+  b = [1, 2].toPackedSet
+  c = [1, 3].toPackedSet
+assert a <= b
+assert b <= b
+assert not (c <= b)
+ Source   +Edit   + +
+
+ +
+
+
+
proc `==`[A](s1, s2: PackedSet[A]): bool
+
+ + Returns true if both s1 and s2 have the same elements and set size. +

Example:

+
assert [1, 2].toPackedSet == [2, 1].toPackedSet
+assert [1, 2].toPackedSet == [2, 1, 2].toPackedSet
+ Source   +Edit   + +
+
+ +
+
+
+
proc `=copy`[A](dest: var PackedSet[A]; src: PackedSet[A])
+
+ + Copies src to dest. dest does not need to be initialized by the initPackedSet proc. + Source   +Edit   + +
+
+ +
+
+
+
proc assign[A](dest: var PackedSet[A]; src: PackedSet[A]) {.inline, ...deprecated.}
+
+
+ Deprecated +
+ + Copies src to dest. dest does not need to be initialized by the initPackedSet proc. +

Example:

+
var
+  a = initPackedSet[int]()
+  b = initPackedSet[int]()
+b.incl(5)
+b.incl(7)
+a.assign(b)
+assert len(a) == 2
+ Source   +Edit   + +
+
+ +
+
+
+
proc card[A](s: PackedSet[A]): int {.inline.}
+
+ +

Alias for len().

+

Card stands for the cardinality of a set.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc clear[A](result: var PackedSet[A])
+
+ + Clears the PackedSet[A] back to an empty state. +

Example:

+
var a = [5, 7].toPackedSet
+clear(a)
+assert len(a) == 0
+ Source   +Edit   + +
+
+ +
+
+
+
proc contains[A](s: PackedSet[A]; key: A): bool
+
+ +

Returns true if key is in s.

+

This allows the usage of the in operator.

+ +

Example:

+
type ABCD = enum A, B, C, D
+
+let a = [1, 3, 5].toPackedSet
+assert a.contains(3)
+assert 3 in a
+assert not a.contains(8)
+assert 8 notin a
+
+let letters = [A, C].toPackedSet
+assert A in letters
+assert C in letters
+assert B notin letters
+ Source   +Edit   + +
+
+ +
+
+
+
proc containsOrIncl[A](s: var PackedSet[A]; key: A): bool
+
+ +

Includes key in the set s and tells if key was already in s.

+

The difference with regards to the incl proc is that this proc returns true if s already contained key. The proc will return false if key was added as a new value to s during this call.

+

See also:

+ + +

Example:

+
var a = initPackedSet[int]()
+assert a.containsOrIncl(3) == false
+assert a.containsOrIncl(3) == true
+assert a.containsOrIncl(4) == false
+ Source   +Edit   + +
+
+ +
+
+
+
proc difference[A](s1, s2: PackedSet[A]): PackedSet[A]
+
+ +

Returns the difference of the sets s1 and s2.

+

The same as s1 - s2.

+ +

Example:

+
let
+  a = [1, 2, 3].toPackedSet
+  b = [3, 4, 5].toPackedSet
+  c = difference(a, b)
+assert c.len == 2
+assert c == [1, 2].toPackedSet
+ Source   +Edit   + +
+
+ +
+
+
+
proc disjoint[A](s1, s2: PackedSet[A]): bool
+
+ + Returns true if the sets s1 and s2 have no items in common. +

Example:

+
let
+  a = [1, 2].toPackedSet
+  b = [2, 3].toPackedSet
+  c = [3, 4].toPackedSet
+assert disjoint(a, b) == false
+assert disjoint(a, c) == true
+ Source   +Edit   + +
+
+ +
+
+
+
proc excl[A](s: var PackedSet[A]; key: A)
+
+ +

Excludes key from the set s.

+

This doesn't do anything if key is not found in s.

+

See also:

+ + +

Example:

+
var a = [3].toPackedSet
+a.excl(3)
+a.excl(3)
+a.excl(99)
+assert len(a) == 0
+ Source   +Edit   + +
+
+
+
proc excl[A](s: var PackedSet[A]; other: PackedSet[A])
+
+ +

Excludes all elements from other from s.

+

This is the in-place version of s - other.

+

See also:

+ + +

Example:

+
var a = [1, 5].toPackedSet
+a.excl([5].toPackedSet)
+assert len(a) == 1
+assert 5 notin a
+ Source   +Edit   + +
+
+ +
+
+
+
proc incl[A](s: var PackedSet[A]; key: A)
+
+ +

Includes an element key in s.

+

This doesn't do anything if key is already in s.

+

See also:

+ + +

Example:

+
var a = initPackedSet[int]()
+a.incl(3)
+a.incl(3)
+assert len(a) == 1
+ Source   +Edit   + +
+
+
+
proc incl[A](s: var PackedSet[A]; other: PackedSet[A])
+
+ +

Includes all elements from other into s.

+

This is the in-place version of s + other.

+

See also:

+ + +

Example:

+
var a = [1].toPackedSet
+a.incl([5].toPackedSet)
+assert len(a) == 2
+assert 5 in a
+ Source   +Edit   + +
+
+ +
+
+
+
proc initPackedSet[A](): PackedSet[A]
+
+ +

Returns an empty PackedSet[A]. A must be Ordinal.

+

See also:

+ + +

Example:

+
let a = initPackedSet[int]()
+assert len(a) == 0
+
+type Id = distinct int
+var ids = initPackedSet[Id]()
+ids.incl(3.Id)
+ Source   +Edit   + +
+
+ +
+
+
+
proc intersection[A](s1, s2: PackedSet[A]): PackedSet[A]
+
+ +

Returns the intersection of the sets s1 and s2.

+

The same as s1 * s2.

+ +

Example:

+
let
+  a = [1, 2, 3].toPackedSet
+  b = [3, 4, 5].toPackedSet
+  c = intersection(a, b)
+assert c.len == 1
+assert c == [3].toPackedSet
+ Source   +Edit   + +
+
+ +
+
+
+
proc isNil[A](x: PackedSet[A]): bool {.inline.}
+
+ + Returns true if x is empty, false otherwise. +

Example:

+
var a = initPackedSet[int]()
+assert a.isNil
+a.incl(2)
+assert not a.isNil
+a.excl(2)
+assert a.isNil
+ Source   +Edit   + +
+
+ +
+
+
+
proc len[A](s: PackedSet[A]): int {.inline.}
+
+ + Returns the number of elements in s. +

Example:

+
let a = [1, 3, 5].toPackedSet
+assert len(a) == 3
+ Source   +Edit   + +
+
+ +
+
+
+
proc missingOrExcl[A](s: var PackedSet[A]; key: A): bool
+
+ +

Excludes key from the set s and tells if key was already missing from s.

+

The difference with regards to the excl proc is that this proc returns true if key was missing from s. The proc will return false if key was in s and it was removed during this call.

+

See also:

+ + +

Example:

+
var a = [5].toPackedSet
+assert a.missingOrExcl(5) == false
+assert a.missingOrExcl(5) == true
+ Source   +Edit   + +
+
+ +
+
+
+
proc symmetricDifference[A](s1, s2: PackedSet[A]): PackedSet[A]
+
+ + Returns the symmetric difference of the sets s1 and s2. +

Example:

+
let
+  a = [1, 2, 3].toPackedSet
+  b = [3, 4, 5].toPackedSet
+  c = symmetricDifference(a, b)
+assert c.len == 4
+assert c == [1, 2, 4, 5].toPackedSet
+ Source   +Edit   + +
+
+ +
+
+
+
proc toPackedSet[A](x: openArray[A]): PackedSet[A]
+
+ +

Creates a new PackedSet[A] that contains the elements of x.

+

Duplicates are removed.

+

See also:

+ + +

Example:

+
let a = [5, 6, 7, 8, 8].toPackedSet
+assert len(a) == 4
+assert $a == "{5, 6, 7, 8}"
+ Source   +Edit   + +
+
+ +
+
+
+
proc union[A](s1, s2: PackedSet[A]): PackedSet[A]
+
+ +

Returns the union of the sets s1 and s2.

+

The same as s1 + s2.

+ +

Example:

+
let
+  a = [1, 2, 3].toPackedSet
+  b = [3, 4, 5].toPackedSet
+  c = union(a, b)
+assert c.len == 5
+assert c == [1, 2, 3, 4, 5].toPackedSet
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator items[A](s: PackedSet[A]): A {.inline.}
+
+ + Iterates over any included element of s. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/packedsets.idx b/packedsets.idx new file mode 100644 index 0000000000000..7293c796ecf0c --- /dev/null +++ b/packedsets.idx @@ -0,0 +1,34 @@ +nimTitle packedsets packedsets.html module std/packedsets 0 +nim PackedSet packedsets.html#PackedSet object PackedSet 46 +nim items packedsets.html#items.i,PackedSet[A] iterator items[A](s: PackedSet[A]): A 138 +nim initPackedSet packedsets.html#initPackedSet proc initPackedSet[A](): PackedSet[A] 160 +nim contains packedsets.html#contains,PackedSet[A],A proc contains[A](s: PackedSet[A]; key: A): bool 182 +nim incl packedsets.html#incl,PackedSet[A],A proc incl[A](s: var PackedSet[A]; key: A) 213 +nim incl packedsets.html#incl,PackedSet[A],PackedSet[A] proc incl[A](s: var PackedSet[A]; other: PackedSet[A]) 243 +nim toPackedSet packedsets.html#toPackedSet,openArray[A] proc toPackedSet[A](x: openArray[A]): PackedSet[A] 260 +nim containsOrIncl packedsets.html#containsOrIncl,PackedSet[A],A proc containsOrIncl[A](s: var PackedSet[A]; key: A): bool 276 +nim excl packedsets.html#excl,PackedSet[A],A proc excl[A](s: var PackedSet[A]; key: A) 311 +nim excl packedsets.html#excl,PackedSet[A],PackedSet[A] proc excl[A](s: var PackedSet[A]; other: PackedSet[A]) 329 +nim len packedsets.html#len,PackedSet[A] proc len[A](s: PackedSet[A]): int 347 +nim missingOrExcl packedsets.html#missingOrExcl,PackedSet[A],A proc missingOrExcl[A](s: var PackedSet[A]; key: A): bool 361 +nim clear packedsets.html#clear,PackedSet[A] proc clear[A](result: var PackedSet[A]) 382 +nim isNil packedsets.html#isNil,PackedSet[A] proc isNil[A](x: PackedSet[A]): bool 398 +nim `=copy` packedsets.html#=copy,PackedSet[A],PackedSet[A] proc `=copy`[A](dest: var PackedSet[A]; src: PackedSet[A]) 410 +nim assign packedsets.html#assign,PackedSet[A],PackedSet[A] proc assign[A](dest: var PackedSet[A]; src: PackedSet[A]) 441 +nim union packedsets.html#union,PackedSet[A],PackedSet[A] proc union[A](s1, s2: PackedSet[A]): PackedSet[A] 454 +nim intersection packedsets.html#intersection,PackedSet[A],PackedSet[A] proc intersection[A](s1, s2: PackedSet[A]): PackedSet[A] 469 +nim difference packedsets.html#difference,PackedSet[A],PackedSet[A] proc difference[A](s1, s2: PackedSet[A]): PackedSet[A] 486 +nim symmetricDifference packedsets.html#symmetricDifference,PackedSet[A],PackedSet[A] proc symmetricDifference[A](s1, s2: PackedSet[A]): PackedSet[A] 503 +nim `+` packedsets.html#+,PackedSet[A],PackedSet[A] proc `+`[A](s1, s2: PackedSet[A]): PackedSet[A] 518 +nim `*` packedsets.html#*,PackedSet[A],PackedSet[A] proc `*`[A](s1, s2: PackedSet[A]): PackedSet[A] 522 +nim `-` packedsets.html#-,PackedSet[A],PackedSet[A] proc `-`[A](s1, s2: PackedSet[A]): PackedSet[A] 526 +nim disjoint packedsets.html#disjoint,PackedSet[A],PackedSet[A] proc disjoint[A](s1, s2: PackedSet[A]): bool 530 +nim card packedsets.html#card,PackedSet[A] proc card[A](s: PackedSet[A]): int 545 +nim `<=` packedsets.html#<=,PackedSet[A],PackedSet[A] proc `<=`[A](s1, s2: PackedSet[A]): bool 552 +nim `<` packedsets.html#<,PackedSet[A],PackedSet[A] proc `<`[A](s1, s2: PackedSet[A]): bool 571 +nim `==` packedsets.html#==,PackedSet[A],PackedSet[A] proc `==`[A](s1, s2: PackedSet[A]): bool 587 +nim `$` packedsets.html#$,PackedSet[A] proc `$`[A](s: PackedSet[A]): string 595 +idx sparse bit set packedsets.html#sparse-bit-set_1 Module packedsets 0 +heading See also packedsets.html#see-also See also 0 +nimgrp excl packedsets.html#excl-procs-all proc 311 +nimgrp incl packedsets.html#incl-procs-all proc 213 diff --git a/parsecfg.html b/parsecfg.html new file mode 100644 index 0000000000000..218dc116040e4 --- /dev/null +++ b/parsecfg.html @@ -0,0 +1,731 @@ + + + + + + + +std/parsecfg + + + + + + + + + + + + + + + + +
+
+

std/parsecfg

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

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 quoted string literals are supported as in the Nim programming language.

+

Example of how a configuration file may look like:

+
# This is a comment.
+; this too.
+
+[Common]
+cc=gcc     # '=' and ':' are the same
+--foo="bar"   # '--cc' and 'cc' are the same, 'bar' and '"bar"' are the same (except for '#')
+macrosym: "#"  # Note that '#' is interpreted as a comment without the quotation
+--verbose
+
+[Windows]
+isConsoleApplication=False ; another comment
+
+[Posix]
+isConsoleApplication=True
+
+key1: "in this string backslash escapes are interpreted\n"
+key2: r"in this string not"
+key3: """triple quotes strings
+are also supported. They may span
+multiple lines."""
+
+--"long option with spaces": r"c:\myfiles\test.txt" 
+
+

Here is an example of how to use the configuration file parser:

+ +

Example: cmd: -r:off

+
import std/parsecfg
+import std/[strutils, streams]
+
+let configFile = "example.ini"
+var f = newFileStream(configFile, fmRead)
+assert f != nil, "cannot open " & configFile
+var p: CfgParser
+open(p, f, configFile)
+while true:
+  var e = next(p)
+  case e.kind
+  of cfgEof: break
+  of cfgSectionStart:   ## a `[section]` has been parsed
+    echo "new section: " & e.section
+  of cfgKeyValuePair:
+    echo "key-value-pair: " & e.key & ": " & e.value
+  of cfgOption:
+    echo "command: " & e.key & ": " & e.value
+  of cfgError:
+    echo e.msg
+close(p)
+

Configuration file example

charset = "utf-8"
+[Package]
+name = "hello"
+--threads:on
+[Author]
+name = "nim-lang"
+website = "nim-lang.org"
+

Creating a configuration file

+

Example:

+
import std/parsecfg
+var dict = newConfig()
+dict.setSectionKey("","charset", "utf-8")
+dict.setSectionKey("Package", "name", "hello")
+dict.setSectionKey("Package", "--threads", "on")
+dict.setSectionKey("Author", "name", "nim-lang")
+dict.setSectionKey("Author", "website", "nim-lang.org")
+assert $dict == """
+charset=utf-8
+[Package]
+name=hello
+--threads:on
+[Author]
+name=nim-lang
+website=nim-lang.org
+"""
+

Reading a configuration file

+

Example: cmd: -r:off

+
import std/parsecfg
+let dict = loadConfig("config.ini")
+let charset = dict.getSectionValue("","charset")
+let threads = dict.getSectionValue("Package","--threads")
+let pname = dict.getSectionValue("Package","name")
+let name = dict.getSectionValue("Author","name")
+let website = dict.getSectionValue("Author","website")
+echo pname & "\n" & name & "\n" & website
+

Modifying a configuration file

+

Example: cmd: -r:off

+
import std/parsecfg
+var dict = loadConfig("config.ini")
+dict.setSectionKey("Author", "name", "nim-lang")
+dict.writeConfig("config.ini")
+

Deleting a section key in a configuration file

+

Example: cmd: -r:off

+
import std/parsecfg
+var dict = loadConfig("config.ini")
+dict.delSectionKey("Author", "website")
+dict.writeConfig("config.ini")
+

Supported INI File structure

+

Example:

+
import std/parsecfg
+import std/streams
+
+var dict = loadConfig(newStringStream("""[Simple Values]
+    key=value
+    spaces in keys=allowed
+    spaces in values=allowed as well
+    spaces around the delimiter = obviously
+    you can also use : to delimit keys from values
+    [All Values Are Strings]
+    values like this: 19990429
+    or this: 3.14159265359
+    are they treated as numbers : no
+    integers floats and booleans are held as: strings
+    can use the API to get converted values directly: true
+    [No Values]
+    key_without_value
+    # empty string value is not allowed =
+    [ Seletion A   ]
+    space around section name will be ignored
+    [You can use comments]
+    # like this
+    ; or this
+    # By default only in an empty line.
+    # Inline comments can be harmful because they prevent users
+    # from using the delimiting characters as parts of values.
+    # That being said, this can be customized.
+        [Sections Can Be Indented]
+            can_values_be_as_well = True
+            does_that_mean_anything_special = False
+            purpose = formatting for readability
+            # Did I mention we can indent comments, too?
+    """)
+)
+
+let section1 = "Simple Values"
+assert dict.getSectionValue(section1, "key") == "value"
+assert dict.getSectionValue(section1, "spaces in keys") == "allowed"
+assert dict.getSectionValue(section1, "spaces in values") == "allowed as well"
+assert dict.getSectionValue(section1, "spaces around the delimiter") == "obviously"
+assert dict.getSectionValue(section1, "you can also use") == "to delimit keys from values"
+
+let section2 = "All Values Are Strings"
+assert dict.getSectionValue(section2, "values like this") == "19990429"
+assert dict.getSectionValue(section2, "or this") == "3.14159265359"
+assert dict.getSectionValue(section2, "are they treated as numbers") == "no"
+assert dict.getSectionValue(section2, "integers floats and booleans are held as") == "strings"
+assert dict.getSectionValue(section2, "can use the API to get converted values directly") == "true"
+
+let section3 = "Seletion A"
+assert dict.getSectionValue(section3, 
+  "space around section name will be ignored", "not an empty value") == ""
+
+let section4 = "Sections Can Be Indented"
+assert dict.getSectionValue(section4, "can_values_be_as_well") == "True"
+assert dict.getSectionValue(section4, "does_that_mean_anything_special") == "False"
+assert dict.getSectionValue(section4, "purpose") == "formatting for readability"

+ +
+

Types

+
+
+
CfgEvent = object of RootObj
+  case kind*: CfgEventKind   ## the kind of the event
+  of cfgEof:
+    nil
+  of cfgSectionStart:
+    section*: string         ## `section` contains the name of the
+                             ## parsed section start (syntax: `[section]`)
+  of cfgKeyValuePair, cfgOption:
+    key*, value*: string     ## contains the (key, value) pair if an option
+                             ## of the form `--key: value` or an ordinary
+                             ## `key= value` pair has been parsed.
+                             ## `value==""` if it was not specified in the
+                             ## configuration file.
+  of cfgError:              ## the parser encountered an error: `msg`
+    msg*: string             ## contains the error message. No exceptions
+                             ## are thrown if a parse error occurs.
+
+ + describes a parsing event + Source   +Edit   + +
+
+
+
CfgEventKind = enum
+  cfgEof,                   ## end of file reached
+  cfgSectionStart,          ## a `[section]` has been parsed
+  cfgKeyValuePair,          ## a `key=value` pair has been detected
+  cfgOption,                ## a `--key=value` command line option
+  cfgError                   ## an error occurred during parsing
+
+ + enumeration of all events that may occur when parsing + Source   +Edit   + +
+
+
+
CfgParser = object of BaseLexer
+
+ + the parser object. + Source   +Edit   + +
+
+ + +
+
+
+

Procs

+
+
+
+
proc `$`(dict: Config): string {....raises: [IOError, OSError],
+                                 tags: [WriteIOEffect], forbids: [].}
+
+ + Writes the contents of the table to string.
Note: +Comment statement will be ignored.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc close(c: var CfgParser) {....gcsafe, extern: "npc$1",
+                               raises: [IOError, OSError],
+                               tags: [WriteIOEffect], forbids: [].}
+
+ + Closes the parser c and its associated input stream. + Source   +Edit   + +
+
+ +
+
+
+
proc delSection(dict: var Config; section: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Deletes the specified section and all of its sub keys. + Source   +Edit   + +
+
+ +
+
+
+
proc delSectionKey(dict: var Config; section, key: string) {....raises: [KeyError],
+    tags: [], forbids: [].}
+
+ + Deletes the key of the specified section. + Source   +Edit   + +
+
+ +
+
+
+
proc errorStr(c: CfgParser; msg: string): string {....gcsafe, extern: "npc$1",
+    raises: [ValueError], tags: [], forbids: [].}
+
+ + Returns a properly formatted error message containing current line and column information. + Source   +Edit   + +
+
+ +
+
+
+
proc getColumn(c: CfgParser): int {....gcsafe, extern: "npc$1", raises: [],
+                                    tags: [], forbids: [].}
+
+ + Gets the current column the parser has arrived at. + Source   +Edit   + +
+
+ +
+
+
+
proc getFilename(c: CfgParser): string {....gcsafe, extern: "npc$1", raises: [],
+    tags: [], forbids: [].}
+
+ + Gets the filename of the file that the parser processes. + Source   +Edit   + +
+
+ +
+
+
+
proc getLine(c: CfgParser): int {....gcsafe, extern: "npc$1", raises: [], tags: [],
+                                  forbids: [].}
+
+ + Gets the current line the parser has arrived at. + Source   +Edit   + +
+
+ +
+
+
+
proc getSectionValue(dict: Config; section, key: string; defaultVal = ""): string {.
+    ...raises: [KeyError], tags: [], forbids: [].}
+
+ + Gets the key value of the specified Section. Returns the specified default value if the specified key does not exist. + Source   +Edit   + +
+
+ +
+
+
+
proc ignoreMsg(c: CfgParser; e: CfgEvent): string {....gcsafe, extern: "npc$1",
+    raises: [ValueError], tags: [], forbids: [].}
+
+ + Returns a properly formatted warning message containing that an entry is ignored. + Source   +Edit   + +
+
+ +
+
+
+
proc loadConfig(filename: string): Config {.
+    ...raises: [IOError, OSError, Exception, ValueError, KeyError],
+    tags: [WriteIOEffect, ReadIOEffect, RootEffect], forbids: [].}
+
+ + Loads the specified configuration file into a new Config instance. + Source   +Edit   + +
+
+
+
proc loadConfig(stream: Stream; filename: string = "[stream]"): Config {.
+    ...raises: [IOError, OSError, Exception, ValueError, KeyError],
+    tags: [ReadIOEffect, RootEffect, WriteIOEffect], forbids: [].}
+
+ + Loads the specified configuration from stream into a new Config instance. filename parameter is only used for nicer error messages. + Source   +Edit   + +
+
+ +
+
+
+
proc newConfig(): Config {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new configuration table. Useful when wanting to create a configuration file. + Source   +Edit   + +
+
+ +
+
+
+
proc next(c: var CfgParser): CfgEvent {....gcsafe, extern: "npc$1",
+                                        raises: [IOError, OSError, ValueError],
+                                        tags: [ReadIOEffect], forbids: [].}
+
+ + Retrieves the first/next event. This controls the parser. + Source   +Edit   + +
+
+ +
+
+
+
proc open(c: var CfgParser; input: Stream; filename: string; lineOffset = 0) {.
+    ...gcsafe, extern: "npc$1", raises: [IOError, OSError, Exception],
+    tags: [ReadIOEffect, RootEffect], forbids: [].}
+
+ + Initializes the parser with an input stream. Filename is only used for nice error messages. lineOffset can be used to influence the line number information in the generated error messages. + Source   +Edit   + +
+
+ +
+
+
+
proc setSectionKey(dict: var Config; section, key, value: string) {.
+    ...raises: [KeyError], tags: [], forbids: [].}
+
+ + Sets the Key value of the specified Section. + Source   +Edit   + +
+
+ +
+
+
+
proc warningStr(c: CfgParser; msg: string): string {....gcsafe, extern: "npc$1",
+    raises: [ValueError], tags: [], forbids: [].}
+
+ + Returns a properly formatted warning message containing current line and column information. + Source   +Edit   + +
+
+ +
+
+
+
proc writeConfig(dict: Config; filename: string) {....raises: [IOError, OSError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + Writes the contents of the table to the specified configuration file.
Note: +Comment statement will be ignored.
+ + Source   +Edit   + +
+
+
+
proc writeConfig(dict: Config; stream: Stream) {....raises: [IOError, OSError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + Writes the contents of the table to the specified stream.
Note: +Comment statement will be ignored.
+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator sections(dict: Config): lent string {....raises: [], tags: [], forbids: [].}
+
+ + Iterates through the sections in the dict. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/parsecfg.idx b/parsecfg.idx new file mode 100644 index 0000000000000..c3a67526519f1 --- /dev/null +++ b/parsecfg.idx @@ -0,0 +1,38 @@ +nimTitle parsecfg parsecfg.html module std/parsecfg 0 +nim cfgEof parsecfg.html#cfgEof CfgEventKind.cfgEof 184 +nim cfgSectionStart parsecfg.html#cfgSectionStart CfgEventKind.cfgSectionStart 184 +nim cfgKeyValuePair parsecfg.html#cfgKeyValuePair CfgEventKind.cfgKeyValuePair 184 +nim cfgOption parsecfg.html#cfgOption CfgEventKind.cfgOption 184 +nim cfgError parsecfg.html#cfgError CfgEventKind.cfgError 184 +nim CfgEventKind parsecfg.html#CfgEventKind enum CfgEventKind 184 +nim CfgEvent parsecfg.html#CfgEvent object CfgEvent 191 +nim CfgParser parsecfg.html#CfgParser object CfgParser 214 +nim open parsecfg.html#open,CfgParser,Stream,string,int proc open(c: var CfgParser; input: Stream; filename: string; lineOffset = 0) 225 +nim close parsecfg.html#close,CfgParser proc close(c: var CfgParser) 237 +nim getColumn parsecfg.html#getColumn,CfgParser proc getColumn(c: CfgParser): int 241 +nim getLine parsecfg.html#getLine,CfgParser proc getLine(c: CfgParser): int 245 +nim getFilename parsecfg.html#getFilename,CfgParser proc getFilename(c: CfgParser): string 249 +nim errorStr parsecfg.html#errorStr,CfgParser,string proc errorStr(c: CfgParser; msg: string): string 428 +nim warningStr parsecfg.html#warningStr,CfgParser,string proc warningStr(c: CfgParser; msg: string): string 434 +nim ignoreMsg parsecfg.html#ignoreMsg,CfgParser,CfgEvent proc ignoreMsg(c: CfgParser; e: CfgEvent): string 440 +nim next parsecfg.html#next,CfgParser proc next(c: var CfgParser): CfgEvent 471 +nim Config parsecfg.html#Config type Config 501 +nim newConfig parsecfg.html#newConfig proc newConfig(): Config 503 +nim loadConfig parsecfg.html#loadConfig,Stream,string proc loadConfig(stream: Stream; filename: string = "[stream]"): Config 508 +nim loadConfig parsecfg.html#loadConfig,string proc loadConfig(filename: string): Config 541 +nim writeConfig parsecfg.html#writeConfig,Config,Stream proc writeConfig(dict: Config; stream: Stream) 566 +nim `$` parsecfg.html#$,Config proc `$`(dict: Config): string 606 +nim writeConfig parsecfg.html#writeConfig,Config,string proc writeConfig(dict: Config; filename: string) 615 +nim getSectionValue parsecfg.html#getSectionValue,Config,string,string,string proc getSectionValue(dict: Config; section, key: string; defaultVal = ""): string 624 +nim setSectionKey parsecfg.html#setSectionKey,Config,string,string,string proc setSectionKey(dict: var Config; section, key, value: string) 635 +nim delSection parsecfg.html#delSection,Config,string proc delSection(dict: var Config; section: string) 643 +nim delSectionKey parsecfg.html#delSectionKey,Config,string,string proc delSectionKey(dict: var Config; section, key: string) 647 +nim sections parsecfg.html#sections.i,Config iterator sections(dict: Config): lent string 656 +heading Configuration file example parsecfg.html#configuration-file-example Configuration file example 0 +heading Creating a configuration file parsecfg.html#creating-a-configuration-file Creating a configuration file 0 +heading Reading a configuration file parsecfg.html#reading-a-configuration-file Reading a configuration file 0 +heading Modifying a configuration file parsecfg.html#modifying-a-configuration-file Modifying a configuration file 0 +heading Deleting a section key in a configuration file parsecfg.html#deleting-a-section-key-in-a-configuration-file Deleting a section key in a configuration file 0 +heading Supported INI File structure parsecfg.html#supported-ini-file-structure Supported INI File structure 0 +nimgrp writeconfig parsecfg.html#writeConfig-procs-all proc 566 +nimgrp loadconfig parsecfg.html#loadConfig-procs-all proc 508 diff --git a/parsecsv.html b/parsecsv.html new file mode 100644 index 0000000000000..6b15b22d1aaa3 --- /dev/null +++ b/parsecsv.html @@ -0,0 +1,430 @@ + + + + + + + +std/parsecsv + + + + + + + + + + + + + + + + +
+
+

std/parsecsv

+
+ +
+ Source   +Edit   + +
+ +

This module implements a simple high performance CSV (comma separated value) parser. +

Basic usage

import std/parsecsv
+from std/os import paramStr
+from std/streams import newFileStream
+
+var s = newFileStream(paramStr(1), fmRead)
+if s == nil:
+  quit("cannot open the file" & paramStr(1))
+
+var x: CsvParser
+open(x, s, paramStr(1))
+while readRow(x):
+  echo "new row: "
+  for val in items(x.row):
+    echo "##", val, "##"
+close(x)

+

For CSV files with a header row, the header can be read and then used as a reference for item access with rowEntry:

+

import std/parsecsv
+
+# Prepare a file
+let content = """One,Two,Three,Four
+1,2,3,4
+10,20,30,40
+100,200,300,400
+"""
+writeFile("temp.csv", content)
+
+var p: CsvParser
+p.open("temp.csv")
+p.readHeaderRow()
+while p.readRow():
+  echo "new row: "
+  for col in items(p.headers):
+    echo "##", col, ":", p.rowEntry(col), "##"
+p.close()

+ +

See also

+

+ +
+

Types

+
+
+
CsvError = object of IOError
+
+ + An exception that is raised if a parsing error occurs. + Source   +Edit   + +
+
+
+
CsvParser = object of BaseLexer
+  row*: CsvRow
+  headers*: seq[string]
+
+ +

The parser object.

+

It consists of two public fields:

+
  • row is the current row
  • +
  • headers are the columns that are defined in the csv file (read using readHeaderRow). Used with rowEntry).
  • +
+ + Source   +Edit   + +
+
+
+
CsvRow = seq[string]
+
+ + A row in a CSV file. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc close(self: var CsvParser) {.inline, ...raises: [IOError, OSError],
+                                  tags: [WriteIOEffect], forbids: [].}
+
+ + Closes the parser self and its associated input stream. + Source   +Edit   + +
+
+ +
+
+
+
proc open(self: var CsvParser; filename: string; separator = ','; quote = '\"';
+          escape = '\x00'; skipInitialSpace = false) {.
+    ...raises: [CsvError, IOError, OSError], tags: [ReadIOEffect], forbids: [].}
+
+ + Similar to the other open proc, but creates the file stream for you. +

Example:

+
from std/os import removeFile
+writeFile("tmp.csv", "One,Two,Three\n1,2,3\n10,20,300")
+var parser: CsvParser
+parser.open("tmp.csv")
+parser.close()
+removeFile("tmp.csv")
+ Source   +Edit   + +
+
+
+
proc open(self: var CsvParser; input: Stream; filename: string; separator = ',';
+          quote = '\"'; escape = '\x00'; skipInitialSpace = false) {.
+    ...raises: [IOError, OSError], tags: [ReadIOEffect], forbids: [].}
+
+ + Initializes the parser with an input stream. Filename is only used for nice error messages. The parser's behaviour can be controlled by the diverse optional parameters:
  • separator: character used to separate fields
  • +
  • quote: Used to quote fields containing special characters like separator, quote or new-line characters. '\0' disables the parsing of quotes.
  • +
  • escape: removes any special meaning from the following character; '\0' disables escaping; if escaping is disabled and quote is not '\0', two quote characters are parsed one literal quote character.
  • +
  • skipInitialSpace: If true, whitespace immediately following the separator is ignored.
  • +
+

See also:

+
  • open proc which creates the file stream for you
  • +
+ +

Example:

+
import std/streams
+var strm = newStringStream("One,Two,Three\n1,2,3\n10,20,30")
+var parser: CsvParser
+parser.open(strm, "tmp.csv")
+parser.close()
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc processedRows(self: var CsvParser): int {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Returns number of the processed rows.

+

But even if readRow arrived at EOF then processed rows counter is incremented.

+ +

Example:

+
import std/streams
+
+var strm = newStringStream("One,Two,Three\n1,2,3")
+var parser: CsvParser
+parser.open(strm, "tmp.csv")
+doAssert parser.readRow()
+doAssert parser.processedRows() == 1
+doAssert parser.readRow()
+doAssert parser.processedRows() == 2
+## Even if `readRow` arrived at EOF then `processedRows` is incremented.
+doAssert parser.readRow() == false
+doAssert parser.processedRows() == 3
+doAssert parser.readRow() == false
+doAssert parser.processedRows() == 4
+parser.close()
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readHeaderRow(self: var CsvParser) {....raises: [IOError, OSError, CsvError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + Reads the first row and creates a look-up table for column numbers See also: + +

Example:

+
import std/streams
+
+var strm = newStringStream("One,Two,Three\n1,2,3")
+var parser: CsvParser
+parser.open(strm, "tmp.csv")
+
+parser.readHeaderRow()
+doAssert parser.headers == @["One", "Two", "Three"]
+doAssert parser.row == @["One", "Two", "Three"]
+
+doAssert parser.readRow()
+doAssert parser.headers == @["One", "Two", "Three"]
+doAssert parser.row == @["1", "2", "3"]
+
+parser.close()
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readRow(self: var CsvParser; columns = 0): bool {.
+    ...raises: [IOError, OSError, CsvError], tags: [ReadIOEffect], forbids: [].}
+
+ +

Reads the next row; if columns > 0, it expects the row to have exactly this many columns. Returns false if the end of the file has been encountered else true.

+

Blank lines are skipped.

+ +

Example:

+
import std/streams
+var strm = newStringStream("One,Two,Three\n1,2,3\n\n10,20,30")
+var parser: CsvParser
+parser.open(strm, "tmp.csv")
+doAssert parser.readRow()
+doAssert parser.row == @["One", "Two", "Three"]
+doAssert parser.readRow()
+doAssert parser.row == @["1", "2", "3"]
+## Blank lines are skipped.
+doAssert parser.readRow()
+doAssert parser.row == @["10", "20", "30"]
+
+var emptySeq: seq[string]
+doAssert parser.readRow() == false
+doAssert parser.row == emptySeq
+doAssert parser.readRow() == false
+doAssert parser.row == emptySeq
+
+parser.close()
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc rowEntry(self: var CsvParser; entry: string): var string {.
+    ...raises: [KeyError], tags: [], forbids: [].}
+
+ +

Accesses a specified entry from the current row.

+

Assumes that readHeaderRow has already been called.

+

If specified entry does not exist, raises KeyError.

+ +

Example:

+
import std/streams
+var strm = newStringStream("One,Two,Three\n1,2,3\n\n10,20,30")
+var parser: CsvParser
+parser.open(strm, "tmp.csv")
+## Requires calling `readHeaderRow`.
+parser.readHeaderRow()
+doAssert parser.readRow()
+doAssert parser.rowEntry("One") == "1"
+doAssert parser.rowEntry("Two") == "2"
+doAssert parser.rowEntry("Three") == "3"
+doAssertRaises(KeyError):
+  discard parser.rowEntry("NonexistentEntry")
+parser.close()
+strm.close()
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/parsecsv.idx b/parsecsv.idx new file mode 100644 index 0000000000000..bf63e902fe9c4 --- /dev/null +++ b/parsecsv.idx @@ -0,0 +1,16 @@ +nimTitle parsecsv parsecsv.html module std/parsecsv 0 +nim CsvRow parsecsv.html#CsvRow type CsvRow 76 +nim CsvParser parsecsv.html#CsvParser object CsvParser 77 +nim CsvError parsecsv.html#CsvError object CsvError 91 +nim open parsecsv.html#open,CsvParser,Stream,string,char,char,char proc open(self: var CsvParser; input: Stream; filename: string; separator = ',';\n quote = '\"'; escape = '\x00'; skipInitialSpace = false) 107 +nim open parsecsv.html#open,CsvParser,string,char,char,char proc open(self: var CsvParser; filename: string; separator = ','; quote = '\"';\n escape = '\x00'; skipInitialSpace = false) 141 +nim processedRows parsecsv.html#processedRows,CsvParser proc processedRows(self: var CsvParser): int 202 +nim readRow parsecsv.html#readRow,CsvParser,int proc readRow(self: var CsvParser; columns = 0): bool 227 +nim close parsecsv.html#close,CsvParser proc close(self: var CsvParser) 292 +nim readHeaderRow parsecsv.html#readHeaderRow,CsvParser proc readHeaderRow(self: var CsvParser) 296 +nim rowEntry parsecsv.html#rowEntry,CsvParser,string proc rowEntry(self: var CsvParser; entry: string): var string 322 +idx CSV parsecsv.html#csv_1 Module parsecsv 0 +idx comma separated value parsecsv.html#comma-separated-value_1 Module parsecsv 0 +heading Basic usage parsecsv.html#basic-usage Basic usage 0 +heading See also parsecsv.html#see-also See also 0 +nimgrp open parsecsv.html#open-procs-all proc 107 diff --git a/parsejson.html b/parsejson.html new file mode 100644 index 0000000000000..f49b05c6c39e2 --- /dev/null +++ b/parsejson.html @@ -0,0 +1,556 @@ + + + + + + + +std/parsejson + + + + + + + + + + + + + + + + +
+
+

std/parsejson

+
+ +
+ Source   +Edit   + +
+ +

This module implements a json parser. It is used and exported by the json standard library module, but can also be used in its own right.

+ +
+

Types

+
+
+
JsonError = enum
+  errNone,                  ## no error
+  errInvalidToken,          ## invalid token
+  errStringExpected,        ## string expected
+  errColonExpected,         ## `:` expected
+  errCommaExpected,         ## `,` expected
+  errBracketRiExpected,     ## `]` expected
+  errCurlyRiExpected,       ## `}` expected
+  errQuoteExpected,         ## `"` or `'` expected
+  errEOC_Expected,          ## `*/` expected
+  errEofExpected,           ## EOF expected
+  errExprExpected            ## expr expected
+
+ + enumeration that lists all errors that can occur + Source   +Edit   + +
+
+
+
JsonEventKind = enum
+  jsonError,                ## an error occurred during parsing
+  jsonEof,                  ## end of file reached
+  jsonString,               ## a string literal
+  jsonInt,                  ## an integer literal
+  jsonFloat,                ## a float literal
+  jsonTrue,                 ## the value `true`
+  jsonFalse,                ## the value `false`
+  jsonNull,                 ## the value `null`
+  jsonObjectStart,          ## start of an object: the `{` token
+  jsonObjectEnd,            ## end of an object: the `}` token
+  jsonArrayStart,           ## start of an array: the `[` token
+  jsonArrayEnd               ## end of an array: the `]` token
+
+ + enumeration of all events that may occur when parsing + Source   +Edit   + +
+
+
+
JsonKindError = object of ValueError
+
+ + raised by the to macro if the JSON kind is incorrect. + Source   +Edit   + +
+
+
+
JsonParser = object of BaseLexer
+  a*: string
+  tok*: TokKind
+
+ + the parser object. + Source   +Edit   + +
+
+
+
JsonParsingError = object of ValueError
+
+ + is raised for a JSON error + Source   +Edit   + +
+
+
+
TokKind = enum
+  tkError, tkEof, tkString, tkInt, tkFloat, tkTrue, tkFalse, tkNull, tkCurlyLe,
+  tkCurlyRi, tkBracketLe, tkBracketRi, tkColon, tkComma
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
errorMessages: array[JsonError, string] = ["no error", "invalid token",
+    "string expected", "\':\' expected", "\',\' expected", "\']\' expected",
+    "\'}\' expected", "\'\"\' or \"\'\" expected", "\'*/\' expected",
+    "EOF expected", "expression expected"]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc close(my: var JsonParser) {.inline, ...raises: [IOError, OSError],
+                                 tags: [WriteIOEffect], forbids: [].}
+
+ + closes the parser my and its associated input stream. + Source   +Edit   + +
+
+ +
+
+
+
proc eat(p: var JsonParser; tok: TokKind) {.
+    ...raises: [IOError, OSError, JsonParsingError, ValueError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc errorMsg(my: JsonParser): string {....raises: [ValueError], tags: [],
+                                        forbids: [].}
+
+ + returns a helpful error message for the event jsonError + Source   +Edit   + +
+
+ +
+
+
+
proc errorMsgExpected(my: JsonParser; e: string): string {....raises: [ValueError],
+    tags: [], forbids: [].}
+
+ + returns an error message "e expected" in the same format as the other error messages + Source   +Edit   + +
+
+ +
+
+
+
proc getColumn(my: JsonParser): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + get the current column the parser has arrived at. + Source   +Edit   + +
+
+ +
+
+
+
proc getFilename(my: JsonParser): string {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + get the filename of the file that the parser processes. + Source   +Edit   + +
+
+ +
+
+
+
proc getFloat(my: JsonParser): float {.inline, ...raises: [ValueError], tags: [],
+                                       forbids: [].}
+
+ + returns the number for the event: jsonFloat + Source   +Edit   + +
+
+ +
+
+
+
proc getInt(my: JsonParser): BiggestInt {.inline, ...raises: [ValueError],
+    tags: [], forbids: [].}
+
+ + returns the number for the event: jsonInt + Source   +Edit   + +
+
+ +
+
+
+
proc getLine(my: JsonParser): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + get the current line the parser has arrived at. + Source   +Edit   + +
+
+ +
+
+
+
proc getTok(my: var JsonParser): TokKind {....raises: [IOError, OSError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc kind(my: JsonParser): JsonEventKind {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + returns the current event type for the JSON parser + Source   +Edit   + +
+
+ +
+
+
+
proc next(my: var JsonParser) {....raises: [IOError, OSError],
+                                tags: [ReadIOEffect], forbids: [].}
+
+ + retrieves the first/next event. This controls the parser. + Source   +Edit   + +
+
+ +
+
+
+
proc open(my: var JsonParser; input: Stream; filename: string;
+          rawStringLiterals = false) {....raises: [IOError, OSError],
+                                       tags: [ReadIOEffect], forbids: [].}
+
+ + initializes the parser with an input stream. Filename is only used for nice error messages. If rawStringLiterals is true, string literals are kept with their surrounding quotes and escape sequences in them are left untouched too. + Source   +Edit   + +
+
+ +
+
+
+
proc parseEscapedUTF16(buf: cstring; pos: var int): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc raiseParseErr(p: JsonParser; msg: string) {.noinline, noreturn,
+    ...raises: [JsonParsingError, ValueError], tags: [], forbids: [].}
+
+ + raises an EJsonParsingError exception. + Source   +Edit   + +
+
+ +
+
+
+
proc str(my: JsonParser): string {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + returns the character data for the events: jsonInt, jsonFloat, jsonString + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/parsejson.idx b/parsejson.idx new file mode 100644 index 0000000000000..ec2284469526d --- /dev/null +++ b/parsejson.idx @@ -0,0 +1,61 @@ +nimTitle parsejson parsejson.html module std/parsejson 0 +nim jsonError parsejson.html#jsonError JsonEventKind.jsonError 21 +nim jsonEof parsejson.html#jsonEof JsonEventKind.jsonEof 21 +nim jsonString parsejson.html#jsonString JsonEventKind.jsonString 21 +nim jsonInt parsejson.html#jsonInt JsonEventKind.jsonInt 21 +nim jsonFloat parsejson.html#jsonFloat JsonEventKind.jsonFloat 21 +nim jsonTrue parsejson.html#jsonTrue JsonEventKind.jsonTrue 21 +nim jsonFalse parsejson.html#jsonFalse JsonEventKind.jsonFalse 21 +nim jsonNull parsejson.html#jsonNull JsonEventKind.jsonNull 21 +nim jsonObjectStart parsejson.html#jsonObjectStart JsonEventKind.jsonObjectStart 21 +nim jsonObjectEnd parsejson.html#jsonObjectEnd JsonEventKind.jsonObjectEnd 21 +nim jsonArrayStart parsejson.html#jsonArrayStart JsonEventKind.jsonArrayStart 21 +nim jsonArrayEnd parsejson.html#jsonArrayEnd JsonEventKind.jsonArrayEnd 21 +nim JsonEventKind parsejson.html#JsonEventKind enum JsonEventKind 21 +nim tkError parsejson.html#tkError TokKind.tkError 35 +nim tkEof parsejson.html#tkEof TokKind.tkEof 35 +nim tkString parsejson.html#tkString TokKind.tkString 35 +nim tkInt parsejson.html#tkInt TokKind.tkInt 35 +nim tkFloat parsejson.html#tkFloat TokKind.tkFloat 35 +nim tkTrue parsejson.html#tkTrue TokKind.tkTrue 35 +nim tkFalse parsejson.html#tkFalse TokKind.tkFalse 35 +nim tkNull parsejson.html#tkNull TokKind.tkNull 35 +nim tkCurlyLe parsejson.html#tkCurlyLe TokKind.tkCurlyLe 35 +nim tkCurlyRi parsejson.html#tkCurlyRi TokKind.tkCurlyRi 35 +nim tkBracketLe parsejson.html#tkBracketLe TokKind.tkBracketLe 35 +nim tkBracketRi parsejson.html#tkBracketRi TokKind.tkBracketRi 35 +nim tkColon parsejson.html#tkColon TokKind.tkColon 35 +nim tkComma parsejson.html#tkComma TokKind.tkComma 35 +nim TokKind parsejson.html#TokKind enum TokKind 35 +nim errNone parsejson.html#errNone JsonError.errNone 51 +nim errInvalidToken parsejson.html#errInvalidToken JsonError.errInvalidToken 51 +nim errStringExpected parsejson.html#errStringExpected JsonError.errStringExpected 51 +nim errColonExpected parsejson.html#errColonExpected JsonError.errColonExpected 51 +nim errCommaExpected parsejson.html#errCommaExpected JsonError.errCommaExpected 51 +nim errBracketRiExpected parsejson.html#errBracketRiExpected JsonError.errBracketRiExpected 51 +nim errCurlyRiExpected parsejson.html#errCurlyRiExpected JsonError.errCurlyRiExpected 51 +nim errQuoteExpected parsejson.html#errQuoteExpected JsonError.errQuoteExpected 51 +nim errEOC_Expected parsejson.html#errEOC_Expected JsonError.errEOC_Expected 51 +nim errEofExpected parsejson.html#errEofExpected JsonError.errEofExpected 51 +nim errExprExpected parsejson.html#errExprExpected JsonError.errExprExpected 51 +nim JsonError parsejson.html#JsonError_2 enum JsonError 51 +nim JsonParser parsejson.html#JsonParser object JsonParser 68 +nim JsonKindError parsejson.html#JsonKindError object JsonKindError 77 +nim JsonParsingError parsejson.html#JsonParsingError object JsonParsingError 79 +nim errorMessages parsejson.html#errorMessages const errorMessages 82 +nim open parsejson.html#open,JsonParser,Stream,string proc open(my: var JsonParser; input: Stream; filename: string;\n rawStringLiterals = false) 107 +nim close parsejson.html#close,JsonParser proc close(my: var JsonParser) 120 +nim str parsejson.html#str,JsonParser proc str(my: JsonParser): string 124 +nim getInt parsejson.html#getInt,JsonParser proc getInt(my: JsonParser): BiggestInt 130 +nim getFloat parsejson.html#getFloat,JsonParser proc getFloat(my: JsonParser): float 135 +nim kind parsejson.html#kind,JsonParser proc kind(my: JsonParser): JsonEventKind 140 +nim getColumn parsejson.html#getColumn,JsonParser proc getColumn(my: JsonParser): int 144 +nim getLine parsejson.html#getLine,JsonParser proc getLine(my: JsonParser): int 148 +nim getFilename parsejson.html#getFilename,JsonParser proc getFilename(my: JsonParser): string 152 +nim errorMsg parsejson.html#errorMsg,JsonParser proc errorMsg(my: JsonParser): string 156 +nim errorMsgExpected parsejson.html#errorMsgExpected,JsonParser,string proc errorMsgExpected(my: JsonParser; e: string): string 162 +nim parseEscapedUTF16 parsejson.html#parseEscapedUTF16,cstring,int proc parseEscapedUTF16(buf: cstring; pos: var int): int 168 +nim getTok parsejson.html#getTok,JsonParser proc getTok(my: var JsonParser): TokKind 354 +nim next parsejson.html#next,JsonParser proc next(my: var JsonParser) 399 +nim raiseParseErr parsejson.html#raiseParseErr,JsonParser,string proc raiseParseErr(p: JsonParser; msg: string) 516 +nim eat parsejson.html#eat,JsonParser,TokKind proc eat(p: var JsonParser; tok: TokKind) 520 diff --git a/parseopt.html b/parseopt.html new file mode 100644 index 0000000000000..16dc1d1f9644e --- /dev/null +++ b/parseopt.html @@ -0,0 +1,508 @@ + + + + + + + +std/parseopt + + + + + + + + + + + + + + + + +
+
+

std/parseopt

+
+ +
+ Source   +Edit   + +
+ +

This module provides the standard Nim command line parser. It supports one convenience iterator over all command line options and some lower-level features. +

Supported Syntax

The following syntax is supported when arguments for the shortNoVal and longNoVal parameters, which are described later, are not provided:

+
  1. Short options: -abcd, -e:5, -e=5
  2. +
  3. Long options: --foo:bar, --foo=bar, --foo
  4. +
  5. Arguments: everything that does not start with a -
  6. +
+

These three kinds of tokens are enumerated in the CmdLineKind enum.

+

When option values begin with ':' or '=', they need to be doubled up (as in --delim::) or alternated (as in --delim=:).

+

The -- option, commonly used to denote that every token that follows is an argument, is interpreted as a long option, and its name is the empty string.

+ +

Parsing

Use an OptParser to parse command line options. It can be created with initOptParser, and next advances the parser by one token.

+

For each token, the parser's kind, key, and val fields give information about that token. If the token is a long or short option, key is the option's name, and val is either the option's value, if provided, or the empty string. For arguments, the key field contains the argument itself, and val is unused. To check if the end of the command line has been reached, check if kind is equal to cmdEnd.

+

Here is an example:

+

import std/parseopt
+
+var p = initOptParser("-ab -e:5 --foo --bar=20 file.txt")
+while true:
+  p.next()
+  case p.kind
+  of cmdEnd: break
+  of cmdShortOption, cmdLongOption:
+    if p.val == "":
+      echo "Option: ", p.key
+    else:
+      echo "Option and value: ", p.key, ", ", p.val
+  of cmdArgument:
+    echo "Argument: ", p.key
+
+# Output:
+# Option: a
+# Option: b
+# Option and value: e, 5
+# Option: foo
+# Option and value: bar, 20
+# Argument: file.txt

+

The getopt iterator, which is provided for convenience, can be used to iterate through all command line options as well.

+

To set a default value for a variable assigned through getopt and accept arguments from the cmd line. Assign the default value to a variable before parsing. Then set the variable to the new value while parsing.

+

Here is an example:

+

import std/parseopt
+
+var varName: string = "defaultValue"
+
+for kind, key, val in getopt():
+  case kind
+  of cmdArgument:
+    discard
+  of cmdLongOption, cmdShortOption:
+    case key:
+    of "varName": # --varName:<value> in the console when executing
+      varName = val # do input sanitization in production systems
+  of cmdEnd:
+    discard

+ +

shortNoVal and longNoVal

The optional shortNoVal and longNoVal parameters present in initOptParser are for specifying which short and long options do not accept values.

+

When shortNoVal is non-empty, users are not required to separate short options and their values with a ':' or '=' since the parser knows which options accept values and which ones do not. This behavior also applies for long options if longNoVal is non-empty. For short options, -j4 becomes supported syntax, and for long options, --foo bar becomes supported. This is in addition to the previously mentioned syntax. Users can still separate options and their values with ':' or '=', but that becomes optional.

+

As more options which do not accept values are added to your program, remember to amend shortNoVal and longNoVal accordingly.

+

The following example illustrates the difference between having an empty shortNoVal and longNoVal, which is the default, and providing arguments for those two parameters:

+

import std/parseopt
+
+proc printToken(kind: CmdLineKind, key: string, val: string) =
+  case kind
+  of cmdEnd: doAssert(false)  # Doesn't happen with getopt()
+  of cmdShortOption, cmdLongOption:
+    if val == "":
+      echo "Option: ", key
+    else:
+      echo "Option and value: ", key, ", ", val
+  of cmdArgument:
+    echo "Argument: ", key
+
+let cmdLine = "-j4 --first bar"
+
+var emptyNoVal = initOptParser(cmdLine)
+for kind, key, val in emptyNoVal.getopt():
+  printToken(kind, key, val)
+
+# Output:
+# Option: j
+# Option: 4
+# Option: first
+# Argument: bar
+
+var withNoVal = initOptParser(cmdLine, shortNoVal = {'c'},
+                              longNoVal = @["second"])
+for kind, key, val in withNoVal.getopt():
+  printToken(kind, key, val)
+
+# Output:
+# Option and value: j, 4
+# Option and value: first, bar

+ +

See also

+

+
+

Imports

+
+ strutils, os +
+
+
+

Types

+
+
+
CmdLineKind = enum
+  cmdEnd,                   ## End of command line reached
+  cmdArgument,              ## An argument such as a filename
+  cmdLongOption,            ## A long option such as --option
+  cmdShortOption             ## A short option such as -c
+
+ + The detected command line token. + Source   +Edit   + +
+
+
+
OptParser = object of RootObj
+  kind*: CmdLineKind         ## The detected command line token
+  key*, val*: string         ## Key and value pair; the key is the option
+                             ## or the argument, and the value is not "" if
+                             ## the option was given a value
+
+ +

+Implementation of the command line parser.

+

To initialize it, use the initOptParser proc.

+ + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc cmdLineRest(p: OptParser): string {....gcsafe, extern: "npo$1", raises: [],
+    tags: [], forbids: [].}
+
+ +

Retrieves the rest of the command line that has not been parsed yet.

+

See also:

+ +

Examples:

+

var p = initOptParser("--left -r:2 -- foo.txt bar.txt")
+while true:
+  p.next()
+  if p.kind == cmdLongOption and p.key == "":  # Look for "--"
+    break
+doAssert p.cmdLineRest == "foo.txt bar.txt"

+ + Source   +Edit   + +
+
+ +
+
+
+
proc initOptParser(cmdline = ""; shortNoVal: set[char] = {};
+                   longNoVal: seq[string] = @[];
+                   allowWhitespaceAfterColon = true): OptParser {....raises: [],
+    tags: [ReadIOEffect], forbids: [].}
+
+ +

Initializes the command line parser.

+

If cmdline == "", the real command line as provided by the os module is retrieved instead if it is available. If the command line is not available, a ValueError will be raised.

+

shortNoVal and longNoVal are used to specify which options do not take values. See the documentation about these parameters for more information on how this affects parsing.

+

This does not provide a way of passing default values to arguments.

+

See also:

+ + +

Example:

+
var p = initOptParser()
+p = initOptParser("--left --debug:3 -l -r:2")
+p = initOptParser("--left --debug:3 -l -r:2",
+                  shortNoVal = {'l'}, longNoVal = @["left"])
+ Source   +Edit   + +
+
+
+
proc initOptParser(cmdline: seq[string]; shortNoVal: set[char] = {};
+                   longNoVal: seq[string] = @[];
+                   allowWhitespaceAfterColon = true): OptParser {....raises: [],
+    tags: [ReadIOEffect], forbids: [].}
+
+ +

Initializes the command line parser.

+

If cmdline.len == 0, the real command line as provided by the os module is retrieved instead if it is available. If the command line is not available, a ValueError will be raised. Behavior of the other parameters remains the same as in initOptParser(string, ...).

+

See also:

+ + +

Example:

+
var p = initOptParser()
+p = initOptParser(@["--left", "--debug:3", "-l", "-r:2"])
+p = initOptParser(@["--left", "--debug:3", "-l", "-r:2"],
+                  shortNoVal = {'l'}, longNoVal = @["left"])
+ Source   +Edit   + +
+
+ +
+
+
+
proc next(p: var OptParser) {....gcsafe, extern: "npo$1", raises: [], tags: [],
+                              forbids: [].}
+
+ +

Parses the next token.

+

p.kind describes what kind of token has been parsed. p.key and p.val are set accordingly.

+ +

Example:

+
var p = initOptParser("--left -r:2 file.txt")
+p.next()
+doAssert p.kind == cmdLongOption and p.key == "left"
+p.next()
+doAssert p.kind == cmdShortOption and p.key == "r" and p.val == "2"
+p.next()
+doAssert p.kind == cmdArgument and p.key == "file.txt"
+p.next()
+doAssert p.kind == cmdEnd
+ Source   +Edit   + +
+
+ +
+
+
+
proc remainingArgs(p: OptParser): seq[string] {....gcsafe, extern: "npo$1",
+    raises: [], tags: [], forbids: [].}
+
+ +

Retrieves a sequence of the arguments that have not been parsed yet.

+

See also:

+ +

Examples:

+

var p = initOptParser("--left -r:2 -- foo.txt bar.txt")
+while true:
+  p.next()
+  if p.kind == cmdLongOption and p.key == "":  # Look for "--"
+    break
+doAssert p.remainingArgs == @["foo.txt", "bar.txt"]

+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator getopt(cmdline: seq[string] = @[]; shortNoVal: set[char] = {};
+                longNoVal: seq[string] = @[]): tuple[kind: CmdLineKind,
+    key, val: string] {....raises: [], tags: [ReadIOEffect], forbids: [].}
+
+ +

Convenience iterator for iterating over command line arguments.

+

This creates a new OptParser. If no command line arguments are provided, the real command line as provided by the os module is retrieved instead.

+

shortNoVal and longNoVal are used to specify which options do not take values. See the documentation about these parameters for more information on how this affects parsing.

+

There is no need to check for cmdEnd while iterating. If using getopt with case switching, checking for cmdEnd is required.

+

See also:

+ +

Examples:

+

# these are placeholders, of course
+proc writeHelp() = discard
+proc writeVersion() = discard
+
+var filename: string
+let params = @["--left", "--debug:3", "-l", "-r:2"]
+
+for kind, key, val in getopt(params):
+  case kind
+  of cmdArgument:
+    filename = key
+  of cmdLongOption, cmdShortOption:
+    case key
+    of "help", "h": writeHelp()
+    of "version", "v": writeVersion()
+  of cmdEnd: assert(false) # cannot happen
+if filename == "":
+  # no filename has been written, so we show the help
+  writeHelp()

+ + Source   +Edit   + +
+
+
+
iterator getopt(p: var OptParser): tuple[kind: CmdLineKind, key, val: string] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Convenience iterator for iterating over the given OptParser.

+

There is no need to check for cmdEnd while iterating. If using getopt with case switching, checking for cmdEnd is required.

+

See also:

+ +

Examples:

+

# these are placeholders, of course
+proc writeHelp() = discard
+proc writeVersion() = discard
+
+var filename: string
+var p = initOptParser("--left --debug:3 -l -r:2")
+
+for kind, key, val in p.getopt():
+  case kind
+  of cmdArgument:
+    filename = key
+  of cmdLongOption, cmdShortOption:
+    case key
+    of "help", "h": writeHelp()
+    of "version", "v": writeVersion()
+  of cmdEnd: assert(false) # cannot happen
+if filename == "":
+  # no filename has been given, so we show the help
+  writeHelp()

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/parseopt.idx b/parseopt.idx new file mode 100644 index 0000000000000..ba71299926372 --- /dev/null +++ b/parseopt.idx @@ -0,0 +1,20 @@ +nimTitle parseopt parseopt.html module std/parseopt 0 +nim cmdEnd parseopt.html#cmdEnd CmdLineKind.cmdEnd 183 +nim cmdArgument parseopt.html#cmdArgument CmdLineKind.cmdArgument 183 +nim cmdLongOption parseopt.html#cmdLongOption CmdLineKind.cmdLongOption 183 +nim cmdShortOption parseopt.html#cmdShortOption CmdLineKind.cmdShortOption 183 +nim CmdLineKind parseopt.html#CmdLineKind enum CmdLineKind 183 +nim OptParser parseopt.html#OptParser object OptParser 188 +nim initOptParser parseopt.html#initOptParser,seq[string],set[char],seq[string] proc initOptParser(cmdline: seq[string]; shortNoVal: set[char] = {};\n longNoVal: seq[string] = @[]; allowWhitespaceAfterColon = true): OptParser 221 +nim initOptParser parseopt.html#initOptParser,string,set[char],seq[string] proc initOptParser(cmdline = ""; shortNoVal: set[char] = {};\n longNoVal: seq[string] = @[]; allowWhitespaceAfterColon = true): OptParser 276 +nim next parseopt.html#next,OptParser proc next(p: var OptParser) 328 +nim cmdLineRest parseopt.html#cmdLineRest,OptParser proc cmdLineRest(p: OptParser): string 399 +nim remainingArgs parseopt.html#remainingArgs,OptParser proc remainingArgs(p: OptParser): seq[string] 416 +nim getopt parseopt.html#getopt.i,OptParser iterator getopt(p: var OptParser): tuple[kind: CmdLineKind, key, val: string] 434 +nim getopt parseopt.html#getopt.i,seq[string],set[char],seq[string] iterator getopt(cmdline: seq[string] = @[]; shortNoVal: set[char] = {};\n longNoVal: seq[string] = @[]): tuple[kind: CmdLineKind, key, val: string] 475 +heading Supported Syntax parseopt.html#supported-syntax Supported Syntax 0 +heading Parsing parseopt.html#parsing Parsing 0 +heading nimshortNoVal and nimlongNoVal parseopt.html#nimshortnoval-and-nimlongnoval shortNoVal and longNoVal 0 +heading See also parseopt.html#see-also See also 0 +nimgrp initoptparser parseopt.html#initOptParser-procs-all proc 221 +nimgrp getopt parseopt.html#getopt-iterators-all iterator 434 diff --git a/parsesql.html b/parsesql.html new file mode 100644 index 0000000000000..7d4fd31b504c3 --- /dev/null +++ b/parsesql.html @@ -0,0 +1,407 @@ + + + + + + + +std/parsesql + + + + + + + + + + + + + + + + +
+
+

std/parsesql

+
+ +
+ Source   +Edit   + +
+ +

The parsesql module implements a high performance SQL file parser. It parses PostgreSQL syntax and the SQL ANSI standard.

+

Unstable API.

+

+ +
+

Types

+
+
+
SqlLexer = object of BaseLexer
+
+ + the parser object. + Source   +Edit   + +
+
+
+
SqlNode = ref SqlNodeObj
+
+ + an SQL abstract syntax tree node + Source   +Edit   + +
+
+
+
SqlNodeKind = enum
+  nkNone, nkIdent, nkQuotedIdent, nkStringLit, nkBitStringLit, nkHexStringLit,
+  nkIntegerLit, nkNumericLit, nkPrimaryKey, nkForeignKey, nkNotNull, nkNull,
+  nkStmtList, nkDot, nkDotDot, nkPrefix, nkInfix, nkCall, nkPrGroup,
+  nkColumnReference, nkReferences, nkDefault, nkCheck, nkConstraint, nkUnique,
+  nkIdentity, nkColumnDef,  ## name, datatype, constraints
+  nkInsert, nkUpdate, nkDelete, nkSelect, nkSelectDistinct, nkSelectColumns,
+  nkSelectPair, nkAsgn, nkFrom, nkFromItemPair, nkJoin, nkNaturalJoin, nkUsing,
+  nkGroup, nkLimit, nkOffset, nkHaving, nkOrder, nkDesc, nkUnion, nkIntersect,
+  nkExcept, nkColumnList, nkValueList, nkWhere, nkCreateTable,
+  nkCreateTableIfNotExists, nkCreateType, nkCreateTypeIfNotExists,
+  nkCreateIndex, nkCreateIndexIfNotExists, nkEnumDef
+
+ + kind of SQL abstract syntax tree + Source   +Edit   + +
+
+
+
SqlNodeObj = object
+  case kind*: SqlNodeKind    ## kind of syntax tree
+  of LiteralNodes:
+    strVal*: string          ## AST leaf: the identifier, numeric literal
+                             ## string literal, etc.
+  else:
+    sons*: seq[SqlNode]      ## the node's children
+
+ + an SQL abstract syntax tree node + Source   +Edit   + +
+
+
+
SqlParseError = object of ValueError
+
+ + Invalid SQL encountered + Source   +Edit   + +
+
+
+
SqlParser = object of SqlLexer
+
+ + SQL parser object + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(n: SqlNode): string {....raises: [Exception], tags: [RootEffect],
+                               forbids: [].}
+
+ + an alias for renderSql. + Source   +Edit   + +
+
+ +
+
+
+
proc `[]`(n: SqlNode; i: BackwardsIndex): SqlNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `[]`(n: SqlNode; i: int): SqlNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc add(father, n: SqlNode) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc len(n: SqlNode): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newNode(k: SqlNodeKind): SqlNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newNode(k: SqlNodeKind; s: string): SqlNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newNode(k: SqlNodeKind; sons: seq[SqlNode]): SqlNode {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc parseSql(input: Stream; filename: string): SqlNode {....raises: [IOError,
+    OSError, IOError, OSError, ValueError, SqlParseError, Exception],
+    tags: [ReadIOEffect, RootEffect, WriteIOEffect], forbids: [].}
+
+ + parses the SQL from input into an AST and returns the AST. filename is only used for error messages. Syntax errors raise an SqlParseError exception. + Source   +Edit   + +
+
+
+
proc parseSql(input: string; filename = ""): SqlNode {.
+    ...raises: [IOError, OSError, ValueError, SqlParseError, Exception],
+    tags: [ReadIOEffect, RootEffect, WriteIOEffect], forbids: [].}
+
+ + parses the SQL from input into an AST and returns the AST. filename is only used for error messages. Syntax errors raise an SqlParseError exception. + Source   +Edit   + +
+
+ +
+
+
+
proc renderSql(n: SqlNode; upperCase = false): string {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + Converts an SQL abstract syntax tree to its string representation. + Source   +Edit   + +
+
+ +
+
+
+
proc treeRepr(s: SqlNode): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/parsesql.idx b/parsesql.idx new file mode 100644 index 0000000000000..cca0d7520305f --- /dev/null +++ b/parsesql.idx @@ -0,0 +1,81 @@ +nimTitle parsesql parsesql.html module std/parsesql 0 +nim SqlLexer parsesql.html#SqlLexer object SqlLexer 50 +nim nkNone parsesql.html#nkNone SqlNodeKind.nkNone 471 +nim nkIdent parsesql.html#nkIdent SqlNodeKind.nkIdent 471 +nim nkQuotedIdent parsesql.html#nkQuotedIdent SqlNodeKind.nkQuotedIdent 471 +nim nkStringLit parsesql.html#nkStringLit SqlNodeKind.nkStringLit 471 +nim nkBitStringLit parsesql.html#nkBitStringLit SqlNodeKind.nkBitStringLit 471 +nim nkHexStringLit parsesql.html#nkHexStringLit SqlNodeKind.nkHexStringLit 471 +nim nkIntegerLit parsesql.html#nkIntegerLit SqlNodeKind.nkIntegerLit 471 +nim nkNumericLit parsesql.html#nkNumericLit SqlNodeKind.nkNumericLit 471 +nim nkPrimaryKey parsesql.html#nkPrimaryKey SqlNodeKind.nkPrimaryKey 471 +nim nkForeignKey parsesql.html#nkForeignKey SqlNodeKind.nkForeignKey 471 +nim nkNotNull parsesql.html#nkNotNull SqlNodeKind.nkNotNull 471 +nim nkNull parsesql.html#nkNull SqlNodeKind.nkNull 471 +nim nkStmtList parsesql.html#nkStmtList SqlNodeKind.nkStmtList 471 +nim nkDot parsesql.html#nkDot SqlNodeKind.nkDot 471 +nim nkDotDot parsesql.html#nkDotDot SqlNodeKind.nkDotDot 471 +nim nkPrefix parsesql.html#nkPrefix SqlNodeKind.nkPrefix 471 +nim nkInfix parsesql.html#nkInfix SqlNodeKind.nkInfix 471 +nim nkCall parsesql.html#nkCall SqlNodeKind.nkCall 471 +nim nkPrGroup parsesql.html#nkPrGroup SqlNodeKind.nkPrGroup 471 +nim nkColumnReference parsesql.html#nkColumnReference SqlNodeKind.nkColumnReference 471 +nim nkReferences parsesql.html#nkReferences SqlNodeKind.nkReferences 471 +nim nkDefault parsesql.html#nkDefault SqlNodeKind.nkDefault 471 +nim nkCheck parsesql.html#nkCheck SqlNodeKind.nkCheck 471 +nim nkConstraint parsesql.html#nkConstraint SqlNodeKind.nkConstraint 471 +nim nkUnique parsesql.html#nkUnique SqlNodeKind.nkUnique 471 +nim nkIdentity parsesql.html#nkIdentity SqlNodeKind.nkIdentity 471 +nim nkColumnDef parsesql.html#nkColumnDef SqlNodeKind.nkColumnDef 471 +nim nkInsert parsesql.html#nkInsert SqlNodeKind.nkInsert 471 +nim nkUpdate parsesql.html#nkUpdate SqlNodeKind.nkUpdate 471 +nim nkDelete parsesql.html#nkDelete SqlNodeKind.nkDelete 471 +nim nkSelect parsesql.html#nkSelect SqlNodeKind.nkSelect 471 +nim nkSelectDistinct parsesql.html#nkSelectDistinct SqlNodeKind.nkSelectDistinct 471 +nim nkSelectColumns parsesql.html#nkSelectColumns SqlNodeKind.nkSelectColumns 471 +nim nkSelectPair parsesql.html#nkSelectPair SqlNodeKind.nkSelectPair 471 +nim nkAsgn parsesql.html#nkAsgn SqlNodeKind.nkAsgn 471 +nim nkFrom parsesql.html#nkFrom SqlNodeKind.nkFrom 471 +nim nkFromItemPair parsesql.html#nkFromItemPair SqlNodeKind.nkFromItemPair 471 +nim nkJoin parsesql.html#nkJoin SqlNodeKind.nkJoin 471 +nim nkNaturalJoin parsesql.html#nkNaturalJoin SqlNodeKind.nkNaturalJoin 471 +nim nkUsing parsesql.html#nkUsing SqlNodeKind.nkUsing 471 +nim nkGroup parsesql.html#nkGroup SqlNodeKind.nkGroup 471 +nim nkLimit parsesql.html#nkLimit SqlNodeKind.nkLimit 471 +nim nkOffset parsesql.html#nkOffset SqlNodeKind.nkOffset 471 +nim nkHaving parsesql.html#nkHaving SqlNodeKind.nkHaving 471 +nim nkOrder parsesql.html#nkOrder SqlNodeKind.nkOrder 471 +nim nkDesc parsesql.html#nkDesc SqlNodeKind.nkDesc 471 +nim nkUnion parsesql.html#nkUnion SqlNodeKind.nkUnion 471 +nim nkIntersect parsesql.html#nkIntersect SqlNodeKind.nkIntersect 471 +nim nkExcept parsesql.html#nkExcept SqlNodeKind.nkExcept 471 +nim nkColumnList parsesql.html#nkColumnList SqlNodeKind.nkColumnList 471 +nim nkValueList parsesql.html#nkValueList SqlNodeKind.nkValueList 471 +nim nkWhere parsesql.html#nkWhere SqlNodeKind.nkWhere 471 +nim nkCreateTable parsesql.html#nkCreateTable SqlNodeKind.nkCreateTable 471 +nim nkCreateTableIfNotExists parsesql.html#nkCreateTableIfNotExists SqlNodeKind.nkCreateTableIfNotExists 471 +nim nkCreateType parsesql.html#nkCreateType SqlNodeKind.nkCreateType 471 +nim nkCreateTypeIfNotExists parsesql.html#nkCreateTypeIfNotExists SqlNodeKind.nkCreateTypeIfNotExists 471 +nim nkCreateIndex parsesql.html#nkCreateIndex SqlNodeKind.nkCreateIndex 471 +nim nkCreateIndexIfNotExists parsesql.html#nkCreateIndexIfNotExists SqlNodeKind.nkCreateIndexIfNotExists 471 +nim nkEnumDef parsesql.html#nkEnumDef SqlNodeKind.nkEnumDef 471 +nim SqlNodeKind parsesql.html#SqlNodeKind enum SqlNodeKind 471 +nim SqlParseError parsesql.html#SqlParseError object SqlParseError 540 +nim SqlNode parsesql.html#SqlNode type SqlNode 541 +nim SqlNodeObj parsesql.html#SqlNodeObj object SqlNodeObj 542 +nim SqlParser parsesql.html#SqlParser object SqlParser 550 +nim newNode parsesql.html#newNode,SqlNodeKind proc newNode(k: SqlNodeKind): SqlNode 553 +nim newNode parsesql.html#newNode,SqlNodeKind,string proc newNode(k: SqlNodeKind; s: string): SqlNode 563 +nim newNode parsesql.html#newNode,SqlNodeKind,seq[SqlNode] proc newNode(k: SqlNodeKind; sons: seq[SqlNode]): SqlNode 567 +nim len parsesql.html#len,SqlNode proc len(n: SqlNode): int 571 +nim `[]` parsesql.html#[],SqlNode,int proc `[]`(n: SqlNode; i: int): SqlNode 577 +nim `[]` parsesql.html#[],SqlNode,BackwardsIndex proc `[]`(n: SqlNode; i: BackwardsIndex): SqlNode 578 +nim add parsesql.html#add,SqlNode,SqlNode proc add(father, n: SqlNode) 580 +nim renderSql parsesql.html#renderSql,SqlNode proc renderSql(n: SqlNode; upperCase = false): string 1526 +nim `$` parsesql.html#$,SqlNode proc `$`(n: SqlNode): string 1534 +nim treeRepr parsesql.html#treeRepr,SqlNode proc treeRepr(s: SqlNode): string 1550 +nim parseSql parsesql.html#parseSql,Stream,string proc parseSql(input: Stream; filename: string): SqlNode 1568 +nim parseSql parsesql.html#parseSql,string,string proc parseSql(input: string; filename = ""): SqlNode 1579 +nimgrp parsesql parsesql.html#parseSql-procs-all proc 1568 +nimgrp [] parsesql.html#[]-procs-all proc 577 +nimgrp newnode parsesql.html#newNode-procs-all proc 553 diff --git a/parseutils.html b/parseutils.html new file mode 100644 index 0000000000000..4d240c4eeca39 --- /dev/null +++ b/parseutils.html @@ -0,0 +1,1305 @@ + + + + + + + +std/parseutils + + + + + + + + + + + + + + + + +
+
+

std/parseutils

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module contains helpers for parsing tokens, numbers, integers, floats, identifiers, etc.

+

To unpack raw bytes look at the streams module.

+

let logs = @["2019-01-10: OK_", "2019-01-11: FAIL_", "2019-01: aaaa"]
+var outp: seq[string]
+
+for log in logs:
+  var res: string
+  if parseUntil(log, res, ':') == 10: # YYYY-MM-DD == 10
+    outp.add(res & " - " & captureBetween(log, ' ', '_'))
+doAssert outp == @["2019-01-10 - OK", "2019-01-11 - FAIL"]

+

from std/strutils import Digits, parseInt
+
+let
+  input1 = "2019 school start"
+  input2 = "3 years back"
+  startYear = input1[0 .. skipWhile(input1, Digits)-1] # 2019
+  yearsBack = input2[0 .. skipWhile(input2, Digits)-1] # 3
+  examYear = parseInt(startYear) + parseInt(yearsBack)
+doAssert "Examination is in " & $examYear == "Examination is in 2022"

+

See also:

+ +

+
+

Types

+
+
+
InterpolatedKind = enum
+  ikStr,                    ## ``str`` part of the interpolated string
+  ikDollar,                 ## escaped ``$`` part of the interpolated string
+  ikVar,                    ## ``var`` part of the interpolated string
+  ikExpr                     ## ``expr`` part of the interpolated string
+
+ + Describes for interpolatedFragments which part of the interpolated string is yielded; for example in "str$$$var${expr}" + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc captureBetween(s: openArray[char]; first: char; second = '\x00'): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Finds the first occurrence of first, then returns everything from there up to second (if second is '0', then first is used). +

Example:

+
doAssert captureBetween("Hello World", 'e') == "llo World"
+doAssert captureBetween("Hello World", 'e', 'r') == "llo Wo"
+doAssert captureBetween("Hello World".toOpenArray(6, "Hello World".high), 'l') == "d"
+ Source   +Edit   + +
+
+
+
proc captureBetween(s: string; first: char; second = '\x00'; start = 0): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Finds the first occurrence of first, then returns everything from there up to second (if second is '0', then first is used). +

Example:

+
doAssert captureBetween("Hello World", 'e') == "llo World"
+doAssert captureBetween("Hello World", 'e', 'r') == "llo Wo"
+doAssert captureBetween("Hello World", 'l', start = 6) == "d"
+ Source   +Edit   + +
+
+ +
+
+
+
proc parseBiggestFloat(s: openArray[char]; number: var BiggestFloat): int {.
+    magic: "ParseBiggestFloat", importc: "nimParseBiggestFloat", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Parses a float and stores the value into number. Result is the number of processed chars or 0 if a parsing error occurred. + Source   +Edit   + +
+
+
+
proc parseBiggestFloat(s: string; number: var BiggestFloat; start = 0): int {.
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + Parses a float starting at start and stores the value into number. Result is the number of processed chars or 0 if a parsing error occurred. + Source   +Edit   + +
+
+ +
+
+
+
proc parseBiggestInt(s: openArray[char]; number: var BiggestInt): int {....gcsafe,
+    extern: "npuParseBiggestInt", noSideEffect, ...raises: [ValueError], tags: [],
+    forbids: [].}
+
+ + Parses an integer and stores the value into number. Result is the number of processed chars or 0 if there is no integer. ValueError is raised if the parsed integer is out of the valid range. +

Example:

+
var res: BiggestInt
+doAssert parseBiggestInt("9223372036854775807", res) == 19
+doAssert res == 9223372036854775807
+doAssert parseBiggestInt("-2024_05_09", res) == 11
+doAssert res == -20240509
+ Source   +Edit   + +
+
+
+
proc parseBiggestInt(s: string; number: var BiggestInt; start = 0): int {.
+    noSideEffect, ...raises: [ValueError], tags: [], forbids: [].}
+
+ + Parses an integer starting at start and stores the value into number. Result is the number of processed chars or 0 if there is no integer. ValueError is raised if the parsed integer is out of the valid range. +

Example:

+
var res: BiggestInt
+doAssert parseBiggestInt("9223372036854775807", res, 0) == 19
+doAssert res == 9223372036854775807
+doAssert parseBiggestInt("-2024_05_09", res) == 11
+doAssert res == -20240509
+doAssert parseBiggestInt("-2024_05_02", res, 7) == 4
+doAssert res == 502
+ Source   +Edit   + +
+
+ +
+
+
+
proc parseBiggestUInt(s: openArray[char]; number: var BiggestUInt): int {.
+    ...gcsafe, extern: "npuParseBiggestUInt", noSideEffect, ...raises: [ValueError],
+    tags: [], forbids: [].}
+
+ + Parses an unsigned integer and stores the value into number. ValueError is raised if the parsed integer is out of the valid range. +

Example:

+
var res: BiggestUInt
+doAssert parseBiggestUInt("12", res, 0) == 2
+doAssert res == 12
+doAssert parseBiggestUInt("1111111111111111111", res, 0) == 19
+doAssert res == 1111111111111111111'u64
+ Source   +Edit   + +
+
+
+
proc parseBiggestUInt(s: string; number: var BiggestUInt; start = 0): int {.
+    noSideEffect, ...raises: [ValueError], tags: [], forbids: [].}
+
+ + Parses an unsigned integer starting at start and stores the value into number. ValueError is raised if the parsed integer is out of the valid range. +

Example:

+
var res: BiggestUInt
+doAssert parseBiggestUInt("12", res, 0) == 2
+doAssert res == 12
+doAssert parseBiggestUInt("1111111111111111111", res, 0) == 19
+doAssert res == 1111111111111111111'u64
+ Source   +Edit   + +
+
+ +
+
+
+
proc parseBin[T: SomeInteger](s: openArray[char]; number: var T; maxLen = 0): int {.
+    noSideEffect.}
+
+ +

Parses a binary number and stores its value in number.

+

Returns the number of the parsed characters or 0 in case of an error. If error, the value of number is not changed.

+

If maxLen == 0, the parsing continues until the first non-bin character or to the end of the string. Otherwise, no more than maxLen characters are parsed starting from the start position.

+

It does not check for overflow. If the value represented by the string is too big to fit into number, only the value of last fitting characters will be stored in number without producing an error.

+ +

Example:

+
var num: int
+doAssert parseBin("0100_1110_0110_1001_1110_1101", num) == 29
+doAssert num == 5138925
+doAssert parseBin("3", num) == 0
+var num8: int8
+doAssert parseBin("0b_0100_1110_0110_1001_1110_1101", num8) == 32
+doAssert num8 == 0b1110_1101'i8
+doAssert parseBin("0b_0100_1110_0110_1001_1110_1101", num8, 3, 9) == 9
+doAssert num8 == 0b0100_1110'i8
+var num8u: uint8
+doAssert parseBin("0b_0100_1110_0110_1001_1110_1101", num8u) == 32
+doAssert num8u == 237
+var num64: int64
+doAssert parseBin("0100111001101001111011010100111001101001", num64) == 40
+doAssert num64 == 336784608873
+ Source   +Edit   + +
+
+
+
proc parseBin[T: SomeInteger](s: string; number: var T; start = 0; maxLen = 0): int {.
+    noSideEffect.}
+
+ +

Parses a binary number and stores its value in number.

+

Returns the number of the parsed characters or 0 in case of an error. If error, the value of number is not changed.

+

If maxLen == 0, the parsing continues until the first non-bin character or to the end of the string. Otherwise, no more than maxLen characters are parsed starting from the start position.

+

It does not check for overflow. If the value represented by the string is too big to fit into number, only the value of last fitting characters will be stored in number without producing an error.

+ +

Example:

+
var num: int
+doAssert parseBin("0100_1110_0110_1001_1110_1101", num) == 29
+doAssert num == 5138925
+doAssert parseBin("3", num) == 0
+var num8: int8
+doAssert parseBin("0b_0100_1110_0110_1001_1110_1101", num8) == 32
+doAssert num8 == 0b1110_1101'i8
+doAssert parseBin("0b_0100_1110_0110_1001_1110_1101", num8, 3, 9) == 9
+doAssert num8 == 0b0100_1110'i8
+var num8u: uint8
+doAssert parseBin("0b_0100_1110_0110_1001_1110_1101", num8u) == 32
+doAssert num8u == 237
+var num64: int64
+doAssert parseBin("0100111001101001111011010100111001101001", num64) == 40
+doAssert num64 == 336784608873
+ Source   +Edit   + +
+
+ +
+
+
+
proc parseChar(s: openArray[char]; c: var char): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + Parses a single character, stores it in c and returns 1. In case of error (if start >= s.len) it returns 0 and the value of c is unchanged. +

Example:

+
var c: char
+doAssert "nim".parseChar(c, 3) == 0
+doAssert c == '\0'
+doAssert "nim".parseChar(c, 0) == 1
+doAssert c == 'n'
+ Source   +Edit   + +
+
+
+
proc parseChar(s: string; c: var char; start = 0): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + Parses a single character, stores it in c and returns 1. In case of error (if start >= s.len) it returns 0 and the value of c is unchanged. +

Example:

+
var c: char
+doAssert "nim".parseChar(c, 3) == 0
+doAssert c == '\0'
+doAssert "nim".parseChar(c, 0) == 1
+doAssert c == 'n'
+ Source   +Edit   + +
+
+ +
+
+
+
proc parseFloat(s: openArray[char]; number: var float): int {....gcsafe,
+    extern: "npuParseFloat", noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + Parses a float and stores the value into number. Result is the number of processed chars or 0 if there occurred a parsing error. +

Example:

+
var res: float
+doAssert parseFloat("32", res, 0) == 2
+doAssert res == 32.0
+doAssert parseFloat("32.57", res, 0) == 5
+doAssert res == 32.57
+doAssert parseFloat("32.57", res, 3) == 2
+doAssert res == 57.00
+ Source   +Edit   + +
+
+
+
proc parseFloat(s: string; number: var float; start = 0): int {.noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Parses a float starting at start and stores the value into number. Result is the number of processed chars or 0 if there occurred a parsing error. +

Example:

+
var res: float
+doAssert parseFloat("32", res, 0) == 2
+doAssert res == 32.0
+doAssert parseFloat("32.57", res, 0) == 5
+doAssert res == 32.57
+doAssert parseFloat("32.57", res, 3) == 2
+doAssert res == 57.00
+ Source   +Edit   + +
+
+ +
+
+
+
proc parseHex[T: SomeInteger](s: openArray[char]; number: var T; maxLen = 0): int {.
+    noSideEffect.}
+
+ +

Parses a hexadecimal number and stores its value in number.

+

Returns the number of the parsed characters or 0 in case of an error. If error, the value of number is not changed.

+

If maxLen == 0, the parsing continues until the first non-hex character or to the end of the string. Otherwise, no more than maxLen characters are parsed starting from the start position.

+

It does not check for overflow. If the value represented by the string is too big to fit into number, only the value of last fitting characters will be stored in number without producing an error.

+ +

Example:

+
var num: int
+doAssert parseHex("4E_69_ED", num) == 8
+doAssert num == 5138925
+doAssert parseHex("X", num) == 0
+doAssert parseHex("#ABC", num) == 4
+var num8: int8
+doAssert parseHex("0x_4E_69_ED", num8) == 11
+doAssert num8 == 0xED'i8
+doAssert parseHex("0x_4E_69_ED", num8, 3, 2) == 2
+doAssert num8 == 0x4E'i8
+var num8u: uint8
+doAssert parseHex("0x_4E_69_ED", num8u) == 11
+doAssert num8u == 237
+var num64: int64
+doAssert parseHex("4E69ED4E69ED", num64) == 12
+doAssert num64 == 86216859871725
+ Source   +Edit   + +
+
+
+
proc parseHex[T: SomeInteger](s: string; number: var T; start = 0; maxLen = 0): int {.
+    noSideEffect.}
+
+ +

Parses a hexadecimal number and stores its value in number.

+

Returns the number of the parsed characters or 0 in case of an error. If error, the value of number is not changed.

+

If maxLen == 0, the parsing continues until the first non-hex character or to the end of the string. Otherwise, no more than maxLen characters are parsed starting from the start position.

+

It does not check for overflow. If the value represented by the string is too big to fit into number, only the value of last fitting characters will be stored in number without producing an error.

+ +

Example:

+
var num: int
+doAssert parseHex("4E_69_ED", num) == 8
+doAssert num == 5138925
+doAssert parseHex("X", num) == 0
+doAssert parseHex("#ABC", num) == 4
+var num8: int8
+doAssert parseHex("0x_4E_69_ED", num8) == 11
+doAssert num8 == 0xED'i8
+doAssert parseHex("0x_4E_69_ED", num8, 3, 2) == 2
+doAssert num8 == 0x4E'i8
+var num8u: uint8
+doAssert parseHex("0x_4E_69_ED", num8u) == 11
+doAssert num8u == 237
+var num64: int64
+doAssert parseHex("4E69ED4E69ED", num64) == 12
+doAssert num64 == 86216859871725
+ Source   +Edit   + +
+
+ +
+
+
+
proc parseIdent(s: openArray[char]): string {....raises: [], tags: [], forbids: [].}
+
+ + Parses an identifier and returns it or an empty string in case of an error. +

Example:

+
doAssert parseIdent("Hello World", 0) == "Hello"
+doAssert parseIdent("Hello World", 1) == "ello"
+doAssert parseIdent("Hello World", 5) == ""
+doAssert parseIdent("Hello World", 6) == "World"
+ Source   +Edit   + +
+
+
+
proc parseIdent(s: openArray[char]; ident: var string): int {....raises: [],
+    tags: [], forbids: [].}
+
+ + Parses an identifier and stores it in ident. Returns the number of the parsed characters or 0 in case of an error. If error, the value of ident is not changed. +

Example:

+
var res: string
+doAssert parseIdent("Hello World", res, 0) == 5
+doAssert res == "Hello"
+doAssert parseIdent("Hello World", res, 1) == 4
+doAssert res == "ello"
+doAssert parseIdent("Hello World", res, 6) == 5
+doAssert res == "World"
+ Source   +Edit   + +
+
+
+
proc parseIdent(s: string; ident: var string; start = 0): int {....raises: [],
+    tags: [], forbids: [].}
+
+ + Parses an identifier and stores it in ident. Returns the number of the parsed characters or 0 in case of an error. If error, the value of ident is not changed. +

Example:

+
var res: string
+doAssert parseIdent("Hello World", res, 0) == 5
+doAssert res == "Hello"
+doAssert parseIdent("Hello World", res, 1) == 4
+doAssert res == "ello"
+doAssert parseIdent("Hello World", res, 6) == 5
+doAssert res == "World"
+ Source   +Edit   + +
+
+
+
proc parseIdent(s: string; start = 0): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + Parses an identifier and returns it or an empty string in case of an error. +

Example:

+
doAssert parseIdent("Hello World", 0) == "Hello"
+doAssert parseIdent("Hello World", 1) == "ello"
+doAssert parseIdent("Hello World", 5) == ""
+doAssert parseIdent("Hello World", 6) == "World"
+ Source   +Edit   + +
+
+ +
+
+
+
proc parseInt(s: openArray[char]; number: var int): int {....gcsafe,
+    extern: "npuParseInt", noSideEffect, ...raises: [ValueError], tags: [],
+    forbids: [].}
+
+ + Parses an integer and stores the value into number. Result is the number of processed chars or 0 if there is no integer. ValueError is raised if the parsed integer is out of the valid range. +

Example:

+
var res: int
+doAssert parseInt("-2024_05_02", res) == 11
+doAssert res == -20240502
+ Source   +Edit   + +
+
+
+
proc parseInt(s: string; number: var int; start = 0): int {.noSideEffect,
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ + Parses an integer starting at start and stores the value into number. Result is the number of processed chars or 0 if there is no integer. ValueError is raised if the parsed integer is out of the valid range. +

Example:

+
var res: int
+doAssert parseInt("-2024_05_02", res) == 11
+doAssert res == -20240502
+doAssert parseInt("-2024_05_02", res, 7) == 4
+doAssert res == 502
+ Source   +Edit   + +
+
+ +
+
+
+
proc parseOct[T: SomeInteger](s: openArray[char]; number: var T; maxLen = 0): int {.
+    noSideEffect.}
+
+ +

Parses an octal number and stores its value in number.

+

Returns the number of the parsed characters or 0 in case of an error. If error, the value of number is not changed.

+

If maxLen == 0, the parsing continues until the first non-oct character or to the end of the string. Otherwise, no more than maxLen characters are parsed starting from the start position.

+

It does not check for overflow. If the value represented by the string is too big to fit into number, only the value of last fitting characters will be stored in number without producing an error.

+ +

Example:

+
var num: int
+doAssert parseOct("0o23464755", num) == 10
+doAssert num == 5138925
+doAssert parseOct("8", num) == 0
+var num8: int8
+doAssert parseOct("0o_1464_755", num8) == 11
+doAssert num8 == -19
+doAssert parseOct("0o_1464_755", num8, 3, 3) == 3
+doAssert num8 == 102
+var num8u: uint8
+doAssert parseOct("1464755", num8u) == 7
+doAssert num8u == 237
+var num64: int64
+doAssert parseOct("2346475523464755", num64) == 16
+doAssert num64 == 86216859871725
+ Source   +Edit   + +
+
+
+
proc parseOct[T: SomeInteger](s: string; number: var T; start = 0; maxLen = 0): int {.
+    noSideEffect.}
+
+ +

Parses an octal number and stores its value in number.

+

Returns the number of the parsed characters or 0 in case of an error. If error, the value of number is not changed.

+

If maxLen == 0, the parsing continues until the first non-oct character or to the end of the string. Otherwise, no more than maxLen characters are parsed starting from the start position.

+

It does not check for overflow. If the value represented by the string is too big to fit into number, only the value of last fitting characters will be stored in number without producing an error.

+ +

Example:

+
var num: int
+doAssert parseOct("0o23464755", num) == 10
+doAssert num == 5138925
+doAssert parseOct("8", num) == 0
+var num8: int8
+doAssert parseOct("0o_1464_755", num8) == 11
+doAssert num8 == -19
+doAssert parseOct("0o_1464_755", num8, 3, 3) == 3
+doAssert num8 == 102
+var num8u: uint8
+doAssert parseOct("1464755", num8u) == 7
+doAssert num8u == 237
+var num64: int64
+doAssert parseOct("2346475523464755", num64) == 16
+doAssert num64 == 86216859871725
+ Source   +Edit   + +
+
+ +
+
+
+
proc parseSaturatedNatural(s: openArray[char]; b: var int): int {....raises: [],
+    tags: [], forbids: [].}
+
+ + Parses a natural number into b. This cannot raise an overflow error. high(int) is returned for an overflow. The number of processed character is returned. This is usually what you really want to use instead of parseInt. +

Example:

+
var res = 0
+discard parseSaturatedNatural("848", res)
+doAssert res == 848
+ Source   +Edit   + +
+
+
+
proc parseSaturatedNatural(s: string; b: var int; start = 0): int {....raises: [],
+    tags: [], forbids: [].}
+
+ + Parses a natural number into b. This cannot raise an overflow error. high(int) is returned for an overflow. The number of processed character is returned. This is usually what you really want to use instead of parseInt. +

Example:

+
var res = 0
+discard parseSaturatedNatural("848", res)
+doAssert res == 848
+ Source   +Edit   + +
+
+ +
+
+
+
func parseSize(s: openArray[char]; size: var int64; alwaysBin = false): int {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Parse a size qualified by binary or metric units into size. This format is often called "human readable". Result is the number of processed chars or 0 on parse errors and size is rounded to the nearest integer. Trailing garbage like "/s" in "1k/s" is allowed and detected by result < s.len.

+

To simplify use, following non-rare wild conventions, and since fractional data like milli-bytes is so rare, unit matching is case-insensitive but for the 'i' distinguishing binary-metric from metric (which cannot be 'I').

+

An optional trailing 'B|b' is ignored but processed. I.e., you must still know if units are bytes | bits or infer this fact via the case of s[1] (if users can even be relied upon to use 'B' for byte and 'b' for bit or have that be s[1]).

+

If alwaysBin==true then scales are always binary-metric, but e.g. "KiB" is still accepted for clarity. If the value would exceed the range of int64, size saturates to int64.high. Supported metric prefix chars include k, m, g, t, p, e, z, y (but z & y saturate unless the number is a small fraction).

+

See also:

+ + +

Example:

+
var res: int64  # caller must still know if 'b' refers to bytes|bits
+doAssert parseSize("10.5 MB", res) == 7
+doAssert res == 10_500_000  # decimal metric Mega prefix
+doAssert parseSize("64 mib", res) == 6
+doAssert res == 67108864    # 64 shl 20
+doAssert parseSize("1G/h", res, true) == 2 # '/' stops parse
+doAssert res == 1073741824  # 1 shl 30, forced binary metric
+ Source   +Edit   + +
+
+ +
+
+
+
proc parseUInt(s: openArray[char]; number: var uint): int {....gcsafe,
+    extern: "npuParseUInt", noSideEffect, ...raises: [ValueError], tags: [],
+    forbids: [].}
+
+ + Parses an unsigned integer and stores the value into number. ValueError is raised if the parsed integer is out of the valid range. +

Example:

+
var res: uint
+doAssert parseUInt("3450", res) == 4
+doAssert res == 3450
+doAssert parseUInt("3450", res, 2) == 2
+doAssert res == 50
+ Source   +Edit   + +
+
+
+
proc parseUInt(s: string; number: var uint; start = 0): int {.noSideEffect,
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ + Parses an unsigned integer starting at start and stores the value into number. ValueError is raised if the parsed integer is out of the valid range. +

Example:

+
var res: uint
+doAssert parseUInt("3450", res) == 4
+doAssert res == 3450
+doAssert parseUInt("3450", res, 2) == 2
+doAssert res == 50
+ Source   +Edit   + +
+
+ +
+
+
+
proc parseUntil(s: openArray[char]; token: var string; until: char): int {.
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ + Parses a token and stores it in token. Returns the number of the parsed characters or 0 in case of an error. A token consists of any character that is not the until character. +

Example:

+
var myToken: string
+doAssert parseUntil("Hello World", myToken, 'W') == 6
+doAssert myToken == "Hello "
+doAssert parseUntil("Hello World", myToken, 'o') == 4
+doAssert myToken == "Hell"
+doAssert parseUntil("Hello World", myToken, 'o', 2) == 2
+doAssert myToken == "ll"
+ Source   +Edit   + +
+
+
+
proc parseUntil(s: openArray[char]; token: var string; until: set[char]): int {.
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ + Parses a token and stores it in token. Returns the number of the parsed characters or 0 in case of an error. A token consists of the characters notin until. +

Example:

+
var myToken: string
+doAssert parseUntil("Hello World", myToken, {'W', 'o', 'r'}) == 4
+doAssert myToken == "Hell"
+doAssert parseUntil("Hello World", myToken, {'W', 'r'}) == 6
+doAssert myToken == "Hello "
+doAssert parseUntil("Hello World", myToken, {'W', 'r'}, 3) == 3
+doAssert myToken == "lo "
+ Source   +Edit   + +
+
+
+
proc parseUntil(s: openArray[char]; token: var string; until: string): int {.
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ + Parses a token and stores it in token. Returns the number of the parsed characters or 0 in case of an error. A token consists of any character that comes before the until token. +

Example:

+
var myToken: string
+doAssert parseUntil("Hello World", myToken, "Wor") == 6
+doAssert myToken == "Hello "
+doAssert parseUntil("Hello World", myToken, "Wor", 2) == 4
+doAssert myToken == "llo "
+ Source   +Edit   + +
+
+
+
proc parseUntil(s: string; token: var string; until: char; start = 0): int {.
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ + Parses a token and stores it in token. Returns the number of the parsed characters or 0 in case of an error. A token consists of any character that is not the until character. +

Example:

+
var myToken: string
+doAssert parseUntil("Hello World", myToken, 'W') == 6
+doAssert myToken == "Hello "
+doAssert parseUntil("Hello World", myToken, 'o') == 4
+doAssert myToken == "Hell"
+doAssert parseUntil("Hello World", myToken, 'o', 2) == 2
+doAssert myToken == "ll"
+ Source   +Edit   + +
+
+
+
proc parseUntil(s: string; token: var string; until: set[char]; start = 0): int {.
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ + Parses a token and stores it in token. Returns the number of the parsed characters or 0 in case of an error. A token consists of the characters notin until. +

Example:

+
var myToken: string
+doAssert parseUntil("Hello World", myToken, {'W', 'o', 'r'}) == 4
+doAssert myToken == "Hell"
+doAssert parseUntil("Hello World", myToken, {'W', 'r'}) == 6
+doAssert myToken == "Hello "
+doAssert parseUntil("Hello World", myToken, {'W', 'r'}, 3) == 3
+doAssert myToken == "lo "
+ Source   +Edit   + +
+
+
+
proc parseUntil(s: string; token: var string; until: string; start = 0): int {.
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ + Parses a token and stores it in token. Returns the number of the parsed characters or 0 in case of an error. A token consists of any character that comes before the until token. +

Example:

+
var myToken: string
+doAssert parseUntil("Hello World", myToken, "Wor") == 6
+doAssert myToken == "Hello "
+doAssert parseUntil("Hello World", myToken, "Wor", 2) == 4
+doAssert myToken == "llo "
+ Source   +Edit   + +
+
+ +
+
+
+
proc parseWhile(s: openArray[char]; token: var string; validChars: set[char]): int {.
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ + Parses a token and stores it in token. Returns the number of the parsed characters or 0 in case of an error. A token consists of the characters in validChars. +

Example:

+
var myToken: string
+doAssert parseWhile("Hello World", myToken, {'W', 'o', 'r'}, 0) == 0
+doAssert myToken.len() == 0
+doAssert parseWhile("Hello World", myToken, {'W', 'o', 'r'}, 6) == 3
+doAssert myToken == "Wor"
+ Source   +Edit   + +
+
+
+
proc parseWhile(s: string; token: var string; validChars: set[char]; start = 0): int {.
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ + Parses a token and stores it in token. Returns the number of the parsed characters or 0 in case of an error. A token consists of the characters in validChars. +

Example:

+
var myToken: string
+doAssert parseWhile("Hello World", myToken, {'W', 'o', 'r'}, 0) == 0
+doAssert myToken.len() == 0
+doAssert parseWhile("Hello World", myToken, {'W', 'o', 'r'}, 6) == 3
+doAssert myToken == "Wor"
+ Source   +Edit   + +
+
+ +
+
+
+
proc skip(s, token: openArray[char]): int {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Skips the token starting at s[start]. Returns the length of token or 0 if there was no token at s[start]. +

Example:

+
doAssert skip("2019-01-22", "2019", 0) == 4
+doAssert skip("2019-01-22", "19", 0) == 0
+doAssert skip("2019-01-22", "19", 2) == 2
+doAssert skip("CAPlow", "CAP", 0) == 3
+doAssert skip("CAPlow", "cap", 0) == 0
+ Source   +Edit   + +
+
+
+
proc skip(s, token: string; start = 0): int {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Skips the token starting at s[start]. Returns the length of token or 0 if there was no token at s[start]. +

Example:

+
doAssert skip("2019-01-22", "2019", 0) == 4
+doAssert skip("2019-01-22", "19", 0) == 0
+doAssert skip("2019-01-22", "19", 2) == 2
+doAssert skip("CAPlow", "CAP", 0) == 3
+doAssert skip("CAPlow", "cap", 0) == 0
+ Source   +Edit   + +
+
+ +
+
+
+
proc skipIgnoreCase(s, token: openArray[char]): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + Same as skip but case is ignored for token matching. +

Example:

+
doAssert skipIgnoreCase("CAPlow", "CAP", 0) == 3
+doAssert skipIgnoreCase("CAPlow", "cap", 0) == 3
+ Source   +Edit   + +
+
+
+
proc skipIgnoreCase(s, token: string; start = 0): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + Same as skip but case is ignored for token matching. +

Example:

+
doAssert skipIgnoreCase("CAPlow", "CAP", 0) == 3
+doAssert skipIgnoreCase("CAPlow", "cap", 0) == 3
+ Source   +Edit   + +
+
+ +
+
+
+
proc skipUntil(s: openArray[char]; until: char): int {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Skips all characters until the char until is found or the end is reached. Returns number of characters skipped. +

Example:

+
doAssert skipUntil("Hello World", 'o', 0) == 4
+doAssert skipUntil("Hello World", 'o', 4) == 0
+doAssert skipUntil("Hello World", 'W', 0) == 6
+doAssert skipUntil("Hello World", 'w', 0) == 11
+ Source   +Edit   + +
+
+
+
proc skipUntil(s: openArray[char]; until: set[char]): int {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Skips all characters until one char from the set until is found or the end is reached. Returns number of characters skipped. +

Example:

+
doAssert skipUntil("Hello World", {'W', 'e'}, 0) == 1
+doAssert skipUntil("Hello World", {'W'}, 0) == 6
+doAssert skipUntil("Hello World", {'W', 'd'}, 0) == 6
+ Source   +Edit   + +
+
+
+
proc skipUntil(s: string; until: char; start = 0): int {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Skips all characters until the char until is found or the end is reached. Returns number of characters skipped. +

Example:

+
doAssert skipUntil("Hello World", 'o', 0) == 4
+doAssert skipUntil("Hello World", 'o', 4) == 0
+doAssert skipUntil("Hello World", 'W', 0) == 6
+doAssert skipUntil("Hello World", 'w', 0) == 11
+ Source   +Edit   + +
+
+
+
proc skipUntil(s: string; until: set[char]; start = 0): int {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Skips all characters until one char from the set until is found or the end is reached. Returns number of characters skipped. +

Example:

+
doAssert skipUntil("Hello World", {'W', 'e'}, 0) == 1
+doAssert skipUntil("Hello World", {'W'}, 0) == 6
+doAssert skipUntil("Hello World", {'W', 'd'}, 0) == 6
+ Source   +Edit   + +
+
+ +
+
+
+
proc skipWhile(s: openArray[char]; toSkip: set[char]): int {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Skips all characters while one char from the set toSkip is found. Returns number of characters skipped. +

Example:

+
doAssert skipWhile("Hello World", {'H', 'e'}) == 2
+doAssert skipWhile("Hello World", {'e'}) == 0
+doAssert skipWhile("Hello World", {'W', 'o', 'r'}, 6) == 3
+ Source   +Edit   + +
+
+
+
proc skipWhile(s: string; toSkip: set[char]; start = 0): int {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Skips all characters while one char from the set toSkip is found. Returns number of characters skipped. +

Example:

+
doAssert skipWhile("Hello World", {'H', 'e'}) == 2
+doAssert skipWhile("Hello World", {'e'}) == 0
+doAssert skipWhile("Hello World", {'W', 'o', 'r'}, 6) == 3
+ Source   +Edit   + +
+
+ +
+
+
+
proc skipWhitespace(s: openArray[char]): int {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Skips the whitespace starting at s[start]. Returns the number of skipped characters. +

Example:

+
doAssert skipWhitespace("Hello World", 0) == 0
+doAssert skipWhitespace(" Hello World", 0) == 1
+doAssert skipWhitespace("Hello World", 5) == 1
+doAssert skipWhitespace("Hello  World", 5) == 2
+ Source   +Edit   + +
+
+
+
proc skipWhitespace(s: string; start = 0): int {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Skips the whitespace starting at s[start]. Returns the number of skipped characters. +

Example:

+
doAssert skipWhitespace("Hello World", 0) == 0
+doAssert skipWhitespace(" Hello World", 0) == 1
+doAssert skipWhitespace("Hello World", 5) == 1
+doAssert skipWhitespace("Hello  World", 5) == 2
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator interpolatedFragments(s: openArray[char]): tuple[
+    kind: InterpolatedKind, value: string] {....raises: [ValueError], tags: [],
+    forbids: [].}
+
+ + Tokenizes the string s into substrings for interpolation purposes. +

Example:

+
var outp: seq[tuple[kind: InterpolatedKind, value: string]]
+for k, v in interpolatedFragments("  $this is ${an  example}  $$"):
+  outp.add (k, v)
+doAssert outp == @[(ikStr, "  "),
+                   (ikVar, "this"),
+                   (ikStr, " is "),
+                   (ikExpr, "an  example"),
+                   (ikStr, "  "),
+                   (ikDollar, "$")]
+ Source   +Edit   + +
+
+
+
iterator interpolatedFragments(s: string): tuple[kind: InterpolatedKind,
+    value: string] {....raises: [ValueError], tags: [], forbids: [].}
+
+ + Tokenizes the string s into substrings for interpolation purposes. +

Example:

+
var outp: seq[tuple[kind: InterpolatedKind, value: string]]
+for k, v in interpolatedFragments("  $this is ${an  example}  $$"):
+  outp.add (k, v)
+doAssert outp == @[(ikStr, "  "),
+                   (ikVar, "this"),
+                   (ikStr, " is "),
+                   (ikExpr, "an  example"),
+                   (ikStr, "  "),
+                   (ikDollar, "$")]
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/parseutils.idx b/parseutils.idx new file mode 100644 index 0000000000000..a11c1d98a5d89 --- /dev/null +++ b/parseutils.idx @@ -0,0 +1,80 @@ +nimTitle parseutils parseutils.html module std/parseutils 0 +nim parseBin parseutils.html#parseBin,openArray[char],T,int proc parseBin[T: SomeInteger](s: openArray[char]; number: var T; maxLen = 0): int 63 +nim parseOct parseutils.html#parseOct,openArray[char],T,int proc parseOct[T: SomeInteger](s: openArray[char]; number: var T; maxLen = 0): int 109 +nim parseHex parseutils.html#parseHex,openArray[char],T,int proc parseHex[T: SomeInteger](s: openArray[char]; number: var T; maxLen = 0): int 155 +nim parseIdent parseutils.html#parseIdent,openArray[char],string proc parseIdent(s: openArray[char]; ident: var string): int 210 +nim parseIdent parseutils.html#parseIdent,openArray[char] proc parseIdent(s: openArray[char]): string 229 +nim parseChar parseutils.html#parseChar,openArray[char],char proc parseChar(s: openArray[char]; c: var char): int 244 +nim skipWhitespace parseutils.html#skipWhitespace,openArray[char] proc skipWhitespace(s: openArray[char]): int 258 +nim skip parseutils.html#skip,openArray[char],openArray[char] proc skip(s, token: openArray[char]): int 269 +nim skipIgnoreCase parseutils.html#skipIgnoreCase,openArray[char],openArray[char] proc skipIgnoreCase(s, token: openArray[char]): int 284 +nim skipUntil parseutils.html#skipUntil,openArray[char],set[char] proc skipUntil(s: openArray[char]; until: set[char]): int 294 +nim skipUntil parseutils.html#skipUntil,openArray[char],char proc skipUntil(s: openArray[char]; until: char): int 305 +nim skipWhile parseutils.html#skipWhile,openArray[char],set[char] proc skipWhile(s: openArray[char]; toSkip: set[char]): int 317 +nim parseUntil parseutils.html#parseUntil,openArray[char],string,set[char] proc parseUntil(s: openArray[char]; token: var string; until: set[char]): int 331 +nim parseUntil parseutils.html#parseUntil,openArray[char],string,char proc parseUntil(s: openArray[char]; token: var string; until: char): int 349 +nim parseUntil parseutils.html#parseUntil,openArray[char],string,string proc parseUntil(s: openArray[char]; token: var string; until: string): int 367 +nim parseWhile parseutils.html#parseWhile,openArray[char],string,set[char] proc parseWhile(s: openArray[char]; token: var string; validChars: set[char]): int 393 +nim captureBetween parseutils.html#captureBetween,openArray[char],char,char proc captureBetween(s: openArray[char]; first: char; second = '\x00'): string 409 +nim parseBiggestInt parseutils.html#parseBiggestInt,openArray[char],BiggestInt proc parseBiggestInt(s: openArray[char]; number: var BiggestInt): int 455 +nim parseInt parseutils.html#parseInt,openArray[char],int proc parseInt(s: openArray[char]; number: var int): int 473 +nim parseSaturatedNatural parseutils.html#parseSaturatedNatural,openArray[char],int proc parseSaturatedNatural(s: openArray[char]; b: var int): int 490 +nim parseBiggestUInt parseutils.html#parseBiggestUInt,openArray[char],BiggestUInt proc parseBiggestUInt(s: openArray[char]; number: var BiggestUInt): int 534 +nim parseUInt parseutils.html#parseUInt,openArray[char],uint proc parseUInt(s: openArray[char]; number: var uint): int 552 +nim parseBiggestFloat parseutils.html#parseBiggestFloat,openArray[char],BiggestFloat proc parseBiggestFloat(s: openArray[char]; number: var BiggestFloat): int 571 +nim parseFloat parseutils.html#parseFloat,openArray[char],float proc parseFloat(s: openArray[char]; number: var float): int 577 +nim parseSize parseutils.html#parseSize,openArray[char],int64 proc parseSize(s: openArray[char]; size: var int64; alwaysBin = false): int 598 +nim ikStr parseutils.html#ikStr InterpolatedKind.ikStr 661 +nim ikDollar parseutils.html#ikDollar InterpolatedKind.ikDollar 661 +nim ikVar parseutils.html#ikVar InterpolatedKind.ikVar 661 +nim ikExpr parseutils.html#ikExpr InterpolatedKind.ikExpr 661 +nim InterpolatedKind parseutils.html#InterpolatedKind enum InterpolatedKind 661 +nim interpolatedFragments parseutils.html#interpolatedFragments.i,openArray[char] iterator interpolatedFragments(s: openArray[char]): tuple[kind: InterpolatedKind,\n value: string] 669 +nim parseBin parseutils.html#parseBin,string,T,int,int proc parseBin[T: SomeInteger](s: string; number: var T; start = 0; maxLen = 0): int 732 +nim parseOct parseutils.html#parseOct,string,T,int,int proc parseOct[T: SomeInteger](s: string; number: var T; start = 0; maxLen = 0): int 764 +nim parseHex parseutils.html#parseHex,string,T,int,int proc parseHex[T: SomeInteger](s: string; number: var T; start = 0; maxLen = 0): int 796 +nim parseIdent parseutils.html#parseIdent,string,string,int proc parseIdent(s: string; ident: var string; start = 0): int 829 +nim parseIdent parseutils.html#parseIdent,string,int proc parseIdent(s: string; start = 0): string 843 +nim parseChar parseutils.html#parseChar,string,char,int proc parseChar(s: string; c: var char; start = 0): int 853 +nim skipWhitespace parseutils.html#skipWhitespace,string,int proc skipWhitespace(s: string; start = 0): int 865 +nim skip parseutils.html#skip,string,string,int proc skip(s, token: string; start = 0): int 875 +nim skipIgnoreCase parseutils.html#skipIgnoreCase,string,string,int proc skipIgnoreCase(s, token: string; start = 0): int 886 +nim skipUntil parseutils.html#skipUntil,string,set[char],int proc skipUntil(s: string; until: set[char]; start = 0): int 893 +nim skipUntil parseutils.html#skipUntil,string,char,int proc skipUntil(s: string; until: char; start = 0): int 903 +nim skipWhile parseutils.html#skipWhile,string,set[char],int proc skipWhile(s: string; toSkip: set[char]; start = 0): int 914 +nim parseUntil parseutils.html#parseUntil,string,string,set[char],int proc parseUntil(s: string; token: var string; until: set[char]; start = 0): int 923 +nim parseUntil parseutils.html#parseUntil,string,string,char,int proc parseUntil(s: string; token: var string; until: char; start = 0): int 938 +nim parseUntil parseutils.html#parseUntil,string,string,string,int proc parseUntil(s: string; token: var string; until: string; start = 0): int 953 +nim parseWhile parseutils.html#parseWhile,string,string,set[char],int proc parseWhile(s: string; token: var string; validChars: set[char]; start = 0): int 966 +nim captureBetween parseutils.html#captureBetween,string,char,char,int proc captureBetween(s: string; first: char; second = '\x00'; start = 0): string 979 +nim parseBiggestInt parseutils.html#parseBiggestInt,string,BiggestInt,int proc parseBiggestInt(s: string; number: var BiggestInt; start = 0): int 988 +nim parseInt parseutils.html#parseInt,string,int,int proc parseInt(s: string; number: var int; start = 0): int 1002 +nim parseSaturatedNatural parseutils.html#parseSaturatedNatural,string,int,int proc parseSaturatedNatural(s: string; b: var int; start = 0): int 1015 +nim parseBiggestUInt parseutils.html#parseBiggestUInt,string,BiggestUInt,int proc parseBiggestUInt(s: string; number: var BiggestUInt; start = 0): int 1028 +nim parseUInt parseutils.html#parseUInt,string,uint,int proc parseUInt(s: string; number: var uint; start = 0): int 1040 +nim parseBiggestFloat parseutils.html#parseBiggestFloat,string,BiggestFloat,int proc parseBiggestFloat(s: string; number: var BiggestFloat; start = 0): int 1052 +nim parseFloat parseutils.html#parseFloat,string,float,int proc parseFloat(s: string; number: var float; start = 0): int 1058 +nim interpolatedFragments parseutils.html#interpolatedFragments.i,string iterator interpolatedFragments(s: string): tuple[kind: InterpolatedKind, value: string] 1072 +idx parseInt parseutils.html#parseint_1 Module parseutils 0 +idx parseInt parseutils.html#parseint_2 Module parseutils 0 +nimgrp parsebiggestfloat parseutils.html#parseBiggestFloat-procs-all proc 571 +nimgrp parsehex parseutils.html#parseHex-procs-all proc 155 +nimgrp skip parseutils.html#skip-procs-all proc 269 +nimgrp parsebiggestint parseutils.html#parseBiggestInt-procs-all proc 455 +nimgrp parsefloat parseutils.html#parseFloat-procs-all proc 577 +nimgrp capturebetween parseutils.html#captureBetween-procs-all proc 409 +nimgrp parsesaturatednatural parseutils.html#parseSaturatedNatural-procs-all proc 490 +nimgrp parseuint parseutils.html#parseUInt-procs-all proc 552 +nimgrp parsebiggestuint parseutils.html#parseBiggestUInt-procs-all proc 534 +nimgrp parsebin parseutils.html#parseBin-procs-all proc 63 +nimgrp parseoct parseutils.html#parseOct-procs-all proc 109 +nimgrp parsewhile parseutils.html#parseWhile-procs-all proc 393 +nimgrp skipwhitespace parseutils.html#skipWhitespace-procs-all proc 258 +nimgrp parseident parseutils.html#parseIdent-procs-all proc 210 +nimgrp skipuntil parseutils.html#skipUntil-procs-all proc 294 +nimgrp parsechar parseutils.html#parseChar-procs-all proc 244 +nimgrp parseint parseutils.html#parseInt-procs-all proc 473 +nimgrp skipignorecase parseutils.html#skipIgnoreCase-procs-all proc 284 +nimgrp parseuntil parseutils.html#parseUntil-procs-all proc 331 +nimgrp skipwhile parseutils.html#skipWhile-procs-all proc 317 +nimgrp interpolatedfragments parseutils.html#interpolatedFragments-iterators-all iterator 669 diff --git a/parsexml.html b/parsexml.html new file mode 100644 index 0000000000000..f4780d2a0245c --- /dev/null +++ b/parsexml.html @@ -0,0 +1,661 @@ + + + + + + + +std/parsexml + + + + + + + + + + + + + + + + +
+
+

std/parsexml

+
+ +
+ Source   +Edit   + +
+ +

This 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 most "wild HTML" found on the web can be parsed with it. Note: This parser does not check that each <tag> has a corresponding </tag>! These checks have do be implemented by the client code for various reasons:

  • Old HTML contains tags that have no end tag: <br> for example.
  • +
  • HTML tags are case insensitive, XML tags are case sensitive. Since this library can parse both, only the client knows which comparison is to be used.
  • +
  • Thus the checks would have been very difficult to implement properly with little benefit, especially since they are simple to implement in the client. The client should use the errorMsgExpected proc to generate a nice error message that fits the other error messages this library creates.
  • +
+ +

Example 1: Retrieve HTML title

The file examples/htmltitle.nim demonstrates how to use the XML parser to accomplish a simple task: To determine the title of an HTML document.

+

# Example program to show the parsexml module
+# This program reads an HTML file and writes its title to stdout.
+# Errors and whitespace are ignored.
+
+import std/[os, streams, parsexml, strutils]
+
+if paramCount() < 1:
+  quit("Usage: htmltitle filename[.html]")
+
+var filename = addFileExt(paramStr(1), "html")
+var s = newFileStream(filename, fmRead)
+if s == nil: quit("cannot open the file " & filename)
+var x: XmlParser
+open(x, s, filename)
+while true:
+  x.next()
+  case x.kind
+  of xmlElementStart:
+    if cmpIgnoreCase(x.elementName, "title") == 0:
+      var title = ""
+      x.next()  # skip "<title>"
+      while x.kind == xmlCharData:
+        title.add(x.charData)
+        x.next()
+      if x.kind == xmlElementEnd and cmpIgnoreCase(x.elementName, "title") == 0:
+        echo("Title: " & title)
+        quit(0) # Success!
+      else:
+        echo(x.errorMsgExpected("/title"))
+  
+  of xmlEof: break # end of file reached
+  else: discard # ignore other events
+
+x.close()
+quit("Could not determine title!")

+ +

Example 2: Retrieve all HTML links

The file examples/htmlrefs.nim demonstrates how to use the XML parser to accomplish another simple task: To determine all the links an HTML document contains.

+

# Example program to show the new parsexml module
+# This program reads an HTML file and writes all its used links to stdout.
+# Errors and whitespace are ignored.
+
+import std/[os, streams, parsexml, strutils]
+
+proc `=?=` (a, b: string): bool =
+  # little trick: define our own comparator that ignores case
+  return cmpIgnoreCase(a, b) == 0
+
+if paramCount() < 1:
+  quit("Usage: htmlrefs filename[.html]")
+
+var links = 0 # count the number of links
+var filename = addFileExt(paramStr(1), "html")
+var s = newFileStream(filename, fmRead)
+if s == nil: quit("cannot open the file " & filename)
+var x: XmlParser
+open(x, s, filename)
+next(x) # get first event
+block mainLoop:
+  while true:
+    case x.kind
+    of xmlElementOpen:
+      # the <a href = "xyz"> tag we are interested in always has an attribute,
+      # thus we search for ``xmlElementOpen`` and not for ``xmlElementStart``
+      if x.elementName =?= "a":
+        x.next()
+        if x.kind == xmlAttribute:
+          if x.attrKey =?= "href":
+            var link = x.attrValue
+            inc(links)
+            # skip until we have an ``xmlElementClose`` event
+            while true:
+              x.next()
+              case x.kind
+              of xmlEof: break mainLoop
+              of xmlElementClose: break
+              else: discard
+            x.next() # skip ``xmlElementClose``
+            # now we have the description for the ``a`` element
+            var desc = ""
+            while x.kind == xmlCharData:
+              desc.add(x.charData)
+              x.next()
+            echo(desc & ": " & link)
+      else:
+        x.next()
+    of xmlEof: break # end of file reached
+    of xmlError:
+      echo(errorMsg(x))
+      x.next()
+    else: x.next() # skip other events
+
+echo($links & " link(s) found!")
+x.close()

+

+ +
+

Types

+
+
+
XmlErrorKind = enum
+  errNone,                  ## no error
+  errEndOfCDataExpected,    ## ``]]>`` expected
+  errNameExpected,          ## name expected
+  errSemicolonExpected,     ## ``;`` expected
+  errQmGtExpected,          ## ``?>`` expected
+  errGtExpected,            ## ``>`` expected
+  errEqExpected,            ## ``=`` expected
+  errQuoteExpected,         ## ``"`` or ``'`` expected
+  errEndOfCommentExpected,  ## ``-->`` expected
+  errAttributeValueExpected  ## non-empty attribute value expected
+
+ + enumeration that lists all errors that can occur + Source   +Edit   + +
+
+
+
XmlEventKind = enum
+  xmlError,                 ## an error occurred during parsing
+  xmlEof,                   ## end of file reached
+  xmlCharData,              ## character data
+  xmlWhitespace,            ## whitespace has been parsed
+  xmlComment,               ## a comment has been parsed
+  xmlPI,                    ## processing instruction (``<?name something ?>``)
+  xmlElementStart,          ## ``<elem>``
+  xmlElementEnd,            ## ``</elem>``
+  xmlElementOpen,           ## ``<elem
+  xmlAttribute,             ## ``key = "value"`` pair
+  xmlElementClose,          ## ``>``
+  xmlCData,                 ## ``<![CDATA[`` ... data ... ``]]>``
+  xmlEntity,                ## &entity;
+  xmlSpecial                 ## ``<! ... data ... >``
+
+ + enumeration of all events that may occur when parsing + Source   +Edit   + +
+
+
+
XmlParseOption = enum
+  reportWhitespace,         ## report whitespace
+  reportComments,           ## report comments
+  allowUnquotedAttribs,     ## allow unquoted attribute values (for HTML)
+  allowEmptyAttribs          ## allow empty attributes (without explicit value)
+
+ + options for the XML parser + Source   +Edit   + +
+
+
+
XmlParser = object of BaseLexer
+
+ + the parser object. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc close(my: var XmlParser) {.inline, ...raises: [IOError, OSError],
+                                tags: [WriteIOEffect], forbids: [].}
+
+ + closes the parser my and its associated input stream. + Source   +Edit   + +
+
+ +
+
+
+
proc errorMsg(my: XmlParser): string {....raises: [ValueError], tags: [],
+                                       forbids: [].}
+
+ + returns a helpful error message for the event xmlError + Source   +Edit   + +
+
+
+
proc errorMsg(my: XmlParser; msg: string): string {....raises: [ValueError],
+    tags: [], forbids: [].}
+
+ + returns an error message with text msg in the same format as the other error messages + Source   +Edit   + +
+
+ +
+
+
+
proc errorMsgExpected(my: XmlParser; tag: string): string {.
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ + returns an error message "<tag> expected" in the same format as the other error messages + Source   +Edit   + +
+
+ +
+
+
+
proc getColumn(my: XmlParser): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + get the current column the parser has arrived at. + Source   +Edit   + +
+
+ +
+
+
+
proc getFilename(my: XmlParser): string {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + get the filename of the file that the parser processes. + Source   +Edit   + +
+
+ +
+
+
+
proc getLine(my: XmlParser): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + get the current line the parser has arrived at. + Source   +Edit   + +
+
+ +
+
+
+
proc kind(my: XmlParser): XmlEventKind {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + returns the current event type for the XML parser + Source   +Edit   + +
+
+ +
+
+
+
proc next(my: var XmlParser) {....raises: [IOError, OSError], tags: [ReadIOEffect],
+                               forbids: [].}
+
+ + retrieves the first/next event. This controls the parser. + Source   +Edit   + +
+
+ +
+
+
+
proc open(my: var XmlParser; input: Stream; filename: string;
+          options: set[XmlParseOption] = {}) {....raises: [IOError, OSError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + initializes the parser with an input stream. Filename is only used for nice error messages. The parser's behaviour can be controlled by the options parameter: If options contains reportWhitespace a whitespace token is reported as an xmlWhitespace event. If options contains reportComments a comment token is reported as an xmlComment event. + Source   +Edit   + +
+
+ +
+
+
+
proc rawData(my: var XmlParser): lent string {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + returns the underlying 'data' string by reference. This is only used for speed hacks. + Source   +Edit   + +
+
+ +
+
+
+
proc rawData2(my: var XmlParser): lent string {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + returns the underlying second 'data' string by reference. This is only used for speed hacks. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template attrKey(my: XmlParser): string
+
+ + returns the attribute key for the event xmlAttribute Raises an assertion in debug mode if my.kind is not xmlAttribute. In release mode, this will not trigger an error but the value returned will not be valid. + Source   +Edit   + +
+
+ +
+
+
+
template attrValue(my: XmlParser): string
+
+ + returns the attribute value for the event xmlAttribute Raises an assertion in debug mode if my.kind is not xmlAttribute. In release mode, this will not trigger an error but the value returned will not be valid. + Source   +Edit   + +
+
+ +
+
+
+
template charData(my: XmlParser): string
+
+ + returns the character data for the events: xmlCharData, xmlWhitespace, xmlComment, xmlCData, xmlSpecial Raises an assertion in debug mode if my.kind is not one of those events. In release mode, this will not trigger an error but the value returned will not be valid. + Source   +Edit   + +
+
+ +
+
+
+
template elementName(my: XmlParser): string
+
+ + returns the element name for the events: xmlElementStart, xmlElementEnd, xmlElementOpen Raises an assertion in debug mode if my.kind is not one of those events. In release mode, this will not trigger an error but the value returned will not be valid. + Source   +Edit   + +
+
+ +
+
+
+
template entityName(my: XmlParser): string
+
+ + returns the entity name for the event: xmlEntity Raises an assertion in debug mode if my.kind is not xmlEntity. In release mode, this will not trigger an error but the value returned will not be valid. + Source   +Edit   + +
+
+ +
+
+
+
template piName(my: XmlParser): string
+
+ + returns the processing instruction name for the event xmlPI Raises an assertion in debug mode if my.kind is not xmlPI. In release mode, this will not trigger an error but the value returned will not be valid. + Source   +Edit   + +
+
+ +
+
+
+
template piRest(my: XmlParser): string
+
+ + returns the rest of the processing instruction for the event xmlPI Raises an assertion in debug mode if my.kind is not xmlPI. In release mode, this will not trigger an error but the value returned will not be valid. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/parsexml.idx b/parsexml.idx new file mode 100644 index 0000000000000..8d9cf96cda538 --- /dev/null +++ b/parsexml.idx @@ -0,0 +1,57 @@ +nimTitle parsexml parsexml.html module std/parsexml 0 +nim xmlError parsexml.html#xmlError XmlEventKind.xmlError 160 +nim xmlEof parsexml.html#xmlEof XmlEventKind.xmlEof 160 +nim xmlCharData parsexml.html#xmlCharData XmlEventKind.xmlCharData 160 +nim xmlWhitespace parsexml.html#xmlWhitespace XmlEventKind.xmlWhitespace 160 +nim xmlComment parsexml.html#xmlComment XmlEventKind.xmlComment 160 +nim xmlPI parsexml.html#xmlPI XmlEventKind.xmlPI 160 +nim xmlElementStart parsexml.html#xmlElementStart XmlEventKind.xmlElementStart 160 +nim xmlElementEnd parsexml.html#xmlElementEnd XmlEventKind.xmlElementEnd 160 +nim xmlElementOpen parsexml.html#xmlElementOpen XmlEventKind.xmlElementOpen 160 +nim xmlAttribute parsexml.html#xmlAttribute XmlEventKind.xmlAttribute 160 +nim xmlElementClose parsexml.html#xmlElementClose XmlEventKind.xmlElementClose 160 +nim xmlCData parsexml.html#xmlCData XmlEventKind.xmlCData 160 +nim xmlEntity parsexml.html#xmlEntity XmlEventKind.xmlEntity 160 +nim xmlSpecial parsexml.html#xmlSpecial XmlEventKind.xmlSpecial 160 +nim XmlEventKind parsexml.html#XmlEventKind enum XmlEventKind 160 +nim errNone parsexml.html#errNone XmlErrorKind.errNone 176 +nim errEndOfCDataExpected parsexml.html#errEndOfCDataExpected XmlErrorKind.errEndOfCDataExpected 176 +nim errNameExpected parsexml.html#errNameExpected XmlErrorKind.errNameExpected 176 +nim errSemicolonExpected parsexml.html#errSemicolonExpected XmlErrorKind.errSemicolonExpected 176 +nim errQmGtExpected parsexml.html#errQmGtExpected XmlErrorKind.errQmGtExpected 176 +nim errGtExpected parsexml.html#errGtExpected XmlErrorKind.errGtExpected 176 +nim errEqExpected parsexml.html#errEqExpected XmlErrorKind.errEqExpected 176 +nim errQuoteExpected parsexml.html#errQuoteExpected XmlErrorKind.errQuoteExpected 176 +nim errEndOfCommentExpected parsexml.html#errEndOfCommentExpected XmlErrorKind.errEndOfCommentExpected 176 +nim errAttributeValueExpected parsexml.html#errAttributeValueExpected XmlErrorKind.errAttributeValueExpected 176 +nim XmlErrorKind parsexml.html#XmlErrorKind enum XmlErrorKind 176 +nim reportWhitespace parsexml.html#reportWhitespace XmlParseOption.reportWhitespace 191 +nim reportComments parsexml.html#reportComments XmlParseOption.reportComments 191 +nim allowUnquotedAttribs parsexml.html#allowUnquotedAttribs XmlParseOption.allowUnquotedAttribs 191 +nim allowEmptyAttribs parsexml.html#allowEmptyAttribs XmlParseOption.allowEmptyAttribs 191 +nim XmlParseOption parsexml.html#XmlParseOption enum XmlParseOption 191 +nim XmlParser parsexml.html#XmlParser object XmlParser 197 +nim open parsexml.html#open,XmlParser,Stream,string,set[XmlParseOption] proc open(my: var XmlParser; input: Stream; filename: string;\n options: set[XmlParseOption] = {}) 220 +nim close parsexml.html#close,XmlParser proc close(my: var XmlParser) 238 +nim kind parsexml.html#kind,XmlParser proc kind(my: XmlParser): XmlEventKind 242 +nim charData parsexml.html#charData.t,XmlParser template charData(my: XmlParser): string 246 +nim elementName parsexml.html#elementName.t,XmlParser template elementName(my: XmlParser): string 256 +nim entityName parsexml.html#entityName.t,XmlParser template entityName(my: XmlParser): string 265 +nim attrKey parsexml.html#attrKey.t,XmlParser template attrKey(my: XmlParser): string 273 +nim attrValue parsexml.html#attrValue.t,XmlParser template attrValue(my: XmlParser): string 281 +nim piName parsexml.html#piName.t,XmlParser template piName(my: XmlParser): string 289 +nim piRest parsexml.html#piRest.t,XmlParser template piRest(my: XmlParser): string 297 +nim rawData parsexml.html#rawData,XmlParser proc rawData(my: var XmlParser): lent string 305 +nim rawData2 parsexml.html#rawData2,XmlParser proc rawData2(my: var XmlParser): lent string 310 +nim getColumn parsexml.html#getColumn,XmlParser proc getColumn(my: XmlParser): int 315 +nim getLine parsexml.html#getLine,XmlParser proc getLine(my: XmlParser): int 319 +nim getFilename parsexml.html#getFilename,XmlParser proc getFilename(my: XmlParser): string 323 +nim errorMsg parsexml.html#errorMsg,XmlParser proc errorMsg(my: XmlParser): string 327 +nim errorMsgExpected parsexml.html#errorMsgExpected,XmlParser,string proc errorMsgExpected(my: XmlParser; tag: string): string 333 +nim errorMsg parsexml.html#errorMsg,XmlParser,string proc errorMsg(my: XmlParser; msg: string): string 339 +nim next parsexml.html#next,XmlParser proc next(my: var XmlParser) 757 +idx XML parsexml.html#xml_1 Module parsexml 0 +idx HTML parsexml.html#html_1 Module parsexml 0 +heading Example 1: Retrieve HTML title parsexml.html#example-1colon-retrieve-html-title Example 1: Retrieve HTML title 0 +heading Example 2: Retrieve all HTML links parsexml.html#example-2colon-retrieve-all-html-links Example 2: Retrieve all HTML links 0 +nimgrp errormsg parsexml.html#errorMsg-procs-all proc 327 diff --git a/pathnorm.html b/pathnorm.html new file mode 100644 index 0000000000000..5fc9333b4e11f --- /dev/null +++ b/pathnorm.html @@ -0,0 +1,207 @@ + + + + + + + +std/pathnorm + + + + + + + + + + + + + + + + +
+
+

std/pathnorm

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

OS-Path normalization. Used by os.nim but also generally useful for dealing with paths.

+

Unstable API.

+

+
+

Imports

+
+ osseps +
+
+
+

Types

+
+
+
PathIter = object
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc addNormalizePath(x: string; result: var string; state: var int;
+                      dirSep = DirSep) {....raises: [], tags: [], forbids: [].}
+
+ + Low level proc. Undocumented. + Source   +Edit   + +
+
+ +
+
+
+
proc hasNext(it: PathIter; x: string): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc next(it: var PathIter; x: string): (int, int) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc normalizePath(path: string; dirSep = DirSep): string {....raises: [],
+    tags: [], forbids: [].}
+
+ + +

Example:

+
when defined(posix):
+  doAssert normalizePath("./foo//bar/../baz") == "foo/baz"
  • Turns multiple slashes into single slashes.
  • +
  • Resolves '/foo/../bar' to '/bar'.
  • +
  • Removes './' from the path, but "foo/.." becomes ".".
  • +
+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/pathnorm.idx b/pathnorm.idx new file mode 100644 index 0000000000000..8471b9dad047c --- /dev/null +++ b/pathnorm.idx @@ -0,0 +1,6 @@ +nimTitle pathnorm pathnorm.html module std/pathnorm 0 +nim PathIter pathnorm.html#PathIter object PathIter 20 +nim hasNext pathnorm.html#hasNext,PathIter,string proc hasNext(it: PathIter; x: string): bool 24 +nim next pathnorm.html#next,PathIter,string proc next(it: var PathIter; x: string): (int, int) 27 +nim addNormalizePath pathnorm.html#addNormalizePath,string,string,int proc addNormalizePath(x: string; result: var string; state: var int; dirSep = DirSep) 58 +nim normalizePath pathnorm.html#normalizePath,string proc normalizePath(path: string; dirSep = DirSep): string 111 diff --git a/paths.html b/paths.html new file mode 100644 index 0000000000000..788bdd5501ea8 --- /dev/null +++ b/paths.html @@ -0,0 +1,730 @@ + + + + + + + +std/paths + + + + + + + + + + + + + + + + +
+
+

std/paths

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements path handling.

+

See also:

+ +

+ +
+

Types

+
+
+
Path = distinct string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `/`(head, tail: Path): Path {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Joins two directory names to one.

+

returns normalized path concatenation of head and tail, preserving whether or not tail has a trailing slash (or, if tail if empty, whether head has one).

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func `/../`(head, tail: Path): Path {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

The same as parentDir(head) / tail, unless there is no parent directory. Then head / tail is performed instead.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func `==`(x, y: Path): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Compares two paths.

+

On a case-sensitive filesystem this is done case-sensitively otherwise case-insensitively.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc absolutePath(path: Path; root = getCurrentDir()): Path {.
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ +

Returns the absolute path of path, rooted at root (which must be absolute; default: current directory). If path is absolute, return it, ignoring root.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func add(x: var Path; y: Path) {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func addFileExt(filename: Path; ext: string): Path {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Adds the file extension ext to filename, unless filename already has an extension.

+

Ext should be given without the leading '.', because some filesystems may use a different character. (Although I know of none such beast.)

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func changeFileExt(filename: Path; ext: string): Path {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Changes the file extension to ext.

+

If the filename has no extension, ext will be added. If ext == "" then any extension is removed.

+

Ext should be given without the leading '.', because some filesystems may use a different character. (Although I know of none such beast.)

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc expandTilde(path: Path): Path {.inline,
+                                     ...tags: [ReadEnvEffect, ReadIOEffect],
+                                     raises: [], forbids: [].}
+
+ +

Expands ~ or a path starting with ~/ to a full path, replacing ~ with getHomeDir() (otherwise returns path unmodified).

+

Windows: this is still supported despite the Windows platform not having this convention; also, both ~/ and ~\ are handled.

+ +

Example:

+
import std/appdirs
+assert expandTilde(Path("~") / Path("appname.cfg")) == getHomeDir() / Path("appname.cfg")
+assert expandTilde(Path("~/foo/bar")) == getHomeDir() / Path("foo/bar")
+assert expandTilde(Path("/foo/bar")) == Path("/foo/bar")
+ Source   +Edit   + +
+
+ +
+
+
+
func extractFilename(path: Path): Path {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Extracts the filename of a given path.

+

This is the same as name & ext from splitFile(path) proc.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getCurrentDir(): Path {.inline, ...tags: [], raises: [OSError], forbids: [].}
+
+ +

Returns the current working directory i.e. where the built binary is run.

+

So the path returned by this proc is determined at run time.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func hash(x: Path): Hash {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func isAbsolute(path: Path): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Checks whether a given path is absolute.

+

On Windows, network paths are considered absolute too.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc isRelativeTo(path: Path; base: Path): bool {.inline, ...raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + Returns true if path is relative to base. + Source   +Edit   + +
+
+ +
+
+
+
func isRootDir(path: Path): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Checks whether a given path is a root directory. + Source   +Edit   + +
+
+ +
+
+
+
func lastPathPart(path: Path): Path {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Like extractFilename proc, but ignores trailing dir separator; aka: baseName in some other languages.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc normalizeExe(file: var Path) {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc normalizePath(path: var Path) {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc normalizePathEnd(path: var Path; trailingSep = false) {.borrow, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func parentDir(path: Path): Path {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the parent directory of path.

+

This is similar to splitPath(path).head when path doesn't end in a dir separator, but also takes care of path normalizations. The remainder can be obtained with lastPathPart(path) proc.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc relativePath(path, base: Path; sep = DirSep): Path {.inline,
+    ...raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ +

Converts path to a path relative to base.

+

The sep (default: DirSep) is used for the path normalizations, this can be useful to ensure the relative path only contains '/' so that it can be used for URL constructions.

+

On Windows, if a root of path and a root of base are different, returns path as is because it is impossible to make a relative path. That means an absolute path can be returned.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func splitFile(path: Path): tuple[dir, name: Path, ext: string] {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Splits a filename into (dir, name, extension) tuple.

+

dir does not end in DirSep unless it's /. extension includes the leading dot.

+

If path has no extension, ext is the empty string. If path has no directory component, dir is the empty string. If path has no filename component, name and ext are empty strings.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func splitPath(path: Path): tuple[head, tail: Path] {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Splits a directory into (head, tail) tuple, so that head / tail == path (except for edge cases like "/usr").

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func tailDir(path: Path): Path {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the tail part of path.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func unixToNativePath(path: Path; drive = Path("")): Path {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Converts an UNIX-like path to a native one.

+

On an UNIX system this does nothing. Else it converts '/', '.', '..' to the appropriate things.

+

On systems with a concept of "drives", drive is used to determine which drive label to use during absolute path conversion. drive defaults to the drive of the current working directory, and is ignored on systems that do not have a concept of "drives".

+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator parentDirs(path: Path; fromRoot = false; inclusive = true): Path {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Walks over all parent directories of a given path.

+

If fromRoot is true (default: false), the traversal will start from the file system root directory. If inclusive is true (default), the original argument will be included in the traversal.

+

Relative paths won't be expanded by this iterator. Instead, it will traverse only the directories appearing in the relative path.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template `$`(x: Path): string
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/paths.idx b/paths.idx new file mode 100644 index 0000000000000..2e32cc8364578 --- /dev/null +++ b/paths.idx @@ -0,0 +1,30 @@ +nimTitle paths paths.html module std/paths 0 +nim Path paths.html#Path type Path 26 +nim hash paths.html#hash,Path proc hash(x: Path): Hash 28 +nim `$` paths.html#$.t,Path template `$`(x: Path): string 35 +nim `==` paths.html#==,Path,Path proc `==`(x, y: Path): bool 38 +nim add paths.html#add,Path,Path proc add(x: var Path; y: Path) 55 +nim `/` paths.html#/,Path,Path proc `/`(head, tail: Path): Path 57 +nim splitPath paths.html#splitPath,Path proc splitPath(path: Path): tuple[head, tail: Path] 70 +nim splitFile paths.html#splitFile,Path proc splitFile(path: Path): tuple[dir, name: Path, ext: string] 82 +nim isAbsolute paths.html#isAbsolute,Path proc isAbsolute(path: Path): bool 100 +nim relativePath paths.html#relativePath,Path,Path proc relativePath(path, base: Path; sep = DirSep): Path 106 +nim isRelativeTo paths.html#isRelativeTo,Path,Path proc isRelativeTo(path: Path; base: Path): bool 123 +nim parentDir paths.html#parentDir,Path proc parentDir(path: Path): Path 128 +nim tailDir paths.html#tailDir,Path proc tailDir(path: Path): Path 142 +nim isRootDir paths.html#isRootDir,Path proc isRootDir(path: Path): bool 151 +nim parentDirs paths.html#parentDirs.i,Path iterator parentDirs(path: Path; fromRoot = false; inclusive = true): Path 155 +nim `/../` paths.html#/../,Path,Path proc `/../`(head, tail: Path): Path 172 +nim extractFilename paths.html#extractFilename,Path proc extractFilename(path: Path): Path 181 +nim lastPathPart paths.html#lastPathPart,Path proc lastPathPart(path: Path): Path 193 +nim changeFileExt paths.html#changeFileExt,Path,string proc changeFileExt(filename: Path; ext: string): Path 204 +nim addFileExt paths.html#addFileExt,Path,string proc addFileExt(filename: Path; ext: string): Path 221 +nim unixToNativePath paths.html#unixToNativePath,Path proc unixToNativePath(path: Path; drive = Path("")): Path 236 +nim getCurrentDir paths.html#getCurrentDir proc getCurrentDir(): Path 248 +nim normalizeExe paths.html#normalizeExe,Path proc normalizeExe(file: var Path) 263 +nim normalizePath paths.html#normalizePath,Path proc normalizePath(path: var Path) 265 +nim normalizePathEnd paths.html#normalizePathEnd,Path proc normalizePathEnd(path: var Path; trailingSep = false) 267 +nim absolutePath paths.html#absolutePath,Path proc absolutePath(path: Path; root = getCurrentDir()): Path 269 +nim expandTilde paths.html#expandTilde,Path proc expandTilde(path: Path): Path 290 +idx baseName paths.html#basename_1 Module paths 0 +idx current working directory paths.html#current-working-directory_1 Module paths 0 diff --git a/pcre.html b/pcre.html new file mode 100644 index 0000000000000..55d8a43d4a2e8 --- /dev/null +++ b/pcre.html @@ -0,0 +1,2645 @@ + + + + + + + +std/pcre + + + + + + + + + + + + + + + + +
+
+

std/pcre

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
+

Types

+
+
+
CalloutBlock = object
+  version*: cint             ## Identifies version of block
+  callout_number*: cint      ## Number compiled into pattern
+  offset_vector*: ptr cint   ## The offset vector
+  subject*: cstring          ## The subject being matched
+  subject_length*: cint      ## The length of the subject
+  start_match*: cint         ## Offset to start of this match attempt
+  current_position*: cint    ## Where we currently are in the subject
+  capture_top*: cint         ## Max current capture
+  capture_last*: cint        ## Most recently closed capture
+  callout_data*: pointer     ## Data passed in with the call
+  pattern_position*: cint    ## Offset to next item in the pattern
+  next_item_length*: cint    ## Length of next item in the pattern
+  mark*: pointer             ## Pointer to current mark or NULL
+
+ + + Source   +Edit   + +
+
+
+
ExtraData = object
+  flags*: clong              ## Bits for which fields are set
+  study_data*: pointer       ## Opaque data from pcre_study()
+  match_limit*: clong        ## Maximum number of calls to match()
+  callout_data*: pointer     ## Data passed back in callouts
+  tables*: pointer           ## Pointer to character tables
+  match_limit_recursion*: clong ## Max recursive calls to match()
+  mark*: pointer             ## For passing back a mark pointer
+  executable_jit*: pointer   ## Contains a pointer to a compiled jit code
+
+ + + Source   +Edit   + +
+
+
+
JitCallback = proc (a: pointer): ptr JitStack {.cdecl.}
+
+ + + Source   +Edit   + +
+
+
+
JitStack = object
+
+ + + Source   +Edit   + +
+
+
+
JitStack16 = object
+
+ + + Source   +Edit   + +
+
+
+
JitStack32 = object
+
+ + + Source   +Edit   + +
+
+
+
Pcre = object
+
+ + + Source   +Edit   + +
+
+
+
Pcre16 = object
+
+ + + Source   +Edit   + +
+
+
+
Pcre32 = object
+
+ + + Source   +Edit   + +
+
+
+
PJitStack {....deprecated.} = ptr JitStack
+
+
+ Deprecated +
+ + + Source   +Edit   + +
+
+
+
PPcre {....deprecated.} = ptr Pcre
+
+
+ Deprecated +
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
ANCHORED = 0x00000010
+
+ + + Source   +Edit   + +
+
+
+
AUTO_CALLOUT = 0x00004000
+
+ + + Source   +Edit   + +
+
+
+
BSR_ANYCRLF = 0x00800000
+
+ + + Source   +Edit   + +
+
+
+
BSR_UNICODE = 0x01000000
+
+ + + Source   +Edit   + +
+
+
+
CASELESS = 0x00000001
+
+ + + Source   +Edit   + +
+
+
+
CONFIG_BSR = 8
+
+ + + Source   +Edit   + +
+
+
+
CONFIG_JIT = 9
+
+ + + Source   +Edit   + +
+
+
+
CONFIG_JITTARGET = 11
+
+ + + Source   +Edit   + +
+
+ +
+
CONFIG_MATCH_LIMIT = 4
+
+ + + Source   +Edit   + +
+
+
+
CONFIG_MATCH_LIMIT_RECURSION = 7
+
+ + + Source   +Edit   + +
+
+
+
CONFIG_NEWLINE = 1
+
+ + + Source   +Edit   + +
+
+
+
CONFIG_PARENS_LIMIT = 13
+
+ + + Source   +Edit   + +
+
+
+
CONFIG_POSIX_MALLOC_THRESHOLD = 3
+
+ + + Source   +Edit   + +
+
+
+
CONFIG_STACKRECURSE = 5
+
+ + + Source   +Edit   + +
+
+
+
CONFIG_UNICODE_PROPERTIES = 6
+
+ + + Source   +Edit   + +
+
+
+
CONFIG_UTF8 = 0
+
+ + + Source   +Edit   + +
+
+
+
CONFIG_UTF16 = 10
+
+ + + Source   +Edit   + +
+
+
+
CONFIG_UTF32 = 12
+
+ + + Source   +Edit   + +
+
+
+
DFA_RESTART = 0x00020000
+
+ + + Source   +Edit   + +
+
+
+
DFA_SHORTEST = 0x00010000
+
+ + + Source   +Edit   + +
+
+
+
DOLLAR_ENDONLY = 0x00000020
+
+ + + Source   +Edit   + +
+
+
+
DOTALL = 0x00000004
+
+ + + Source   +Edit   + +
+
+
+
DUPNAMES = 0x00080000
+
+ + + Source   +Edit   + +
+
+
+
ERROR_BADCOUNT = -15
+
+ + + Source   +Edit   + +
+
+
+
ERROR_BADENDIANNESS = -29
+
+ + + Source   +Edit   + +
+
+
+
ERROR_BADLENGTH = -32
+
+ + + Source   +Edit   + +
+
+
+
ERROR_BADMAGIC = -4
+
+ + + Source   +Edit   + +
+
+
+
ERROR_BADMODE = -28
+
+ + + Source   +Edit   + +
+
+
+
ERROR_BADNEWLINE = -23
+
+ + + Source   +Edit   + +
+
+
+
ERROR_BADOFFSET = -24
+
+ + + Source   +Edit   + +
+
+
+
ERROR_BADOPTION = -3
+
+ + + Source   +Edit   + +
+
+
+
ERROR_BADPARTIAL = -13
+
+ + + Source   +Edit   + +
+
+
+
ERROR_BADUTF8 = -10
+
+ + Same for 8/16/32 + Source   +Edit   + +
+
+
+
ERROR_BADUTF8_OFFSET = -11
+
+ + Same for 8/16 + Source   +Edit   + +
+
+
+
ERROR_BADUTF16 = -10
+
+ + Same for 8/16/32 + Source   +Edit   + +
+
+
+
ERROR_BADUTF16_OFFSET = -11
+
+ + Same for 8/16 + Source   +Edit   + +
+
+
+
ERROR_BADUTF32 = -10
+
+ + Same for 8/16/32 + Source   +Edit   + +
+
+
+
ERROR_CALLOUT = -9
+
+ + Never used by PCRE itself + Source   +Edit   + +
+
+
+
ERROR_DFA_BADRESTART = -30
+
+ + + Source   +Edit   + +
+
+
+
ERROR_DFA_RECURSE = -20
+
+ + + Source   +Edit   + +
+
+
+
ERROR_DFA_UCOND = -17
+
+ + + Source   +Edit   + +
+
+
+
ERROR_DFA_UITEM = -16
+
+ + + Source   +Edit   + +
+
+
+
ERROR_DFA_UMLIMIT = -18
+
+ + + Source   +Edit   + +
+
+
+
ERROR_DFA_WSSIZE = -19
+
+ + + Source   +Edit   + +
+
+
+
ERROR_INTERNAL = -14
+
+ + + Source   +Edit   + +
+
+
+
ERROR_JIT_BADOPTION = -31
+
+ + + Source   +Edit   + +
+
+
+
ERROR_JIT_STACKLIMIT = -27
+
+ + + Source   +Edit   + +
+
+
+
ERROR_MATCHLIMIT = -8
+
+ + + Source   +Edit   + +
+
+
+
ERROR_NOMATCH = -1
+
+ + + Source   +Edit   + +
+
+
+
ERROR_NOMEMORY = -6
+
+ + + Source   +Edit   + +
+
+
+
ERROR_NOSUBSTRING = -7
+
+ + + Source   +Edit   + +
+
+
+
ERROR_NULL = -2
+
+ + + Source   +Edit   + +
+
+
+
ERROR_NULLWSLIMIT = -22
+
+ + No longer actually used + Source   +Edit   + +
+
+
+
ERROR_PARTIAL = -12
+
+ + + Source   +Edit   + +
+
+
+
ERROR_RECURSELOOP = -26
+
+ + + Source   +Edit   + +
+
+
+
ERROR_RECURSIONLIMIT = -21
+
+ + + Source   +Edit   + +
+
+
+
ERROR_SHORTUTF8 = -25
+
+ + + Source   +Edit   + +
+
+
+
ERROR_SHORTUTF16 = -25
+
+ + Same for 8/16 + Source   +Edit   + +
+
+
+
ERROR_UNKNOWN_NODE = -5
+
+ + For backward compatibility + Source   +Edit   + +
+
+
+
ERROR_UNKNOWN_OPCODE = -5
+
+ + + Source   +Edit   + +
+
+
+
ERROR_UNSET = -33
+
+ + + Source   +Edit   + +
+
+
+
EXTENDED = 0x00000008
+
+ + + Source   +Edit   + +
+
+
+
EXTRA = 0x00000040
+
+ + + Source   +Edit   + +
+
+
+
EXTRA_CALLOUT_DATA = 0x00000004
+
+ + + Source   +Edit   + +
+
+
+
EXTRA_EXECUTABLE_JIT = 0x00000040
+
+ + + Source   +Edit   + +
+
+
+
EXTRA_MARK = 0x00000020
+
+ + + Source   +Edit   + +
+
+
+
EXTRA_MATCH_LIMIT = 0x00000002
+
+ + + Source   +Edit   + +
+
+
+
EXTRA_MATCH_LIMIT_RECURSION = 0x00000010
+
+ + + Source   +Edit   + +
+
+
+
EXTRA_STUDY_DATA = 0x00000001
+
+ + + Source   +Edit   + +
+
+
+
EXTRA_TABLES = 0x00000008
+
+ + + Source   +Edit   + +
+
+
+
FIRSTLINE = 0x00040000
+
+ + + Source   +Edit   + +
+
+
+
INFO_BACKREFMAX = 3
+
+ + + Source   +Edit   + +
+
+
+
INFO_CAPTURECOUNT = 2
+
+ + + Source   +Edit   + +
+
+
+
INFO_DEFAULT_TABLES = 11
+
+ + + Source   +Edit   + +
+
+
+
INFO_FIRSTBYTE = 4
+
+ + + Source   +Edit   + +
+
+
+
INFO_FIRSTCHAR = 4
+
+ + For backwards compatibility + Source   +Edit   + +
+
+
+
INFO_FIRSTCHARACTER = 19
+
+ + + Source   +Edit   + +
+
+
+
INFO_FIRSTCHARACTERFLAGS = 20
+
+ + + Source   +Edit   + +
+
+
+
INFO_FIRSTTABLE = 5
+
+ + + Source   +Edit   + +
+
+
+
INFO_HASCRORLF = 14
+
+ + + Source   +Edit   + +
+
+
+
INFO_JCHANGED = 13
+
+ + + Source   +Edit   + +
+
+
+
INFO_JIT = 16
+
+ + + Source   +Edit   + +
+
+
+
INFO_JITSIZE = 17
+
+ + + Source   +Edit   + +
+
+
+
INFO_LASTLITERAL = 6
+
+ + + Source   +Edit   + +
+
+
+
INFO_MATCH_EMPTY = 25
+
+ + + Source   +Edit   + +
+
+
+
INFO_MATCHLIMIT = 23
+
+ + + Source   +Edit   + +
+
+
+
INFO_MAXLOOKBEHIND = 18
+
+ + + Source   +Edit   + +
+
+
+
INFO_MINLENGTH = 15
+
+ + + Source   +Edit   + +
+
+
+
INFO_NAMECOUNT = 8
+
+ + + Source   +Edit   + +
+
+
+
INFO_NAMEENTRYSIZE = 7
+
+ + + Source   +Edit   + +
+
+
+
INFO_NAMETABLE = 9
+
+ + + Source   +Edit   + +
+
+
+
INFO_OKPARTIAL = 12
+
+ + + Source   +Edit   + +
+
+
+
INFO_OPTIONS = 0
+
+ + + Source   +Edit   + +
+
+
+
INFO_RECURSIONLIMIT = 24
+
+ + + Source   +Edit   + +
+
+
+
INFO_REQUIREDCHAR = 21
+
+ + + Source   +Edit   + +
+
+
+
INFO_REQUIREDCHARFLAGS = 22
+
+ + + Source   +Edit   + +
+
+
+
INFO_SIZE = 1
+
+ + + Source   +Edit   + +
+
+
+
INFO_STUDYSIZE = 10
+
+ + + Source   +Edit   + +
+
+
+
JAVASCRIPT_COMPAT = 0x02000000
+
+ + + Source   +Edit   + +
+
+
+
MULTILINE = 0x00000002
+
+ + + Source   +Edit   + +
+
+
+
NEVER_UTF = 0x00010000
+
+ + + Source   +Edit   + +
+
+
+
NEWLINE_ANY = 0x00400000
+
+ + + Source   +Edit   + +
+
+
+
NEWLINE_ANYCRLF = 0x00500000
+
+ + + Source   +Edit   + +
+
+
+
NEWLINE_CR = 0x00100000
+
+ + + Source   +Edit   + +
+
+
+
NEWLINE_CRLF = 0x00300000
+
+ + + Source   +Edit   + +
+
+
+
NEWLINE_LF = 0x00200000
+
+ + + Source   +Edit   + +
+
+
+
NO_AUTO_CAPTURE = 0x00001000
+
+ + + Source   +Edit   + +
+
+
+
NO_AUTO_POSSESS = 0x00020000
+
+ + + Source   +Edit   + +
+
+
+
NO_START_OPTIMISE = 0x04000000
+
+ + + Source   +Edit   + +
+
+
+
NO_START_OPTIMIZE = 0x04000000
+
+ + + Source   +Edit   + +
+
+
+
NO_UTF8_CHECK = 0x00002000
+
+ + + Source   +Edit   + +
+
+
+
NO_UTF16_CHECK = 0x00002000
+
+ + + Source   +Edit   + +
+
+
+
NO_UTF32_CHECK = 0x00002000
+
+ + + Source   +Edit   + +
+
+
+
NOTBOL = 0x00000080
+
+ + + Source   +Edit   + +
+
+
+
NOTEMPTY = 0x00000400
+
+ + + Source   +Edit   + +
+
+
+
NOTEMPTY_ATSTART = 0x10000000
+
+ + + Source   +Edit   + +
+
+
+
NOTEOL = 0x00000100
+
+ + + Source   +Edit   + +
+
+
+
PARTIAL = 0x00008000
+
+ + + Source   +Edit   + +
+
+
+
PARTIAL_HARD = 0x08000000
+
+ + + Source   +Edit   + +
+
+
+
PARTIAL_SOFT = 0x00008000
+
+ + + Source   +Edit   + +
+
+
+
PCRE_DATE = "2014-09-26"
+
+ + + Source   +Edit   + +
+
+
+
PCRE_MAJOR = 8
+
+ + + Source   +Edit   + +
+
+
+
PCRE_MINOR = 36
+
+ + + Source   +Edit   + +
+
+
+
PCRE_PRERELEASE = true
+
+ + + Source   +Edit   + +
+
+
+
STUDY_EXTRA_NEEDED = 0x00000008
+
+ + + Source   +Edit   + +
+
+
+
STUDY_JIT_COMPILE = 0x00000001
+
+ + + Source   +Edit   + +
+
+
+
STUDY_JIT_PARTIAL_HARD_COMPILE = 0x00000004
+
+ + + Source   +Edit   + +
+
+
+
STUDY_JIT_PARTIAL_SOFT_COMPILE = 0x00000002
+
+ + + Source   +Edit   + +
+
+
+
UCP = 0x20000000
+
+ + + Source   +Edit   + +
+
+
+
UNGREEDY = 0x00000200
+
+ + + Source   +Edit   + +
+
+
+
UTF8 = 0x00000800
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR0 = 0
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR1 = 1
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR2 = 2
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR3 = 3
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR4 = 4
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR5 = 5
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR6 = 6
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR7 = 7
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR8 = 8
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR9 = 9
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR10 = 10
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR11 = 11
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR12 = 12
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR13 = 13
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR14 = 14
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR15 = 15
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR16 = 16
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR17 = 17
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR18 = 18
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR19 = 19
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR20 = 20
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR21 = 21
+
+ + + Source   +Edit   + +
+
+
+
UTF8_ERR22 = 22
+
+ + + Source   +Edit   + +
+
+
+
UTF16 = 0x00000800
+
+ + + Source   +Edit   + +
+
+
+
UTF16_ERR0 = 0
+
+ + + Source   +Edit   + +
+
+
+
UTF16_ERR1 = 1
+
+ + + Source   +Edit   + +
+
+
+
UTF16_ERR2 = 2
+
+ + + Source   +Edit   + +
+
+
+
UTF16_ERR3 = 3
+
+ + + Source   +Edit   + +
+
+
+
UTF16_ERR4 = 4
+
+ + + Source   +Edit   + +
+
+
+
UTF32 = 0x00000800
+
+ + + Source   +Edit   + +
+
+
+
UTF32_ERR0 = 0
+
+ + + Source   +Edit   + +
+
+
+
UTF32_ERR1 = 1
+
+ + + Source   +Edit   + +
+
+
+
UTF32_ERR2 = 2
+
+ + + Source   +Edit   + +
+
+
+
UTF32_ERR3 = 3
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc assign_jit_stack(extra: ptr ExtraData; callback: JitCallback; data: pointer) {.
+    cdecl, importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc compile(pattern: cstring; options: cint; errptr: ptr cstring;
+             erroffset: ptr cint; tableptr: pointer): ptr Pcre {.cdecl,
+    importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc compile2(pattern: cstring; options: cint; errorcodeptr: ptr cint;
+              errptr: ptr cstring; erroffset: ptr cint; tableptr: pointer): ptr Pcre {.
+    cdecl, importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc config(what: cint; where: pointer): cint {.cdecl, importc: "pcre_$1",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc copy_named_substring(code: ptr Pcre; subject: cstring; ovector: ptr cint;
+                          stringcount: cint; stringname: cstring;
+                          buffer: cstring; buffersize: cint): cint {.cdecl,
+    importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc copy_substring(subject: cstring; ovector: ptr cint; stringcount: cint;
+                    stringnumber: cint; buffer: cstring; buffersize: cint): cint {.
+    cdecl, importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc dfa_exec(code: ptr Pcre; extra: ptr ExtraData; subject: cstring;
+              length: cint; startoffset: cint; options: cint; ovector: ptr cint;
+              ovecsize: cint; workspace: ptr cint; wscount: cint): cint {.cdecl,
+    importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc exec(code: ptr Pcre; extra: ptr ExtraData; subject: cstring; length: cint;
+          startoffset: cint; options: cint; ovector: ptr cint; ovecsize: cint): cint {.
+    cdecl, importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc free_study(extra: ptr ExtraData) {.cdecl, importc: "pcre_$1", ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc free_substring(stringptr: cstring) {.cdecl, importc: "pcre_$1", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc free_substring_list(stringptr: cstringArray) {.cdecl, importc: "pcre_$1",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fullinfo(code: ptr Pcre; extra: ptr ExtraData; what: cint; where: pointer): cint {.
+    cdecl, importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc get_named_substring(code: ptr Pcre; subject: cstring; ovector: ptr cint;
+                         stringcount: cint; stringname: cstring;
+                         stringptr: cstringArray): cint {.cdecl,
+    importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc get_stringnumber(code: ptr Pcre; name: cstring): cint {.cdecl,
+    importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc get_stringtable_entries(code: ptr Pcre; name: cstring; first: cstringArray;
+                             last: cstringArray): cint {.cdecl,
+    importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc get_substring(subject: cstring; ovector: ptr cint; stringcount: cint;
+                   stringnumber: cint; stringptr: cstringArray): cint {.cdecl,
+    importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc get_substring_list(subject: cstring; ovector: ptr cint; stringcount: cint;
+                        listptr: ptr cstringArray): cint {.cdecl,
+    importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc jit_exec(code: ptr Pcre; extra: ptr ExtraData; subject: cstring;
+              length: cint; startoffset: cint; options: cint; ovector: ptr cint;
+              ovecsize: cint; jstack: ptr JitStack): cint {.cdecl,
+    importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc jit_free_unused_memory() {.cdecl, importc: "pcre_$1", ...raises: [], tags: [],
+                                forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc jit_stack_alloc(startsize: cint; maxsize: cint): ptr JitStack {.cdecl,
+    importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc jit_stack_free(stack: ptr JitStack) {.cdecl, importc: "pcre_$1",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc maketables(): pointer {.cdecl, importc: "pcre_$1", ...raises: [], tags: [],
+                             forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pattern_to_host_byte_order(code: ptr Pcre; extra: ptr ExtraData;
+                                tables: pointer): cint {.cdecl,
+    importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc refcount(code: ptr Pcre; adjust: cint): cint {.cdecl, importc: "pcre_$1",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc study(code: ptr Pcre; options: cint; errptr: ptr cstring): ptr ExtraData {.
+    cdecl, importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc study(code: ptr Pcre; options: cint; errptr: var cstring): ptr ExtraData {.
+    ...deprecated, cdecl, importc: "pcre_$1", ...raises: [], tags: [], forbids: [].}
+
+
+ Deprecated +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc version(): cstring {.cdecl, importc: "pcre_$1", ...raises: [], tags: [],
+                          forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/pegs.html b/pegs.html new file mode 100644 index 0000000000000..5d213c1c08612 --- /dev/null +++ b/pegs.html @@ -0,0 +1,1878 @@ + + + + + + + +std/pegs + + + + + + + + + + + + + + + + +
+
+

std/pegs

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Simple PEG (Parsing expression grammar) matching. Uses no memorization, but uses superoperators and symbol inlining to improve performance. Note: Matching performance is hopefully competitive with optimized regular expression engines. +

PEG syntax and semantics

A PEG (Parsing expression grammar) is a simple deterministic grammar, that can be directly used for parsing. The current implementation has been designed as a more powerful replacement for regular expressions. UTF-8 is supported.

+

The notation used for a PEG is similar to that of EBNF:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
notationmeaning
A / ... / ZOrdered choice: Apply expressions A, ..., Z, in this order, to the text ahead, until one of them succeeds and possibly consumes some text. Indicate success if one of expressions succeeded. Otherwise, do not consume any text and indicate failure.
A ... ZSequence: Apply expressions A, ..., Z, in this order, to consume consecutive portions of the text ahead, as long as they succeed. Indicate success if all succeeded. Otherwise, do not consume any text and indicate failure. The sequence's precedence is higher than that of ordered choice: A B / C means (A B) / Z and not A (B / Z).
(E)Grouping: Parenthesis can be used to change operator priority.
{E}Capture: Apply expression E and store the substring that matched E into a capture that can be accessed after the matching process.
{}Empty capture: Delete the last capture. No character is consumed.
$iBack reference to the ith capture. i counts forwards from 1 or backwards (last capture to first) from ^1.
$Anchor: Matches at the end of the input. No character is consumed. Same as !..
^Anchor: Matches at the start of the input. No character is consumed.
&EAnd predicate: Indicate success if expression E matches the text ahead; otherwise indicate failure. Do not consume any text.
!ENot predicate: Indicate failure if expression E matches the text ahead; otherwise indicate success. Do not consume any text.
E+One or more: Apply expression E repeatedly to match the text ahead, as long as it succeeds. Consume the matched text (if any) and indicate success if there was at least one match. Otherwise, indicate failure.
E*Zero or more: Apply expression E repeatedly to match the text ahead, as long as it succeeds. Consume the matched text (if any). Always indicate success.
E?Zero or one: If expression E matches the text ahead, consume it. Always indicate success.
[s]Character class: If the character ahead appears in the string s, consume it and indicate success. Otherwise, indicate failure.
[a-b]Character range: If the character ahead is one from the range a through b, consume it and indicate success. Otherwise, indicate failure.
's'String: If the text ahead is the string s, consume it and indicate success. Otherwise, indicate failure.
i's'String match ignoring case.
y's'String match ignoring style.
v's'Verbatim string match: Use this to override a global \i or \y modifier.
i$jString match ignoring case for back reference.
y$jString match ignoring style for back reference.
v$jVerbatim string match for back reference.
.Any character: If there is a character ahead, consume it and indicate success. Otherwise, (that is, at the end of input) indicate failure.
_Any Unicode character: If there is a UTF-8 character ahead, consume it and indicate success. Otherwise, indicate failure.
@ESearch: Shorthand for (!E .)* E. (Search loop for the pattern E.)
{@} ECaptured Search: Shorthand for {(!E .)*} E. (Search loop for the pattern E.) Everything until and excluding E is captured.
@@ ESame as {@} E.
A <- ERule: Bind the expression E to the nonterminal symbol A. Left recursive rules are not possible and crash the matching engine.
\identifierBuilt-in macro for a longer expression.
\dddCharacter with decimal code ddd.
\", etc.Literal ", etc.
+

Built-in macros

+ + + + + + + + + + + + + + + + + + +
macromeaning
\dany decimal digit: [0-9]
\Dany character that is not a decimal digit: [^0-9]
\sany whitespace character: [ \9-\13]
\Sany character that is not a whitespace character: [^ \9-\13]
\wany "word" character: [a-zA-Z0-9_]
\Wany "non-word" character: [^a-zA-Z0-9_]
\asame as [a-zA-Z]
\Asame as [^a-zA-Z]
\nany newline combination: \10 / \13\10 / \13
\iignore case for matching; use this at the start of the PEG
\yignore style for matching; use this at the start of the PEG
\skip patskip pattern pat before trying to match other tokens; this is useful for whitespace skipping, for example: \skip(\s*) {\ident} ':' {\ident} matches key value pairs ignoring whitespace around the ':'.
\identa standard ASCII identifier: [a-zA-Z_][a-zA-Z_0-9]*
\letterany Unicode letter
\upperany Unicode uppercase letter
\lowerany Unicode lowercase letter
\titleany Unicode title letter
\whiteany Unicode whitespace character

A backslash followed by a letter is a built-in macro, otherwise it is used for ordinary escaping:

+ + + + +
notationmeaning
\\a single backslash
\*same as '*'
\tnot a tabulator, but an (unknown) built-in
+

Supported PEG grammar

The PEG parser implements this grammar (written in PEG syntax):

+
# Example grammar of PEG in PEG syntax.
+# Comments start with '#'.
+# First symbol is the start symbol.
+
+grammar <- rule* / expr
+
+identifier <- [A-Za-z][A-Za-z0-9_]*
+charsetchar <- "\\" . / [^\]]
+charset <- "[" "^"? (charsetchar ("-" charsetchar)?)+ "]"
+stringlit <- identifier? ("\"" ("\\" . / [^"])* "\"" /
+                          "'" ("\\" . / [^'])* "'")
+builtin <- "\\" identifier / [^\13\10]
+
+comment <- '#' @ \n
+ig <- (\s / comment)* # things to ignore
+
+rule <- identifier \s* "<-" expr ig
+identNoArrow <- identifier !(\s* "<-")
+prefixOpr <- ig '&' / ig '!' / ig '@' / ig '{@}' / ig '@@'
+literal <- ig identifier? '$' '^'? [0-9]+ / '$' / '^' /
+           ig identNoArrow /
+           ig charset /
+           ig stringlit /
+           ig builtin /
+           ig '.' /
+           ig '_' /
+           (ig "(" expr ig ")") /
+           (ig "{" expr? ig "}")
+postfixOpr <- ig '?' / ig '*' / ig '+'
+primary <- prefixOpr* (literal postfixOpr*)
+
+# Concatenation has higher priority than choice:
+# ``a b / c`` means ``(a b) / c``
+
+seqExpr <- primary+
+expr <- seqExpr (ig "/" expr)*
+

Note: As a special syntactic extension if the whole PEG is only a single expression, identifiers are not interpreted as non-terminals, but are interpreted as verbatim string:

+

abc =~ peg"abc" # is true

+

So it is not necessary to write peg" 'abc' " in the above example.

+ +

Examples

Check if s matches Nim's "while" keyword:

+

s =~ peg" y'while'"

+

Exchange (key, val)-pairs:

+

"key: val; key2: val2".replacef(peg"{\ident} \s* ':' \s* {\ident}", "$2: $1")

+

Determine the #include'ed files of a C file:

+

for line in lines("myfile.c"):
+  if line =~ peg"""s <- ws '#include' ws '"' {[^"]+} '"' ws
+                   comment <- '/*' @ '*/' / '//' .*
+                   ws <- (comment / \s+)* """:
+    echo matches[0]

+ +

PEG vs regular expression

As a regular expression \[.*\] matches the longest possible text between '[' and ']'. As a PEG it never matches anything, because a PEG is deterministic: .* consumes the rest of the input, so \] never matches. As a PEG this needs to be written as: \[ ( !\] . )* \] (or \[ @ \]).

+

Note that the regular expression does not behave as intended either: in the example * should not be greedy, so \[.*?\] should be used instead.

+ +

PEG construction

There are two ways to construct a PEG in Nim code:

+
  1. Parsing a string into an AST which consists of Peg nodes with the peg proc.
  2. +
  3. Constructing the AST directly with proc calls. This method does not support constructing rules, only simple expressions and is not as convenient. Its only advantage is that it does not pull in the whole PEG parser into your executable.
  4. +
+

+ +
+

Types

+
+
+
Captures = object
+
+ + contains the captured substrings. + Source   +Edit   + +
+
+
+
EInvalidPeg = object of ValueError
+
+ + raised if an invalid PEG has been detected + Source   +Edit   + +
+
+
+
NonTerminal = ref NonTerminalObj
+
+ + + Source   +Edit   + +
+
+
+
NonTerminalFlag = enum
+  ntDeclared, ntUsed
+
+ + + Source   +Edit   + +
+
+
+
Peg {.shallow.} = object
+  case
+  of pkEmpty .. pkWhitespace:
+    nil
+  of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle:
+  of pkChar, pkGreedyRepChar:
+  of pkCharChoice, pkGreedyRepSet:
+  of pkNonTerminal:
+  of pkBackRef .. pkBackRefIgnoreStyle:
+  else:
+
+ + type that represents a PEG + Source   +Edit   + +
+
+
+
PegKind = enum
+  pkEmpty, pkAny,           ## any character (.)
+  pkAnyRune,                ## any Unicode character (_)
+  pkNewLine,                ## CR-LF, LF, CR
+  pkLetter,                 ## Unicode letter
+  pkLower,                  ## Unicode lower case letter
+  pkUpper,                  ## Unicode upper case letter
+  pkTitle,                  ## Unicode title character
+  pkWhitespace,             ## Unicode whitespace character
+  pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle, pkChar, ## single character to match
+  pkCharChoice, pkNonTerminal, pkSequence, ## a b c ... --> Internal DSL: peg(a, b, c)
+  pkOrderedChoice,          ## a / b / ... --> Internal DSL: a / b or /[a, b, c]
+  pkGreedyRep,              ## a*     --> Internal DSL: *a
+                             ## a+     --> (a a*)
+  pkGreedyRepChar,          ## x* where x is a single character (superop)
+  pkGreedyRepSet,           ## [set]* (superop)
+  pkGreedyAny,              ## .* or _* (superop)
+  pkOption,                 ## a?     --> Internal DSL: ?a
+  pkAndPredicate,           ## &a     --> Internal DSL: &a
+  pkNotPredicate,           ## !a     --> Internal DSL: !a
+  pkCapture,                ## {a}    --> Internal DSL: capture(a)
+  pkBackRef,                ## $i     --> Internal DSL: backref(i)
+  pkBackRefIgnoreCase, pkBackRefIgnoreStyle, pkSearch, ## @a     --> Internal DSL: !*a
+  pkCapturedSearch,         ## {@} a  --> Internal DSL: !*\a
+  pkRule,                   ## a <- b
+  pkList,                   ## a, b
+  pkStartAnchor              ## ^      --> Internal DSL: startAnchor()
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
MaxSubpatterns = 20
+
+ + defines the maximum number of subpatterns that can be captured. More subpatterns cannot be captured! + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `!`(a: Peg): Peg {....gcsafe, extern: "npegsNotPredicate", raises: [],
+                        tags: [], forbids: [].}
+
+ + constructs a "not predicate" with the PEG a + Source   +Edit   + +
+
+ +
+
+
+
func `!*`(a: Peg): Peg {....gcsafe, extern: "npegsSearch", raises: [], tags: [],
+                         forbids: [].}
+
+ + constructs a "search" for the PEG a + Source   +Edit   + +
+
+ +
+
+
+
func `!*\`(a: Peg): Peg {....gcsafe, extern: "npgegsCapturedSearch", raises: [],
+                          tags: [], forbids: [].}
+
+ + constructs a "captured search" for the PEG a + Source   +Edit   + +
+
+ +
+
+
+
func `$`(r: Peg): string {....gcsafe, extern: "npegsToString", raises: [],
+                           tags: [], forbids: [].}
+
+ + converts a PEG to its string representation + Source   +Edit   + +
+
+ +
+
+
+
func `&`(a: Peg): Peg {....gcsafe, extern: "npegsAndPredicate", raises: [],
+                        tags: [], forbids: [].}
+
+ + constructs an "and predicate" with the PEG a + Source   +Edit   + +
+
+ +
+
+
+
func `*`(a: Peg): Peg {....gcsafe, extern: "npegsGreedyRep", raises: [], tags: [],
+                        forbids: [].}
+
+ + constructs a "greedy repetition" for the PEG a + Source   +Edit   + +
+
+ +
+
+
+
func `+`(a: Peg): Peg {....gcsafe, extern: "npegsGreedyPosRep", raises: [],
+                        tags: [], forbids: [].}
+
+ + constructs a "greedy positive repetition" with the PEG a + Source   +Edit   + +
+
+ +
+
+
+
func `/`(a: varargs[Peg]): Peg {....gcsafe, extern: "npegsOrderedChoice",
+                                 raises: [], tags: [], forbids: [].}
+
+ + constructs an ordered choice with the PEGs in a + Source   +Edit   + +
+
+ +
+
+
+
func `?`(a: Peg): Peg {....gcsafe, extern: "npegsOptional", raises: [], tags: [],
+                        forbids: [].}
+
+ + constructs an optional for the PEG a + Source   +Edit   + +
+
+ +
+
+
+
func any(): Peg {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + constructs the PEG any character (.) + Source   +Edit   + +
+
+ +
+
+
+
func anyRune(): Peg {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + constructs the PEG any rune (_) + Source   +Edit   + +
+
+ +
+
+
+
func backref(index: range[1 .. MaxSubpatterns]; reverse: bool = false): Peg {.
+    ...gcsafe, extern: "npegs$1", raises: [], tags: [], forbids: [].}
+
+ + constructs a back reference of the given index. index starts counting from 1. reverse specifies whether indexing starts from the end of the capture list. + Source   +Edit   + +
+
+ +
+
+
+
func backrefIgnoreCase(index: range[1 .. MaxSubpatterns]; reverse: bool = false): Peg {.
+    ...gcsafe, extern: "npegs$1", raises: [], tags: [], forbids: [].}
+
+ + constructs a back reference of the given index. index starts counting from 1. reverse specifies whether indexing starts from the end of the capture list. Ignores case for matching. + Source   +Edit   + +
+
+ +
+
+
+
func backrefIgnoreStyle(index: range[1 .. MaxSubpatterns]; reverse: bool = false): Peg {.
+    ...gcsafe, extern: "npegs$1", raises: [], tags: [], forbids: [].}
+
+ + constructs a back reference of the given index. index starts counting from 1. reverse specifies whether indexing starts from the end of the capture list. Ignores style for matching. + Source   +Edit   + +
+
+ +
+
+
+
func bounds(c: Captures; i: range[0 .. 20 - 1]): tuple[first, last: int] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + returns the bounds [first..last] of the i'th capture. + Source   +Edit   + +
+
+ +
+
+
+
func capture(a: Peg = Peg(kind: pkEmpty)): Peg {....gcsafe, extern: "npegsCapture",
+    raises: [], tags: [], forbids: [].}
+
+ + constructs a capture with the PEG a + Source   +Edit   + +
+
+ +
+
+
+
func ch(p: Peg): char {....raises: [], tags: [], forbids: [].}
+
+ + Returns the char representation of a given Peg variant object where present. + Source   +Edit   + +
+
+ +
+
+
+
func charChoice(p: Peg): ref set[char] {....raises: [], tags: [], forbids: [].}
+
+ + Returns the charChoice field of a given Peg variant object where present. + Source   +Edit   + +
+
+ +
+
+
+
func charSet(s: set[char]): Peg {....gcsafe, extern: "npegs$1", raises: [],
+                                  tags: [], forbids: [].}
+
+ + constructs a PEG from a character set s + Source   +Edit   + +
+
+ +
+
+
+
func col(nt: NonTerminal): int {....raises: [], tags: [], forbids: [].}
+
+ + Gets the column number of the definition of the parent Peg object variant of a given NonTerminal. + Source   +Edit   + +
+
+ +
+
+
+
func contains(s: string; pattern: Peg; matches: var openArray[string]; start = 0): bool {.
+    ...gcsafe, extern: "npegs$1Capture", raises: [], tags: [RootEffect],
+    forbids: [].}
+
+ + same as find(s, pattern, matches, start) >= 0 + Source   +Edit   + +
+
+
+
func contains(s: string; pattern: Peg; start = 0): bool {....gcsafe,
+    extern: "npegs$1", raises: [], tags: [RootEffect], forbids: [].}
+
+ + same as find(s, pattern, start) >= 0 + Source   +Edit   + +
+
+ +
+
+
+
func endAnchor(): Peg {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + constructs the PEG $ which matches the end of the input. + Source   +Edit   + +
+
+ +
+
+
+
func endsWith(s: string; suffix: Peg; start = 0): bool {....gcsafe,
+    extern: "npegs$1", raises: [], tags: [RootEffect], forbids: [].}
+
+ + returns true if s ends with the pattern suffix + Source   +Edit   + +
+
+ +
+
+
+
func escapePeg(s: string): string {....raises: [], tags: [], forbids: [].}
+
+ + escapes s so that it is matched verbatim when used as a peg. + Source   +Edit   + +
+
+ +
+
+
+
func find(s: string; pattern: Peg; matches: var openArray[string]; start = 0): int {.
+    ...gcsafe, extern: "npegs$1Capture", raises: [], tags: [RootEffect],
+    forbids: [].}
+
+ + returns the starting position of pattern in s and the captured substrings in the array matches. If it does not match, nothing is written into matches and -1 is returned. + Source   +Edit   + +
+
+
+
func find(s: string; pattern: Peg; start = 0): int {....gcsafe, extern: "npegs$1",
+    raises: [], tags: [RootEffect], forbids: [].}
+
+ + returns the starting position of pattern in s. If it does not match, -1 is returned. + Source   +Edit   + +
+
+ +
+
+
+
func findAll(s: string; pattern: Peg; start = 0): seq[string] {....gcsafe,
+    extern: "npegs$1", raises: [], tags: [RootEffect], forbids: [].}
+
+ + returns all matching substrings of s that match pattern. If it does not match, @[] is returned. + Source   +Edit   + +
+
+ +
+
+
+
func findBounds(s: string; pattern: Peg; matches: var openArray[string];
+                start = 0): tuple[first, last: int] {....gcsafe,
+    extern: "npegs$1Capture", raises: [], tags: [RootEffect], forbids: [].}
+
+ + returns the starting position and end position of pattern in s and the captured substrings in the array matches. If it does not match, nothing is written into matches and (-1,0) is returned. + Source   +Edit   + +
+
+ +
+
+
+
func flags(nt: NonTerminal): set[NonTerminalFlag] {....raises: [], tags: [],
+    forbids: [].}
+
+ + Gets the NonTerminalFlag-typed flags field of the parent Peg variant object of a given NonTerminal. + Source   +Edit   + +
+
+ +
+
+
+
func index(p: Peg): range[-20 .. 20 - 1] {....raises: [], tags: [], forbids: [].}
+
+ + Returns the back-reference index of a captured sub-pattern in the Captures object for a given Peg variant object where present. + Source   +Edit   + +
+
+ +
+
+
+
func kind(p: Peg): PegKind {....raises: [], tags: [], forbids: [].}
+
+ + Returns the PegKind of a given Peg object. + Source   +Edit   + +
+
+ +
+
+
+
func line(nt: NonTerminal): int {....raises: [], tags: [], forbids: [].}
+
+ + Gets the line number of the definition of the parent Peg object variant of a given NonTerminal. + Source   +Edit   + +
+
+ +
+
+
+
func match(s: string; pattern: Peg; matches: var openArray[string]; start = 0): bool {.
+    ...gcsafe, extern: "npegs$1Capture", raises: [], tags: [RootEffect],
+    forbids: [].}
+
+ + returns true if s[start..] matches the pattern and the captured substrings in the array matches. If it does not match, nothing is written into matches and false is returned. + Source   +Edit   + +
+
+
+
func match(s: string; pattern: Peg; start = 0): bool {....gcsafe,
+    extern: "npegs$1", raises: [], tags: [RootEffect], forbids: [].}
+
+ + returns true if s matches the pattern beginning from start. + Source   +Edit   + +
+
+ +
+
+
+
func matchLen(s: string; pattern: Peg; matches: var openArray[string]; start = 0): int {.
+    ...gcsafe, extern: "npegs$1Capture", raises: [], tags: [RootEffect],
+    forbids: [].}
+
+ + the same as match, but it returns the length of the match, if there is no match, -1 is returned. Note that a match length of zero can happen. It's possible that a suffix of s remains that does not belong to the match. + Source   +Edit   + +
+
+
+
func matchLen(s: string; pattern: Peg; start = 0): int {....gcsafe,
+    extern: "npegs$1", raises: [], tags: [RootEffect], forbids: [].}
+
+ + the same as match, but it returns the length of the match, if there is no match, -1 is returned. Note that a match length of zero can happen. It's possible that a suffix of s remains that does not belong to the match. + Source   +Edit   + +
+
+ +
+
+
+
func name(nt: NonTerminal): string {....raises: [], tags: [], forbids: [].}
+
+ + Gets the name of the symbol represented by the parent Peg object variant of a given NonTerminal. + Source   +Edit   + +
+
+ +
+
+
+
func newLine(): Peg {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + constructs the PEG newline (\n) + Source   +Edit   + +
+
+ +
+
+
+
func newNonTerminal(name: string; line, column: int): NonTerminal {....gcsafe,
+    extern: "npegs$1", raises: [], tags: [], forbids: [].}
+
+ + constructs a nonterminal symbol + Source   +Edit   + +
+
+ +
+
+
+
func nonterminal(n: NonTerminal): Peg {....gcsafe, extern: "npegs$1", raises: [],
+                                        tags: [], forbids: [].}
+
+ + constructs a PEG that consists of the nonterminal symbol + Source   +Edit   + +
+
+ +
+
+
+
func nt(p: Peg): NonTerminal {....raises: [], tags: [], forbids: [].}
+
+ + Returns the NonTerminal object of a given Peg variant object where present. + Source   +Edit   + +
+
+ +
+
+
+
func parallelReplace(s: string; subs: varargs[tuple[pattern: Peg, repl: string]]): string {.
+    ...gcsafe, extern: "npegs$1", raises: [ValueError], tags: [RootEffect],
+    forbids: [].}
+
+ + Returns a modified copy of s with the substitutions in subs applied in parallel. + Source   +Edit   + +
+
+ +
+
+
+
func parsePeg(pattern: string; filename = "pattern"; line = 1; col = 0): Peg {.
+    ...raises: [ValueError, EInvalidPeg, Exception], tags: [RootEffect],
+    forbids: [].}
+
+ + constructs a Peg object from pattern. filename, line, col are used for error messages, but they only provide start offsets. parsePeg keeps track of line and column numbers within pattern. + Source   +Edit   + +
+
+ +
+
+
+
func peg(pattern: string): Peg {....raises: [ValueError, EInvalidPeg, Exception],
+                                 tags: [RootEffect], forbids: [].}
+
+ + constructs a Peg object from the pattern. The short name has been chosen to encourage its use as a raw string modifier:
peg"{\ident} \s* '=' \s* {.*}"
+ + Source   +Edit   + +
+
+ +
+
+
+
func rawMatch(s: string; p: Peg; start: int; c: var Captures): int {....gcsafe,
+    extern: "npegs$1", raises: [], tags: [RootEffect], forbids: [].}
+
+ + low-level matching proc that implements the PEG interpreter. Use this for maximum efficiency (every other PEG operation ends up calling this proc). Returns -1 if it does not match, else the length of the match + Source   +Edit   + +
+
+ +
+
+
+
func replace(s: string; sub: Peg;
+             cb: proc (match: int; cnt: int; caps: openArray[string]): string): string {.
+    ...gcsafe, extern: "npegs$1cb", effectsOf: cb, ...raises: [], tags: [RootEffect],
+    forbids: [].}
+
+ +

Replaces sub in s by the resulting strings from the callback. The callback proc receives the index of the current match (starting with 0), the count of captures and an open array with the captures of each match. Examples:

+

func handleMatches*(m: int, n: int, c: openArray[string]): string =
+  result = ""
+  if m > 0:
+    result.add ", "
+  result.add case n:
+    of 2: c[0].toLower & ": '" & c[1] & "'"
+    of 1: c[0].toLower & ": ''"
+    else: ""
+
+let s = "Var1=key1;var2=Key2;   VAR3"
+echo s.replace(peg"{\ident}('='{\ident})* ';'* \s*", handleMatches)

+

Results in:

+

"var1: 'key1', var2: 'Key2', var3: ''"

+ + Source   +Edit   + +
+
+
+
func replace(s: string; sub: Peg; by = ""): string {....gcsafe, extern: "npegs$1",
+    raises: [], tags: [RootEffect], forbids: [].}
+
+ + Replaces sub in s by the string by. Captures cannot be accessed in by. + Source   +Edit   + +
+
+ +
+
+
+
func replacef(s: string; sub: Peg; by: string): string {....gcsafe,
+    extern: "npegs$1", raises: [ValueError], tags: [RootEffect], forbids: [].}
+
+ +

Replaces sub in s by the string by. Captures can be accessed in by with the notation $i and $# (see strutils.%). Examples:

+

"var1=key; var2=key2".replacef(peg"{\ident}'='{\ident}", "$1<-$2$2")

+

Results in:

+

"var1<-keykey; val2<-key2key2"

+ + Source   +Edit   + +
+
+ +
+
+
+
func rule(nt: NonTerminal): Peg {....raises: [], tags: [], forbids: [].}
+
+ + Gets the Peg object representing the rule definition of the parent Peg object variant of a given NonTerminal. + Source   +Edit   + +
+
+ +
+
+
+
func sequence(a: varargs[Peg]): Peg {....gcsafe, extern: "npegs$1", raises: [],
+                                      tags: [], forbids: [].}
+
+ + constructs a sequence with all the PEGs from a + Source   +Edit   + +
+
+ +
+
+
+
func split(s: string; sep: Peg): seq[string] {....gcsafe, extern: "npegs$1",
+    raises: [], tags: [RootEffect], forbids: [].}
+
+ + Splits the string s into substrings. + Source   +Edit   + +
+
+ +
+
+
+
func startAnchor(): Peg {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + constructs the PEG ^ which matches the start of the input. + Source   +Edit   + +
+
+ +
+
+
+
func startsWith(s: string; prefix: Peg; start = 0): bool {....gcsafe,
+    extern: "npegs$1", raises: [], tags: [RootEffect], forbids: [].}
+
+ + returns true if s starts with the pattern prefix + Source   +Edit   + +
+
+ +
+
+
+
func term(p: Peg): string {....raises: [], tags: [], forbids: [].}
+
+ + Returns the string representation of a given Peg variant object where present. + Source   +Edit   + +
+
+
+
func term(t: char): Peg {....gcsafe, extern: "npegs$1Char", raises: [], tags: [],
+                          forbids: [].}
+
+ + constructs a PEG from a terminal char + Source   +Edit   + +
+
+
+
func term(t: string): Peg {....gcsafe, extern: "npegs$1Str", raises: [], tags: [],
+                            forbids: [].}
+
+ + constructs a PEG from a terminal string + Source   +Edit   + +
+
+ +
+
+
+
func termIgnoreCase(t: string): Peg {....gcsafe, extern: "npegs$1", raises: [],
+                                      tags: [], forbids: [].}
+
+ + constructs a PEG from a terminal string; ignore case for matching + Source   +Edit   + +
+
+ +
+
+
+
func termIgnoreStyle(t: string): Peg {....gcsafe, extern: "npegs$1", raises: [],
+                                       tags: [], forbids: [].}
+
+ + constructs a PEG from a terminal string; ignore style for matching + Source   +Edit   + +
+
+ +
+
+
+
proc transformFile(infile, outfile: string;
+                   subs: varargs[tuple[pattern: Peg, repl: string]]) {....gcsafe,
+    extern: "npegs$1", raises: [IOError, ValueError],
+    tags: [ReadIOEffect, WriteIOEffect, RootEffect], forbids: [].}
+
+ +

reads in the file infile, performs a parallel replacement (calls parallelReplace) and writes back to outfile. Raises IOError if an error occurs. This is supposed to be used for quick scripting.

+

Note: this proc does not exist while using the JS backend.

+ + Source   +Edit   + +
+
+ +
+
+
+
func unicodeLetter(): Peg {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + constructs the PEG \letter which matches any Unicode letter. + Source   +Edit   + +
+
+ +
+
+
+
func unicodeLower(): Peg {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + constructs the PEG \lower which matches any Unicode lowercase letter. + Source   +Edit   + +
+
+ +
+
+
+
func unicodeTitle(): Peg {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + constructs the PEG \title which matches any Unicode title letter. + Source   +Edit   + +
+
+ +
+
+
+
func unicodeUpper(): Peg {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + constructs the PEG \upper which matches any Unicode uppercase letter. + Source   +Edit   + +
+
+ +
+
+
+
func unicodeWhitespace(): Peg {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + constructs the PEG \white which matches any Unicode whitespace character. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator findAll(s: string; pattern: Peg; start = 0): string {....raises: [],
+    tags: [RootEffect], forbids: [].}
+
+ + yields all matching substrings of s that match pattern. + Source   +Edit   + +
+
+ +
+
+
+
iterator items(p: Peg): Peg {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Yields the child nodes of a Peg variant object where present. + Source   +Edit   + +
+
+ +
+
+
+
iterator pairs(p: Peg): (int, Peg) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Yields the indices and child nodes of a Peg variant object where present. + Source   +Edit   + +
+
+ +
+
+
+
iterator split(s: string; sep: Peg): string {....raises: [], tags: [RootEffect],
+    forbids: [].}
+
+ +

Splits the string s into substrings.

+

Substrings are separated by the PEG sep. Examples:

+

for word in split("00232this02939is39an22example111", peg"\d+"):
+  writeLine(stdout, word)

+

Results in:

+

"this"
+"is"
+"an"
+"example"

+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template `=~`(s: string; pattern: Peg): bool
+
+ +

This calls match with an implicit declared matches array that can be used in the scope of the =~ call:

+

if line =~ peg"\s* {\w+} \s* '=' \s* {\w+}":
+  # matches a key=value pair:
+  echo("Key: ", matches[0])
+  echo("Value: ", matches[1])
+elif line =~ peg"\s*{'#'.*}":
+  # matches a comment
+  # note that the implicit ``matches`` array is different from the
+  # ``matches`` array of the first branch
+  echo("comment: ", matches[0])
+else:
+  echo("syntax error")

+ + Source   +Edit   + +
+
+ +
+
+
+
template digits(): Peg
+
+ + expands to charset({'0'..'9'}) + Source   +Edit   + +
+
+ +
+
+
+
template eventParser(pegAst, handlers: untyped): (proc (s: string): int)
+
+ +

Generates an interpreting event parser proc according to the specified PEG AST and handler code blocks. The proc can be called with a string to be parsed and will execute the handler code blocks whenever their associated grammar element is matched. It returns -1 if the string does not match, else the length of the total match. The following example code evaluates an arithmetic expression defined by a simple PEG:

+

import std/[strutils, pegs]
+
+let
+  pegAst = """
+Expr    <- Sum
+Sum     <- Product (('+' / '-')Product)*
+Product <- Value (('*' / '/')Value)*
+Value   <- [0-9]+ / '(' Expr ')'
+  """.peg
+  txt = "(5+3)/2-7*22"
+
+var
+  pStack: seq[string] = @[]
+  valStack: seq[float] = @[]
+  opStack = ""
+let
+  parseArithExpr = pegAst.eventParser:
+    pkNonTerminal:
+      enter:
+        pStack.add p.nt.name
+      leave:
+        pStack.setLen pStack.high
+        if length > 0:
+          let matchStr = s.substr(start, start+length-1)
+          case p.nt.name
+          of "Value":
+            try:
+              valStack.add matchStr.parseFloat
+              echo valStack
+            except ValueError:
+              discard
+          of "Sum", "Product":
+            try:
+              let val = matchStr.parseFloat
+            except ValueError:
+              if valStack.len > 1 and opStack.len > 0:
+                valStack[^2] = case opStack[^1]
+                of '+': valStack[^2] + valStack[^1]
+                of '-': valStack[^2] - valStack[^1]
+                of '*': valStack[^2] * valStack[^1]
+                else: valStack[^2] / valStack[^1]
+                valStack.setLen valStack.high
+                echo valStack
+                opStack.setLen opStack.high
+                echo opStack
+    pkChar:
+      leave:
+        if length == 1 and "Value" != pStack[^1]:
+          let matchChar = s[start]
+          opStack.add matchChar
+          echo opStack
+
+let pLen = parseArithExpr(txt)

+

The handlers parameter consists of code blocks for PegKinds, which define the grammar elements of interest. Each block can contain handler code to be executed when the parser enters and leaves text matching the grammar element. An enter handler can access the specific PEG AST node being matched as p, the entire parsed string as s and the position of the matched text segment in s as start. A leave handler can access p, s, start and also the length of the matched text segment as length. For an unsuccessful match, the enter and leave handlers will be executed, with length set to -1.

+

Symbols declared in an enter handler can be made visible in the corresponding leave handler by annotating them with an inject pragma.

+ + Source   +Edit   + +
+
+ +
+
+
+
template ident(): Peg
+
+ + same as [a-zA-Z_][a-zA-z_0-9]*; standard identifier + Source   +Edit   + +
+
+ +
+
+
+
template identChars(): Peg
+
+ + expands to charset({'a'..'z', 'A'..'Z', '0'..'9', '_'}) + Source   +Edit   + +
+
+ +
+
+
+
template identStartChars(): Peg
+
+ + expands to charset({'A'..'Z', 'a'..'z', '_'}) + Source   +Edit   + +
+
+ +
+
+
+
template letters(): Peg
+
+ + expands to charset({'A'..'Z', 'a'..'z'}) + Source   +Edit   + +
+
+ +
+
+
+
template natural(): Peg
+
+ + same as \d+ + Source   +Edit   + +
+
+ +
+
+
+
template whitespace(): Peg
+
+ + expands to charset({' ', '\9'..'\13'}) + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/pegs.idx b/pegs.idx new file mode 100644 index 0000000000000..8d7a362cc33d8 --- /dev/null +++ b/pegs.idx @@ -0,0 +1,136 @@ +nimTitle pegs pegs.html module std/pegs 0 +nim MaxSubpatterns pegs.html#MaxSubpatterns const MaxSubpatterns 34 +nim pkEmpty pegs.html#pkEmpty PegKind.pkEmpty 38 +nim pkAny pegs.html#pkAny PegKind.pkAny 38 +nim pkAnyRune pegs.html#pkAnyRune PegKind.pkAnyRune 38 +nim pkNewLine pegs.html#pkNewLine PegKind.pkNewLine 38 +nim pkLetter pegs.html#pkLetter PegKind.pkLetter 38 +nim pkLower pegs.html#pkLower PegKind.pkLower 38 +nim pkUpper pegs.html#pkUpper PegKind.pkUpper 38 +nim pkTitle pegs.html#pkTitle PegKind.pkTitle 38 +nim pkWhitespace pegs.html#pkWhitespace PegKind.pkWhitespace 38 +nim pkTerminal pegs.html#pkTerminal PegKind.pkTerminal 38 +nim pkTerminalIgnoreCase pegs.html#pkTerminalIgnoreCase PegKind.pkTerminalIgnoreCase 38 +nim pkTerminalIgnoreStyle pegs.html#pkTerminalIgnoreStyle PegKind.pkTerminalIgnoreStyle 38 +nim pkChar pegs.html#pkChar PegKind.pkChar 38 +nim pkCharChoice pegs.html#pkCharChoice PegKind.pkCharChoice 38 +nim pkNonTerminal pegs.html#pkNonTerminal PegKind.pkNonTerminal 38 +nim pkSequence pegs.html#pkSequence PegKind.pkSequence 38 +nim pkOrderedChoice pegs.html#pkOrderedChoice PegKind.pkOrderedChoice 38 +nim pkGreedyRep pegs.html#pkGreedyRep PegKind.pkGreedyRep 38 +nim pkGreedyRepChar pegs.html#pkGreedyRepChar PegKind.pkGreedyRepChar 38 +nim pkGreedyRepSet pegs.html#pkGreedyRepSet PegKind.pkGreedyRepSet 38 +nim pkGreedyAny pegs.html#pkGreedyAny PegKind.pkGreedyAny 38 +nim pkOption pegs.html#pkOption PegKind.pkOption 38 +nim pkAndPredicate pegs.html#pkAndPredicate PegKind.pkAndPredicate 38 +nim pkNotPredicate pegs.html#pkNotPredicate PegKind.pkNotPredicate 38 +nim pkCapture pegs.html#pkCapture PegKind.pkCapture 38 +nim pkBackRef pegs.html#pkBackRef PegKind.pkBackRef 38 +nim pkBackRefIgnoreCase pegs.html#pkBackRefIgnoreCase PegKind.pkBackRefIgnoreCase 38 +nim pkBackRefIgnoreStyle pegs.html#pkBackRefIgnoreStyle PegKind.pkBackRefIgnoreStyle 38 +nim pkSearch pegs.html#pkSearch PegKind.pkSearch 38 +nim pkCapturedSearch pegs.html#pkCapturedSearch PegKind.pkCapturedSearch 38 +nim pkRule pegs.html#pkRule PegKind.pkRule 38 +nim pkList pegs.html#pkList PegKind.pkList 38 +nim pkStartAnchor pegs.html#pkStartAnchor PegKind.pkStartAnchor 38 +nim PegKind pegs.html#PegKind enum PegKind 38 +nim ntDeclared pegs.html#ntDeclared NonTerminalFlag.ntDeclared 73 +nim ntUsed pegs.html#ntUsed NonTerminalFlag.ntUsed 73 +nim NonTerminalFlag pegs.html#NonTerminalFlag enum NonTerminalFlag 73 +nim Peg pegs.html#Peg object Peg 81 +nim NonTerminal pegs.html#NonTerminal type NonTerminal 90 +nim kind pegs.html#kind,Peg proc kind(p: Peg): PegKind 92 +nim term pegs.html#term,Peg proc term(p: Peg): string 95 +nim ch pegs.html#ch,Peg proc ch(p: Peg): char 99 +nim charChoice pegs.html#charChoice,Peg proc charChoice(p: Peg): ref set[char] 103 +nim nt pegs.html#nt,Peg proc nt(p: Peg): NonTerminal 107 +nim index pegs.html#index,Peg proc index(p: Peg): range[-20 .. 20 - 1] 111 +nim items pegs.html#items.i,Peg iterator items(p: Peg): Peg 115 +nim pairs pegs.html#pairs.i,Peg iterator pairs(p: Peg): (int, Peg) 120 +nim name pegs.html#name,NonTerminal proc name(nt: NonTerminal): string 125 +nim line pegs.html#line,NonTerminal proc line(nt: NonTerminal): int 129 +nim col pegs.html#col,NonTerminal proc col(nt: NonTerminal): int 133 +nim flags pegs.html#flags,NonTerminal proc flags(nt: NonTerminal): set[NonTerminalFlag] 137 +nim rule pegs.html#rule,NonTerminal proc rule(nt: NonTerminal): Peg 141 +nim term pegs.html#term,string proc term(t: string): Peg 145 +nim termIgnoreCase pegs.html#termIgnoreCase,string proc termIgnoreCase(t: string): Peg 152 +nim termIgnoreStyle pegs.html#termIgnoreStyle,string proc termIgnoreStyle(t: string): Peg 157 +nim term pegs.html#term,char proc term(t: char): Peg 162 +nim charSet pegs.html#charSet,set[char] proc charSet(s: set[char]): Peg 167 +nim `/` pegs.html#/,varargs[Peg] proc `/`(a: varargs[Peg]): Peg 201 +nim sequence pegs.html#sequence,varargs[Peg] proc sequence(a: varargs[Peg]): Peg 218 +nim `?` pegs.html#?,Peg proc `?`(a: Peg): Peg 223 +nim `*` pegs.html#*,Peg proc `*`(a: Peg): Peg 233 +nim `!*` pegs.html#!*,Peg proc `!*`(a: Peg): Peg 248 +nim `!*\` pegs.html#!*\,Peg proc `!*\`(a: Peg): Peg 252 +nim `+` pegs.html#+,Peg proc `+`(a: Peg): Peg 257 +nim `&` pegs.html#&,Peg proc `&`(a: Peg): Peg 261 +nim `!` pegs.html#!,Peg proc `!`(a: Peg): Peg 265 +nim any pegs.html#any proc any(): Peg 269 +nim anyRune pegs.html#anyRune proc anyRune(): Peg 273 +nim newLine pegs.html#newLine proc newLine(): Peg 277 +nim unicodeLetter pegs.html#unicodeLetter proc unicodeLetter(): Peg 281 +nim unicodeLower pegs.html#unicodeLower proc unicodeLower(): Peg 285 +nim unicodeUpper pegs.html#unicodeUpper proc unicodeUpper(): Peg 289 +nim unicodeTitle pegs.html#unicodeTitle proc unicodeTitle(): Peg 293 +nim unicodeWhitespace pegs.html#unicodeWhitespace proc unicodeWhitespace(): Peg 297 +nim startAnchor pegs.html#startAnchor proc startAnchor(): Peg 302 +nim endAnchor pegs.html#endAnchor proc endAnchor(): Peg 306 +nim capture pegs.html#capture,Peg proc capture(a: Peg = Peg(kind: pkEmpty)): Peg 310 +nim backref pegs.html#backref,range[],bool proc backref(index: range[1 .. MaxSubpatterns]; reverse: bool = false): Peg 314 +nim backrefIgnoreCase pegs.html#backrefIgnoreCase,range[],bool proc backrefIgnoreCase(index: range[1 .. MaxSubpatterns]; reverse: bool = false): Peg 321 +nim backrefIgnoreStyle pegs.html#backrefIgnoreStyle,range[],bool proc backrefIgnoreStyle(index: range[1 .. MaxSubpatterns]; reverse: bool = false): Peg 328 +nim nonterminal pegs.html#nonterminal,NonTerminal proc nonterminal(n: NonTerminal): Peg 350 +nim newNonTerminal pegs.html#newNonTerminal,string,int,int proc newNonTerminal(name: string; line, column: int): NonTerminal 360 +nim letters pegs.html#letters.t template letters(): Peg 365 +nim digits pegs.html#digits.t template digits(): Peg 369 +nim whitespace pegs.html#whitespace.t template whitespace(): Peg 373 +nim identChars pegs.html#identChars.t template identChars(): Peg 377 +nim identStartChars pegs.html#identStartChars.t template identStartChars(): Peg 381 +nim ident pegs.html#ident.t template ident(): Peg 385 +nim natural pegs.html#natural.t template natural(): Peg 390 +nim `$` pegs.html#$,Peg proc `$`(r: Peg): string 528 +nim Captures pegs.html#Captures object Captures 536 +nim bounds pegs.html#bounds,Captures,range[] proc bounds(c: Captures; i: range[0 .. 20 - 1]): tuple[first, last: int] 541 +nim rawMatch pegs.html#rawMatch,string,Peg,int,Captures proc rawMatch(s: string; p: Peg; start: int; c: var Captures): int 871 +nim eventParser pegs.html#eventParser.t,untyped,untyped template eventParser(pegAst, handlers: untyped): (proc (s: string): int) 957 +nim matchLen pegs.html#matchLen,string,Peg,openArray[string],int proc matchLen(s: string; pattern: Peg; matches: var openArray[string]; start = 0): int 1086 +nim matchLen pegs.html#matchLen,string,Peg,int proc matchLen(s: string; pattern: Peg; start = 0): int 1097 +nim match pegs.html#match,string,Peg,openArray[string],int proc match(s: string; pattern: Peg; matches: var openArray[string]; start = 0): bool 1107 +nim match pegs.html#match,string,Peg,int proc match(s: string; pattern: Peg; start = 0): bool 1115 +nim find pegs.html#find,string,Peg,openArray[string],int proc find(s: string; pattern: Peg; matches: var openArray[string]; start = 0): int 1121 +nim findBounds pegs.html#findBounds,string,Peg,openArray[string],int proc findBounds(s: string; pattern: Peg; matches: var openArray[string]; start = 0): tuple[\n first, last: int] 1136 +nim find pegs.html#find,string,Peg,int proc find(s: string; pattern: Peg; start = 0): int 1153 +nim findAll pegs.html#findAll.i,string,Peg,int iterator findAll(s: string; pattern: Peg; start = 0): string 1163 +nim findAll pegs.html#findAll,string,Peg,int proc findAll(s: string; pattern: Peg; start = 0): seq[string] 1177 +nim `=~` pegs.html#=~.t,string,Peg template `=~`(s: string; pattern: Peg): bool 1184 +nim contains pegs.html#contains,string,Peg,int proc contains(s: string; pattern: Peg; start = 0): bool 1208 +nim contains pegs.html#contains,string,Peg,openArray[string],int proc contains(s: string; pattern: Peg; matches: var openArray[string]; start = 0): bool 1213 +nim startsWith pegs.html#startsWith,string,Peg,int proc startsWith(s: string; prefix: Peg; start = 0): bool 1218 +nim endsWith pegs.html#endsWith,string,Peg,int proc endsWith(s: string; suffix: Peg; start = 0): bool 1223 +nim replacef pegs.html#replacef,string,Peg,string proc replacef(s: string; sub: Peg; by: string): string 1231 +nim replace pegs.html#replace,string,Peg,string proc replace(s: string; sub: Peg; by = ""): string 1261 +nim parallelReplace pegs.html#parallelReplace,string,varargs[tuple[Peg,string]] proc parallelReplace(s: string; subs: varargs[tuple[pattern: Peg, repl: string]]): string 1278 +nim replace pegs.html#replace,string,Peg,proc(int,int,openArray[string]) proc replace(s: string; sub: Peg;\n cb: proc (match: int; cnt: int; caps: openArray[string]): string): string 1305 +nim transformFile pegs.html#transformFile,string,string,varargs[tuple[Peg,string]] proc transformFile(infile, outfile: string;\n subs: varargs[tuple[pattern: Peg, repl: string]]) 1350 +nim split pegs.html#split.i,string,Peg iterator split(s: string; sep: Peg): string 1362 +nim split pegs.html#split,string,Peg proc split(s: string; sep: Peg): seq[string] 1398 +nim EInvalidPeg pegs.html#EInvalidPeg object EInvalidPeg 1821 +nim parsePeg pegs.html#parsePeg,string,string,int,int proc parsePeg(pattern: string; filename = "pattern"; line = 1; col = 0): Peg 2051 +nim peg pegs.html#peg,string proc peg(pattern: string): Peg 2066 +nim escapePeg pegs.html#escapePeg,string proc escapePeg(s: string): string 2073 +heading PEG syntax and semantics pegs.html#peg-syntax-and-semantics PEG syntax and semantics 0 +heading Built-in macros pegs.html#peg-syntax-and-semantics-builtminusin-macros Built-in macros 0 +heading Supported PEG grammar pegs.html#peg-syntax-and-semantics-supported-peg-grammar Supported PEG grammar 0 +heading Examples pegs.html#peg-syntax-and-semantics-examples Examples 0 +heading PEG vs regular expression pegs.html#peg-syntax-and-semantics-peg-vs-regular-expression PEG vs regular expression 0 +heading PEG construction pegs.html#peg-syntax-and-semantics-peg-construction PEG construction 0 +idx any rune pegs.html#any-rune_1 PEG construction 0 +idx newline pegs.html#newline_1 PEG construction 0 +idx any character pegs.html#any-character_1 PEG construction 0 +nimgrp replace pegs.html#replace-procs-all proc 1261 +nimgrp match pegs.html#match-procs-all proc 1107 +nimgrp find pegs.html#find-procs-all proc 1121 +nimgrp contains pegs.html#contains-procs-all proc 1208 +nimgrp term pegs.html#term-procs-all proc 95 +nimgrp matchlen pegs.html#matchLen-procs-all proc 1086 diff --git a/posix.html b/posix.html new file mode 100644 index 0000000000000..5904da9c77b74 --- /dev/null +++ b/posix.html @@ -0,0 +1,18407 @@ + + + + + + + +std/posix + + + + + + + + + + + + + + + + +
+
+

std/posix

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This is a raw POSIX interface module. It does not not provide any convenience: cstrings are used instead of proper Nim strings and return codes indicate errors. If you want exceptions and a proper Nim-like interface, use the OS module or write a wrapper.

+

For high-level wrappers specialized for Linux and BSDs see: posix_utils

+

Coding conventions: ALL types are named the same as in the POSIX standard except that they start with 'T' or 'P' (if they are pointers) and without the '_t' suffix to be consistent with Nim conventions. If an identifier is a Nim keyword the `identifier` notation is used.

+

This library relies on the header files of your C compiler. The resulting C code will just #include <XYZ.h> and not define the symbols declared here.

+

+
+

Imports

+
+ syncio +
+
+
+

Types

+
+
+
AddrInfo {.importc: "struct addrinfo", pure, final, header: "<netdb.h>".} = object
+  ai_flags*: cint            ## Input flags.
+  ai_family*: cint           ## Address family of socket.
+  ai_socktype*: cint         ## Socket type.
+  ai_protocol*: cint         ## Protocol of socket.
+  ai_addrlen*: SockLen       ## Length of socket address.
+  ai_addr*: ptr SockAddr     ## Socket address of socket.
+  ai_canonname*: cstring     ## Canonical name of service location.
+  ai_next*: ptr AddrInfo     ## Pointer to next in list.
+
+ + struct addrinfo + Source   +Edit   + +
+
+
+
Blkcnt {.importc: "blkcnt_t", header: "<sys/types.h>".} = clong
+
+ + used for file block counts + Source   +Edit   + +
+
+
+
Blksize {.importc: "blksize_t", header: "<sys/types.h>".} = clong
+
+ + used for block sizes + Source   +Edit   + +
+
+
+
Clock {.importc: "clock_t", header: "<sys/types.h>".} = clong
+
+ + + Source   +Edit   + +
+
+
+
ClockId {.importc: "clockid_t", header: "<sys/types.h>".} = cint
+
+ + + Source   +Edit   + +
+
+
+
Dev {.importc: "dev_t", header: "<sys/types.h>".} = culong
+
+ + + Source   +Edit   + +
+
+
+
DIR {.importc: "DIR", header: "<dirent.h>", incompleteStruct.} = object
+
+ + A type representing a directory stream. + Source   +Edit   + +
+
+
+
Dirent {.importc: "struct dirent", header: "<dirent.h>", final, pure.} = object
+  d_ino*: Ino
+  d_off*: Off
+  d_reclen*: cushort
+  d_type*: int8
+  d_name*: array[256, cchar]
+
+ + dirent_t struct + Source   +Edit   + +
+
+
+
Fsblkcnt {.importc: "fsblkcnt_t", header: "<sys/types.h>".} = culong
+
+ + + Source   +Edit   + +
+
+
+
Fsfilcnt {.importc: "fsfilcnt_t", header: "<sys/types.h>".} = culong
+
+ + + Source   +Edit   + +
+
+
+
Gid {.importc: "gid_t", header: "<sys/types.h>".} = cuint
+
+ + + Source   +Edit   + +
+
+
+
Glob {.importc: "glob_t", header: "<glob.h>", final, pure.} = object
+  gl_pathc*: csize_t         ## Count of paths matched by pattern.
+  gl_pathv*: cstringArray    ## Pointer to a list of matched pathnames.
+  gl_offs*: csize_t          ## Slots to reserve at the beginning of gl_pathv.
+  gl_flags*: cint
+  gl_closedir*: pointer
+  gl_readdir*: pointer
+  gl_opendir*: pointer
+  gl_lstat*: pointer
+  gl_stat*: pointer
+
+ + glob_t + Source   +Edit   + +
+
+
+
Group {.importc: "struct group", header: "<grp.h>", final, pure.} = object
+  gr_name*: cstring          ## The name of the group.
+  gr_passwd*: cstring
+  gr_gid*: Gid               ## Numerical group ID.
+  gr_mem*: cstringArray      ## Pointer to a null-terminated array of character
+                             ## pointers to member names.
+
+ + struct group + Source   +Edit   + +
+
+
+
Hostent {.importc: "struct hostent", pure, final, header: "<netdb.h>".} = object
+  h_name*: cstring           ## Official name of the host.
+  h_aliases*: cstringArray   ## A pointer to an array of pointers to
+                             ## alternative host names, terminated by a
+                             ## null pointer.
+  h_addrtype*: cint          ## Address type.
+  h_length*: cint            ## The length, in bytes, of the address.
+  h_addr_list*: cstringArray ## A pointer to an array of pointers to network
+                             ## addresses (in network byte order) for the
+                             ## host, terminated by a null pointer.
+
+ + struct hostent + Source   +Edit   + +
+
+
+
Iconv {.importc: "iconv_t", header: "<iconv.h>".} = pointer
+
+ + Identifies the conversion from one codeset to another. + Source   +Edit   + +
+
+
+
Id {.importc: "id_t", header: "<sys/types.h>".} = cuint
+
+ + + Source   +Edit   + +
+
+
+
In6Addr {.importc: "struct in6_addr", pure, final, header: "<netinet/in.h>".} = object
+  s6_addr*: array[0 .. 15, char]
+
+ + struct in6_addr + Source   +Edit   + +
+
+
+
InAddr {.importc: "struct in_addr", pure, final, header: "<netinet/in.h>".} = object
+  s_addr*: InAddrScalar
+
+ + struct in_addr + Source   +Edit   + +
+
+
+
InAddrScalar = uint32
+
+ + + Source   +Edit   + +
+
+
+
InAddrT {.importc: "in_addr_t", pure, final, header: "<netinet/in.h>".} = uint32
+
+ + + Source   +Edit   + +
+
+
+
Ino {.importc: "ino_t", header: "<sys/types.h>".} = culong
+
+ + + Source   +Edit   + +
+
+
+
InPort = uint16
+
+ + + Source   +Edit   + +
+
+
+
IOVec {.importc: "struct iovec", pure, final, header: "<sys/uio.h>".} = object
+  iov_base*: pointer         ## Base address of a memory region for input or output.
+  iov_len*: csize_t          ## The size of the memory pointed to by iov_base.
+
+ + struct iovec + Source   +Edit   + +
+
+
+
Ipc_perm {.importc: "struct ipc_perm", header: "<sys/ipc.h>", final, pure.} = object
+  uid*: Uid                  ## Owner's user ID.
+  gid*: Gid                  ## Owner's group ID.
+  cuid*: Uid                 ## Creator's user ID.
+  cgid*: Gid                 ## Creator's group ID.
+  mode*: cshort              ## Read/write permission.
+
+ + struct ipc_perm + Source   +Edit   + +
+
+
+
Itimerspec {.importc: "struct itimerspec", header: "<time.h>", final, pure.} = object
+  it_interval*: Timespec     ## Timer period.
+  it_value*: Timespec        ## Timer expiration.
+
+ + struct itimerspec + Source   +Edit   + +
+
+
+
Key {.importc: "key_t", header: "<sys/types.h>".} = cint
+
+ + + Source   +Edit   + +
+
+
+
Lconv {.importc: "struct lconv", header: "<locale.h>", final, pure.} = object
+  decimal_point*: cstring
+  thousands_sep*: cstring
+  grouping*: cstring
+  int_curr_symbol*: cstring
+  currency_symbol*: cstring
+  mon_decimal_point*: cstring
+  mon_thousands_sep*: cstring
+  mon_grouping*: cstring
+  positive_sign*: cstring
+  negative_sign*: cstring
+  int_frac_digits*: char
+  frac_digits*: char
+  p_cs_precedes*: char
+  p_sep_by_space*: char
+  n_cs_precedes*: char
+  n_sep_by_space*: char
+  p_sign_posn*: char
+  n_sign_posn*: char
+  int_p_cs_precedes*: char
+  int_p_sep_by_space*: char
+  int_n_cs_precedes*: char
+  int_n_sep_by_space*: char
+  int_p_sign_posn*: char
+  int_n_sign_posn*: char
+
+ + + Source   +Edit   + +
+
+
+
Mcontext {.importc: "mcontext_t", header: "<ucontext.h>", final, pure.} = object
+
+ + + Source   +Edit   + +
+
+
+
Mode {.importc: "mode_t", header: "<sys/types.h>".} = uint32
+
+ + + Source   +Edit   + +
+
+
+
MqAttr {.importc: "struct mq_attr", header: "<mqueue.h>", final, pure.} = object
+  mq_flags*: clong           ## Message queue flags.
+  mq_maxmsg*: clong          ## Maximum number of messages.
+  mq_msgsize*: clong         ## Maximum message size.
+  mq_curmsgs*: clong         ## Number of messages currently queued.
+
+ + message queue attribute + Source   +Edit   + +
+
+
+
Mqd {.importc: "mqd_t", header: "<mqueue.h>".} = cint
+
+ + + Source   +Edit   + +
+
+
+
Nl_catd {.importc: "nl_catd", header: "<nl_types.h>".} = pointer
+
+ + + Source   +Edit   + +
+
+
+
Nl_item {.importc: "nl_item", header: "<nl_types.h>".} = cint
+
+ + + Source   +Edit   + +
+
+ +
+
Off {.importc: "off_t", header: "<sys/types.h>".} = clong
+
+ + + Source   +Edit   + +
+
+
+
Passwd {.importc: "struct passwd", header: "<pwd.h>", final, pure.} = object
+  pw_name*: cstring          ## User's login name.
+  pw_passwd*: cstring
+  pw_uid*: Uid               ## Numerical user ID.
+  pw_gid*: Gid               ## Numerical group ID.
+  pw_gecos*: cstring
+  pw_dir*: cstring           ## Initial working directory.
+  pw_shell*: cstring         ## Program to use as shell.
+
+ + struct passwd + Source   +Edit   + +
+
+
+
Pid {.importc: "pid_t", header: "<sys/types.h>".} = cint
+
+ + + Source   +Edit   + +
+
+
+
Protoent {.importc: "struct protoent", pure, final, header: "<netdb.h>".} = object
+  p_name*: cstring           ## Official name of the protocol.
+  p_aliases*: cstringArray   ## A pointer to an array of pointers to
+                             ## alternative protocol names, terminated by
+                             ## a null pointer.
+  p_proto*: cint             ## The protocol number.
+
+ + struct protoent + Source   +Edit   + +
+
+
+
Pthread {.importc: "pthread_t", header: "<sys/types.h>".} = culong
+
+ + + Source   +Edit   + +
+
+
+
Pthread_attr {.importc: "pthread_attr_t", header: "<sys/types.h>", pure, final.} = object
+
+ + + Source   +Edit   + +
+
+
+
Pthread_barrier {.importc: "pthread_barrier_t", header: "<sys/types.h>", pure,
+                  final.} = object
+
+ + + Source   +Edit   + +
+
+
+
Pthread_barrierattr {.importc: "pthread_barrierattr_t", header: "<sys/types.h>",
+                      pure, final.} = object
+
+ + + Source   +Edit   + +
+
+
+
Pthread_cond {.importc: "pthread_cond_t", header: "<sys/types.h>", pure, final.} = object
+
+ + + Source   +Edit   + +
+
+
+
Pthread_condattr {.importc: "pthread_condattr_t", header: "<sys/types.h>", pure,
+                   final.} = object
+
+ + + Source   +Edit   + +
+
+
+
Pthread_key {.importc: "pthread_key_t", header: "<sys/types.h>".} = cuint
+
+ + + Source   +Edit   + +
+
+
+
Pthread_mutex {.importc: "pthread_mutex_t", header: "<sys/types.h>", pure, final.} = object
+
+ + + Source   +Edit   + +
+
+
+
Pthread_mutexattr {.importc: "pthread_mutexattr_t", header: "<sys/types.h>",
+                    pure, final.} = object
+
+ + + Source   +Edit   + +
+
+
+
Pthread_once {.importc: "pthread_once_t", header: "<sys/types.h>".} = cint
+
+ + + Source   +Edit   + +
+
+
+
Pthread_rwlock {.importc: "pthread_rwlock_t", header: "<sys/types.h>", pure,
+                 final.} = object
+
+ + + Source   +Edit   + +
+
+
+
Pthread_rwlockattr {.importc: "pthread_rwlockattr_t", header: "<sys/types.h>".} = object
+
+ + + Source   +Edit   + +
+
+
+
Pthread_spinlock {.importc: "pthread_spinlock_t", header: "<sys/types.h>".} = cint
+
+ + + Source   +Edit   + +
+
+
+
RLimit {.importc: "struct rlimit", header: "<sys/resource.h>", pure, final.} = object
+  rlim_cur*: int
+  rlim_max*: int
+
+ + + Source   +Edit   + +
+
+
+
Rusage {.importc: "struct rusage", header: "<sys/resource.h>", bycopy.} = object
+  ru_utime*, ru_stime*: Timeval
+  ru_maxrss*, ru_ixrss*, ru_idrss*, ru_isrss*, ru_minflt*, ru_majflt*,
+  ru_nswap*, ru_inblock*, ru_oublock*, ru_msgsnd*, ru_msgrcv*, ru_nsignals*,
+  ru_nvcsw*, ru_nivcsw*: clong
+
+ + + Source   +Edit   + +
+
+
+
Sched_param {.importc: "struct sched_param", header: "<sched.h>", final, pure.} = object
+  sched_priority*: cint
+
+ + struct sched_param + Source   +Edit   + +
+
+
+
Sem {.importc: "sem_t", header: "<semaphore.h>", final, pure.} = object
+
+ + + Source   +Edit   + +
+
+
+
Servent {.importc: "struct servent", pure, final, header: "<netdb.h>".} = object
+  s_name*: cstring           ## Official name of the service.
+  s_aliases*: cstringArray   ## A pointer to an array of pointers to
+                             ## alternative service names, terminated by
+                             ## a null pointer.
+  s_port*: cint              ## The port number at which the service
+                             ## resides, in network byte order.
+  s_proto*: cstring          ## The name of the protocol to use when
+                             ## contacting the service.
+
+ + struct servent + Source   +Edit   + +
+
+
+
Sig_atomic {.importc: "sig_atomic_t", header: "<signal.h>".} = cint
+
+ + Possibly volatile-qualified integer type of an object that can be accessed as an atomic entity, even in the presence of asynchronous interrupts. + Source   +Edit   + +
+
+
+
Sigaction {.importc: "struct sigaction", header: "<signal.h>", final, pure.} = object
+  sa_handler*: proc (x: cint) {.noconv.} ## Pointer to a signal-catching
+                                         ## function or one of the macros
+                                         ## SIG_IGN or SIG_DFL.
+  sa_mask*: Sigset           ## Set of signals to be blocked during execution of
+                             ## the signal handling function.
+  sa_flags*: cint            ## Special flags.
+  ## not intended for application use.
+
+ + struct sigaction + Source   +Edit   + +
+
+
+
SigEvent {.importc: "struct sigevent", header: "<signal.h>", final, pure.} = object
+  sigev_value*: SigVal       ## Signal value.
+  sigev_signo*: cint         ## Signal number.
+  sigev_notify*: cint        ## Notification type.
+  sigev_notify_function*: proc (x: SigVal) {.noconv.} ## Notification func.
+  sigev_notify_attributes*: ptr Pthread_attr ## Notification attributes.
+
+ + struct sigevent + Source   +Edit   + +
+
+
+
SigInfo {.importc: "siginfo_t", header: "<signal.h>", final, pure.} = object
+  si_signo*: cint            ## Signal number.
+  si_errno*: cint            ## If non-zero, an errno value associated with
+                             ## this signal, as defined in <errno.h>.
+  si_code*: cint             ## Signal code.
+  si_pid*: Pid               ## Sending process ID.
+  si_uid*: Uid               ## Real user ID of sending process.
+  si_addr*: pointer          ## Address of faulting instruction.
+  si_status*: cint           ## Exit value or signal.
+  si_band*: int              ## Band event for SIGPOLL.
+  si_value*: SigVal          ## Signal value.
+
+ + siginfo_t + Source   +Edit   + +
+
+
+
Sigset {.importc: "sigset_t", header: "<signal.h>", final, pure.} = object
+
+ + + Source   +Edit   + +
+
+
+
SigStack {.importc: "struct sigstack", header: "<signal.h>", final, pure.} = object
+  ss_onstack*: cint          ## Non-zero when signal stack is in use.
+  ss_sp*: pointer            ## Signal stack pointer.
+
+ + struct sigstack + Source   +Edit   + +
+
+
+
SigVal {.importc: "union sigval", header: "<signal.h>", final, pure.} = object
+  sival_ptr*: pointer        ## pointer signal value;
+                             ## integer signal value not defined!
+
+ + struct sigval + Source   +Edit   + +
+
+
+
SockAddr {.importc: "struct sockaddr", header: "<sys/socket.h>", pure, final.} = object
+  sa_family*: TSa_Family     ## Address family.
+  sa_data*: array[14, char]  ## Socket address (variable-length data).
+
+ + struct sockaddr + Source   +Edit   + +
+
+
+
Sockaddr_in {.importc: "struct sockaddr_in", pure, final,
+              header: "<netinet/in.h>".} = object
+  sin_family*: TSa_Family    ## AF_INET.
+  sin_port*: InPort          ## Port number.
+  sin_addr*: InAddr          ## IP address.
+
+ + struct sockaddr_in + Source   +Edit   + +
+
+
+
Sockaddr_in6 {.importc: "struct sockaddr_in6", pure, final,
+               header: "<netinet/in.h>".} = object
+  sin6_family*: TSa_Family   ## AF_INET6.
+  sin6_port*: InPort         ## Port number.
+  sin6_flowinfo*: uint32     ## IPv6 traffic class and flow information.
+  sin6_addr*: In6Addr        ## IPv6 address.
+  sin6_scope_id*: uint32     ## Set of interfaces for a scope.
+
+ + struct sockaddr_in6 + Source   +Edit   + +
+
+
+
Sockaddr_storage {.importc: "struct sockaddr_storage", header: "<sys/socket.h>",
+                   pure, final.} = object
+  ss_family*: TSa_Family     ## Address family.
+
+ + struct sockaddr_storage + Source   +Edit   + +
+
+
+
Sockaddr_un {.importc: "struct sockaddr_un", header: "<sys/un.h>", pure, final.} = object
+  sun_family*: TSa_Family    ## Address family.
+  sun_path*: array[108, char] ## Socket path
+
+ + struct sockaddr_un + Source   +Edit   + +
+
+
+
SocketHandle = distinct cint
+
+ + + Source   +Edit   + +
+
+
+
SockLen {.importc: "socklen_t", header: "<sys/socket.h>".} = cuint
+
+ + + Source   +Edit   + +
+
+
+
Stack {.importc: "stack_t", header: "<signal.h>", final, pure.} = object
+  ss_sp*: pointer            ## Stack base or pointer.
+  ss_size*: int              ## Stack size.
+  ss_flags*: cint            ## Flags.
+
+ + stack_t + Source   +Edit   + +
+
+
+
Stat {.importc: "struct stat", header: "<sys/stat.h>", final, pure.} = object
+  st_dev*: Dev               ## Device ID of device containing file.
+  st_ino*: Ino               ## File serial number.
+  st_nlink*: Nlink           ## Number of hard links to the file.
+  st_mode*: Mode             ## Mode of file (see below).
+  st_uid*: Uid               ## User ID of file.
+  st_gid*: Gid               ## Group ID of file.
+  st_rdev*: Dev              ## Device ID (if file is character or block special).
+  st_size*: Off              ## For regular files, the file size in bytes.
+                             ## For symbolic links, the length in bytes of the
+                             ## pathname contained in the symbolic link.
+                             ## For a shared memory object, the length in bytes.
+                             ## For a typed memory object, the length in bytes.
+                             ## For other file types, the use of this field is
+                             ## unspecified.
+  st_blksize*: Blksize       ## A file system-specific preferred I/O block size
+                             ## for this object. In some file system types, this
+                             ## may vary from file to file.
+  st_blocks*: Blkcnt         ## Number of blocks allocated for this object.
+  st_atim*: Timespec         ## Time of last access.
+  st_mtim*: Timespec         ## Time of last data modification.
+  st_ctim*: Timespec         ## Time of last status change.
+
+ + struct stat + Source   +Edit   + +
+
+
+
Statvfs {.importc: "struct statvfs", header: "<sys/statvfs.h>", final, pure.} = object
+  f_bsize*: culong           ## File system block size.
+  f_frsize*: culong          ## Fundamental file system block size.
+  f_blocks*: Fsblkcnt        ## Total number of blocks on file system
+                             ## in units of f_frsize.
+  f_bfree*: Fsblkcnt         ## Total number of free blocks.
+  f_bavail*: Fsblkcnt        ## Number of free blocks available to
+                             ## non-privileged process.
+  f_files*: Fsfilcnt         ## Total number of file serial numbers.
+  f_ffree*: Fsfilcnt         ## Total number of free file serial numbers.
+  f_favail*: Fsfilcnt        ## Number of file serial numbers available to
+                             ## non-privileged process.
+  f_fsid*: culong            ## File system ID.
+  f_flag*: culong            ## Bit mask of f_flag values.
+  f_namemax*: culong         ## Maximum filename length.
+
+ + struct statvfs + Source   +Edit   + +
+
+
+
Suseconds {.importc: "suseconds_t", header: "<sys/types.h>".} = clong
+
+ + + Source   +Edit   + +
+
+
+
Taiocb {.importc: "struct aiocb", header: "<aio.h>", final, pure.} = object
+  aio_fildes*: cint          ## File descriptor.
+  aio_lio_opcode*: cint      ## Operation to be performed.
+  aio_reqprio*: cint         ## Request priority offset.
+  aio_buf*: pointer          ## Location of buffer.
+  aio_nbytes*: csize_t       ## Length of transfer.
+  aio_sigevent*: SigEvent    ## Signal number and value.
+  aio_offset*: Off           ## File offset.
+
+ + struct aiocb + Source   +Edit   + +
+
+
+
Tcmsghdr {.importc: "struct cmsghdr", pure, final, header: "<sys/socket.h>".} = object
+  cmsg_len*: csize_t         ## Data byte count, including the cmsghdr.
+  cmsg_level*: cint          ## Originating protocol.
+  cmsg_type*: cint           ## Protocol-specific type.
+
+ + struct cmsghdr + Source   +Edit   + +
+
+
+
TFdSet {.importc: "fd_set", header: "<sys/select.h>", final, pure.} = object
+
+ + + Source   +Edit   + +
+
+
+
Tflock {.importc: "struct flock", final, pure, header: "<fcntl.h>".} = object
+  l_type*: cshort            ## Type of lock; F_RDLCK, F_WRLCK, F_UNLCK.
+  l_whence*: cshort          ## Flag for starting offset.
+  l_start*: Off              ## Relative offset in bytes.
+  l_len*: Off                ## Size; if 0 then until EOF.
+  l_pid*: Pid                ## Process ID of the process holding the lock;
+                             ## returned with F_GETLK.
+
+ + flock type + Source   +Edit   + +
+
+
+
Tif_nameindex {.importc: "struct if_nameindex", final, pure,
+                header: "<net/if.h>".} = object
+  if_index*: cuint           ## Numeric index of the interface.
+  if_name*: cstring          ## Null-terminated name of the interface.
+
+ + struct if_nameindex + Source   +Edit   + +
+
+
+
Time {.importc: "time_t", header: "<time.h>".} = distinct clong
+
+ + + Source   +Edit   + +
+
+
+
Timer {.importc: "timer_t", header: "<sys/types.h>".} = pointer
+
+ + + Source   +Edit   + +
+
+
+
Timespec {.importc: "struct timespec", header: "<time.h>", final, pure.} = object
+  tv_sec*: Time              ## Seconds.
+  tv_nsec*: clong            ## Nanoseconds.
+
+ + struct timespec + Source   +Edit   + +
+
+
+
Timeval {.importc: "struct timeval", header: "<sys/select.h>", final, pure.} = object
+  tv_sec*: Time              ## Seconds.
+  tv_usec*: Suseconds        ## Microseconds.
+
+ + struct timeval + Source   +Edit   + +
+
+
+
Tipv6_mreq {.importc: "struct ipv6_mreq", pure, final, header: "<netinet/in.h>".} = object
+  ipv6mr_multiaddr*: In6Addr ## IPv6 multicast address.
+  ipv6mr_interface*: cuint   ## Interface index.
+
+ + struct ipv6_mreq + Source   +Edit   + +
+
+
+
TLinger {.importc: "struct linger", pure, final, header: "<sys/socket.h>".} = object
+  l_onoff*: cint             ## Indicates whether linger option is enabled.
+  l_linger*: cint            ## Linger time, in seconds.
+
+ + struct linger + Source   +Edit   + +
+
+
+
Tm {.importc: "struct tm", header: "<time.h>", final, pure.} = object
+  tm_sec*: cint              ## Seconds [0,60].
+  tm_min*: cint              ## Minutes [0,59].
+  tm_hour*: cint             ## Hour [0,23].
+  tm_mday*: cint             ## Day of month [1,31].
+  tm_mon*: cint              ## Month of year [0,11].
+  tm_year*: cint             ## Years since 1900.
+  tm_wday*: cint             ## Day of week [0,6] (Sunday =0).
+  tm_yday*: cint             ## Day of year [0,365].
+  tm_isdst*: cint            ## Daylight Savings flag.
+  tm_gmtoff*: clong
+  tm_zone*: cstring
+
+ + struct tm + Source   +Edit   + +
+
+
+
Tmsghdr {.importc: "struct msghdr", pure, final, header: "<sys/socket.h>".} = object
+  msg_name*: pointer         ## Optional address.
+  msg_namelen*: SockLen      ## Size of address.
+  msg_iov*: ptr IOVec        ## Scatter/gather array.
+  msg_iovlen*: csize_t       ## Members in msg_iov.
+  msg_control*: pointer      ## Ancillary data; see below.
+  msg_controllen*: csize_t   ## Ancillary data buffer len.
+  msg_flags*: cint           ## Flags on received message.
+
+ + struct msghdr + Source   +Edit   + +
+
+
+
Tnetent {.importc: "struct netent", pure, final, header: "<netdb.h>".} = object
+  n_name*: cstring           ## Official, fully-qualified (including the
+                             ## domain) name of the host.
+  n_aliases*: cstringArray   ## A pointer to an array of pointers to
+                             ## alternative network names, terminated by a
+                             ## null pointer.
+  n_addrtype*: cint          ## The address type of the network.
+  n_net*: uint32             ## The network number, in host byte order.
+
+ + struct netent + Source   +Edit   + +
+
+
+
Tnfds {.importc: "nfds_t", header: "<poll.h>".} = culong
+
+ + + Source   +Edit   + +
+
+
+
TPollfd {.importc: "struct pollfd", pure, final, header: "<poll.h>".} = object
+  fd*: cint                  ## The following descriptor being polled.
+  events*: cshort            ## The input event flags (see below).
+  revents*: cshort           ## The output event flags (see below).
+
+ + struct pollfd + Source   +Edit   + +
+
+
+
Tposix_spawn_file_actions {.importc: "posix_spawn_file_actions_t",
+                            header: "<spawn.h>", final, pure.} = object
+
+ + + Source   +Edit   + +
+
+
+
Tposix_spawnattr {.importc: "posix_spawnattr_t", header: "<spawn.h>", final,
+                   pure.} = object
+
+ + + Source   +Edit   + +
+
+
+
TSa_Family {.importc: "sa_family_t", header: "<sys/socket.h>".} = cushort
+
+ + + Source   +Edit   + +
+
+
+
Ucontext {.importc: "ucontext_t", header: "<ucontext.h>", final, pure.} = object
+  uc_link*: ptr Ucontext     ## Pointer to the context that is resumed
+                             ## when this context returns.
+  uc_stack*: Stack           ## The stack used by this context.
+  uc_mcontext*: Mcontext     ## A machine-specific representation of the saved
+                             ## context.
+  uc_sigmask*: Sigset        ## The set of signals that are blocked when this
+                             ## context is active.
+
+ + ucontext_t + Source   +Edit   + +
+
+
+
Uid {.importc: "uid_t", header: "<sys/types.h>".} = cuint
+
+ + + Source   +Edit   + +
+
+
+
Useconds {.importc: "useconds_t", header: "<sys/types.h>".} = cuint
+
+ + + Source   +Edit   + +
+
+
+
Utsname {.importc: "struct utsname", header: "<sys/utsname.h>", final, pure.} = object
+  sysname*,                 ## Name of this implementation of the operating system.
+  nodename*,                ## Name of this node within the communications
+                             ## network to which this node is attached, if any.
+  release*,                 ## Current release level of this implementation.
+  version*,                 ## Current version level of this release.
+  machine*,                 ## Name of the hardware type on which the
+                             ## system is running.
+  domainname*: array[65, char]
+
+ + struct utsname + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
daylight {.importc, header: "<time.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
errno {.importc, header: "<errno.h>".}: cint
+
+ + error variable + Source   +Edit   + +
+
+
+
h_errno {.importc, header: "<netdb.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
in6addr_any {.importc, header: "<netinet/in.h>".}: In6Addr
+
+ + + Source   +Edit   + +
+
+
+
in6addr_loopback {.importc, header: "<netinet/in.h>".}: In6Addr
+
+ + + Source   +Edit   + +
+
+
+
timezone {.importc, header: "<time.h>".}: clong
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
ABDAY_1 = 131072'i32
+
+ + + Source   +Edit   + +
+
+
+
ABDAY_2 = 131073'i32
+
+ + + Source   +Edit   + +
+
+
+
ABDAY_3 = 131074'i32
+
+ + + Source   +Edit   + +
+
+
+
ABDAY_4 = 131075'i32
+
+ + + Source   +Edit   + +
+
+
+
ABDAY_5 = 131076'i32
+
+ + + Source   +Edit   + +
+
+
+
ABDAY_6 = 131077'i32
+
+ + + Source   +Edit   + +
+
+
+
ABDAY_7 = 131078'i32
+
+ + + Source   +Edit   + +
+
+
+
ABMON_1 = 131086'i32
+
+ + + Source   +Edit   + +
+
+
+
ABMON_2 = 131087'i32
+
+ + + Source   +Edit   + +
+
+
+
ABMON_3 = 131088'i32
+
+ + + Source   +Edit   + +
+
+
+
ABMON_4 = 131089'i32
+
+ + + Source   +Edit   + +
+
+
+
ABMON_5 = 131090'i32
+
+ + + Source   +Edit   + +
+
+
+
ABMON_6 = 131091'i32
+
+ + + Source   +Edit   + +
+
+
+
ABMON_7 = 131092'i32
+
+ + + Source   +Edit   + +
+
+
+
ABMON_8 = 131093'i32
+
+ + + Source   +Edit   + +
+
+
+
ABMON_9 = 131094'i32
+
+ + + Source   +Edit   + +
+
+
+
ABMON_10 = 131095'i32
+
+ + + Source   +Edit   + +
+
+
+
ABMON_11 = 131096'i32
+
+ + + Source   +Edit   + +
+
+
+
ABMON_12 = 131097'i32
+
+ + + Source   +Edit   + +
+
+
+
AF_INET = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
AF_INET6 = 10'i32
+
+ + + Source   +Edit   + +
+
+
+
AF_UNIX = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
AF_UNSPEC = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
AI_ADDRCONFIG = 32'i32
+
+ + + Source   +Edit   + +
+
+
+
AI_ALL = 16'i32
+
+ + + Source   +Edit   + +
+
+
+
AI_CANONNAME = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
AI_NUMERICHOST = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
AI_NUMERICSERV = 1024'i32
+
+ + + Source   +Edit   + +
+
+
+
AI_PASSIVE = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
AI_V4MAPPED = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
AIO_ALLDONE = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
AIO_CANCELED = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
AIO_NOTCANCELED = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
ALT_DIGITS = 131119'i32
+
+ + + Source   +Edit   + +
+
+
+
AM_STR = 131110'i32
+
+ + + Source   +Edit   + +
+
+
+
CLOCK_MONOTONIC = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
CLOCK_PROCESS_CPUTIME_ID = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
CLOCK_REALTIME = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
CLOCK_THREAD_CPUTIME_ID = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
CLOCKS_PER_SEC = 1000000
+
+ + + Source   +Edit   + +
+
+
+
CODESET = 14'i32
+
+ + + Source   +Edit   + +
+
+
+
CRNCYSTR = 262159'i32
+
+ + + Source   +Edit   + +
+
+
+
CS_PATH = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
CS_POSIX_V6_ILP32_OFF32_CFLAGS = 1116'i32
+
+ + + Source   +Edit   + +
+
+
+
CS_POSIX_V6_ILP32_OFF32_LDFLAGS = 1117'i32
+
+ + + Source   +Edit   + +
+
+
+
CS_POSIX_V6_ILP32_OFF32_LIBS = 1118'i32
+
+ + + Source   +Edit   + +
+
+
+
CS_POSIX_V6_ILP32_OFFBIG_CFLAGS = 1120'i32
+
+ + + Source   +Edit   + +
+
+
+
CS_POSIX_V6_ILP32_OFFBIG_LDFLAGS = 1121'i32
+
+ + + Source   +Edit   + +
+
+
+
CS_POSIX_V6_ILP32_OFFBIG_LIBS = 1122'i32
+
+ + + Source   +Edit   + +
+
+
+
CS_POSIX_V6_LP64_OFF64_CFLAGS = 1124'i32
+
+ + + Source   +Edit   + +
+
+
+
CS_POSIX_V6_LP64_OFF64_LDFLAGS = 1125'i32
+
+ + + Source   +Edit   + +
+
+
+
CS_POSIX_V6_LP64_OFF64_LIBS = 1126'i32
+
+ + + Source   +Edit   + +
+
+
+
CS_POSIX_V6_LPBIG_OFFBIG_CFLAGS = 1128'i32
+
+ + + Source   +Edit   + +
+
+
+
CS_POSIX_V6_LPBIG_OFFBIG_LDFLAGS = 1129'i32
+
+ + + Source   +Edit   + +
+
+
+
CS_POSIX_V6_LPBIG_OFFBIG_LIBS = 1130'i32
+
+ + + Source   +Edit   + +
+
+
+
CS_POSIX_V6_WIDTH_RESTRICTED_ENVS = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
D_FMT = 131113'i32
+
+ + + Source   +Edit   + +
+
+
+
D_T_FMT = 131112'i32
+
+ + + Source   +Edit   + +
+
+
+
DAY_1 = 131079'i32
+
+ + + Source   +Edit   + +
+
+
+
DAY_2 = 131080'i32
+
+ + + Source   +Edit   + +
+
+
+
DAY_3 = 131081'i32
+
+ + + Source   +Edit   + +
+
+
+
DAY_4 = 131082'i32
+
+ + + Source   +Edit   + +
+
+
+
DAY_5 = 131083'i32
+
+ + + Source   +Edit   + +
+
+
+
DAY_6 = 131084'i32
+
+ + + Source   +Edit   + +
+
+
+
DAY_7 = 131085'i32
+
+ + + Source   +Edit   + +
+
+
+
DT_BLK = 6
+
+ + Block device. + Source   +Edit   + +
+
+
+
DT_CHR = 2
+
+ + Character device. + Source   +Edit   + +
+
+
+
DT_DIR = 4
+
+ + Directory. + Source   +Edit   + +
+
+
+
DT_FIFO = 1
+
+ + Named pipe, or FIFO. + Source   +Edit   + +
+
+
+
DT_LNK = 10
+
+ + Symbolic link. + Source   +Edit   + +
+
+
+
DT_REG = 8
+
+ + Regular file. + Source   +Edit   + +
+
+
+
DT_SOCK = 12
+
+ + UNIX domain socket. + Source   +Edit   + +
+
+
+
DT_UNKNOWN = 0
+
+ + Unknown file type. + Source   +Edit   + +
+
+
+
DT_WHT = 14
+
+ + + Source   +Edit   + +
+
+
+
E2BIG = 7'i32
+
+ + + Source   +Edit   + +
+
+
+
EACCES = 13'i32
+
+ + + Source   +Edit   + +
+
+
+
EADDRINUSE = 98'i32
+
+ + + Source   +Edit   + +
+
+
+
EADDRNOTAVAIL = 99'i32
+
+ + + Source   +Edit   + +
+
+
+
EAFNOSUPPORT = 97'i32
+
+ + + Source   +Edit   + +
+
+
+
EAGAIN = 11'i32
+
+ + + Source   +Edit   + +
+
+
+
EAI_AGAIN = -3'i32
+
+ + + Source   +Edit   + +
+
+
+
EAI_BADFLAGS = -1'i32
+
+ + + Source   +Edit   + +
+
+
+
EAI_FAIL = -4'i32
+
+ + + Source   +Edit   + +
+
+
+
EAI_FAMILY = -6'i32
+
+ + + Source   +Edit   + +
+
+
+
EAI_MEMORY = -10'i32
+
+ + + Source   +Edit   + +
+
+
+
EAI_NONAME = -2'i32
+
+ + + Source   +Edit   + +
+
+
+
EAI_OVERFLOW = -12'i32
+
+ + + Source   +Edit   + +
+
+
+
EAI_SERVICE = -8'i32
+
+ + + Source   +Edit   + +
+
+
+
EAI_SOCKTYPE = -7'i32
+
+ + + Source   +Edit   + +
+
+
+
EAI_SYSTEM = -11'i32
+
+ + + Source   +Edit   + +
+
+
+
EALREADY = 114'i32
+
+ + + Source   +Edit   + +
+
+
+
EBADF = 9'i32
+
+ + + Source   +Edit   + +
+
+
+
EBADMSG = 74'i32
+
+ + + Source   +Edit   + +
+
+
+
EBUSY = 16'i32
+
+ + + Source   +Edit   + +
+
+
+
ECANCELED = 125'i32
+
+ + + Source   +Edit   + +
+
+
+
ECHILD = 10'i32
+
+ + + Source   +Edit   + +
+
+
+
ECONNABORTED = 103'i32
+
+ + + Source   +Edit   + +
+
+
+
ECONNREFUSED = 111'i32
+
+ + + Source   +Edit   + +
+
+
+
ECONNRESET = 104'i32
+
+ + + Source   +Edit   + +
+
+
+
EDEADLK = 35'i32
+
+ + + Source   +Edit   + +
+
+
+
EDESTADDRREQ = 89'i32
+
+ + + Source   +Edit   + +
+
+
+
EDOM = 33'i32
+
+ + + Source   +Edit   + +
+
+
+
EDQUOT = 122'i32
+
+ + + Source   +Edit   + +
+
+
+
EEXIST = 17'i32
+
+ + + Source   +Edit   + +
+
+
+
EFAULT = 14'i32
+
+ + + Source   +Edit   + +
+
+
+
EFBIG = 27'i32
+
+ + + Source   +Edit   + +
+
+
+
EHOSTUNREACH = 113'i32
+
+ + + Source   +Edit   + +
+
+
+
EIDRM = 43'i32
+
+ + + Source   +Edit   + +
+
+
+
EILSEQ = 84'i32
+
+ + + Source   +Edit   + +
+
+
+
EINPROGRESS = 115'i32
+
+ + + Source   +Edit   + +
+
+
+
EINTR = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
EINVAL = 22'i32
+
+ + + Source   +Edit   + +
+
+
+
EIO = 5'i32
+
+ + + Source   +Edit   + +
+
+
+
EISCONN = 106'i32
+
+ + + Source   +Edit   + +
+
+
+
EISDIR = 21'i32
+
+ + + Source   +Edit   + +
+
+
+
ELOOP = 40'i32
+
+ + + Source   +Edit   + +
+
+
+
EMFILE = 24'i32
+
+ + + Source   +Edit   + +
+
+ +
+
EMSGSIZE = 90'i32
+
+ + + Source   +Edit   + +
+
+
+
EMULTIHOP = 72'i32
+
+ + + Source   +Edit   + +
+
+
+
ENAMETOOLONG = 36'i32
+
+ + + Source   +Edit   + +
+
+
+
ENETDOWN = 100'i32
+
+ + + Source   +Edit   + +
+
+
+
ENETRESET = 102'i32
+
+ + + Source   +Edit   + +
+
+
+
ENETUNREACH = 101'i32
+
+ + + Source   +Edit   + +
+
+
+
ENFILE = 23'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOBUFS = 105'i32
+
+ + + Source   +Edit   + +
+
+
+
ENODATA = 61'i32
+
+ + + Source   +Edit   + +
+
+
+
ENODEV = 19'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOENT = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOEXEC = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOLCK = 37'i32
+
+ + + Source   +Edit   + +
+
+ +
+
ENOMEM = 12'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOMSG = 42'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOPROTOOPT = 92'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOSPC = 28'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOSR = 63'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOSTR = 60'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOSYS = 38'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOTCONN = 107'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOTDIR = 20'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOTEMPTY = 39'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOTSOCK = 88'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOTSUP = 95'i32
+
+ + + Source   +Edit   + +
+
+
+
ENOTTY = 25'i32
+
+ + + Source   +Edit   + +
+
+
+
ENXIO = 6'i32
+
+ + + Source   +Edit   + +
+
+
+
EOPNOTSUPP = 95'i32
+
+ + + Source   +Edit   + +
+
+
+
EOVERFLOW = 75'i32
+
+ + + Source   +Edit   + +
+
+
+
EPERM = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
EPIPE = 32'i32
+
+ + + Source   +Edit   + +
+
+
+
EPROTO = 71'i32
+
+ + + Source   +Edit   + +
+
+
+
EPROTONOSUPPORT = 93'i32
+
+ + + Source   +Edit   + +
+
+
+
EPROTOTYPE = 91'i32
+
+ + + Source   +Edit   + +
+
+
+
ERA = 131116'i32
+
+ + + Source   +Edit   + +
+
+
+
ERA_D_FMT = 131118'i32
+
+ + + Source   +Edit   + +
+
+
+
ERA_D_T_FMT = 131120'i32
+
+ + + Source   +Edit   + +
+
+
+
ERA_T_FMT = 131121'i32
+
+ + + Source   +Edit   + +
+
+
+
ERANGE = 34'i32
+
+ + + Source   +Edit   + +
+
+
+
EROFS = 30'i32
+
+ + + Source   +Edit   + +
+
+
+
ESPIPE = 29'i32
+
+ + + Source   +Edit   + +
+
+
+
ESRCH = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
ESTALE = 116'i32
+
+ + + Source   +Edit   + +
+
+
+
ETIME = 62'i32
+
+ + + Source   +Edit   + +
+
+
+
ETIMEDOUT = 110'i32
+
+ + + Source   +Edit   + +
+
+
+
ETXTBSY = 26'i32
+
+ + + Source   +Edit   + +
+
+
+
EWOULDBLOCK = 11'i32
+
+ + + Source   +Edit   + +
+
+
+
EXDEV = 18'i32
+
+ + + Source   +Edit   + +
+
+
+
F_DUPFD = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
F_DUPFD_CLOEXEC = 1030'i32
+
+ + + Source   +Edit   + +
+
+
+
F_GETFD = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
F_GETFL = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
F_GETLK = 5'i32
+
+ + + Source   +Edit   + +
+
+
+
F_GETOWN = 9'i32
+
+ + + Source   +Edit   + +
+
+
+
F_LOCK = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
F_OK = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
F_RDLCK = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
F_SETFD = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
F_SETFL = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
F_SETLK = 6'i32
+
+ + + Source   +Edit   + +
+
+
+
F_SETLKW = 7'i32
+
+ + + Source   +Edit   + +
+
+
+
F_SETOWN = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
F_TEST = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
F_TLOCK = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
F_ULOCK = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
F_UNLCK = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
F_WRLCK = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
FD_CLOEXEC = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
FD_SETSIZE = 1024'i32
+
+ + + Source   +Edit   + +
+
+
+
FE_ALL_EXCEPT = 61'i32
+
+ + + Source   +Edit   + +
+
+
+
FE_DFL_ENV = -1'i32
+
+ + + Source   +Edit   + +
+
+
+
FE_DIVBYZERO = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
FE_DOWNWARD = 1024'i32
+
+ + + Source   +Edit   + +
+
+
+
FE_INEXACT = 32'i32
+
+ + + Source   +Edit   + +
+
+
+
FE_INVALID = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
FE_OVERFLOW = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
FE_TONEAREST = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
FE_TOWARDZERO = 3072'i32
+
+ + + Source   +Edit   + +
+
+
+
FE_UNDERFLOW = 16'i32
+
+ + + Source   +Edit   + +
+
+
+
FE_UPWARD = 2048'i32
+
+ + + Source   +Edit   + +
+
+
+
FNM_NOESCAPE = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
FNM_NOMATCH = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
FNM_NOSYS = -1'i32
+
+ + + Source   +Edit   + +
+
+
+
FNM_PATHNAME = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
FNM_PERIOD = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
FTW_CHDIR = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
FTW_D = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
FTW_DEPTH = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
FTW_DNR = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
FTW_DP = 5'i32
+
+ + + Source   +Edit   + +
+
+
+
FTW_F = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
FTW_MOUNT = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
FTW_NS = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
FTW_PHYS = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
FTW_SL = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
FTW_SLN = 6'i32
+
+ + + Source   +Edit   + +
+
+
+
GLOB_ABORTED = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
GLOB_APPEND = 32'i32
+
+ + + Source   +Edit   + +
+
+
+
GLOB_DOOFFS = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
GLOB_ERR = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
GLOB_MARK = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
GLOB_NOCHECK = 16'i32
+
+ + + Source   +Edit   + +
+
+
+
GLOB_NOESCAPE = 64'i32
+
+ + + Source   +Edit   + +
+
+
+
GLOB_NOMATCH = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
GLOB_NOSORT = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
GLOB_NOSPACE = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
GLOB_NOSYS = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
HOST_NOT_FOUND = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
IF_NAMESIZE = 16'i32
+
+ + + Source   +Edit   + +
+
+
+
INADDR_ANY = 0'u
+
+ + + Source   +Edit   + +
+
+
+
INADDR_BROADCAST = 4294967295'u
+
+ + + Source   +Edit   + +
+
+
+
INADDR_LOOPBACK = 2130706433'u
+
+ + + Source   +Edit   + +
+
+
+
INET6_ADDRSTRLEN = 46'i32
+
+ + + Source   +Edit   + +
+
+
+
INET_ADDRSTRLEN = 16'i32
+
+ + + Source   +Edit   + +
+
+
+
INVALID_SOCKET = -1'i32
+
+ + + Source   +Edit   + +
+
+
+
IOFBF = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
IONBF = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
IPC_CREAT = 512'i32
+
+ + + Source   +Edit   + +
+
+
+
IPC_EXCL = 1024'i32
+
+ + + Source   +Edit   + +
+
+
+
IPC_NOWAIT = 2048'i32
+
+ + + Source   +Edit   + +
+
+
+
IPC_PRIVATE = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
IPC_RMID = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
IPC_SET = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
IPC_STAT = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
IPPORT_RESERVED = 1024'i32
+
+ + + Source   +Edit   + +
+
+
+
IPPROTO_ICMP = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
IPPROTO_ICMPV6 = 58'i32
+
+ + + Source   +Edit   + +
+
+
+
IPPROTO_IP = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
IPPROTO_IPV6 = 41'i32
+
+ + + Source   +Edit   + +
+
+
+
IPPROTO_RAW = 255'i32
+
+ + + Source   +Edit   + +
+
+
+
IPPROTO_TCP = 6'i32
+
+ + + Source   +Edit   + +
+
+
+
IPPROTO_UDP = 17'i32
+
+ + + Source   +Edit   + +
+
+
+
IPV6_JOIN_GROUP = 20'i32
+
+ + + Source   +Edit   + +
+
+
+
IPV6_LEAVE_GROUP = 21'i32
+
+ + + Source   +Edit   + +
+
+
+
IPV6_MULTICAST_HOPS = 18'i32
+
+ + + Source   +Edit   + +
+
+
+
IPV6_MULTICAST_IF = 17'i32
+
+ + + Source   +Edit   + +
+
+
+
IPV6_MULTICAST_LOOP = 19'i32
+
+ + + Source   +Edit   + +
+
+
+
IPV6_UNICAST_HOPS = 16'i32
+
+ + + Source   +Edit   + +
+
+
+
IPV6_V6ONLY = 26'i32
+
+ + + Source   +Edit   + +
+
+
+
LC_ALL = 6'i32
+
+ + + Source   +Edit   + +
+
+
+
LC_COLLATE = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
LC_CTYPE = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
LC_MESSAGES = 5'i32
+
+ + + Source   +Edit   + +
+
+
+
LC_MONETARY = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
LC_NUMERIC = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
LC_TIME = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
LIO_NOP = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
LIO_NOWAIT = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
LIO_READ = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
LIO_WAIT = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
LIO_WRITE = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
MAP_ANONYMOUS = 32'i32
+
+ + + Source   +Edit   + +
+
+
+
MAP_FAILED = 0xFFFFFFFF
+
+ + + Source   +Edit   + +
+
+
+
MAP_FIXED = 16'i32
+
+ + + Source   +Edit   + +
+
+
+
MAP_FIXED_NOREPLACE = 1048576'i32
+
+ + + Source   +Edit   + +
+
+
+
MAP_NORESERVE = 16384'i32
+
+ + + Source   +Edit   + +
+
+
+
MAP_POPULATE = 32768'i32
+
+ + + Source   +Edit   + +
+
+
+
MAP_PRIVATE = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
MAP_SHARED = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
MCL_CURRENT = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
MCL_FUTURE = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
MINSIGSTKSZ = 2048'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_APPL = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_CONSOLE = 512'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_ERROR = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_FIRM = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_HALT = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_HARD = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_INFO = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_NOCON = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_NOMSG = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_NOSEV = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_NOTOK = -1'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_NRECOV = 128'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_NULLACT = nil
+
+ + + Source   +Edit   + +
+
+
+
MM_NULLLBL = nil
+
+ + + Source   +Edit   + +
+
+
+
MM_NULLMC = 0
+
+ + + Source   +Edit   + +
+
+
+
MM_NULLSEV = 0
+
+ + + Source   +Edit   + +
+
+
+
MM_NULLTAG = nil
+
+ + + Source   +Edit   + +
+
+
+
MM_NULLTXT = nil
+
+ + + Source   +Edit   + +
+
+
+
MM_OK = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_OPSYS = 32'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_PRINT = 256'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_RECOVER = 64'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_SOFT = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_UTIL = 16'i32
+
+ + + Source   +Edit   + +
+
+
+
MM_WARNING = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
MON_1 = 131098'i32
+
+ + + Source   +Edit   + +
+
+
+
MON_2 = 131099'i32
+
+ + + Source   +Edit   + +
+
+
+
MON_3 = 131100'i32
+
+ + + Source   +Edit   + +
+
+
+
MON_4 = 131101'i32
+
+ + + Source   +Edit   + +
+
+
+
MON_5 = 131102'i32
+
+ + + Source   +Edit   + +
+
+
+
MON_6 = 131103'i32
+
+ + + Source   +Edit   + +
+
+
+
MON_7 = 131104'i32
+
+ + + Source   +Edit   + +
+
+
+
MON_8 = 131105'i32
+
+ + + Source   +Edit   + +
+
+
+
MON_9 = 131106'i32
+
+ + + Source   +Edit   + +
+
+
+
MON_10 = 131107'i32
+
+ + + Source   +Edit   + +
+
+
+
MON_11 = 131108'i32
+
+ + + Source   +Edit   + +
+
+
+
MON_12 = 131109'i32
+
+ + + Source   +Edit   + +
+
+
+
MS_ASYNC = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
MS_INVALIDATE = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
MS_SYNC = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
MSG_CTRUNC = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
MSG_DONTROUTE = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
MSG_EOR = 128'i32
+
+ + + Source   +Edit   + +
+
+
+
MSG_NOSIGNAL = 16384'i32
+
+ + + Source   +Edit   + +
+
+
+
MSG_OOB = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
MSG_PEEK = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
MSG_TRUNC = 32'i32
+
+ + + Source   +Edit   + +
+
+
+
MSG_WAITALL = 256'i32
+
+ + + Source   +Edit   + +
+
+
+
NI_DGRAM = 16'i32
+
+ + + Source   +Edit   + +
+
+
+
NI_NAMEREQD = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
NI_NOFQDN = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
NI_NUMERICHOST = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
NI_NUMERICSERV = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
NL_CAT_LOCALE = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
NL_SETD = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
NO_DATA = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
NO_RECOVERY = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
NOEXPR = 327681'i32
+
+ + + Source   +Edit   + +
+
+
+
O_ACCMODE = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
O_APPEND = 1024'i32
+
+ + + Source   +Edit   + +
+
+
+
O_CLOEXEC = 524288'i32
+
+ + + Source   +Edit   + +
+
+
+
O_CREAT = 64'i32
+
+ + + Source   +Edit   + +
+
+
+
O_DIRECT = 16384'i32
+
+ + + Source   +Edit   + +
+
+
+
O_DSYNC = 4096'i32
+
+ + + Source   +Edit   + +
+
+
+
O_EXCL = 128'i32
+
+ + + Source   +Edit   + +
+
+
+
O_NOATIME = 262144'i32
+
+ + + Source   +Edit   + +
+
+
+
O_NOCTTY = 256'i32
+
+ + + Source   +Edit   + +
+
+
+
O_NONBLOCK = 2048'i32
+
+ + + Source   +Edit   + +
+
+
+
O_PATH = 2097152'i32
+
+ + + Source   +Edit   + +
+
+
+
O_RDONLY = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
O_RDWR = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
O_RSYNC = 1052672'i32
+
+ + + Source   +Edit   + +
+
+
+
O_SYNC = 1052672'i32
+
+ + + Source   +Edit   + +
+
+
+
O_TMPFILE = 4259840'i32
+
+ + + Source   +Edit   + +
+
+
+
O_TRUNC = 512'i32
+
+ + + Source   +Edit   + +
+
+
+
O_WRONLY = 1'i32
+
+ + + Source   +Edit   + +
+
+ +
+
PC_ALLOC_SIZE_MIN = 18'i32
+
+ + + Source   +Edit   + +
+
+
+
PC_ASYNC_IO = 10'i32
+
+ + + Source   +Edit   + +
+
+
+
PC_CHOWN_RESTRICTED = 6'i32
+
+ + + Source   +Edit   + +
+
+
+
PC_FILESIZEBITS = 13'i32
+
+ + + Source   +Edit   + +
+
+ +
+
PC_MAX_CANON = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
PC_MAX_INPUT = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
PC_NAME_MAX = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
PC_NO_TRUNC = 7'i32
+
+ + + Source   +Edit   + +
+
+
+
PC_PATH_MAX = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
PC_PIPE_BUF = 5'i32
+
+ + + Source   +Edit   + +
+
+
+
PC_PRIO_IO = 11'i32
+
+ + + Source   +Edit   + +
+
+
+
PC_REC_INCR_XFER_SIZE = 14'i32
+
+ + + Source   +Edit   + +
+
+
+
PC_REC_MIN_XFER_SIZE = 16'i32
+
+ + + Source   +Edit   + +
+
+
+
PC_REC_XFER_ALIGN = 17'i32
+
+ + + Source   +Edit   + +
+
+ +
+
PC_SYNC_IO = 9'i32
+
+ + + Source   +Edit   + +
+
+
+
PC_VDISABLE = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
PM_STR = 131111'i32
+
+ + + Source   +Edit   + +
+
+
+
POLLERR = 8'i16
+
+ + + Source   +Edit   + +
+
+
+
POLLHUP = 16'i16
+
+ + + Source   +Edit   + +
+
+
+
POLLIN = 1'i16
+
+ + + Source   +Edit   + +
+
+
+
POLLNVAL = 32'i16
+
+ + + Source   +Edit   + +
+
+
+
POLLOUT = 4'i16
+
+ + + Source   +Edit   + +
+
+
+
POLLPRI = 2'i16
+
+ + + Source   +Edit   + +
+
+
+
POLLRDBAND = 128'i16
+
+ + + Source   +Edit   + +
+
+
+
POLLRDNORM = 64'i16
+
+ + + Source   +Edit   + +
+
+
+
POLLWRBAND = 512'i16
+
+ + + Source   +Edit   + +
+
+
+
POLLWRNORM = 256'i16
+
+ + + Source   +Edit   + +
+
+
+
POSIX_ASYNC_IO = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_FADV_DONTNEED = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_FADV_NOREUSE = 5'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_FADV_NORMAL = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_FADV_RANDOM = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_FADV_SEQUENTIAL = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_FADV_WILLNEED = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_MADV_DONTNEED = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_MADV_NORMAL = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_MADV_RANDOM = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_MADV_SEQUENTIAL = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_MADV_WILLNEED = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_SPAWN_RESETIDS = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_SPAWN_SETPGROUP = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_SPAWN_SETSCHEDPARAM = 16'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_SPAWN_SETSCHEDULER = 32'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_SPAWN_SETSIGDEF = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_SPAWN_SETSIGMASK = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
POSIX_SPAWN_USEVFORK = 64'i32
+
+ + + Source   +Edit   + +
+
+
+
PROT_EXEC = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
PROT_NONE = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
PROT_READ = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
PROT_WRITE = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
PTHREAD_BARRIER_SERIAL_THREAD = -1'i32
+
+ + + Source   +Edit   + +
+
+
+
PTHREAD_CANCEL_ASYNCHRONOUS = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
PTHREAD_CANCEL_DEFERRED = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
PTHREAD_CANCEL_DISABLE = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
PTHREAD_CANCEL_ENABLE = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
PTHREAD_CREATE_DETACHED = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
PTHREAD_CREATE_JOINABLE = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
PTHREAD_EXPLICIT_SCHED = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
PTHREAD_INHERIT_SCHED = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
PTHREAD_PROCESS_PRIVATE = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
PTHREAD_PROCESS_SHARED = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
PTHREAD_SCOPE_PROCESS = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
PTHREAD_SCOPE_SYSTEM = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
R_OK = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
RADIXCHAR = 65536'i32
+
+ + + Source   +Edit   + +
+
+
+
RLIMIT_NOFILE = 7'i32
+
+ + + Source   +Edit   + +
+
+
+
RLIMIT_STACK = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
RTLD_GLOBAL = 256'i32
+
+ + + Source   +Edit   + +
+
+
+
RTLD_LAZY = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
RTLD_LOCAL = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
RTLD_NOW = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
RUSAGE_CHILDREN = -1'i32
+
+ + + Source   +Edit   + +
+
+
+
RUSAGE_SELF = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
RUSAGE_THREAD = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IFBLK = 24576'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IFCHR = 8192'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IFDIR = 16384'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IFIFO = 4096'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IFLNK = 40960'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IFMT = 61440'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IFREG = 32768'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IFSOCK = 49152'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IRGRP = 32'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IROTH = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IRUSR = 256'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IRWXG = 56'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IRWXO = 7'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IRWXU = 448'i32
+
+ + + Source   +Edit   + +
+
+
+
S_ISGID = 1024'i32
+
+ + + Source   +Edit   + +
+
+
+
S_ISUID = 2048'i32
+
+ + + Source   +Edit   + +
+
+
+
S_ISVTX = 512'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IWGRP = 16'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IWOTH = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IWUSR = 128'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IXGRP = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IXOTH = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
S_IXUSR = 64'i32
+
+ + + Source   +Edit   + +
+
+
+
SA_NOCLDSTOP = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
SA_NOCLDWAIT = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
SA_NODEFER = 1073741824'i32
+
+ + + Source   +Edit   + +
+
+
+
SA_ONSTACK = 134217728'i32
+
+ + + Source   +Edit   + +
+
+
+
SA_RESETHAND = -2147483648'i32
+
+ + + Source   +Edit   + +
+
+
+
SA_RESTART = 268435456'i32
+
+ + + Source   +Edit   + +
+
+
+
SA_SIGINFO = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_2_C_BIND = 47'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_2_C_DEV = 48'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_2_CHAR_TERM = 95'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_2_FORT_DEV = 49'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_2_FORT_RUN = 50'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_2_LOCALEDEF = 52'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_2_PBS = 168'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_2_PBS_ACCOUNTING = 169'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_2_PBS_CHECKPOINT = 175'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_2_PBS_LOCATE = 170'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_2_PBS_MESSAGE = 171'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_2_PBS_TRACK = 172'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_2_SW_DEV = 51'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_2_UPE = 97'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_2_VERSION = 46'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_ADVISORY_INFO = 132'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_AIO_LISTIO_MAX = 23'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_AIO_MAX = 24'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_AIO_PRIO_DELTA_MAX = 25'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_ARG_MAX = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_ASYNCHRONOUS_IO = 12'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_ATEXIT_MAX = 87'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_BARRIERS = 133'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_BC_BASE_MAX = 36'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_BC_DIM_MAX = 37'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_BC_SCALE_MAX = 38'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_BC_STRING_MAX = 39'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_CHILD_MAX = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_CLK_TCK = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_CLOCK_SELECTION = 137'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_COLL_WEIGHTS_MAX = 40'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_CPUTIME = 138'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_DELAYTIMER_MAX = 26'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_EXPR_NEST_MAX = 42'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_FSYNC = 15'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_GETGR_R_SIZE_MAX = 69'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_GETPW_R_SIZE_MAX = 70'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_HOST_NAME_MAX = 180'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_IOV_MAX = 60'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_IPV6 = 235'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_JOB_CONTROL = 7'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_LINE_MAX = 43'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_LOGIN_NAME_MAX = 71'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_MAPPED_FILES = 16'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_MEMLOCK = 17'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_MEMLOCK_RANGE = 18'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_MEMORY_PROTECTION = 19'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_MESSAGE_PASSING = 20'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_MONOTONIC_CLOCK = 149'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_MQ_OPEN_MAX = 27'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_MQ_PRIO_MAX = 28'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_NGROUPS_MAX = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_NPROCESSORS_ONLN = 84'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_OPEN_MAX = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_PAGESIZE = 30'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_PRIORITIZED_IO = 13'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_PRIORITY_SCHEDULING = 10'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_RAW_SOCKETS = 236'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_RE_DUP_MAX = 44'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_READER_WRITER_LOCKS = 153'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_REALTIME_SIGNALS = 9'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_REGEXP = 155'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_RTSIG_MAX = 31'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_SAVED_IDS = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_SEM_NSEMS_MAX = 32'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_SEM_VALUE_MAX = 33'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_SEMAPHORES = 21'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_SHARED_MEMORY_OBJECTS = 22'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_SHELL = 157'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_SIGQUEUE_MAX = 34'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_SPAWN = 159'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_SPIN_LOCKS = 154'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_SPORADIC_SERVER = 160'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_SS_REPL_MAX = 241'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_STREAM_MAX = 5'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_SYMLOOP_MAX = 173'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_SYNCHRONIZED_IO = 14'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_THREAD_ATTR_STACKADDR = 77'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_THREAD_ATTR_STACKSIZE = 78'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_THREAD_CPUTIME = 139'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_THREAD_DESTRUCTOR_ITERATIONS = 73'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_THREAD_KEYS_MAX = 74'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_THREAD_PRIO_INHERIT = 80'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_THREAD_PRIO_PROTECT = 81'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_THREAD_PRIORITY_SCHEDULING = 79'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_THREAD_PROCESS_SHARED = 82'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_THREAD_SAFE_FUNCTIONS = 68'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_THREAD_SPORADIC_SERVER = 161'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_THREAD_STACK_MIN = 75'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_THREAD_THREADS_MAX = 76'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_THREADS = 67'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_TIMEOUTS = 164'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_TIMER_MAX = 35'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_TIMERS = 11'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_TRACE = 181'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_TRACE_EVENT_FILTER = 182'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_TRACE_EVENT_NAME_MAX = 242'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_TRACE_INHERIT = 183'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_TRACE_LOG = 184'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_TRACE_NAME_MAX = 243'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_TRACE_SYS_MAX = 244'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_TRACE_USER_EVENT_MAX = 245'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_TTY_NAME_MAX = 72'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_TYPED_MEMORY_OBJECTS = 165'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_TZNAME_MAX = 6'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_V6_ILP32_OFF32 = 176'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_V6_ILP32_OFFBIG = 177'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_V6_LP64_OFF64 = 178'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_V6_LPBIG_OFFBIG = 179'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_VERSION = 29'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_XBS5_ILP32_OFF32 = 125'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_XBS5_ILP32_OFFBIG = 126'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_XBS5_LP64_OFF64 = 127'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_XBS5_LPBIG_OFFBIG = 128'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_XOPEN_CRYPT = 92'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_XOPEN_ENH_I18N = 93'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_XOPEN_LEGACY = 129'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_XOPEN_REALTIME = 130'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_XOPEN_REALTIME_THREADS = 131'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_XOPEN_SHM = 94'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_XOPEN_STREAMS = 246'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_XOPEN_UNIX = 91'i32
+
+ + + Source   +Edit   + +
+
+
+
SC_XOPEN_VERSION = 89'i32
+
+ + + Source   +Edit   + +
+
+
+
SCHED_FIFO = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
SCHED_OTHER = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
SCHED_RR = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
SCM_RIGHTS = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
SEEK_CUR = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
SEEK_END = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
SEEK_SET = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
SEM_FAILED = nil
+
+ + + Source   +Edit   + +
+
+
+
SHUT_RD = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
SHUT_RDWR = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
SHUT_WR = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
SIG_BLOCK = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
SIG_DFL = 0
+
+ + + Source   +Edit   + +
+
+
+
SIG_ERR = -1
+
+ + + Source   +Edit   + +
+
+
+
SIG_HOLD = 2
+
+ + + Source   +Edit   + +
+
+
+
SIG_IGN = 1
+
+ + + Source   +Edit   + +
+
+
+
SIG_SETMASK = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
SIG_UNBLOCK = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGABRT = 6'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGALRM = 14'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGBUS = 7'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGCHLD = 17'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGCONT = 18'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGEV_NONE = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGEV_SIGNAL = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGEV_THREAD = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGFPE = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGHUP = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGILL = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGINT = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGKILL = 9'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGPIPE = 13'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGPOLL = 29'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGPROF = 27'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGQUIT = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGSEGV = 11'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGSTKSZ = 8192'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGSTOP = 19'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGSYS = 31'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGTERM = 15'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGTRAP = 5'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGTSTP = 20'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGTTIN = 21'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGTTOU = 22'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGURG = 23'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGUSR1 = 10'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGUSR2 = 12'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGVTALRM = 26'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGXCPU = 24'i32
+
+ + + Source   +Edit   + +
+
+
+
SIGXFSZ = 25'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_ACCEPTCONN = 30'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_BINDTODEVICE = 25'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_BROADCAST = 6'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_DEBUG = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_DONTROUTE = 5'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_ERROR = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_KEEPALIVE = 9'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_LINGER = 13'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_OOBINLINE = 10'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_RCVBUF = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_RCVLOWAT = 18'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_RCVTIMEO = 20'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_REUSEADDR = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_REUSEPORT = 15'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_SNDBUF = 7'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_SNDLOWAT = 19'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_SNDTIMEO = 21'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_TYPE = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
SOCK_CLOEXEC = 524288'i32
+
+ + + Source   +Edit   + +
+
+
+
SOCK_DGRAM = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
SOCK_RAW = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
SOCK_SEQPACKET = 5'i32
+
+ + + Source   +Edit   + +
+
+
+
SOCK_STREAM = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
Sockaddr_un_path_length = 108
+
+ + + Source   +Edit   + +
+
+
+
SOL_SOCKET = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
SOMAXCONN = 4096'i32
+
+ + + Source   +Edit   + +
+
+
+
SS_DISABLE = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
SS_ONSTACK = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
ST_NOSUID = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
ST_RDONLY = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
StatHasNanoseconds = true
+
+ + +Boolean flag that indicates if the system supports nanosecond time resolution in the fields of Stat. Note that the nanosecond based fields (Stat.st_atim, Stat.st_mtim and Stat.st_ctim) can be accessed without checking this flag, because this module defines fallback procs when they are not available. + Source   +Edit   + +
+
+
+
STDERR_FILENO = 2
+
+ + File number of stderr; + Source   +Edit   + +
+
+
+
STDIN_FILENO = 0
+
+ + File number of stdin; + Source   +Edit   + +
+
+
+
STDOUT_FILENO = 1
+
+ + File number of stdout; + Source   +Edit   + +
+
+
+
T_FMT = 131114'i32
+
+ + + Source   +Edit   + +
+
+
+
T_FMT_AMPM = 131115'i32
+
+ + + Source   +Edit   + +
+
+
+
TCP_NODELAY = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
THOUSEP = 65537'i32
+
+ + + Source   +Edit   + +
+
+
+
TIMER_ABSTIME = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
TRY_AGAIN = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
W_OK = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
WCONTINUED = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
WEXITED = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
WNOHANG = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
WNOWAIT = 16777216'i32
+
+ + + Source   +Edit   + +
+
+
+
WSTOPPED = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
WUNTRACED = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
X_OK = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
YESEXPR = 327680'i32
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `-`(a, b: Time): Time {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(a, b: Time): bool {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(x, y: SocketHandle): bool {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc accept(a1: SocketHandle; a2: ptr SockAddr; a3: ptr SockLen): SocketHandle {.
+    importc, header: "<sys/socket.h>", sideEffect, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc accept4(a1: SocketHandle; a2: ptr SockAddr; a3: ptr SockLen; flags: cint): SocketHandle {.
+    importc, header: "<sys/socket.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc access(a1: cstring; a2: cint): cint {.importc, header: "<unistd.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc aio_cancel(a1: cint; a2: ptr Taiocb): cint {.importc, header: "<aio.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc aio_error(a1: ptr Taiocb): cint {.importc, header: "<aio.h>", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc aio_fsync(a1: cint; a2: ptr Taiocb): cint {.importc, header: "<aio.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc aio_read(a1: ptr Taiocb): cint {.importc, header: "<aio.h>", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc aio_return(a1: ptr Taiocb): int {.importc, header: "<aio.h>", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc aio_suspend(a1: ptr ptr Taiocb; a2: cint; a3: ptr Timespec): cint {.
+    importc, header: "<aio.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc aio_write(a1: ptr Taiocb): cint {.importc, header: "<aio.h>", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc alarm(a1: cint): cint {.importc, header: "<unistd.h>", ...raises: [],
+                             tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc asctime(a1: var Tm): cstring {.importc, header: "<time.h>", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc asctime_r(a1: var Tm; a2: cstring): cstring {.importc, header: "<time.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc basename(a1: cstring): cstring {.importc, header: "<libgen.h>", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bindSocket(a1: SocketHandle; a2: ptr SockAddr; a3: SockLen): cint {.
+    importc: "bind", header: "<sys/socket.h>", ...raises: [], tags: [], forbids: [].}
+
+ + is Posix's bind, because bind is a reserved word + Source   +Edit   + +
+
+ +
+
+
+
proc bsd_signal(a1: cint; a2: proc (x: pointer) {.noconv.}) {.importc,
+    header: "<signal.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc catclose(a1: Nl_catd): cint {.importc, header: "<nl_types.h>", ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc catgets(a1: Nl_catd; a2, a3: cint; a4: cstring): cstring {.importc,
+    header: "<nl_types.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc catopen(a1: cstring; a2: cint): Nl_catd {.importc, header: "<nl_types.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc chdir(a1: cstring): cint {.importc, header: "<unistd.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc chmod(a1: cstring; a2: Mode): cint {.importc, header: "<sys/stat.h>",
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc chown(a1: cstring; a2: Uid; a3: Gid): cint {.importc, header: "<unistd.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clock(): Clock {.importc, header: "<time.h>", sideEffect, ...raises: [],
+                      tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clock_getcpuclockid(a1: Pid; a2: var ClockId): cint {.importc,
+    header: "<time.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clock_getres(a1: ClockId; a2: var Timespec): cint {.importc,
+    header: "<time.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clock_gettime(a1: ClockId; a2: var Timespec): cint {.importc,
+    header: "<time.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clock_nanosleep(a1: ClockId; a2: cint; a3: var Timespec; a4: var Timespec): cint {.
+    importc, header: "<time.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clock_settime(a1: ClockId; a2: var Timespec): cint {.importc,
+    header: "<time.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc close(a1: cint | SocketHandle): cint {.importc, header: "<unistd.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc closedir(a1: ptr DIR): cint {.importc, header: "<dirent.h>", ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc CMSG_DATA(cmsg: ptr Tcmsghdr): cstring {.importc, header: "<sys/socket.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc CMSG_FIRSTHDR(mhdr: ptr Tmsghdr): ptr Tcmsghdr {.importc,
+    header: "<sys/socket.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc CMSG_LEN(len: csize_t): csize_t {.importc, header: "<sys/socket.h>",
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc CMSG_NXTHDR(mhdr: ptr Tmsghdr; cmsg: ptr Tcmsghdr): ptr Tcmsghdr {.importc,
+    header: "<sys/socket.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc CMSG_SPACE(len: csize_t): csize_t {.importc, header: "<sys/socket.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc confstr(a1: cint; a2: cstring; a3: int): int {.importc,
+    header: "<unistd.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc connect(a1: SocketHandle; a2: ptr SockAddr; a3: SockLen): cint {.importc,
+    header: "<sys/socket.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc creat(a1: cstring; a2: Mode): cint {.importc, header: "<fcntl.h>",
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc crypt(a1, a2: cstring): cstring {.importc, header: "<unistd.h>",
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ctermid(a1: cstring): cstring {.importc, header: "<unistd.h>", ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ctime(a1: var Time): cstring {.importc, header: "<time.h>", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ctime_r(a1: var Time; a2: cstring): cstring {.importc, header: "<time.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc difftime(a1, a2: Time): cdouble {.importc, header: "<time.h>", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc dirname(a1: cstring): cstring {.importc, header: "<libgen.h>", ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc dlclose(a1: pointer): cint {.importc, header: "<dlfcn.h>", sideEffect,
+                                  ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc dlerror(): cstring {.importc, header: "<dlfcn.h>", sideEffect, ...raises: [],
+                          tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc dlopen(a1: cstring; a2: cint): pointer {.importc, header: "<dlfcn.h>",
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc dlsym(a1: pointer; a2: cstring): pointer {.importc, header: "<dlfcn.h>",
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc dup(a1: cint): cint {.importc, header: "<unistd.h>", ...raises: [], tags: [],
+                           forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc dup2(a1, a2: cint): cint {.importc, header: "<unistd.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc encrypt(a1: array[0 .. 63, char]; a2: cint) {.importc,
+    header: "<unistd.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc endgrent() {.importc, header: "<grp.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc endhostent() {.importc, header: "<netdb.h>", ...raises: [], tags: [],
+                    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc endnetent() {.importc, header: "<netdb.h>", ...raises: [], tags: [],
+                   forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc endprotoent() {.importc, header: "<netdb.h>", ...raises: [], tags: [],
+                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc endpwent() {.importc, header: "<pwd.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc endservent() {.importc, header: "<netdb.h>", ...raises: [], tags: [],
+                    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc execl(a1, a2: cstring): cint {.varargs, importc, header: "<unistd.h>",
+                                    sideEffect, ...raises: [], tags: [],
+                                    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc execle(a1, a2: cstring): cint {.varargs, importc, header: "<unistd.h>",
+                                     sideEffect, ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc execlp(a1, a2: cstring): cint {.varargs, importc, header: "<unistd.h>",
+                                     sideEffect, ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc execv(a1: cstring; a2: cstringArray): cint {.importc, header: "<unistd.h>",
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc execve(a1: cstring; a2, a3: cstringArray): cint {.importc,
+    header: "<unistd.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc execvp(a1: cstring; a2: cstringArray): cint {.importc,
+    header: "<unistd.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc execvpe(a1: cstring; a2: cstringArray; a3: cstringArray): cint {.importc,
+    header: "<unistd.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc exitnow(code: int) {.importc: "_exit", header: "<unistd.h>", ...raises: [],
+                          tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fchdir(a1: cint): cint {.importc, header: "<unistd.h>", sideEffect,
+                              ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fchmod(a1: cint; a2: Mode): cint {.importc, header: "<sys/stat.h>",
+                                        sideEffect, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fchown(a1: cint; a2: Uid; a3: Gid): cint {.importc, header: "<unistd.h>",
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fcntl(a1: cint | SocketHandle; a2: cint): cint {.varargs, importc,
+    header: "<fcntl.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc FD_CLR(a1: cint; a2: var TFdSet) {.importc, header: "<sys/select.h>",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc FD_ISSET(a1: cint | SocketHandle; a2: var TFdSet): cint {.importc,
+    header: "<sys/select.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc FD_SET(a1: cint | SocketHandle; a2: var TFdSet) {.importc: "FD_SET",
+    header: "<sys/select.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc FD_ZERO(a1: var TFdSet) {.importc, header: "<sys/select.h>", ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fdatasync(a1: cint): cint {.importc, header: "<unistd.h>", ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fmtmsg(a1: int; a2: cstring; a3: cint; a4, a5, a6: cstring): cint {.
+    importc, header: "<fmtmsg.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fnmatch(a1, a2: cstring; a3: cint): cint {.importc, header: "<fnmatch.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fork(): Pid {.importc, header: "<unistd.h>", sideEffect, ...raises: [],
+                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fpathconf(a1, a2: cint): int {.importc, header: "<unistd.h>", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc freeAddrInfo(a1: ptr AddrInfo) {.importc: "freeaddrinfo",
+                                      header: "<netdb.h>", ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fstat(a1: cint; a2: var Stat): cint {.importc, header: "<sys/stat.h>",
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fstatvfs(a1: cint; a2: var Statvfs): cint {.importc,
+    header: "<sys/statvfs.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc fsync(a1: cint): cint {.importc, header: "<unistd.h>", ...raises: [],
+                             tags: [], forbids: [].}
+
+ + synchronize a file's buffer cache to the storage device + Source   +Edit   + +
+
+ +
+
+
+
proc ftok(a1: cstring; a2: cint): Key {.importc, header: "<sys/ipc.h>",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ftruncate(a1: cint; a2: Off): cint {.importc, header: "<unistd.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ftw(a1: cstring;
+         a2: proc (x1: cstring; x2: ptr Stat; x3: cint): cint {.noconv.};
+         a3: cint): cint {.importc, header: "<ftw.h>", ...raises: [], tags: [],
+                           forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc gai_strerror(a1: cint): cstring {.importc: "(char *)$1",
+                                       header: "<netdb.h>", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getaddrinfo(a1, a2: cstring; a3: ptr AddrInfo; a4: var ptr AddrInfo): cint {.
+    importc, header: "<netdb.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getcontext(a1: var Ucontext): cint {.importc, header: "<ucontext.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getcwd(a1: cstring; a2: int): cstring {.importc, header: "<unistd.h>",
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getdate(a1: cstring): ptr Tm {.importc, header: "<time.h>", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getegid(): Gid {.importc, header: "<unistd.h>", sideEffect, ...raises: [],
+                      tags: [], forbids: [].}
+
+ + returns the effective group ID of the calling process + Source   +Edit   + +
+
+ +
+
+
+
proc geteuid(): Uid {.importc, header: "<unistd.h>", sideEffect, ...raises: [],
+                      tags: [], forbids: [].}
+
+ + returns the effective user ID of the calling process + Source   +Edit   + +
+
+ +
+
+
+
proc getgid(): Gid {.importc, header: "<unistd.h>", sideEffect, ...raises: [],
+                     tags: [], forbids: [].}
+
+ + returns the real group ID of the calling process + Source   +Edit   + +
+
+ +
+
+
+
proc getgrent(): ptr Group {.importc, header: "<grp.h>", ...raises: [], tags: [],
+                             forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getgrgid(a1: Gid): ptr Group {.importc, header: "<grp.h>", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getgrgid_r(a1: Gid; a2: ptr Group; a3: cstring; a4: int; a5: ptr ptr Group): cint {.
+    importc, header: "<grp.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getgrnam(a1: cstring): ptr Group {.importc, header: "<grp.h>", ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getgrnam_r(a1: cstring; a2: ptr Group; a3: cstring; a4: int;
+                a5: ptr ptr Group): cint {.importc, header: "<grp.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getgroups(a1: cint; a2: ptr array[0 .. 255, Gid]): cint {.importc,
+    header: "<unistd.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc gethostbyaddr(a1: pointer; a2: SockLen; a3: cint): ptr Hostent {.importc,
+    header: "<netdb.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc gethostbyname(a1: cstring): ptr Hostent {.importc, header: "<netdb.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc gethostent(): ptr Hostent {.importc, header: "<netdb.h>", ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc gethostid(): int {.importc, header: "<unistd.h>", sideEffect, ...raises: [],
+                        tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc gethostname(a1: cstring; a2: int): cint {.importc, header: "<unistd.h>",
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getlogin(): cstring {.importc, header: "<unistd.h>", sideEffect,
+                           ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getlogin_r(a1: cstring; a2: int): cint {.importc, header: "<unistd.h>",
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getnameinfo(a1: ptr SockAddr; a2: SockLen; a3: cstring; a4: SockLen;
+                 a5: cstring; a6: SockLen; a7: cint): cint {.importc,
+    header: "<netdb.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getnetbyaddr(a1: int32; a2: cint): ptr Tnetent {.importc,
+    header: "<netdb.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getnetbyname(a1: cstring): ptr Tnetent {.importc, header: "<netdb.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getnetent(): ptr Tnetent {.importc, header: "<netdb.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getopt(a1: cint; a2: cstringArray; a3: cstring): cint {.importc,
+    header: "<unistd.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getpeername(a1: SocketHandle; a2: ptr SockAddr; a3: ptr SockLen): cint {.
+    importc, header: "<sys/socket.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getpgid(a1: Pid): Pid {.importc, header: "<unistd.h>", ...raises: [],
+                             tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getpgrp(): Pid {.importc, header: "<unistd.h>", ...raises: [], tags: [],
+                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getpid(): Pid {.importc, header: "<unistd.h>", sideEffect, ...raises: [],
+                     tags: [], forbids: [].}
+
+ + returns the process ID (PID) of the calling process + Source   +Edit   + +
+
+ +
+
+
+
proc getppid(): Pid {.importc, header: "<unistd.h>", sideEffect, ...raises: [],
+                      tags: [], forbids: [].}
+
+ + returns the process ID of the parent of the calling process + Source   +Edit   + +
+
+ +
+
+
+
proc getprotobyname(a1: cstring): ptr Protoent {.importc, header: "<netdb.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getprotobynumber(a1: cint): ptr Protoent {.importc, header: "<netdb.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getprotoent(): ptr Protoent {.importc, header: "<netdb.h>", ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getpwent(): ptr Passwd {.importc, header: "<pwd.h>", ...raises: [], tags: [],
+                              forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getpwnam(a1: cstring): ptr Passwd {.importc, header: "<pwd.h>", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getpwnam_r(a1: cstring; a2: ptr Passwd; a3: cstring; a4: int;
+                a5: ptr ptr Passwd): cint {.importc, header: "<pwd.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getpwuid(a1: Uid): ptr Passwd {.importc, header: "<pwd.h>", ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getpwuid_r(a1: Uid; a2: ptr Passwd; a3: cstring; a4: int;
+                a5: ptr ptr Passwd): cint {.importc, header: "<pwd.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getrlimit(resource: cint; rlp: var RLimit): cint {.importc: "getrlimit",
+    header: "<sys/resource.h>", ...raises: [], tags: [], forbids: [].}
+
+ + The getrlimit() system call gets resource limits. + Source   +Edit   + +
+
+ +
+
+
+
proc getrusage(who: cint; rusage: ptr Rusage): cint {.importc,
+    header: "<sys/resource.h>", discardable, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getservbyname(a1, a2: cstring): ptr Servent {.importc, header: "<netdb.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getservbyport(a1: cint; a2: cstring): ptr Servent {.importc,
+    header: "<netdb.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getservent(): ptr Servent {.importc, header: "<netdb.h>", ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getsid(a1: Pid): Pid {.importc, header: "<unistd.h>", sideEffect,
+                            ...raises: [], tags: [], forbids: [].}
+
+ + returns the session ID of the calling process + Source   +Edit   + +
+
+ +
+
+
+
proc getsockname(a1: SocketHandle; a2: ptr SockAddr; a3: ptr SockLen): cint {.
+    importc, header: "<sys/socket.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getsockopt(a1: SocketHandle; a2, a3: cint; a4: pointer; a5: ptr SockLen): cint {.
+    importc, header: "<sys/socket.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getuid(): Uid {.importc, header: "<unistd.h>", sideEffect, ...raises: [],
+                     tags: [], forbids: [].}
+
+ + returns the real user ID of the calling process + Source   +Edit   + +
+
+ +
+
+
+
proc getwd(a1: cstring): cstring {.importc, header: "<unistd.h>", ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc glob(a1: cstring; a2: cint;
+          a3: proc (x1: cstring; x2: cint): cint {.noconv.}; a4: ptr Glob): cint {.
+    importc, header: "<glob.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + Filename globbing. Use os.walkPattern() and similar. + Source   +Edit   + +
+
+ +
+
+
+
proc globfree(a1: ptr Glob) {.importc, header: "<glob.h>", ...raises: [], tags: [],
+                              forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc gmtime(a1: var Time): ptr Tm {.importc, header: "<time.h>", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc gmtime_r(a1: var Time; a2: var Tm): ptr Tm {.importc, header: "<time.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hstrerror(herrnum: cint): cstring {.importc: "(char *)$1",
+    header: "<netdb.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc htonl(a1: uint32): uint32 {.importc, header: "<arpa/inet.h>", ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc htons(a1: uint16): uint16 {.importc, header: "<arpa/inet.h>", ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc iconv(a1: Iconv; a2: var cstring; a3: var int; a4: var cstring; a5: var int): int {.
+    importc, header: "<iconv.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc iconv_close(a1: Iconv): cint {.importc, header: "<iconv.h>", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc iconv_open(a1, a2: cstring): Iconv {.importc, header: "<iconv.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc if_freenameindex(a1: ptr Tif_nameindex) {.importc, header: "<net/if.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc if_indextoname(a1: cint; a2: cstring): cstring {.importc,
+    header: "<net/if.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc if_nameindex(): ptr Tif_nameindex {.importc, header: "<net/if.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc if_nametoindex(a1: cstring): cint {.importc, header: "<net/if.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc IN6_IS_ADDR_LINKLOCAL(a1: ptr In6Addr): cint {.importc,
+    header: "<netinet/in.h>", ...raises: [], tags: [], forbids: [].}
+
+ + Unicast link-local address. + Source   +Edit   + +
+
+ +
+
+
+
proc IN6_IS_ADDR_LOOPBACK(a1: ptr In6Addr): cint {.importc,
+    header: "<netinet/in.h>", ...raises: [], tags: [], forbids: [].}
+
+ + Loopback address. + Source   +Edit   + +
+
+ +
+
+
+
proc IN6_IS_ADDR_MC_GLOBAL(a1: ptr In6Addr): cint {.importc,
+    header: "<netinet/in.h>", ...raises: [], tags: [], forbids: [].}
+
+ + Multicast global address. + Source   +Edit   + +
+
+ +
+
+
+
proc IN6_IS_ADDR_MC_LINKLOCAL(a1: ptr In6Addr): cint {.importc,
+    header: "<netinet/in.h>", ...raises: [], tags: [], forbids: [].}
+
+ + Multicast link-local address. + Source   +Edit   + +
+
+ +
+
+
+
proc IN6_IS_ADDR_MC_NODELOCAL(a1: ptr In6Addr): cint {.importc,
+    header: "<netinet/in.h>", ...raises: [], tags: [], forbids: [].}
+
+ + Multicast node-local address. + Source   +Edit   + +
+
+ +
+
+
+
proc IN6_IS_ADDR_MC_ORGLOCAL(a1: ptr In6Addr): cint {.importc,
+    header: "<netinet/in.h>", ...raises: [], tags: [], forbids: [].}
+
+ + Multicast organization-local address. + Source   +Edit   + +
+
+ +
+
+
+
proc IN6_IS_ADDR_MC_SITELOCAL(a1: ptr In6Addr): cint {.importc,
+    header: "<netinet/in.h>", ...raises: [], tags: [], forbids: [].}
+
+ + Multicast site-local address. + Source   +Edit   + +
+
+ +
+
+
+
proc IN6_IS_ADDR_MULTICAST(a1: ptr In6Addr): cint {.importc,
+    header: "<netinet/in.h>", ...raises: [], tags: [], forbids: [].}
+
+ + Multicast address. + Source   +Edit   + +
+
+ +
+
+
+
proc IN6_IS_ADDR_SITELOCAL(a1: ptr In6Addr): cint {.importc,
+    header: "<netinet/in.h>", ...raises: [], tags: [], forbids: [].}
+
+ + Unicast site-local address. + Source   +Edit   + +
+
+ +
+
+
+
proc IN6_IS_ADDR_UNSPECIFIED(a1: ptr In6Addr): cint {.importc,
+    header: "<netinet/in.h>", ...raises: [], tags: [], forbids: [].}
+
+ + Unspecified address. + Source   +Edit   + +
+
+ +
+
+
+
proc IN6_IS_ADDR_V4COMPAT(a1: ptr In6Addr): cint {.importc,
+    header: "<netinet/in.h>", ...raises: [], tags: [], forbids: [].}
+
+ + IPv4-compatible address. + Source   +Edit   + +
+
+ +
+
+
+
proc IN6_IS_ADDR_V4MAPPED(a1: ptr In6Addr): cint {.importc,
+    header: "<netinet/in.h>", ...raises: [], tags: [], forbids: [].}
+
+ + IPv4 mapped address. + Source   +Edit   + +
+
+ +
+
+
+
proc IN6ADDR_ANY_INIT(): In6Addr {.importc, header: "<netinet/in.h>",
+                                   ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc IN6ADDR_LOOPBACK_INIT(): In6Addr {.importc, header: "<netinet/in.h>",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inet_addr(a1: cstring): InAddrT {.importc, header: "<arpa/inet.h>",
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inet_ntoa(a1: InAddr): cstring {.importc, header: "<arpa/inet.h>",
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inet_ntop(a1: cint; a2: pointer | ptr InAddr | ptr In6Addr; a3: cstring;
+               a4: int32): cstring {.importc: "(char *)$1",
+                                     header: "<arpa/inet.h>", ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inet_pton(a1: cint; a2: cstring; a3: pointer | ptr InAddr | ptr In6Addr): cint {.
+    importc, header: "<arpa/inet.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ioctl(f: FileHandle; device: uint): int {.importc: "ioctl",
+    header: "<sys/ioctl.h>", varargs, ...tags: [WriteIOEffect], raises: [],
+    forbids: [].}
+
+ + A system call for device-specific input/output operations and other operations which cannot be expressed by regular system calls + Source   +Edit   + +
+
+ +
+
+
+
proc isatty(a1: cint): cint {.importc, header: "<unistd.h>", ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc kill(a1: Pid; a2: cint): cint {.importc, header: "<signal.h>", sideEffect,
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc killpg(a1: Pid; a2: cint): cint {.importc, header: "<signal.h>",
+                                       sideEffect, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lchown(a1: cstring; a2: Uid; a3: Gid): cint {.importc,
+    header: "<unistd.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
proc lio_listio(a1: cint; a2: ptr ptr Taiocb; a3: cint; a4: ptr SigEvent): cint {.
+    importc, header: "<aio.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc listen(a1: SocketHandle; a2: cint): cint {.importc,
+    header: "<sys/socket.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc localeconv(): ptr Lconv {.importc, header: "<locale.h>", ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc localtime(a1: var Time): ptr Tm {.importc, header: "<time.h>", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc localtime_r(a1: var Time; a2: var Tm): ptr Tm {.importc,
+    header: "<time.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lockf(a1, a2: cint; a3: Off): cint {.importc, header: "<unistd.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lseek(a1: cint; a2: Off; a3: cint): Off {.importc, header: "<unistd.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lstat(a1: cstring; a2: var Stat): cint {.importc, header: "<sys/stat.h>",
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc makecontext(a1: var Ucontext; a4: proc () {.noconv.}; a3: cint) {.varargs,
+    importc, header: "<ucontext.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mkdir(a1: cstring; a2: Mode): cint {.importc, header: "<sys/stat.h>",
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + Use os.createDir() and similar. + Source   +Edit   + +
+
+ +
+
+
+
proc mkdtemp(tmpl: cstring): pointer {.importc, header: "<stdlib.h>",
+                                       sideEffect, ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mkfifo(a1: cstring; a2: Mode): cint {.importc, header: "<sys/stat.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mknod(a1: cstring; a2: Mode; a3: Dev): cint {.importc,
+    header: "<sys/stat.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mkostemp(tmpl: cstring; oflags: cint): cint {.importc,
+    header: "<stdlib.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mkostemps(tmpl: cstring; suffixlen: cint; oflags: cint): cint {.importc,
+    header: "<stdlib.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mkstemp(tmpl: cstring): cint {.importc, header: "<stdlib.h>", sideEffect,
+                                    ...raises: [], tags: [], forbids: [].}
+
+ + Creates a unique temporary file.
Warning: +The tmpl argument is written to by mkstemp and thus can't be a string literal. If in doubt make a copy of the cstring before passing it in.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc mkstemps(tmpl: cstring; suffixlen: int): cint {.importc,
+    header: "<stdlib.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + Creates a unique temporary file.
Warning: +The tmpl argument is written to by mkstemps and thus can't be a string literal. If in doubt make a copy of the cstring before passing it in.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc mktime(a1: var Tm): Time {.importc, header: "<time.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mlock(a1: pointer; a2: int): cint {.importc, header: "<sys/mman.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mlockall(a1: cint): cint {.importc, header: "<sys/mman.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mmap(a1: pointer; a2: int; a3, a4, a5: cint; a6: Off): pointer {.importc,
+    header: "<sys/mman.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mprotect(a1: pointer; a2: int; a3: cint): cint {.importc,
+    header: "<sys/mman.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mq_close(mqdes: Mqd): cint {.importc, header: "<mqueue.h>", ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mq_getattr(mqdes: Mqd; attribute: ptr MqAttr): cint {.importc,
+    header: "<mqueue.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mq_notify(mqdes: Mqd; event: ptr SigEvent): cint {.importc,
+    header: "<mqueue.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mq_open(name: cstring; flags: cint): Mqd {.varargs, importc,
+    header: "<mqueue.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mq_receive(mqdes: Mqd; buffer: cstring; length: csize_t;
+                priority: var cuint): int {.importc, header: "<mqueue.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mq_send(mqdes: Mqd; buffer: cstring; length: csize_t; priority: cuint): cint {.
+    importc, header: "<mqueue.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mq_setattr(mqdes: Mqd; newAttribute, oldAttribute: ptr MqAttr): cint {.
+    importc, header: "<mqueue.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mq_timedreceive(mqdes: Mqd; buffer: cstring; length: csize_t;
+                     priority: cuint; timeout: ptr Timespec): int {.importc,
+    header: "<mqueue.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mq_timedsend(mqdes: Mqd; buffer: cstring; length: csize_t; priority: cuint;
+                  timeout: ptr Timespec): cint {.importc, header: "<mqueue.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
proc msync(a1: pointer; a2: int; a3: cint): cint {.importc,
+    header: "<sys/mman.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc munlock(a1: pointer; a2: int): cint {.importc, header: "<sys/mman.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc munlockall(): cint {.importc, header: "<sys/mman.h>", ...raises: [], tags: [],
+                          forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc munmap(a1: pointer; a2: int): cint {.importc, header: "<sys/mman.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nanosleep(a1, a2: var Timespec): cint {.importc, header: "<time.h>",
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nice(a1: cint): cint {.importc, header: "<unistd.h>", ...raises: [], tags: [],
+                            forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nl_langinfo(a1: Nl_item): cstring {.importc, header: "<langinfo.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ntohl(a1: uint32): uint32 {.importc, header: "<arpa/inet.h>", ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ntohs(a1: uint16): uint16 {.importc, header: "<arpa/inet.h>", ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc open(a1: cstring; a2: cint; mode: Mode | cint = 0.Mode): cint {.inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc opendir(a1: cstring): ptr DIR {.importc, header: "<dirent.h>", sideEffect,
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pathconf(a1: cstring; a2: cint): int {.importc, header: "<unistd.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pause(): cint {.importc, header: "<unistd.h>", ...raises: [], tags: [],
+                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pclose(a: File): cint {.importc, header: "<stdio.h>", ...raises: [], tags: [],
+                             forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pipe(a: array[0 .. 1, cint]): cint {.importc, header: "<unistd.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc poll(a1: ptr TPollfd; a2: Tnfds; a3: cint): cint {.importc,
+    header: "<poll.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc popen(a1, a2: cstring): File {.importc, header: "<stdio.h>", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_fadvise(a1: cint; a2, a3: Off; a4: cint): cint {.importc,
+    header: "<fcntl.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_fallocate(a1: cint; a2, a3: Off): cint {.importc,
+    header: "<fcntl.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_madvise(a1: pointer; a2: int; a3: cint): cint {.importc,
+    header: "<sys/mman.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_mem_offset(a1: pointer; a2: int; a3: var Off; a4: var int;
+                      a5: var cint): cint {.importc, header: "<sys/mman.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_memalign(memptr: pointer; alignment: csize_t; size: csize_t): cint {.
+    importc, header: "<stdlib.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawn(a1: var Pid; a2: cstring; a3: var Tposix_spawn_file_actions;
+                 a4: var Tposix_spawnattr; a5, a6: cstringArray): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawn_file_actions_addclose(a1: var Tposix_spawn_file_actions;
+                                       a2: cint): cint {.importc,
+    header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawn_file_actions_adddup2(a1: var Tposix_spawn_file_actions;
+                                      a2, a3: cint): cint {.importc,
+    header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawn_file_actions_addopen(a1: var Tposix_spawn_file_actions;
+                                      a2: cint; a3: cstring; a4: cint; a5: Mode): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawn_file_actions_destroy(a1: var Tposix_spawn_file_actions): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawn_file_actions_init(a1: var Tposix_spawn_file_actions): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawnattr_destroy(a1: var Tposix_spawnattr): cint {.importc,
+    header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawnattr_getflags(a1: var Tposix_spawnattr; a2: var cshort): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawnattr_getpgroup(a1: var Tposix_spawnattr; a2: var Pid): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawnattr_getschedparam(a1: var Tposix_spawnattr; a2: var Sched_param): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawnattr_getschedpolicy(a1: var Tposix_spawnattr; a2: var cint): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawnattr_getsigdefault(a1: var Tposix_spawnattr; a2: var Sigset): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawnattr_getsigmask(a1: var Tposix_spawnattr; a2: var Sigset): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawnattr_init(a1: var Tposix_spawnattr): cint {.importc,
+    header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawnattr_setflags(a1: var Tposix_spawnattr; a2: cint): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawnattr_setpgroup(a1: var Tposix_spawnattr; a2: Pid): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawnattr_setschedparam(a1: var Tposix_spawnattr; a2: var Sched_param): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawnattr_setschedpolicy(a1: var Tposix_spawnattr; a2: cint): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawnattr_setsigdefault(a1: var Tposix_spawnattr; a2: var Sigset): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawnattr_setsigmask(a1: var Tposix_spawnattr; a2: var Sigset): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_spawnp(a1: var Pid; a2: cstring; a3: var Tposix_spawn_file_actions;
+                  a4: var Tposix_spawnattr; a5, a6: cstringArray): cint {.
+    importc, header: "<spawn.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc posix_typed_mem_open(a1: cstring; a2, a3: cint): cint {.importc,
+    header: "<sys/mman.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pread(a1: cint; a2: pointer; a3: int; a4: Off): int {.importc,
+    header: "<unistd.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pselect(a1: cint; a2, a3, a4: ptr TFdSet; a5: ptr Timespec; a6: var Sigset): cint {.
+    importc, header: "<sys/select.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_atfork(a1, a2, a3: proc () {.noconv.}): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_destroy(a1: ptr Pthread_attr): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_getdetachstate(a1: ptr Pthread_attr; a2: cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_getguardsize(a1: ptr Pthread_attr; a2: var cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_getinheritsched(a1: ptr Pthread_attr; a2: var cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_getschedparam(a1: ptr Pthread_attr; a2: ptr Sched_param): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_getschedpolicy(a1: ptr Pthread_attr; a2: var cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_getscope(a1: ptr Pthread_attr; a2: var cint): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_getstack(a1: ptr Pthread_attr; a2: var pointer; a3: var int): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_getstackaddr(a1: ptr Pthread_attr; a2: var pointer): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_getstacksize(a1: ptr Pthread_attr; a2: var int): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_init(a1: ptr Pthread_attr): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_setdetachstate(a1: ptr Pthread_attr; a2: cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_setguardsize(a1: ptr Pthread_attr; a2: int): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_setinheritsched(a1: ptr Pthread_attr; a2: cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_setschedparam(a1: ptr Pthread_attr; a2: ptr Sched_param): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_setschedpolicy(a1: ptr Pthread_attr; a2: cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_setscope(a1: ptr Pthread_attr; a2: cint): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_setstack(a1: ptr Pthread_attr; a2: pointer; a3: int): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_setstackaddr(a1: ptr Pthread_attr; a2: pointer): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_setstacksize(a1: ptr Pthread_attr; a2: int): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_barrier_destroy(a1: ptr Pthread_barrier): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_barrier_init(a1: ptr Pthread_barrier; a2: ptr Pthread_barrierattr;
+                          a3: cint): cint {.importc, header: "<pthread.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_barrier_wait(a1: ptr Pthread_barrier): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_barrierattr_destroy(a1: ptr Pthread_barrierattr): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_barrierattr_getpshared(a1: ptr Pthread_barrierattr; a2: var cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_barrierattr_init(a1: ptr Pthread_barrierattr): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_barrierattr_setpshared(a1: ptr Pthread_barrierattr; a2: cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_cancel(a1: Pthread): cint {.importc, header: "<pthread.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_cleanup_pop(a1: cint) {.importc, header: "<pthread.h>", ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_cleanup_push(a1: proc (x: pointer) {.noconv.}; a2: pointer) {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_cond_broadcast(a1: ptr Pthread_cond): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_cond_destroy(a1: ptr Pthread_cond): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_cond_init(a1: ptr Pthread_cond; a2: ptr Pthread_condattr): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_cond_signal(a1: ptr Pthread_cond): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_cond_timedwait(a1: ptr Pthread_cond; a2: ptr Pthread_mutex;
+                            a3: ptr Timespec): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_cond_wait(a1: ptr Pthread_cond; a2: ptr Pthread_mutex): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_condattr_destroy(a1: ptr Pthread_condattr): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_condattr_getclock(a1: ptr Pthread_condattr; a2: var ClockId): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_condattr_getpshared(a1: ptr Pthread_condattr; a2: var cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_condattr_init(a1: ptr Pthread_condattr): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_condattr_setclock(a1: ptr Pthread_condattr; a2: ClockId): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_condattr_setpshared(a1: ptr Pthread_condattr; a2: cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_create(a1: ptr Pthread; a2: ptr Pthread_attr;
+                    a3: proc (x: pointer): pointer {.noconv.}; a4: pointer): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_detach(a1: Pthread): cint {.importc, header: "<pthread.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_equal(a1, a2: Pthread): cint {.importc, header: "<pthread.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_exit(a1: pointer) {.importc, header: "<pthread.h>", ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_getconcurrency(): cint {.importc, header: "<pthread.h>",
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_getcpuclockid(a1: Pthread; a2: var ClockId): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_getschedparam(a1: Pthread; a2: var cint; a3: ptr Sched_param): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_getspecific(a1: Pthread_key): pointer {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_join(a1: Pthread; a2: ptr pointer): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_key_create(a1: ptr Pthread_key; a2: proc (x: pointer) {.noconv.}): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_key_delete(a1: Pthread_key): cint {.importc, header: "<pthread.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_kill(a1: Pthread; a2: cint): cint {.importc, header: "<signal.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutex_destroy(a1: ptr Pthread_mutex): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutex_getprioceiling(a1: ptr Pthread_mutex; a2: var cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutex_init(a1: ptr Pthread_mutex; a2: ptr Pthread_mutexattr): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutex_lock(a1: ptr Pthread_mutex): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutex_setprioceiling(a1: ptr Pthread_mutex; a2: cint; a3: var cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutex_timedlock(a1: ptr Pthread_mutex; a2: ptr Timespec): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutex_trylock(a1: ptr Pthread_mutex): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutex_unlock(a1: ptr Pthread_mutex): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutexattr_destroy(a1: ptr Pthread_mutexattr): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutexattr_getprioceiling(a1: ptr Pthread_mutexattr; a2: var cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutexattr_getprotocol(a1: ptr Pthread_mutexattr; a2: var cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutexattr_getpshared(a1: ptr Pthread_mutexattr; a2: var cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutexattr_gettype(a1: ptr Pthread_mutexattr; a2: var cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutexattr_init(a1: ptr Pthread_mutexattr): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutexattr_setprioceiling(a1: ptr Pthread_mutexattr; a2: cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutexattr_setprotocol(a1: ptr Pthread_mutexattr; a2: cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutexattr_setpshared(a1: ptr Pthread_mutexattr; a2: cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_mutexattr_settype(a1: ptr Pthread_mutexattr; a2: cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_once(a1: ptr Pthread_once; a2: proc () {.noconv.}): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_rwlock_destroy(a1: ptr Pthread_rwlock): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_rwlock_init(a1: ptr Pthread_rwlock; a2: ptr Pthread_rwlockattr): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_rwlock_rdlock(a1: ptr Pthread_rwlock): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_rwlock_timedrdlock(a1: ptr Pthread_rwlock; a2: ptr Timespec): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_rwlock_timedwrlock(a1: ptr Pthread_rwlock; a2: ptr Timespec): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_rwlock_tryrdlock(a1: ptr Pthread_rwlock): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_rwlock_trywrlock(a1: ptr Pthread_rwlock): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_rwlock_unlock(a1: ptr Pthread_rwlock): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_rwlock_wrlock(a1: ptr Pthread_rwlock): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_rwlockattr_destroy(a1: ptr Pthread_rwlockattr): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_rwlockattr_getpshared(a1: ptr Pthread_rwlockattr; a2: var cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_rwlockattr_init(a1: ptr Pthread_rwlockattr): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_rwlockattr_setpshared(a1: ptr Pthread_rwlockattr; a2: cint): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_self(): Pthread {.importc, header: "<pthread.h>", ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_setcancelstate(a1: cint; a2: var cint): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_setcanceltype(a1: cint; a2: var cint): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_setconcurrency(a1: cint): cint {.importc, header: "<pthread.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_setschedparam(a1: Pthread; a2: cint; a3: ptr Sched_param): cint {.
+    importc, header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_setschedprio(a1: Pthread; a2: cint): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_setspecific(a1: Pthread_key; a2: pointer): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_sigmask(a1: cint; a2, a3: var Sigset): cint {.importc,
+    header: "<signal.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_spin_destroy(a1: ptr Pthread_spinlock): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_spin_init(a1: ptr Pthread_spinlock; a2: cint): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_spin_lock(a1: ptr Pthread_spinlock): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_spin_trylock(a1: ptr Pthread_spinlock): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_spin_unlock(a1: ptr Pthread_spinlock): cint {.importc,
+    header: "<pthread.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_testcancel() {.importc, header: "<pthread.h>", ...raises: [],
+                            tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pwrite(a1: cint; a2: pointer; a3: int; a4: Off): int {.importc,
+    header: "<unistd.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `raise`(a1: cint): cint {.importc, header: "<signal.h>", ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc read(a1: cint; a2: pointer; a3: int): int {.importc, header: "<unistd.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc readdir(a1: ptr DIR): ptr Dirent {.importc, header: "<dirent.h>",
+                                        sideEffect, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc readdir_r(a1: ptr DIR; a2: ptr Dirent; a3: ptr ptr Dirent): cint {.importc,
+    header: "<dirent.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
proc readv(a1: cint; a2: ptr IOVec; a3: cint): int {.importc,
+    header: "<sys/uio.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc realpath(name, resolved: cstring): cstring {.importc: "realpath",
+    header: "<stdlib.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc recv(a1: SocketHandle; a2: pointer; a3: int; a4: cint): int {.importc,
+    header: "<sys/socket.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc recvfrom(a1: SocketHandle; a2: pointer; a3: int; a4: cint;
+              a5: ptr SockAddr; a6: ptr SockLen): int {.importc,
+    header: "<sys/socket.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc recvmsg(a1: SocketHandle; a2: ptr Tmsghdr; a3: cint): int {.importc,
+    header: "<sys/socket.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rewinddir(a1: ptr DIR) {.importc, header: "<dirent.h>", ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rmdir(a1: cstring): cint {.importc, header: "<unistd.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc S_ISBLK(m: Mode): bool {.importc, header: "<sys/stat.h>", ...raises: [],
+                              tags: [], forbids: [].}
+
+ + Test for a block special file. + Source   +Edit   + +
+
+ +
+
+
+
proc S_ISCHR(m: Mode): bool {.importc, header: "<sys/stat.h>", ...raises: [],
+                              tags: [], forbids: [].}
+
+ + Test for a character special file. + Source   +Edit   + +
+
+ +
+
+
+
proc S_ISDIR(m: Mode): bool {.importc, header: "<sys/stat.h>", ...raises: [],
+                              tags: [], forbids: [].}
+
+ + Test for a directory. + Source   +Edit   + +
+
+ +
+
+
+
proc S_ISFIFO(m: Mode): bool {.importc, header: "<sys/stat.h>", ...raises: [],
+                               tags: [], forbids: [].}
+
+ + Test for a pipe or FIFO special file. + Source   +Edit   + +
+
+ +
+
+
+
proc S_ISLNK(m: Mode): bool {.importc, header: "<sys/stat.h>", ...raises: [],
+                              tags: [], forbids: [].}
+
+ + Test for a symbolic link. + Source   +Edit   + +
+
+ +
+
+
+
proc S_ISREG(m: Mode): bool {.importc, header: "<sys/stat.h>", ...raises: [],
+                              tags: [], forbids: [].}
+
+ + Test for a regular file. + Source   +Edit   + +
+
+ +
+
+
+
proc S_ISSOCK(m: Mode): bool {.importc, header: "<sys/stat.h>", ...raises: [],
+                               tags: [], forbids: [].}
+
+ + Test for a socket. + Source   +Edit   + +
+
+ +
+
+
+
proc S_TYPEISMQ(buf: var Stat): bool {.importc, header: "<sys/stat.h>",
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + Test for a message queue. + Source   +Edit   + +
+
+ +
+
+
+
proc S_TYPEISSEM(buf: var Stat): bool {.importc, header: "<sys/stat.h>",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + Test for a semaphore. + Source   +Edit   + +
+
+ +
+
+
+
proc S_TYPEISSHM(buf: var Stat): bool {.importc, header: "<sys/stat.h>",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + Test for a shared memory object. + Source   +Edit   + +
+
+ +
+
+
+
proc S_TYPEISTMO(buf: var Stat): bool {.importc, header: "<sys/stat.h>",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + Test macro for a typed memory object. + Source   +Edit   + +
+
+ +
+
+
+
proc sa_sigaction=(v: var Sigaction;
+                   x: proc (x: cint; y: ptr SigInfo; z: pointer) {.noconv.}) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sched_get_priority_max(a1: cint): cint {.importc, header: "<sched.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sched_get_priority_min(a1: cint): cint {.importc, header: "<sched.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sched_getparam(a1: Pid; a2: var Sched_param): cint {.importc,
+    header: "<sched.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sched_getscheduler(a1: Pid): cint {.importc, header: "<sched.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sched_rr_get_interval(a1: Pid; a2: var Timespec): cint {.importc,
+    header: "<sched.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sched_setparam(a1: Pid; a2: var Sched_param): cint {.importc,
+    header: "<sched.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sched_setscheduler(a1: Pid; a2: cint; a3: var Sched_param): cint {.importc,
+    header: "<sched.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sched_yield(): cint {.importc, header: "<sched.h>", ...raises: [], tags: [],
+                           forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc seekdir(a1: ptr DIR; a2: int) {.importc, header: "<dirent.h>", ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc select(a1: cint | SocketHandle; a2, a3, a4: ptr TFdSet; a5: ptr Timeval): cint {.
+    importc, header: "<sys/select.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sem_close(a1: ptr Sem): cint {.importc, header: "<semaphore.h>",
+                                    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sem_destroy(a1: ptr Sem): cint {.importc, header: "<semaphore.h>",
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sem_getvalue(a1: ptr Sem; a2: var cint): cint {.importc,
+    header: "<semaphore.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sem_init(a1: ptr Sem; a2: cint; a3: cint): cint {.importc,
+    header: "<semaphore.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sem_open(a1: cstring; a2: cint): ptr Sem {.varargs, importc,
+    header: "<semaphore.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sem_post(a1: ptr Sem): cint {.importc, header: "<semaphore.h>", ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sem_timedwait(a1: ptr Sem; a2: ptr Timespec): cint {.importc,
+    header: "<semaphore.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sem_trywait(a1: ptr Sem): cint {.importc, header: "<semaphore.h>",
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
proc sem_wait(a1: ptr Sem): cint {.importc, header: "<semaphore.h>", ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc send(a1: SocketHandle; a2: pointer; a3: int; a4: cint): int {.importc,
+    header: "<sys/socket.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sendmsg(a1: SocketHandle; a2: ptr Tmsghdr; a3: cint): int {.importc,
+    header: "<sys/socket.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sendto(a1: SocketHandle; a2: pointer; a3: int; a4: cint; a5: ptr SockAddr;
+            a6: SockLen): int {.importc, header: "<sys/socket.h>", sideEffect,
+                                ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setcontext(a1: var Ucontext): cint {.importc, header: "<ucontext.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setegid(a1: Gid): cint {.importc, header: "<unistd.h>", ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc seteuid(a1: Uid): cint {.importc, header: "<unistd.h>", ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setgid(a1: Gid): cint {.importc, header: "<unistd.h>", ...raises: [],
+                             tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setgrent() {.importc, header: "<grp.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sethostent(a1: cint) {.importc, header: "<netdb.h>", ...raises: [], tags: [],
+                            forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setlocale(a1: cint; a2: cstring): cstring {.importc, header: "<locale.h>",
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setnetent(a1: cint) {.importc, header: "<netdb.h>", ...raises: [], tags: [],
+                           forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setpgid(a1, a2: Pid): cint {.importc, header: "<unistd.h>", ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setpgrp(): Pid {.importc, header: "<unistd.h>", ...raises: [], tags: [],
+                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setprotoent(a1: cint) {.importc, header: "<netdb.h>", ...raises: [], tags: [],
+                             forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setpwent() {.importc, header: "<pwd.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setregid(a1, a2: Gid): cint {.importc, header: "<unistd.h>", ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setreuid(a1, a2: Uid): cint {.importc, header: "<unistd.h>", ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setrlimit(resource: cint; rlp: var RLimit): cint {.importc: "setrlimit",
+    header: "<sys/resource.h>", ...raises: [], tags: [], forbids: [].}
+
+ + The setrlimit() system calls sets resource limits. + Source   +Edit   + +
+
+ +
+
+
+
proc setservent(a1: cint) {.importc, header: "<netdb.h>", ...raises: [], tags: [],
+                            forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setsid(): Pid {.importc, header: "<unistd.h>", ...raises: [], tags: [],
+                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setsockopt(a1: SocketHandle; a2, a3: cint; a4: pointer; a5: SockLen): cint {.
+    importc, header: "<sys/socket.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setuid(a1: Uid): cint {.importc, header: "<unistd.h>", ...raises: [],
+                             tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc shm_open(a1: cstring; a2: cint; a3: Mode): cint {.importc,
+    header: "<sys/mman.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
proc shutdown(a1: SocketHandle; a2: cint): cint {.importc,
+    header: "<sys/socket.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigaction(a1: cint; a2, a3: var Sigaction): cint {.importc,
+    header: "<signal.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc sigaction(a1: cint; a2: var Sigaction; a3: ptr Sigaction = nil): cint {.
+    importc, header: "<signal.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigaddset(a1: var Sigset; a2: cint): cint {.importc, header: "<signal.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigaltstack(a1, a2: var Stack): cint {.importc, header: "<signal.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigdelset(a1: var Sigset; a2: cint): cint {.importc, header: "<signal.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigemptyset(a1: var Sigset): cint {.importc, header: "<signal.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigfillset(a1: var Sigset): cint {.importc, header: "<signal.h>",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sighold(a1: cint): cint {.importc, header: "<signal.h>", ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigignore(a1: cint): cint {.importc, header: "<signal.h>", ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc siginterrupt(a1, a2: cint): cint {.importc, header: "<signal.h>",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigismember(a1: var Sigset; a2: cint): cint {.importc,
+    header: "<signal.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc signal(a1: cint; a2: Sighandler) {.importc, header: "<signal.h>",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigpause(a1: cint): cint {.importc, header: "<signal.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigpending(a1: var Sigset): cint {.importc, header: "<signal.h>",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigprocmask(a1: cint; a2, a3: var Sigset): cint {.importc,
+    header: "<signal.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigqueue(a1: Pid; a2: cint; a3: SigVal): cint {.importc,
+    header: "<signal.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigrelse(a1: cint): cint {.importc, header: "<signal.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigset(a1: int; a2: proc (x: cint) {.noconv.}) {.importc,
+    header: "<signal.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigsuspend(a1: var Sigset): cint {.importc, header: "<signal.h>",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigtimedwait(a1: var Sigset; a2: var SigInfo; a3: var Timespec): cint {.
+    importc, header: "<signal.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigwait(a1: var Sigset; a2: var cint): cint {.importc,
+    header: "<signal.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sigwaitinfo(a1: var Sigset; a2: var SigInfo): cint {.importc,
+    header: "<signal.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sleep(a1: cint): cint {.importc, header: "<unistd.h>", ...raises: [],
+                             tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sockatmark(a1: cint): cint {.importc, header: "<sys/socket.h>", ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc socket(a1, a2, a3: cint): SocketHandle {.importc, header: "<sys/socket.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc socketpair(a1, a2, a3: cint; a4: var array[0 .. 1, cint]): cint {.importc,
+    header: "<sys/socket.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc st_atime(s: Stat): Time {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Second-granularity time of last access. + Source   +Edit   + +
+
+ +
+
+
+
proc st_ctime(s: Stat): Time {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Second-granularity time of last status change. + Source   +Edit   + +
+
+ +
+
+
+
proc st_mtime(s: Stat): Time {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Second-granularity time of last data modification. + Source   +Edit   + +
+
+ +
+
+
+
proc stat(a1: cstring; a2: var Stat): cint {.importc, header: "<sys/stat.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc statvfs(a1: cstring; a2: var Statvfs): cint {.importc,
+    header: "<sys/statvfs.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc strerror(errnum: cint): cstring {.importc, header: "<string.h>",
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc strfmon(a1: cstring; a2: int; a3: cstring): int {.varargs, importc,
+    header: "<monetary.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc strftime(a1: cstring; a2: int; a3: cstring; a4: var Tm): int {.importc,
+    header: "<time.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc strptime(a1, a2: cstring; a3: var Tm): cstring {.importc,
+    header: "<time.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc swab(a1, a2: pointer; a3: int) {.importc, header: "<unistd.h>", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc swapcontext(a1, a2: var Ucontext): cint {.importc, header: "<ucontext.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
proc sync() {.importc, header: "<unistd.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sysconf(a1: cint): int {.importc, header: "<unistd.h>", ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc tcgetpgrp(a1: cint): Pid {.importc, header: "<unistd.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc tcsetpgrp(a1: cint; a2: Pid): cint {.importc, header: "<unistd.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc telldir(a1: ptr DIR): int {.importc, header: "<dirent.h>", ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc time(a1: var Time): Time {.importc, header: "<time.h>", sideEffect,
+                                ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc timegm(a1: var Tm): Time {.importc, header: "<time.h>", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc timer_create(a1: ClockId; a2: var SigEvent; a3: var Timer): cint {.importc,
+    header: "<time.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc timer_delete(a1: Timer): cint {.importc, header: "<time.h>", ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc timer_getoverrun(a1: Timer): cint {.importc, header: "<time.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc timer_gettime(a1: Timer; a2: var Itimerspec): cint {.importc,
+    header: "<time.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc timer_settime(a1: Timer; a2: cint; a3: var Itimerspec; a4: var Itimerspec): cint {.
+    importc, header: "<time.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc truncate(a1: cstring; a2: Off): cint {.importc, header: "<unistd.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ttyname(a1: cint): cstring {.importc, header: "<unistd.h>", ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ttyname_r(a1: cint; a2: cstring; a3: int): cint {.importc,
+    header: "<unistd.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc tzset() {.importc, header: "<time.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ualarm(a1, a2: Useconds): Useconds {.importc, header: "<unistd.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc umask(a1: Mode): Mode {.importc, header: "<sys/stat.h>", ...raises: [],
+                             tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc uname(a1: var Utsname): cint {.importc, header: "<sys/utsname.h>",
+                                    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
proc usleep(a1: Useconds): cint {.importc, header: "<unistd.h>", ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc utimes(path: cstring; times: ptr array[2, Timeval]): int {.
+    importc: "utimes", header: "<sys/time.h>", sideEffect, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Sets file access and modification times.

+

Pass the filename and an array of times to set the access and modification times respectively. If you pass nil as the array both attributes will be set to the current time.

+

Returns zero on success.

+

For more information read https://www.unix.com/man-page/posix/3/utimes/.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc vfork(): Pid {.importc, header: "<unistd.h>", ...raises: [], tags: [],
+                    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc wait(a1: ptr cint): Pid {.importc, discardable, header: "<sys/wait.h>",
+                               sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc wait4(pid: Pid; status: ptr cint; options: cint; rusage: ptr Rusage): Pid {.
+    importc, header: "<sys/wait.h>", sideEffect, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc waitid(a1: cint; a2: Id; a3: var SigInfo; a4: cint): cint {.importc,
+    header: "<sys/wait.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc waitpid(a1: Pid; a2: var cint; a3: cint): Pid {.importc,
+    header: "<sys/wait.h>", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc WEXITSTATUS(s: cint): cint {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc WIFCONTINUED(s: cint): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc WIFEXITED(s: cint): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc WIFSIGNALED(s: cint): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc WIFSTOPPED(s: cint): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc write(a1: cint; a2: pointer; a3: int): int {.importc, header: "<unistd.h>",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc writev(a1: cint; a2: ptr IOVec; a3: cint): int {.importc,
+    header: "<sys/uio.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc WSTOPSIG(s: cint): cint {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc WTERMSIG(s: cint): cint {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template onSignal(signals: varargs[cint]; body: untyped)
+
+ +

Setup code to be executed when Unix signals are received. The currently handled signal is injected as sig into the calling scope.

+

Example:

+

from std/posix import SIGINT, SIGTERM, onSignal
+onSignal(SIGINT, SIGTERM):
+  echo "bye from signal ", sig

+ + Source   +Edit   + +
+
+ +
+
+
+
template sa_sigaction(v: Sigaction): proc (x: cint; y: ptr SigInfo; z: pointer) {.
+    noconv.}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/posix_utils.html b/posix_utils.html new file mode 100644 index 0000000000000..63679f2dec725 --- /dev/null +++ b/posix_utils.html @@ -0,0 +1,334 @@ + + + + + + + +std/posix_utils + + + + + + + + + + + + + + + + +
+
+

std/posix_utils

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

A set of helpers for the POSIX module. Raw interfaces are in the other posix*.nim files.

+ +
+

Types

+
+
+
Uname = object
+  sysname*, nodename*, release*, version*, machine*: string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc fsync(fd: int) {....raises: [OSError], tags: [], forbids: [].}
+
+ + synchronize a file's buffer cache to the storage device + Source   +Edit   + +
+
+ +
+
+
+
proc memoryLock(a1: pointer; a2: int) {....raises: [OSError], tags: [], forbids: [].}
+
+ + Locks pages starting from a1 for a1 bytes and prevent them from being swapped. + Source   +Edit   + +
+
+ +
+
+
+
proc memoryLockAll(flags: int) {....raises: [OSError], tags: [], forbids: [].}
+
+ +

Locks all memory for the running process to prevent swapping.

+

example:

+

memoryLockAll(MCL_CURRENT or MCL_FUTURE)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc memoryUnlock(a1: pointer; a2: int) {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ + Unlock pages starting from a1 for a1 bytes and allow them to be swapped. + Source   +Edit   + +
+
+ +
+
+
+
proc memoryUnlockAll() {....raises: [OSError], tags: [], forbids: [].}
+
+ + Unlocks all memory for the running process to allow swapping. + Source   +Edit   + +
+
+ +
+
+
+
proc mkdtemp(prefix: string): string {....raises: [OSError], tags: [], forbids: [].}
+
+ + Creates a unique temporary directory from a prefix string. Adds a six chars suffix. The directory is created with permissions 0700. Returns the directory name. + Source   +Edit   + +
+
+ +
+
+
+
proc mkstemp(prefix: string; suffix = ""): (string, File) {....raises: [OSError],
+    tags: [], forbids: [].}
+
+ + Creates a unique temporary file from a prefix string. A six-character string will be added. If suffix is provided it will be added to the string The file is created with perms 0600. Returns the filename and a file opened in r/w mode. + Source   +Edit   + +
+
+ +
+
+
+
proc osReleaseFile(): Config {....raises: [IOError, OSError, Exception, ValueError,
+                                        KeyError], tags: [ReadDirEffect,
+    WriteIOEffect, ReadIOEffect, RootEffect], forbids: [].}
+
+ + Gets system identification from os-release file and returns it as a parsecfg.Config. You also need to import the parsecfg module to gain access to this object. The os-release file is an official Freedesktop.org open standard. Available in Linux and BSD distributions, except Android and Android-based Linux. os-release file is not available on Windows and OS X by design. + +

Example:

+
import std/parsecfg
+when defined(linux):
+  let data = osReleaseFile()
+  echo "OS name: ", data.getSectionValue("", "NAME") ## the data is up to each distro.
+ Source   +Edit   + +
+
+ +
+
+
+
proc sendSignal(pid: Pid; signal: int) {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ + Sends a signal to a running process by calling kill. Raise exception in case of failure e.g. process not running. + Source   +Edit   + +
+
+ +
+
+
+
proc stat(path: string): Stat {....raises: [OSError], tags: [], forbids: [].}
+
+ + Returns file status in a Stat structure + Source   +Edit   + +
+
+ +
+
+
+
proc uname(): Uname {....raises: [OSError], tags: [], forbids: [].}
+
+ + Provides system information in a Uname struct with sysname, nodename, release, version and machine attributes. +

Example:

+
echo uname().nodename, uname().release, uname().version
+doAssert uname().sysname.len != 0
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/posix_utils.idx b/posix_utils.idx new file mode 100644 index 0000000000000..a910e1fc63212 --- /dev/null +++ b/posix_utils.idx @@ -0,0 +1,13 @@ +nimTitle posix_utils posix_utils.html module std/posix_utils 0 +nim Uname posix_utils.html#Uname object Uname 20 +nim uname posix_utils.html#uname_2 proc uname(): Uname 26 +nim fsync posix_utils.html#fsync,int proc fsync(fd: int) 45 +nim stat posix_utils.html#stat,string proc stat(path: string): Stat 50 +nim memoryLock posix_utils.html#memoryLock,pointer,int proc memoryLock(a1: pointer; a2: int) 55 +nim memoryLockAll posix_utils.html#memoryLockAll,int proc memoryLockAll(flags: int) 60 +nim memoryUnlock posix_utils.html#memoryUnlock,pointer,int proc memoryUnlock(a1: pointer; a2: int) 70 +nim memoryUnlockAll posix_utils.html#memoryUnlockAll proc memoryUnlockAll() 75 +nim sendSignal posix_utils.html#sendSignal,Pid,int proc sendSignal(pid: Pid; signal: int) 80 +nim mkstemp posix_utils.html#mkstemp,string,string proc mkstemp(prefix: string; suffix = ""): (string, File) 86 +nim mkdtemp posix_utils.html#mkdtemp,string proc mkdtemp(prefix: string): string 108 +nim osReleaseFile posix_utils.html#osReleaseFile proc osReleaseFile(): Config 116 diff --git a/postgres.html b/postgres.html new file mode 100644 index 0000000000000..607ff4911c217 --- /dev/null +++ b/postgres.html @@ -0,0 +1,2360 @@ + + + + + + + +src/db_connector/postgres + + + + + + + + + + + + + + + + +
+
+

src/db_connector/postgres

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

+
+

Types

+
+
+
ConnStatusType = enum
+  CONNECTION_OK, CONNECTION_BAD, CONNECTION_STARTED, CONNECTION_MADE,
+  CONNECTION_AWAITING_RESPONSE, CONNECTION_AUTH_OK, CONNECTION_SETENV,
+  CONNECTION_SSL_STARTUP, CONNECTION_NEEDED, CONNECTION_CHECK_WRITABLE,
+  CONNECTION_CONSUME, CONNECTION_GSS_STARTUP, CONNECTION_CHECK_TARGET
+
+ + + +
+
+
+
ExecStatusType = enum
+  PGRES_EMPTY_QUERY = 0, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PGRES_COPY_OUT,
+  PGRES_COPY_IN, PGRES_BAD_RESPONSE, PGRES_NONFATAL_ERROR, PGRES_FATAL_ERROR,
+  PGRES_COPY_BOTH, PGRES_SINGLE_TUPLE
+
+ + + +
+
+
+
Oid = int32
+
+ + + +
+
+
+
PConnStatusType = ptr ConnStatusType
+
+ + + +
+
+
+
PExecStatusType = ptr ExecStatusType
+
+ + + +
+
+
+
PGconn {.pure, final.} = object
+  pghost*: cstring
+  pgtty*: cstring
+  pgport*: cstring
+  pgoptions*: cstring
+  dbName*: cstring
+  status*: ConnStatusType
+  errorMessage*: array[0 .. 4096 - 1, char]
+  Pfin*: File
+  Pfout*: File
+  Pfdebug*: File
+  sock*: int32
+  laddr*: SockAddr
+  raddr*: SockAddr
+  salt*: array[0 .. 2 - 1, char]
+  asyncNotifyWaiting*: int32
+  notifyList*: pointer
+  pguser*: cstring
+  pgpass*: cstring
+  lobjfuncs*: PPGlobjfuncs
+
+ + + +
+
+
+
PGlobjfuncs {.pure, final.} = object
+  fn_lo_open*: Oid
+  fn_lo_close*: Oid
+  fn_lo_creat*: Oid
+  fn_lo_unlink*: Oid
+  fn_lo_lseek*: Oid
+  fn_lo_tell*: Oid
+  fn_lo_read*: Oid
+  fn_lo_write*: Oid
+
+ + + +
+
+
+
pgNotify {.pure, final.} = object
+  relname*: cstring
+  be_pid*: int32
+  extra*: cstring
+
+ + + +
+
+
+
PGresAttDesc {.pure, final.} = object
+  name*: cstring
+  adtid*: Oid
+  adtsize*: int
+
+ + + +
+
+
+
PGresAttValue {.pure, final.} = object
+  length*: int32
+  value*: cstring
+
+ + + +
+
+
+
PGresult {.pure, final.} = object
+  ntups*: int32
+  numAttributes*: int32
+  attDescs*: PPGresAttDesc
+  tuples*: PPPGresAttValue
+  tupArrSize*: int32
+  resultStatus*: ExecStatusType
+  cmdStatus*: array[0 .. 40 - 1, char]
+  binary*: int32
+  conn*: PPGconn
+
+ + + +
+
+
+
PGTransactionStatusType = enum
+  PQTRANS_IDLE, PQTRANS_ACTIVE, PQTRANS_INTRANS, PQTRANS_INERROR,
+  PQTRANS_UNKNOWN
+
+ + + +
+
+
+
PGVerbosity = enum
+  PQERRORS_TERSE, PQERRORS_DEFAULT, PQERRORS_VERBOSE, PQERRORS_SQLSTATE
+
+ + + +
+
+
+
POid = ptr Oid
+
+ + + +
+
+
+
PostgresPollingStatusType = enum
+  PGRES_POLLING_FAILED = 0, PGRES_POLLING_READING, PGRES_POLLING_WRITING,
+  PGRES_POLLING_OK, PGRES_POLLING_ACTIVE
+
+ + + +
+
+
+
PPGconn = ptr PGconn
+
+ + + +
+
+
+
PPGlobjfuncs = ptr PGlobjfuncs
+
+ + + +
+
+
+
PPGNotify = ptr pgNotify
+
+ + + +
+
+
+
PPGresAttDesc = ptr PGresAttDesc
+
+ + + +
+
+
+
PPGresAttValue = ptr PGresAttValue
+
+ + + +
+
+
+
PPGresult = ptr PGresult
+
+ + + +
+
+ +
+
PPGVerbosity = ptr PGVerbosity
+
+ + + +
+
+ +
+
PPPGresAttDesc = ptr PPGresAttDesc
+
+ + + +
+
+
+
PPPGresAttValue = ptr PPGresAttValue
+
+ + + +
+
+
+
PPQArgBlock = ptr PQArgBlock
+
+ + + +
+
+
+
Ppqbool = ptr pqbool
+
+ + + +
+
+
+
PPQconninfoOption = ptr PQconninfoOption
+
+ + + +
+
+
+
PPQprintOpt = ptr PQprintOpt
+
+ + + +
+
+
+
PQArgBlock {.pure, final.} = object
+  length*: int32
+  isint*: int32
+  p*: pointer
+
+ + + +
+
+
+
pqbool = char
+
+ + + +
+
+
+
PQconninfoOption {.pure, final.} = object
+  keyword*: cstring
+  envvar*: cstring
+  compiled*: cstring
+  val*: cstring
+  label*: cstring
+  dispchar*: cstring
+  dispsize*: int32
+
+ + + +
+
+
+
PQnoticeProcessor = proc (arg: pointer; message: cstring) {.cdecl.}
+
+ + + +
+
+
+
PQnoticeReceiver = proc (arg: pointer; res: PPGresult) {.cdecl.}
+
+ + + +
+
+
+
PQprintOpt {.pure, final.} = object
+  header*: pqbool
+  align*: pqbool
+  standard*: pqbool
+  html3*: pqbool
+  expanded*: pqbool
+  pager*: pqbool
+  fieldSep*: cstring
+  tableOpt*: cstring
+  caption*: cstring
+  fieldName*: ptr cstring
+
+ + + +
+
+
+
SockAddr = array[1 .. 112, int8]
+
+ + + +
+
+ +
+
+
+

Consts

+
+
+
CMDSTATUS_LEN = 40
+
+ + + +
+
+
+
ERROR_MSG_LENGTH = 4096
+
+ + + +
+
+ +
+
+
+

Procs

+
+
+
+
proc lo_close(conn: PPGconn; fd: int32): int32 {.cdecl, dynlib: dllName,
+    importc: "lo_close", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc lo_creat(conn: PPGconn; mode: int32): Oid {.cdecl, dynlib: dllName,
+    importc: "lo_creat", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc lo_export(conn: PPGconn; lobjId: Oid; filename: cstring): int32 {.cdecl,
+    dynlib: dllName, importc: "lo_export", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc lo_import(conn: PPGconn; filename: cstring): Oid {.cdecl, dynlib: dllName,
+    importc: "lo_import", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc lo_lseek(conn: PPGconn; fd: int32; offset: int32; whence: int32): int32 {.
+    cdecl, dynlib: dllName, importc: "lo_lseek", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc lo_open(conn: PPGconn; lobjId: Oid; mode: int32): int32 {.cdecl,
+    dynlib: dllName, importc: "lo_open", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc lo_read(conn: PPGconn; fd: int32; buf: cstring; length: int): int32 {.
+    cdecl, dynlib: dllName, importc: "lo_read", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc lo_tell(conn: PPGconn; fd: int32): int32 {.cdecl, dynlib: dllName,
+    importc: "lo_tell", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+ +
+
+
proc lo_write(conn: PPGconn; fd: int32; buf: cstring; length: int): int32 {.
+    cdecl, dynlib: dllName, importc: "lo_write", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqbackendPID(conn: PPGconn): int32 {.cdecl, dynlib: dllName,
+    importc: "PQbackendPID", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqbinaryTuples(res: PPGresult): int32 {.cdecl, dynlib: dllName,
+    importc: "PQbinaryTuples", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqclear(res: PPGresult) {.cdecl, dynlib: dllName, importc: "PQclear",
+                               ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqclientEncoding(conn: PPGconn): int32 {.cdecl, dynlib: dllName,
+    importc: "PQclientEncoding", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqcmdStatus(res: PPGresult): cstring {.cdecl, dynlib: dllName,
+    importc: "PQcmdStatus", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqcmdTuples(res: PPGresult): cstring {.cdecl, dynlib: dllName,
+    importc: "PQcmdTuples", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqconndefaults(): PPQconninfoOption {.cdecl, dynlib: dllName,
+    importc: "PQconndefaults", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqconnectdb(conninfo: cstring): PPGconn {.cdecl, dynlib: dllName,
+    importc: "PQconnectdb", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqconnectionNeedsPassword(conn: PPGconn): int32 {.cdecl, dynlib: dllName,
+    importc: "PQconnectionNeedsPassword", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqconnectionUsedPassword(conn: PPGconn): int32 {.cdecl, dynlib: dllName,
+    importc: "PQconnectionUsedPassword", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqconnectPoll(conn: PPGconn): PostgresPollingStatusType {.cdecl,
+    dynlib: dllName, importc: "PQconnectPoll", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqconnectStart(conninfo: cstring): PPGconn {.cdecl, dynlib: dllName,
+    importc: "PQconnectStart", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqconninfoFree(connOptions: PPQconninfoOption) {.cdecl, dynlib: dllName,
+    importc: "PQconninfoFree", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqconsumeInput(conn: PPGconn): int32 {.cdecl, dynlib: dllName,
+    importc: "PQconsumeInput", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqdb(conn: PPGconn): cstring {.cdecl, dynlib: dllName, importc: "PQdb",
+                                    ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqdisplayTuples(res: PPGresult; fp: File; fillAlign: int32;
+                     fieldSep: cstring; printHeader: int32; quiet: int32) {.
+    cdecl, dynlib: dllName, importc: "PQdisplayTuples", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqendcopy(conn: PPGconn): int32 {.cdecl, dynlib: dllName,
+                                       importc: "PQendcopy", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqenv2encoding(): int32 {.cdecl, dynlib: dllName,
+                               importc: "PQenv2encoding", ...raises: [], tags: [],
+                               forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqerrorMessage(conn: PPGconn): cstring {.cdecl, dynlib: dllName,
+    importc: "PQerrorMessage", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqescapeBytea(bintext: cstring; binlen: int; bytealen: var int): cstring {.
+    cdecl, dynlib: dllName, importc: "PQescapeBytea", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqescapeString(till, from: cstring; len: int): int {.cdecl,
+    dynlib: dllName, importc: "PQescapeString", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqexec(conn: PPGconn; query: cstring): PPGresult {.cdecl, dynlib: dllName,
+    importc: "PQexec", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqexecParams(conn: PPGconn; command: cstring; nParams: int32;
+                  paramTypes: POid; paramValues: cstringArray;
+                  paramLengths, paramFormats: ptr int32; resultFormat: int32): PPGresult {.
+    cdecl, dynlib: dllName, importc: "PQexecParams", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqexecPrepared(conn: PPGconn; stmtName: cstring; nParams: int32;
+                    paramValues: cstringArray;
+                    paramLengths, paramFormats: ptr int32; resultFormat: int32): PPGresult {.
+    cdecl, dynlib: dllName, importc: "PQexecPrepared", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqfformat(res: PPGresult; field_num: int32): int32 {.cdecl,
+    dynlib: dllName, importc: "PQfformat", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqfinish(conn: PPGconn) {.cdecl, dynlib: dllName, importc: "PQfinish",
+                               ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqflush(conn: PPGconn): int32 {.cdecl, dynlib: dllName, importc: "PQflush",
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqfmod(res: PPGresult; field_num: int32): int32 {.cdecl, dynlib: dllName,
+    importc: "PQfmod", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqfn(conn: PPGconn; fnid: int32; result_buf, result_len: ptr int32;
+          result_is_int: int32; args: PPQArgBlock; nargs: int32): PPGresult {.
+    cdecl, dynlib: dllName, importc: "PQfn", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqfname(res: PPGresult; field_num: int32): cstring {.cdecl,
+    dynlib: dllName, importc: "PQfname", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqfnumber(res: PPGresult; field_name: cstring): int32 {.cdecl,
+    dynlib: dllName, importc: "PQfnumber", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqfreemem(p: pointer) {.cdecl, dynlib: dllName, importc: "PQfreemem",
+                             ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqfsize(res: PPGresult; field_num: int32): int32 {.cdecl, dynlib: dllName,
+    importc: "PQfsize", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqftable(res: PPGresult; field_num: int32): Oid {.cdecl, dynlib: dllName,
+    importc: "PQftable", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqftablecol(res: PPGresult; field_num: int32): int32 {.cdecl,
+    dynlib: dllName, importc: "PQftablecol", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqftype(res: PPGresult; field_num: int32): Oid {.cdecl, dynlib: dllName,
+    importc: "PQftype", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqgetCopyData(conn: PPGconn; buffer: cstringArray; async: int32): int32 {.
+    cdecl, dynlib: dllName, importc: "PQgetCopyData", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqgetisnull(res: PPGresult; tup_num: int32; field_num: int32): int32 {.
+    cdecl, dynlib: dllName, importc: "PQgetisnull", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqgetlength(res: PPGresult; tup_num: int32; field_num: int32): int32 {.
+    cdecl, dynlib: dllName, importc: "PQgetlength", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqgetline(conn: PPGconn; str: cstring; len: int32): int32 {.cdecl,
+    dynlib: dllName, importc: "PQgetline", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqgetlineAsync(conn: PPGconn; buffer: cstring; bufsize: int32): int32 {.
+    cdecl, dynlib: dllName, importc: "PQgetlineAsync", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqgetResult(conn: PPGconn): PPGresult {.cdecl, dynlib: dllName,
+    importc: "PQgetResult", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqgetvalue(res: PPGresult; tup_num: int32; field_num: int32): cstring {.
+    cdecl, dynlib: dllName, importc: "PQgetvalue", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqhost(conn: PPGconn): cstring {.cdecl, dynlib: dllName, importc: "PQhost",
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqinitOpenSSL(do_ssl: int32; do_crypto: int32) {.cdecl, dynlib: dllName,
+    importc: "PQinitOpenSSL", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqisBusy(conn: PPGconn): int32 {.cdecl, dynlib: dllName,
+                                      importc: "PQisBusy", ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqisnonblocking(conn: PPGconn): int32 {.cdecl, dynlib: dllName,
+    importc: "PQisnonblocking", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqmakeEmptyPGresult(conn: PPGconn; status: ExecStatusType): PPGresult {.
+    cdecl, dynlib: dllName, importc: "PQmakeEmptyPGresult", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqmblen(s: cstring; encoding: int32): int32 {.cdecl, dynlib: dllName,
+    importc: "PQmblen", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqnfields(res: PPGresult): int32 {.cdecl, dynlib: dllName,
+                                        importc: "PQnfields", ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqnotifies(conn: PPGconn): PPGNotify {.cdecl, dynlib: dllName,
+    importc: "PQnotifies", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqntuples(res: PPGresult): int32 {.cdecl, dynlib: dllName,
+                                        importc: "PQntuples", ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqoidStatus(res: PPGresult): cstring {.cdecl, dynlib: dllName,
+    importc: "PQoidStatus", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqoidValue(res: PPGresult): Oid {.cdecl, dynlib: dllName,
+                                       importc: "PQoidValue", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqoptions(conn: PPGconn): cstring {.cdecl, dynlib: dllName,
+    importc: "PQoptions", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqparameterStatus(conn: PPGconn; paramName: cstring): cstring {.cdecl,
+    dynlib: dllName, importc: "PQparameterStatus", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqpass(conn: PPGconn): cstring {.cdecl, dynlib: dllName, importc: "PQpass",
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqport(conn: PPGconn): cstring {.cdecl, dynlib: dllName, importc: "PQport",
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqprepare(conn: PPGconn; stmtName, query: cstring; nParams: int32;
+               paramTypes: POid): PPGresult {.cdecl, dynlib: dllName,
+    importc: "PQprepare", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqprint(fout: File; res: PPGresult; ps: PPQprintOpt) {.cdecl,
+    dynlib: dllName, importc: "PQprint", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqprintTuples(res: PPGresult; fout: File; printAttName: int32;
+                   terseOutput: int32; width: int32) {.cdecl, dynlib: dllName,
+    importc: "PQprintTuples", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqprotocolVersion(conn: PPGconn): int32 {.cdecl, dynlib: dllName,
+    importc: "PQprotocolVersion", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqputCopyData(conn: PPGconn; buffer: cstring; nbytes: int32): int32 {.
+    cdecl, dynlib: dllName, importc: "PQputCopyData", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqputCopyEnd(conn: PPGconn; errormsg: cstring): int32 {.cdecl,
+    dynlib: dllName, importc: "PQputCopyEnd", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqputline(conn: PPGconn; str: cstring): int32 {.cdecl, dynlib: dllName,
+    importc: "PQputline", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqputnbytes(conn: PPGconn; buffer: cstring; nbytes: int32): int32 {.cdecl,
+    dynlib: dllName, importc: "PQputnbytes", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqrequestCancel(conn: PPGconn): int32 {.cdecl, dynlib: dllName,
+    importc: "PQrequestCancel", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqreset(conn: PPGconn) {.cdecl, dynlib: dllName, importc: "PQreset",
+                              ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqresetPoll(conn: PPGconn): PostgresPollingStatusType {.cdecl,
+    dynlib: dllName, importc: "PQresetPoll", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqresetStart(conn: PPGconn): int32 {.cdecl, dynlib: dllName,
+    importc: "PQresetStart", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqresStatus(status: ExecStatusType): cstring {.cdecl, dynlib: dllName,
+    importc: "PQresStatus", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqresultErrorField(res: PPGresult; fieldcode: int32): cstring {.cdecl,
+    dynlib: dllName, importc: "PQresultErrorField", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqresultErrorMessage(res: PPGresult): cstring {.cdecl, dynlib: dllName,
+    importc: "PQresultErrorMessage", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqresultStatus(res: PPGresult): ExecStatusType {.cdecl, dynlib: dllName,
+    importc: "PQresultStatus", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqsendQuery(conn: PPGconn; query: cstring): int32 {.cdecl, dynlib: dllName,
+    importc: "PQsendQuery", ...raises: [], tags: [], forbids: [].}
+
+ + See also https://www.postgresql.org/docs/current/libpq-async.html + +
+
+ +
+
+
+
proc pqsendQueryParams(conn: PPGconn; command: cstring; nParams: int32;
+                       paramTypes: POid; paramValues: cstringArray;
+                       paramLengths, paramFormats: ptr int32;
+                       resultFormat: int32): int32 {.cdecl, dynlib: dllName,
+    importc: "PQsendQueryParams", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqsendQueryPrepared(conn: PPGconn; stmtName: cstring; nParams: int32;
+                         paramValues: cstringArray;
+                         paramLengths, paramFormats: ptr int32;
+                         resultFormat: int32): int32 {.cdecl, dynlib: dllName,
+    importc: "PQsendQueryPrepared", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqserverVersion(conn: PPGconn): int32 {.cdecl, dynlib: dllName,
+    importc: "PQserverVersion", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqsetClientEncoding(conn: PPGconn; encoding: cstring): int32 {.cdecl,
+    dynlib: dllName, importc: "PQsetClientEncoding", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqsetdb(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME: cstring): PPGconn {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqsetdbLogin(pghost: cstring; pgport: cstring; pgoptions: cstring;
+                  pgtty: cstring; dbName: cstring; login: cstring; pwd: cstring): PPGconn {.
+    cdecl, dynlib: dllName, importc: "PQsetdbLogin", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqsetErrorVerbosity(conn: PPGconn; verbosity: PGVerbosity): PGVerbosity {.
+    cdecl, dynlib: dllName, importc: "PQsetErrorVerbosity", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqsetnonblocking(conn: PPGconn; arg: int32): int32 {.cdecl,
+    dynlib: dllName, importc: "PQsetnonblocking", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqsetNoticeProcessor(conn: PPGconn; theProc: PQnoticeProcessor;
+                          arg: pointer): PQnoticeProcessor {.cdecl,
+    dynlib: dllName, importc: "PQsetNoticeProcessor", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqsetNoticeReceiver(conn: PPGconn; theProc: PQnoticeReceiver; arg: pointer): PQnoticeReceiver {.
+    cdecl, dynlib: dllName, importc: "PQsetNoticeReceiver", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqSetSingleRowMode(conn: PPGconn): int32 {.cdecl, dynlib: dllName,
+    importc: "PQsetSingleRowMode", ...raises: [], tags: [], forbids: [].}
+
+ + See also https://www.postgresql.org/docs/current/libpq-single-row-mode.html + +
+
+ +
+
+
+
proc pqsocket(conn: PPGconn): int32 {.cdecl, dynlib: dllName,
+                                      importc: "PQsocket", ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqstatus(conn: PPGconn): ConnStatusType {.cdecl, dynlib: dllName,
+    importc: "PQstatus", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqtrace(conn: PPGconn; debug_port: File) {.cdecl, dynlib: dllName,
+    importc: "PQtrace", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqtransactionStatus(conn: PPGconn): PGTransactionStatusType {.cdecl,
+    dynlib: dllName, importc: "PQtransactionStatus", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqtty(conn: PPGconn): cstring {.cdecl, dynlib: dllName, importc: "PQtty",
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pqunescapeBytea(strtext: cstring; retbuflen: var int): cstring {.cdecl,
+    dynlib: dllName, importc: "PQunescapeBytea", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pquntrace(conn: PPGconn) {.cdecl, dynlib: dllName, importc: "PQuntrace",
+                                ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc pquser(conn: PPGconn): cstring {.cdecl, dynlib: dllName, importc: "PQuser",
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/prelude.html b/prelude.html new file mode 100644 index 0000000000000..65532bdb16d76 --- /dev/null +++ b/prelude.html @@ -0,0 +1,99 @@ + + + + + + + +std/prelude + + + + + + + + + + + + + + + + +
+
+

std/prelude

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This is an include file that simply imports common modules for your convenience. +

Example:

+
import std/prelude
+include std/prelude
+  # same as:
+  # import std/[os, strutils, times, parseutils, hashes, tables, sets, sequtils, parseopt, strformat]
+let x = 1
+assert "foo $# $#" % [$x, "bar"] == "foo 1 bar"
+assert toSeq(1..3) == @[1, 2, 3]
+when not defined(js) or defined(nodejs):
+  assert getCurrentDir().len > 0
+  assert ($now()).startsWith "20"

+ + +
+
+ + +
+
+ + + + diff --git a/prelude.idx b/prelude.idx new file mode 100644 index 0000000000000..a62f9b6e4068a --- /dev/null +++ b/prelude.idx @@ -0,0 +1 @@ +nimTitle prelude prelude.html module std/prelude 0 diff --git a/punycode.html b/punycode.html new file mode 100644 index 0000000000000..21137c4861085 --- /dev/null +++ b/punycode.html @@ -0,0 +1,193 @@ + + + + + + + +src/punycode + + + + + + + + + + + + + + + + +
+
+

src/punycode

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

Note: +In order to use this module, run nimble install punycode.
+

Implements a representation of Unicode with the limited ASCII character subset.

+ +

Example:

+
import src/punycode
+static:
+  block:
+    doAssert encode("") == ""
+    doAssert encode("a") == "a-"
+    doAssert encode("A") == "A-"
+    doAssert encode("3") == "3-"
+    doAssert encode("-") == "--"
+    doAssert encode("--") == "---"
+    doAssert encode("abc") == "abc-"
+    doAssert encode("London") == "London-"
+    doAssert encode("Lloyd-Atkinson") == "Lloyd-Atkinson-"
+    doAssert encode("This has spaces") == "This has spaces-"
+    doAssert encode("ü") == "tda"
+    doAssert encode("München") == "Mnchen-3ya"
+    doAssert encode("Mnchen-3ya") == "Mnchen-3ya-"
+    doAssert encode("München-Ost") == "Mnchen-Ost-9db"
+    doAssert encode("Bahnhof München-Ost") == "Bahnhof Mnchen-Ost-u6b"
+  block:
+    doAssert decode("") == ""
+    doAssert decode("a-") ==  "a"
+    doAssert decode("A-") == "A"
+    doAssert decode("3-") == "3"
+    doAssert decode("--") == "-"
+    doAssert decode("---") == "--"
+    doAssert decode("abc-") == "abc"
+    doAssert decode("London-") == "London"
+    doAssert decode("Lloyd-Atkinson-") == "Lloyd-Atkinson"
+    doAssert decode("This has spaces-") == "This has spaces"
+    doAssert decode("tda") == "ü"
+    doAssert decode("Mnchen-3ya") == "München"
+    doAssert decode("Mnchen-3ya-") == "Mnchen-3ya"
+    doAssert decode("Mnchen-Ost-9db") == "München-Ost"
+    doAssert decode("Bahnhof Mnchen-Ost-u6b") == "Bahnhof München-Ost"

+
+

Types

+
+
+
PunyError = object of ValueError
+
+ + + +
+
+ +
+
+
+

Procs

+
+
+
+
func decode(encoded: string): string {....raises: [PunyError], tags: [],
+                                       forbids: [].}
+
+ + Decode a Punycode-encoded string + +
+
+ +
+
+
+
func encode(prefix, s: string): string {....raises: [PunyError], tags: [],
+    forbids: [].}
+
+ + Encode a string that may contain Unicode. Prepend prefix to the result + +
+
+
+
func encode(s: string): string {....raises: [PunyError], tags: [], forbids: [].}
+
+ + Encode a string that may contain Unicode. Prefix is empty. + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/punycode.idx b/punycode.idx new file mode 100644 index 0000000000000..0d3188a94aa70 --- /dev/null +++ b/punycode.idx @@ -0,0 +1,6 @@ +nimTitle punycode punycode.html module src/punycode 0 +nim PunyError punycode.html#PunyError object PunyError 31 +nim encode punycode.html#encode,string,string proc encode(prefix, s: string): string 63 +nim encode punycode.html#encode,string proc encode(s: string): string 119 +nim decode punycode.html#decode,string proc decode(encoded: string): string 123 +nimgrp encode punycode.html#encode-procs-all proc 63 diff --git a/random.html b/random.html new file mode 100644 index 0000000000000..15954c4ff1ef1 --- /dev/null +++ b/random.html @@ -0,0 +1,806 @@ + + + + + + + +std/random + + + + + + + + + + + + + + + + +
+
+

std/random

+
+ +
+ Source   +Edit   + +
+ +

Nim's standard random number generator (RNG).

+

Its implementation is based on the xoroshiro128+ (xor/rotate/shift/rotate) library.

+ +

Do not use this module for cryptographic purposes!

+ +

Basic usage

+

Example:

+
import std/random
+# Call randomize() once to initialize the default random number generator.
+# If this is not called, the same results will occur every time these
+# examples are run.
+randomize()
+
+# Pick a number in 0..100.
+let num = rand(100)
+doAssert num in 0..100
+
+# Roll a six-sided die.
+let roll = rand(1..6)
+doAssert roll in 1..6
+
+# Pick a marble from a bag.
+let marbles = ["red", "blue", "green", "yellow", "purple"]
+let pick = sample(marbles)
+doAssert pick in marbles
+
+# Shuffle some cards.
+var cards = ["Ace", "King", "Queen", "Jack", "Ten"]
+shuffle(cards)
+doAssert cards.len == 5

These examples all use the default RNG. The Rand type represents the state of an RNG. For convenience, this module contains a default Rand state that corresponds to the default RNG. Most procs in this module which do not take in a Rand parameter, including those called in the above examples, use the default generator. Those procs are not thread-safe.

+

Note that the default generator always starts in the same state. The randomize proc can be called to initialize the default generator with a seed based on the current time, and it only needs to be called once before the first usage of procs from this module. If randomize is not called, the default generator will always produce the same results.

+

RNGs that are independent of the default one can be created with the initRand proc.

+

Again, it is important to remember that this module must not be used for cryptographic applications.

+ +

See also

+

+ +
+

Types

+
+
+
Rand = object
+
+ +

State of a random number generator.

+

Create a new Rand state using the initRand proc.

+

The module contains a default Rand state for convenience. It corresponds to the default RNG's state. The default Rand state always starts with the same values, but the randomize proc can be used to seed the default generator with a value based on the current time.

+

Many procs have two variations: one that takes in a Rand parameter and another that uses the default generator. The procs that use the default generator are not thread-safe!

+ + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc gauss(mu = 0.0; sigma = 1.0): float {....raises: [], tags: [], forbids: [].}
+
+ +

Returns a Gaussian random variate, with mean mu and standard deviation sigma.

+

If randomize has not been called, the order of outcomes from this proc will always be the same.

+

This proc uses the default RNG. Thus, it is not thread-safe.

+ + Source   +Edit   + +
+
+
+
proc gauss(r: var Rand; mu = 0.0; sigma = 1.0): float {....raises: [], tags: [],
+    forbids: [].}
+
+ + Returns a Gaussian random variate, with mean mu and standard deviation sigma using the given state. + Source   +Edit   + +
+
+ +
+
+
+
proc initRand(): Rand {....raises: [], tags: [], forbids: [].}
+
+ +

Initializes a new Rand state.

+

The resulting state is independent of the default RNG's state.

+

Note: Does not work for the compile-time VM.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc initRand(seed: int64): Rand {....raises: [], tags: [], forbids: [].}
+
+ +

Initializes a new Rand state using the given seed.

+

Providing a specific seed will produce the same results for that seed each time.

+

The resulting state is independent of the default RNG's state. When seed == 0, we internally set the seed to an implementation defined non-zero value.

+

See also:

+ + +

Example:

+
from std/times import getTime, toUnix, nanosecond
+
+var r1 = initRand(123)
+let now = getTime()
+var r2 = initRand(now.toUnix * 1_000_000_000 + now.nanosecond)
+ Source   +Edit   + +
+
+ +
+
+
+
proc next(r: var Rand): uint64 {....raises: [], tags: [], forbids: [].}
+
+ +

Computes a random uint64 number using the given state.

+

See also:

+ + +

Example: cmd: -r:off

+
var r = initRand(2019)
+assert r.next() == 13223559681708962501'u64 # implementation defined
+assert r.next() == 7229677234260823147'u64 # ditto
+ Source   +Edit   + +
+
+ +
+
+
+
proc rand(max: float): float {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ +

Returns a random floating point number in the range 0.0..max.

+

If randomize has not been called, the sequence of random numbers returned from this proc will always be the same.

+

This proc uses the default RNG. Thus, it is not thread-safe.

+

See also:

+ + +

Example:

+
randomize(234)
+let f = rand(1.0) # 8.717181376738381e-07
+ Source   +Edit   + +
+
+
+
proc rand(max: int): int {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ +

Returns a random integer in the range 0..max.

+

If randomize has not been called, the sequence of random numbers returned from this proc will always be the same.

+

This proc uses the default RNG. Thus, it is not thread-safe.

+

See also:

+ + +

Example: cmd: -r:off

+
randomize(123)
+assert [rand(100), rand(100)] == [96, 63] # implementation defined
+ Source   +Edit   + +
+
+
+
proc rand(r: var Rand; max: Natural): int {....gcsafe, raises: [], tags: [],
+    forbids: [].}
+
+ +

Returns a random integer in the range 0..max using the given state.

+

See also:

+ + +

Example:

+
var r = initRand(123)
+if false:
+  assert r.rand(100) == 96 # implementation defined
+ Source   +Edit   + +
+
+
+
proc rand(r: var Rand; max: range[0.0 .. high(float)]): float {....gcsafe,
+    raises: [], tags: [], forbids: [].}
+
+ +

Returns a random floating point number in the range 0.0..max using the given state.

+

See also:

+ + +

Example:

+
var r = initRand(234)
+let f = r.rand(1.0) # 8.717181376738381e-07
+ Source   +Edit   + +
+
+
+
proc rand[T: Ordinal or SomeFloat](r: var Rand; x: HSlice[T, T]): T
+
+ +

For a slice a..b, returns a value in the range a..b using the given state.

+

Allowed types for T are integers, floats, and enums without holes.

+

See also:

+ + +

Example:

+
var r = initRand(345)
+assert r.rand(1..5) <= 5
+assert r.rand(-1.1 .. 1.2) >= -1.1
+ Source   +Edit   + +
+
+
+
proc rand[T: Ordinal or SomeFloat](x: HSlice[T, T]): T
+
+ +

For a slice a..b, returns a value in the range a..b.

+

Allowed types for T are integers, floats, and enums without holes.

+

If randomize has not been called, the sequence of random numbers returned from this proc will always be the same.

+

This proc uses the default RNG. Thus, it is not thread-safe.

+

See also:

+
  • rand proc that accepts a slice and uses a provided state
  • +
  • rand proc that returns an integer
  • +
  • rand proc that returns a floating point number
  • +
  • rand proc that accepts an integer or range type
  • +
+ +

Example:

+
randomize(345)
+assert rand(1..6) <= 6
+ Source   +Edit   + +
+
+
+
proc rand[T: Ordinal](r: var Rand; t: typedesc[T]): T
+
+ +

Returns a random Ordinal in the range low(T)..high(T).

+

If randomize has not been called, the sequence of random numbers returned from this proc will always be the same.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc rand[T: Ordinal](t: typedesc[T]): T
+
+ +

Returns a random Ordinal in the range low(T)..high(T).

+

If randomize has not been called, the sequence of random numbers returned from this proc will always be the same.

+

This proc uses the default RNG. Thus, it is not thread-safe.

+

See also:

+ + +

Example:

+
randomize(567)
+type E = enum a, b, c, d
+
+assert rand(E) in a..d
+assert rand(char) in low(char)..high(char)
+assert rand(int8) in low(int8)..high(int8)
+assert rand(uint32) in low(uint32)..high(uint32)
+assert rand(range[1..16]) in 1..16
+ Source   +Edit   + +
+
+ +
+
+
+
proc randomize() {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ +

Initializes the default random number generator with a seed based on random number source.

+

This proc only needs to be called once, and it should be called before the first usage of procs from this module that use the default RNG.

+

Note: Does not work for the compile-time VM.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc randomize(seed: int64) {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ +

Initializes the default random number generator with the given seed.

+

Providing a specific seed will produce the same results for that seed each time.

+

See also:

+ + +

Example:

+
from std/times import getTime, toUnix, nanosecond
+
+randomize(123)
+
+let now = getTime()
+randomize(now.toUnix * 1_000_000_000 + now.nanosecond)
+ Source   +Edit   + +
+
+ +
+
+
+
proc sample[T, U](a: openArray[T]; cdf: openArray[U]): T
+
+ +

Returns an element from a using a cumulative distribution function (CDF).

+

This proc works similarly to sample. See that proc's documentation for more details.

+

If randomize has not been called, the order of outcomes from this proc will always be the same.

+

This proc uses the default RNG. Thus, it is not thread-safe.

+

See also:

+ + +

Example:

+
from std/math import cumsummed
+
+let marbles = ["red", "blue", "green", "yellow", "purple"]
+let count = [1, 6, 8, 3, 4]
+let cdf = count.cumsummed
+randomize(789)
+assert sample(marbles, cdf) in marbles
+ Source   +Edit   + +
+
+
+
proc sample[T, U](r: var Rand; a: openArray[T]; cdf: openArray[U]): T
+
+ +

Returns an element from a using a cumulative distribution function (CDF) and the given state.

+

The cdf argument does not have to be normalized, and it could contain any type of elements that can be converted to a float. It must be the same length as a. Each element in cdf should be greater than or equal to the previous element.

+

The outcome of the cumsum proc and the return value of the cumsummed proc, which are both in the math module, can be used as the cdf argument.

+

See also:

+ + +

Example:

+
from std/math import cumsummed
+
+let marbles = ["red", "blue", "green", "yellow", "purple"]
+let count = [1, 6, 8, 3, 4]
+let cdf = count.cumsummed
+var r = initRand(789)
+assert r.sample(marbles, cdf) in marbles
+ Source   +Edit   + +
+
+
+
proc sample[T](a: openArray[T]): lent T
+
+ +

Returns a random element from a.

+

If randomize has not been called, the order of outcomes from this proc will always be the same.

+

This proc uses the default RNG. Thus, it is not thread-safe.

+

See also:

+ + +

Example:

+
let marbles = ["red", "blue", "green", "yellow", "purple"]
+randomize(456)
+assert sample(marbles) in marbles
+ Source   +Edit   + +
+
+
+
proc sample[T](r: var Rand; a: openArray[T]): T
+
+ +

Returns a random element from a using the given state.

+

See also:

+ + +

Example:

+
let marbles = ["red", "blue", "green", "yellow", "purple"]
+var r = initRand(456)
+assert r.sample(marbles) in marbles
+ Source   +Edit   + +
+
+
+
proc sample[T](r: var Rand; s: set[T]): T
+
+ +

Returns a random element from the set s using the given state.

+

See also:

+ + +

Example:

+
var r = initRand(987)
+let s = {1, 3, 5, 7, 9}
+assert r.sample(s) in s
+ Source   +Edit   + +
+
+
+
proc sample[T](s: set[T]): T
+
+ +

Returns a random element from the set s.

+

If randomize has not been called, the order of outcomes from this proc will always be the same.

+

This proc uses the default RNG. Thus, it is not thread-safe.

+

See also:

+ + +

Example:

+
randomize(987)
+let s = {1, 3, 5, 7, 9}
+assert sample(s) in s
+ Source   +Edit   + +
+
+ +
+
+
+
proc shuffle[T](r: var Rand; x: var openArray[T])
+
+ +

Shuffles a sequence of elements in-place using the given state.

+

See also:

+ + +

Example:

+
var cards = ["Ace", "King", "Queen", "Jack", "Ten"]
+var r = initRand(678)
+r.shuffle(cards)
+import std/algorithm
+assert cards.sorted == @["Ace", "Jack", "King", "Queen", "Ten"]
+ Source   +Edit   + +
+
+
+
proc shuffle[T](x: var openArray[T])
+
+ +

Shuffles a sequence of elements in-place.

+

If randomize has not been called, the order of outcomes from this proc will always be the same.

+

This proc uses the default RNG. Thus, it is not thread-safe.

+

See also:

+ + +

Example:

+
var cards = ["Ace", "King", "Queen", "Jack", "Ten"]
+randomize(678)
+shuffle(cards)
+import std/algorithm
+assert cards.sorted == @["Ace", "Jack", "King", "Queen", "Ten"]
+ Source   +Edit   + +
+
+ +
+
+
+
proc skipRandomNumbers(s: var Rand) {....raises: [], tags: [], forbids: [].}
+
+ +

The jump function for the generator.

+

This proc is equivalent to 2^64 calls to next, and it can be used to generate 2^64 non-overlapping subsequences for parallel computations.

+

When multiple threads are generating random numbers, each thread must own the Rand state it is using so that the thread can safely obtain random numbers. However, if each thread creates its own Rand state, the subsequences of random numbers that each thread generates may overlap, even if the provided seeds are unique. This is more likely to happen as the number of threads and amount of random numbers generated increases.

+

If many threads will generate random numbers concurrently, it is better to create a single Rand state and pass it to each thread. After passing the Rand state to a thread, call this proc before passing it to the next one. By using the Rand state this way, the subsequences of random numbers generated in each thread will never overlap as long as no thread generates more than 2^64 random numbers.

+

See also:

+ + +

Example: cmd: --threads:on

+
import std/random
+
+const numbers = 100000
+
+var
+  thr: array[0..3, Thread[(Rand, int)]]
+  vals: array[0..3, int]
+
+proc randomSum(params: tuple[r: Rand, index: int]) {.thread.} =
+  var r = params.r
+  var s = 0 # avoid cache thrashing
+  for i in 1..numbers:
+    s += r.rand(0..10)
+  vals[params.index] = s
+
+var r = initRand(2019)
+for i in 0..<thr.len:
+  createThread(thr[i], randomSum, (r, i))
+  r.skipRandomNumbers()
+
+joinThreads(thr)
+
+for val in vals:
+  doAssert abs(val - numbers * 5) / numbers < 0.1
+
+doAssert vals == [501737, 497901, 500683, 500157]
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template randState(): untyped
+
+ + Makes the default Rand state accessible from other modules. Useful for module authors. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/random.idx b/random.idx new file mode 100644 index 0000000000000..51937dab9a456 --- /dev/null +++ b/random.idx @@ -0,0 +1,35 @@ +nimTitle random random.html module std/random 0 +nim Rand random.html#Rand object Rand 95 +nim randState random.html#randState.t template randState(): untyped 130 +nim next random.html#next,Rand proc next(r: var Rand): uint64 138 +nim skipRandomNumbers random.html#skipRandomNumbers,Rand proc skipRandomNumbers(s: var Rand) 161 +nim rand random.html#rand,Rand,Natural proc rand(r: var Rand; max: Natural): int 246 +nim rand random.html#rand,int proc rand(max: int): int 263 +nim rand random.html#rand,Rand,range[] proc rand(r: var Rand; max: range[0.0 .. high(float)]): float 284 +nim rand random.html#rand,float proc rand(max: float): float 311 +nim rand random.html#rand,Rand,HSlice[T: Ordinal or float or float32 or float64,T: Ordinal or float or float32 or float64] proc rand[T: Ordinal or SomeFloat](r: var Rand; x: HSlice[T, T]): T 332 +nim rand random.html#rand,HSlice[T: Ordinal or float or float32 or float64,T: Ordinal or float or float32 or float64] proc rand[T: Ordinal or SomeFloat](x: HSlice[T, T]): T 357 +nim rand random.html#rand,Rand,typedesc[T] proc rand[T: Ordinal](r: var Rand; t: typedesc[T]): T 379 +nim rand random.html#rand,typedesc[T] proc rand[T: Ordinal](t: typedesc[T]): T 400 +nim sample random.html#sample,Rand,set[T] proc sample[T](r: var Rand; s: set[T]): T 425 +nim sample random.html#sample,set[T] proc sample[T](s: set[T]): T 444 +nim sample random.html#sample,Rand,openArray[T] proc sample[T](r: var Rand; a: openArray[T]): T 464 +nim sample random.html#sample,openArray[T] proc sample[T](a: openArray[T]): lent T 479 +nim sample random.html#sample,Rand,openArray[T],openArray[U] proc sample[T, U](r: var Rand; a: openArray[T]; cdf: openArray[U]): T 499 +nim sample random.html#sample,openArray[T],openArray[U] proc sample[T, U](a: openArray[T]; cdf: openArray[U]): T 533 +nim gauss random.html#gauss,Rand,float,float proc gauss(r: var Rand; mu = 0.0; sigma = 1.0): float 562 +nim gauss random.html#gauss,float,float proc gauss(mu = 0.0; sigma = 1.0): float 578 +nim initRand random.html#initRand,int64 proc initRand(seed: int64): Rand 588 +nim randomize random.html#randomize,int64 proc randomize(seed: int64) 616 +nim shuffle random.html#shuffle,Rand,openArray[T] proc shuffle[T](r: var Rand; x: var openArray[T]) 637 +nim shuffle random.html#shuffle,openArray[T] proc shuffle[T](x: var openArray[T]) 653 +nim initRand random.html#initRand proc initRand(): Rand 688 +nim randomize random.html#randomize proc randomize() 739 +heading Basic usage random.html#basic-usage Basic usage 0 +heading See also random.html#see-also See also 0 +nimgrp sample random.html#sample-procs-all proc 425 +nimgrp rand random.html#rand-procs-all proc 246 +nimgrp randomize random.html#randomize-procs-all proc 616 +nimgrp initrand random.html#initRand-procs-all proc 588 +nimgrp gauss random.html#gauss-procs-all proc 562 +nimgrp shuffle random.html#shuffle-procs-all proc 637 diff --git a/rationals.html b/rationals.html new file mode 100644 index 0000000000000..6629083336d3a --- /dev/null +++ b/rationals.html @@ -0,0 +1,792 @@ + + + + + + + +std/rationals + + + + + + + + + + + + + + + + +
+
+

std/rationals

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements rational numbers, consisting of a numerator and a denominator. The denominator can not be 0. +

Example:

+
import std/rationals
+let
+  r1 = 1 // 2
+  r2 = -3 // 4
+
+doAssert r1 + r2 == -1 // 4
+doAssert r1 - r2 ==  5 // 4
+doAssert r1 * r2 == -3 // 8
+doAssert r1 / r2 == -2 // 3

+ +
+

Types

+
+
+
Rational[T] = object
+  num*, den*: T
+
+ + A rational number, consisting of a numerator num and a denominator den. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `$`[T](x: Rational[T]): string
+
+ + Turns a rational number into a string. +

Example:

+
doAssert $(1 // 2) == "1/2"
+ Source   +Edit   + +
+
+ +
+
+
+
func `*`[T](x, y: Rational[T]): Rational[T]
+
+ + Multiplies two rational numbers. + Source   +Edit   + +
+
+
+
func `*`[T](x: Rational[T]; y: T): Rational[T]
+
+ + Multiplies the rational x with the int y. + Source   +Edit   + +
+
+
+
func `*`[T](x: T; y: Rational[T]): Rational[T]
+
+ + Multiplies the int x with the rational y. + Source   +Edit   + +
+
+ +
+
+
+
func `*=`[T](x: var Rational[T]; y: Rational[T])
+
+ + Multiplies the rational x by y in-place. + Source   +Edit   + +
+
+
+
func `*=`[T](x: var Rational[T]; y: T)
+
+ + Multiplies the rational x by the int y in-place. + Source   +Edit   + +
+
+ +
+
+
+
func `+`[T](x, y: Rational[T]): Rational[T]
+
+ + Adds two rational numbers. + Source   +Edit   + +
+
+
+
func `+`[T](x: Rational[T]; y: T): Rational[T]
+
+ + Adds the rational x to the int y. + Source   +Edit   + +
+
+
+
func `+`[T](x: T; y: Rational[T]): Rational[T]
+
+ + Adds the int x to the rational y. + Source   +Edit   + +
+
+ +
+
+
+
func `+=`[T](x: var Rational[T]; y: Rational[T])
+
+ + Adds the rational y to the rational x in-place. + Source   +Edit   + +
+
+
+
func `+=`[T](x: var Rational[T]; y: T)
+
+ + Adds the int y to the rational x in-place. + Source   +Edit   + +
+
+ +
+
+
+
func `-`[T](x, y: Rational[T]): Rational[T]
+
+ + Subtracts two rational numbers. + Source   +Edit   + +
+
+
+
func `-`[T](x: Rational[T]): Rational[T]
+
+ + Unary minus for rational numbers. + Source   +Edit   + +
+
+
+
func `-`[T](x: Rational[T]; y: T): Rational[T]
+
+ + Subtracts the int y from the rational x. + Source   +Edit   + +
+
+
+
func `-`[T](x: T; y: Rational[T]): Rational[T]
+
+ + Subtracts the rational y from the int x. + Source   +Edit   + +
+
+ +
+
+
+
func `-=`[T](x: var Rational[T]; y: Rational[T])
+
+ + Subtracts the rational y from the rational x in-place. + Source   +Edit   + +
+
+
+
func `-=`[T](x: var Rational[T]; y: T)
+
+ + Subtracts the int y from the rational x in-place. + Source   +Edit   + +
+
+ +
+
+
+
func `/`[T](x, y: Rational[T]): Rational[T]
+
+ + Divides the rational x by the rational y. + Source   +Edit   + +
+
+
+
func `/`[T](x: Rational[T]; y: T): Rational[T]
+
+ + Divides the rational x by the int y. + Source   +Edit   + +
+
+
+
func `/`[T](x: T; y: Rational[T]): Rational[T]
+
+ + Divides the int x by the rational y. + Source   +Edit   + +
+
+ +
+
+
+
func `//`[T](num, den: T): Rational[T]
+
+ + A friendlier version of initRational. +

Example:

+
let x = 1 // 3 + 1 // 5
+doAssert x == 8 // 15
+ Source   +Edit   + +
+
+ +
+
+
+
func `/=`[T](x: var Rational[T]; y: Rational[T])
+
+ + Divides the rational x by the rational y in-place. + Source   +Edit   + +
+
+
+
func `/=`[T](x: var Rational[T]; y: T)
+
+ + Divides the rational x by the int y in-place. + Source   +Edit   + +
+
+ +
+
+
+
func `<`(x, y: Rational): bool
+
+ + Returns true if x is less than y. + Source   +Edit   + +
+
+ +
+
+
+
func `<=`(x, y: Rational): bool
+
+ + Returns tue if x is less than or equal to y. + Source   +Edit   + +
+
+ +
+
+
+
func `==`(x, y: Rational): bool
+
+ + Compares two rationals for equality. + Source   +Edit   + +
+
+ +
+
+
+
func `^`[T: SomeInteger](x: Rational[T]; y: T): Rational[T]
+
+ +

Computes x to the power of y.

+

The exponent y must be an integer. Negative exponents are supported but floating point exponents are not.

+ +

Example:

+
doAssert (-3 // 5) ^ 0 == (1 // 1)
+doAssert (-3 // 5) ^ 1 == (-3 // 5)
+doAssert (-3 // 5) ^ 2 == (9 // 25)
+doAssert (-3 // 5) ^ -2 == (25 // 9)
+ Source   +Edit   + +
+
+ +
+
+
+
func abs[T](x: Rational[T]): Rational[T]
+
+ + Returns the absolute value of x. +

Example:

+
doAssert abs(1 // 2) == 1 // 2
+doAssert abs(-1 // 2) == 1 // 2
+ Source   +Edit   + +
+
+ +
+
+
+
func cmp(x, y: Rational): int
+
+ + Compares two rationals. Returns
  • a value less than zero, if x < y
  • +
  • a value greater than zero, if x > y
  • +
  • zero, if x == y
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
func `div`[T: SomeInteger](x, y: Rational[T]): T
+
+ + Computes the rational truncated division. + Source   +Edit   + +
+
+ +
+
+
+
func floorDiv[T: SomeInteger](x, y: Rational[T]): T
+
+ +

Computes the rational floor division.

+

Floor division is conceptually defined as floor(x / y). This is different from the div operator, which is defined as trunc(x / y). That is, div rounds towards 0 and floorDiv rounds down.

+ + Source   +Edit   + +
+
+ +
+
+
+
func floorMod[T: SomeInteger](x, y: Rational[T]): Rational[T]
+
+ +

Computes the rational modulo by floor division (modulo).

+

This is same as x - floorDiv(x, y) * y. This func behaves the same as the % operator in Python.

+ + Source   +Edit   + +
+
+ +
+
+
+
func hash[T](x: Rational[T]): Hash
+
+ + Computes the hash for the rational x. + Source   +Edit   + +
+
+ +
+
+
+
func initRational[T: SomeInteger](num, den: T): Rational[T]
+
+ +

Creates a new rational number with numerator num and denominator den. den must not be 0.

+

Note: den != 0 is not checked when assertions are turned off.

+ + Source   +Edit   + +
+
+ +
+
+
+
func `mod`[T: SomeInteger](x, y: Rational[T]): Rational[T]
+
+ + Computes the rational modulo by truncated division (remainder). This is same as x - (x div y) * y. + Source   +Edit   + +
+
+ +
+
+
+
func reciprocal[T](x: Rational[T]): Rational[T]
+
+ + Calculates the reciprocal of x (1/x). If x is 0, raises DivByZeroDefect. + Source   +Edit   + +
+
+ +
+
+
+
func reduce[T: SomeInteger](x: var Rational[T])
+
+ +

Reduces the rational number x, so that the numerator and denominator have no common divisors other than 1 (and -1). If x is 0, raises DivByZeroDefect.

+

Note: This is called automatically by the various operations on rationals.

+ +

Example:

+
var r = Rational[int](num: 2, den: 4) # 1/2
+reduce(r)
+doAssert r.num == 1
+doAssert r.den == 2
+ Source   +Edit   + +
+
+ +
+
+
+
func toFloat[T](x: Rational[T]): float
+
+ + Converts a rational number x to a float. + Source   +Edit   + +
+
+ +
+
+
+
func toInt[T](x: Rational[T]): int
+
+ + Converts a rational number x to an int. Conversion rounds towards 0 if x does not contain an integer value. + Source   +Edit   + +
+
+ +
+
+
+
func toRational(x: float; n: int = high(int) shr 32): Rational[int] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Calculates the best rational approximation of x, where the denominator is smaller than n (default is the largest possible int for maximal resolution).

+

The algorithm is based on the theory of continued fractions.

+ +

Example:

+
let x = 1.2
+doAssert x.toRational.toFloat == x
+ Source   +Edit   + +
+
+
+
func toRational[T: SomeInteger](x: T): Rational[T]
+
+ + Converts some integer x to a rational number. +

Example:

+
doAssert toRational(42) == 42 // 1
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/rationals.idx b/rationals.idx new file mode 100644 index 0000000000000..bfaa21e1ee7c8 --- /dev/null +++ b/rationals.idx @@ -0,0 +1,52 @@ +nimTitle rationals rationals.html module std/rationals 0 +nim Rational rationals.html#Rational object Rational 28 +nim reduce rationals.html#reduce,Rational[T: SomeInteger] proc reduce[T: SomeInteger](x: var Rational[T]) 32 +nim initRational rationals.html#initRational,T,T proc initRational[T: SomeInteger](num, den: T): Rational[T] 54 +nim `//` rationals.html#//,T,T proc `//`[T](num, den: T): Rational[T] 63 +nim `$` rationals.html#$,Rational[T] proc `$`[T](x: Rational[T]): string 71 +nim toRational rationals.html#toRational,T proc toRational[T: SomeInteger](x: T): Rational[T] 78 +nim toRational rationals.html#toRational,float,int proc toRational(x: float; n: int = high(int) shr 32): Rational[int] 84 +nim toFloat rationals.html#toFloat,Rational[T] proc toFloat[T](x: Rational[T]): float 113 +nim toInt rationals.html#toInt,Rational[T] proc toInt[T](x: Rational[T]): int 117 +nim `+` rationals.html#+,Rational[T],Rational[T] proc `+`[T](x, y: Rational[T]): Rational[T] 122 +nim `+` rationals.html#+,Rational[T],T proc `+`[T](x: Rational[T]; y: T): Rational[T] 130 +nim `+` rationals.html#+,T,Rational[T] proc `+`[T](x: T; y: Rational[T]): Rational[T] 134 +nim `+=` rationals.html#+=,Rational[T],Rational[T] proc `+=`[T](x: var Rational[T]; y: Rational[T]) 138 +nim `+=` rationals.html#+=,Rational[T],T proc `+=`[T](x: var Rational[T]; y: T) 145 +nim `-` rationals.html#-,Rational[T] proc `-`[T](x: Rational[T]): Rational[T] 149 +nim `-` rationals.html#-,Rational[T],Rational[T] proc `-`[T](x, y: Rational[T]): Rational[T] 153 +nim `-` rationals.html#-,Rational[T],T proc `-`[T](x: Rational[T]; y: T): Rational[T] 161 +nim `-` rationals.html#-,T,Rational[T] proc `-`[T](x: T; y: Rational[T]): Rational[T] 165 +nim `-=` rationals.html#-=,Rational[T],Rational[T] proc `-=`[T](x: var Rational[T]; y: Rational[T]) 169 +nim `-=` rationals.html#-=,Rational[T],T proc `-=`[T](x: var Rational[T]; y: T) 176 +nim `*` rationals.html#*,Rational[T],Rational[T] proc `*`[T](x, y: Rational[T]): Rational[T] 180 +nim `*` rationals.html#*,Rational[T],T proc `*`[T](x: Rational[T]; y: T): Rational[T] 185 +nim `*` rationals.html#*,T,Rational[T] proc `*`[T](x: T; y: Rational[T]): Rational[T] 190 +nim `*=` rationals.html#*=,Rational[T],Rational[T] proc `*=`[T](x: var Rational[T]; y: Rational[T]) 195 +nim `*=` rationals.html#*=,Rational[T],T proc `*=`[T](x: var Rational[T]; y: T) 201 +nim reciprocal rationals.html#reciprocal,Rational[T] proc reciprocal[T](x: Rational[T]): Rational[T] 206 +nim `/` rationals.html#/,Rational[T],Rational[T] proc `/`[T](x, y: Rational[T]): Rational[T] 216 +nim `/` rationals.html#/,Rational[T],T proc `/`[T](x: Rational[T]; y: T): Rational[T] 221 +nim `/` rationals.html#/,T,Rational[T] proc `/`[T](x: T; y: Rational[T]): Rational[T] 226 +nim `/=` rationals.html#/=,Rational[T],Rational[T] proc `/=`[T](x: var Rational[T]; y: Rational[T]) 231 +nim `/=` rationals.html#/=,Rational[T],T proc `/=`[T](x: var Rational[T]; y: T) 237 +nim cmp rationals.html#cmp,Rational,Rational proc cmp(x, y: Rational): int 242 +nim `<` rationals.html#<,Rational,Rational proc `<`(x, y: Rational): bool 249 +nim `<=` rationals.html#<=,Rational,Rational proc `<=`(x, y: Rational): bool 253 +nim `==` rationals.html#==,Rational,Rational proc `==`(x, y: Rational): bool 257 +nim abs rationals.html#abs,Rational[T] proc abs[T](x: Rational[T]): Rational[T] 261 +nim `div` rationals.html#div,Rational[T: SomeInteger],Rational[T: SomeInteger] proc `div`[T: SomeInteger](x, y: Rational[T]): T 268 +nim `mod` rationals.html#mod,Rational[T: SomeInteger],Rational[T: SomeInteger] proc `mod`[T: SomeInteger](x, y: Rational[T]): Rational[T] 272 +nim floorDiv rationals.html#floorDiv,Rational[T: SomeInteger],Rational[T: SomeInteger] proc floorDiv[T: SomeInteger](x, y: Rational[T]): T 278 +nim floorMod rationals.html#floorMod,Rational[T: SomeInteger],Rational[T: SomeInteger] proc floorMod[T: SomeInteger](x, y: Rational[T]): Rational[T] 287 +nim hash rationals.html#hash,Rational[T] proc hash[T](x: Rational[T]): Hash 295 +nim `^` rationals.html#^,Rational[T: SomeInteger],T proc `^`[T: SomeInteger](x: Rational[T]; y: T): Rational[T] 307 +nimgrp + rationals.html#+-procs-all proc 122 +nimgrp - rationals.html#--procs-all proc 149 +nimgrp / rationals.html#/-procs-all proc 216 +nimgrp -= rationals.html#-=-procs-all proc 169 +nimgrp * rationals.html#*-procs-all proc 180 +nimgrp torational rationals.html#toRational-procs-all proc 78 +nimgrp *= rationals.html#*=-procs-all proc 195 +nimgrp /= rationals.html#/=-procs-all proc 231 +nimgrp += rationals.html#+=-procs-all proc 138 diff --git a/rdstdin.html b/rdstdin.html new file mode 100644 index 0000000000000..fa23686598bbb --- /dev/null +++ b/rdstdin.html @@ -0,0 +1,141 @@ + + + + + + + +std/rdstdin + + + + + + + + + + + + + + + + +
+
+

std/rdstdin

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module contains code for reading from stdin. On UNIX the linenoise library is wrapped and set up to provide default key bindings (e.g. you can navigate with the arrow keys). On Windows system.readLine is used. This suffices because Windows' console already provides the wanted functionality. +

Example: cmd: -r:off

+
import std/rdstdin
+echo readLineFromStdin("Is Nim awesome? (Y/n): ")
+var line: string
+while true:
+  let ok = readLineFromStdin("How are you? ", line)
+  if not ok: break # ctrl-C or ctrl-D will cause a break
+  if line.len > 0: echo line
+echo "exiting"

+
+

Imports

+
+ linenoise +
+
+
+

Procs

+
+
+
+
proc readLineFromStdin(prompt: string): string {.inline, ...raises: [IOError],
+    tags: [ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc readLineFromStdin(prompt: string; line: var string): bool {.
+    ...tags: [ReadIOEffect, WriteIOEffect], raises: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/rdstdin.idx b/rdstdin.idx new file mode 100644 index 0000000000000..bd67740226dfc --- /dev/null +++ b/rdstdin.idx @@ -0,0 +1,5 @@ +nimTitle rdstdin rdstdin.html module std/rdstdin 0 +nim readLineFromStdin rdstdin.html#readLineFromStdin,string,string proc readLineFromStdin(prompt: string; line: var string): bool 60 +nim readLineFromStdin rdstdin.html#readLineFromStdin,string proc readLineFromStdin(prompt: string): string 72 +idx stdin rdstdin.html#stdin_1 Module rdstdin 0 +nimgrp readlinefromstdin rdstdin.html#readLineFromStdin-procs-all proc 60 diff --git a/re.html b/re.html new file mode 100644 index 0000000000000..866817f362b97 --- /dev/null +++ b/re.html @@ -0,0 +1,979 @@ + + + + + + + +std/re + + + + + + + + + + + + + + + + +
+
+

std/re

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Regular expression support for Nim.

+

This module is implemented by providing a wrapper around the PCRE (Perl-Compatible Regular Expressions) C library. This means that your application will depend on the PCRE library's licence when using this module, which should not be a problem though.

+
Note: +There are also alternative nimble packages such as tinyre and regex.
+

PCRE's licence follows:

+ +

Licence of the PCRE library

PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language.

+

Written by Philip Hazel
Copyright (c) 1997-2005 University of Cambridge


+

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

+
  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • +
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • +
  • Neither the name of the University of Cambridge nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
  • +
+

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+ +

Regular expression syntax and semantics

As the regular expressions supported by this module are enormous, the reader is referred to https://perldoc.perl.org/perlre.html for the full documentation of Perl's regular expressions.

+

Because the backslash \ is a meta character both in the Nim programming language and in regular expressions, it is strongly recommended that one uses the raw strings of Nim, so that backslashes are interpreted by the regular expression engine:

+

  r"\S"  # matches any character that is not whitespace

+

A regular expression is a pattern that is matched against a subject string from left to right. Most characters stand for themselves in a pattern, and match the corresponding characters in the subject. As a trivial example, the pattern:

+
The quick brown fox
+

matches a portion of a subject string that is identical to itself. The power of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are encoded in the pattern by the use of metacharacters, which do not stand for themselves but instead are interpreted in some special way.

+

There are two different sets of metacharacters: those that are recognized anywhere in the pattern except within square brackets, and those that are recognized in square brackets. Outside square brackets, the metacharacters are as follows:

+ + + + + + + + + + + + + +
meta charactermeaning
\general escape character with several uses
^assert start of string (or line, in multiline mode)
$assert end of string (or line, in multiline mode)
.match any character except newline (by default)
[start character class definition
|start of alternative branch
(start subpattern
)end subpattern
{start min/max quantifier
?extends the meaning of (

also 0 or 1 quantifier (equal to {0,1})
also quantifier minimizer

*0 or more quantifier (equal to {0,})
+1 or more quantifier (equal to {1,})

also "possessive quantifier"

Part of a pattern that is in square brackets is called a "character class". In a character class the only metacharacters are:

+ + + + + + +
meta charactermeaning
\general escape character
^negate the class, but only if the first character
-indicates character range
[POSIX character class (only if followed by POSIX syntax)
]terminates the character class

The following sections describe the use of each of the metacharacters.

+ +

Backslash

The backslash character has several uses. Firstly, if it is followed by a non-alphanumeric character, it takes away any special meaning that character may have. This use of backslash as an escape character applies both inside and outside character classes.

+

For example, if you want to match a * character, you write \* in the pattern. This escaping action applies whether or not the following character would otherwise be interpreted as a metacharacter, so it is always safe to precede a non-alphanumeric with backslash to specify that it stands for itself. In particular, if you want to match a backslash, you write \\.

+ +

Non-printing characters

A second use of backslash provides a way of encoding non-printing characters in patterns in a visible manner. There is no restriction on the appearance of non-printing characters, apart from the binary zero that terminates a pattern, but when a pattern is being prepared by text editing, it is usually easier to use one of the following escape sequences than the binary character it represents:

+ + + + + + + + + +
charactermeaning
\aalarm, that is, the BEL character (hex 07)
\eescape (hex 1B)
\fformfeed (hex 0C)
\nnewline (hex 0A)
\rcarriage return (hex 0D)
\ttab (hex 09)
\dddcharacter with octal code ddd, or backreference
\xhhcharacter with hex code hh

After \x, from zero to two hexadecimal digits are read (letters can be in upper or lower case). In UTF-8 mode, any number of hexadecimal digits may appear between \x{ and }, but the value of the character code must be less than 2^31 (that is, the maximum hexadecimal value is 7FFFFFFF). If characters other than hexadecimal digits appear between \x{ and }, or if there is no terminating }, this form of escape is not recognized. Instead, the initial \x will be interpreted as a basic hexadecimal escape, with no following digits, giving a character whose value is zero.

+

After \0 up to two further octal digits are read. In both cases, if there are fewer than two digits, just those that are present are used. Thus the sequence \0\x\07 specifies two binary zeros followed by a BEL character (code value 7). Make sure you supply two digits after the initial zero if the pattern character that follows is itself an octal digit.

+

The handling of a backslash followed by a digit other than 0 is complicated. Outside a character class, PCRE reads it and any following digits as a decimal number. If the number is less than 10, or if there have been at least that many previous capturing left parentheses in the expression, the entire sequence is taken as a back reference. A description of how this works is given later, following the discussion of parenthesized subpatterns.

+

Inside a character class, or if the decimal number is greater than 9 and there have not been that many capturing subpatterns, PCRE re-reads up to three octal digits following the backslash, and generates a single byte from the least significant 8 bits of the value. Any subsequent digits stand for themselves. For example:

+ + + + + + + + + + +
examplemeaning
\040is another way of writing a space
\40is the same, provided there are fewer than 40 previous capturing subpatterns
\7is always a back reference
\11might be a back reference, or another way of writing a tab
\011is always a tab
\0113is a tab followed by the character "3"
\113might be a back reference, otherwise the character with octal code 113
\377might be a back reference, otherwise the byte consisting entirely of 1 bits
\81is either a back reference, or a binary zero followed by the two characters "8" and "1"

Note that octal values of 100 or greater must not be introduced by a leading zero, because no more than three octal digits are ever read.

+

All the sequences that define a single byte value or a single UTF-8 character (in UTF-8 mode) can be used both inside and outside character classes. In addition, inside a character class, the sequence \b is interpreted as the backspace character (hex 08), and the sequence \X is interpreted as the character "X". Outside a character class, these sequences have different meanings (see below).

+ +

Generic character types

The third use of backslash is for specifying generic character types. The following are always recognized:

+ + + + + + + +
character typemeaning
\dany decimal digit
\Dany character that is not a decimal digit
\sany whitespace character
\Sany character that is not a whitespace character
\wany "word" character
\Wany "non-word" character

Each pair of escape sequences partitions the complete set of characters into two disjoint sets. Any given character matches one, and only one, of each pair.

+

These character type sequences can appear both inside and outside character classes. They each match one character of the appropriate type. If the current matching point is at the end of the subject string, all of them fail, since there is no character to match.

+

For compatibility with Perl, \s does not match the VT character (code 11). This makes it different from the POSIX "space" class. The \s characters are HT (9), LF (10), FF (12), CR (13), and space (32).

+

A "word" character is an underscore or any character less than 256 that is a letter or digit. The definition of letters and digits is controlled by PCRE's low-valued character tables, and may vary if locale-specific matching is taking place (see "Locale support" in the pcreapi page). For example, in the "fr_FR" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w.

+

In UTF-8 mode, characters with values greater than 128 never match \d, \s, or \w, and always match \D, \S, and \W. This is true even when Unicode character property support is available.

+ +

Simple assertions

The fourth use of backslash is for certain simple assertions. An assertion specifies a condition that has to be met at a particular point in a match, without consuming any characters from the subject string. The use of subpatterns for more complicated assertions is described below. The backslashed assertions are:

+ + + + + + + +
assertionmeaning
\bmatches at a word boundary
\Bmatches when not at a word boundary
\Amatches at start of subject
\Zmatches at end of subject or before newline at end
\zmatches at end of subject
\Gmatches at first matching position in subject

These assertions may not appear in character classes (but note that \b has a different meaning, namely the backspace character, inside a character class).

+

A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively.

+

The \A, \Z, and \z assertions differ from the traditional circumflex and dollar in that they only ever match at the very start and end of the subject string, whatever options are set. The difference between \Z and \z is that \Z matches before a newline that is the last character of the string as well as at the end of the string, whereas \z matches only at the end.

+ +

Example:

+
import std/re
+## Unless specified otherwise, `start` parameter in each proc indicates
+## where the scan starts, but outputs are relative to the start of the input
+## string, not to `start`:
+doAssert find("uxabc", re"(?<=x|y)ab", start = 1) == 2 # lookbehind assertion
+doAssert find("uxabc", re"ab", start = 3) == -1 # we're past `start` => not found
+doAssert not match("xabc", re"^abc$", start = 1)
+  # can't match start of string since we're starting at 1

+ +
+

Types

+
+
+
Regex = ref RegexDesc
+
+ + a compiled regular expression + Source   +Edit   + +
+
+
+
RegexError = object of ValueError
+
+ + is raised if the pattern is no valid regular expression. + Source   +Edit   + +
+
+
+
RegexFlag = enum
+  reIgnoreCase = 0,         ## do caseless matching
+  reMultiLine = 1,          ## `^` and `$` match newlines within data
+  reDotAll = 2,             ## `.` matches anything including NL
+  reExtended = 3,           ## ignore whitespace and `#` comments
+  reStudy = 4                ## study the expression (may be omitted if the
+                             ## expression will be used only once)
+
+ + options for regular expressions + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
MaxReBufSize = 2147483647'i32
+
+ + Maximum PCRE (API 1) buffer start/size equal to high(cint), which even for 64-bit systems can be either 231-1 or 263-1. + Source   +Edit   + +
+
+
+
MaxSubpatterns = 20
+
+ + defines the maximum number of subpatterns that can be captured. This limit still exists for replacef and parallelReplace. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc contains(s: string; pattern: Regex; matches: var openArray[string];
+              start = 0): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + same as find(s, pattern, matches, start) >= 0
Note: +The memory for matches needs to be allocated before this function is called, otherwise it will just remain empty.
+ + Source   +Edit   + +
+
+
+
proc contains(s: string; pattern: Regex; start = 0): bool {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + same as find(s, pattern, start) >= 0 + Source   +Edit   + +
+
+ +
+
+
+
proc endsWith(s: string; suffix: Regex): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + returns true if s ends with the pattern suffix + Source   +Edit   + +
+
+ +
+
+
+
proc escapeRe(s: string): string {....raises: [], tags: [], forbids: [].}
+
+ + escapes s so that it is matched verbatim when used as a regular expression. + Source   +Edit   + +
+
+ +
+
+
+
proc find(buf: cstring; pattern: Regex; matches: var openArray[string];
+          start = 0; bufSize: int): int {....raises: [], tags: [], forbids: [].}
+
+ + returns the starting position of pattern in buf and the captured substrings in the array matches. If it does not match, nothing is written into matches and -1 is returned. buf has length bufSize (not necessarily '\0' terminated).
Note: +The memory for matches needs to be allocated before this function is called, otherwise it will just remain empty.
+ + Source   +Edit   + +
+
+
+
proc find(buf: cstring; pattern: Regex; start = 0; bufSize: int): int {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + returns the starting position of pattern in buf, where buf has length bufSize (not necessarily '\0' terminated). If it does not match, -1 is returned. + Source   +Edit   + +
+
+
+
proc find(s: string; pattern: Regex; matches: var openArray[string]; start = 0): int {.
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ + returns the starting position of pattern in s and the captured substrings in the array matches. If it does not match, nothing is written into matches and -1 is returned.
Note: +The memory for matches needs to be allocated before this function is called, otherwise it will just remain empty.
+ + Source   +Edit   + +
+
+
+
proc find(s: string; pattern: Regex; start = 0): int {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + returns the starting position of pattern in s. If it does not match, -1 is returned. We start the scan at start. +

Example:

+
doAssert find("abcdefg", re"cde") == 2
+doAssert find("abcdefg", re"abc") == 0
+doAssert find("abcdefg", re"zz") == -1 # not found
+doAssert find("abcdefg", re"cde", start = 2) == 2 # still 2
+doAssert find("abcdefg", re"cde", start = 3) == -1 # we're past the start position
+doAssert find("xabc", re"(?<=x|y)abc", start = 1) == 1
+  # lookbehind assertion `(?<=x|y)` can look behind `start`
+ Source   +Edit   + +
+
+ +
+
+
+
proc findAll(s: string; pattern: Regex; start = 0): seq[string] {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + returns all matching substrings of s that match pattern. If it does not match, @[] is returned. + Source   +Edit   + +
+
+ +
+
+
+
proc findBounds(buf: cstring; pattern: Regex;
+                matches: var openArray[tuple[first, last: int]]; start = 0;
+                bufSize: int): tuple[first, last: int] {....raises: [], tags: [],
+    forbids: [].}
+
+ + returns the starting position and end position of pattern in buf (where buf has length bufSize and is not necessarily '\0' terminated), and the captured substrings in the array matches. If it does not match, nothing is written into matches and (-1,0) is returned.
Note: +The memory for matches needs to be allocated before this function is called, otherwise it will just remain empty.
+ + Source   +Edit   + +
+
+
+
proc findBounds(buf: cstring; pattern: Regex; matches: var openArray[string];
+                start = 0; bufSize: int): tuple[first, last: int] {....raises: [],
+    tags: [], forbids: [].}
+
+ +

returns the starting position and end position of pattern in buf (where buf has length bufSize and is not necessarily '\0' terminated), and the captured substrings in the array matches. If it does not match, nothing is written into matches and (-1,0) is returned.

+

Note: The memory for matches needs to be allocated before this function is called, otherwise it will just remain empty.

+ + Source   +Edit   + +
+
+
+
proc findBounds(buf: cstring; pattern: Regex; start = 0; bufSize: int): tuple[
+    first, last: int] {....raises: [], tags: [], forbids: [].}
+
+ + returns the first and last position of pattern in buf, where buf has length bufSize (not necessarily '\0' terminated). If it does not match, (-1,0) is returned. + Source   +Edit   + +
+
+
+
proc findBounds(s: string; pattern: Regex;
+                matches: var openArray[tuple[first, last: int]]; start = 0): tuple[
+    first, last: int] {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + returns the starting position and end position of pattern in s and the captured substrings in the array matches. If it does not match, nothing is written into matches and (-1,0) is returned.
Note: +The memory for matches needs to be allocated before this function is called, otherwise it will just remain empty.
+ +

Example:

+
var matches = newSeq[tuple[first, last: int]](1)
+let (first, last) = findBounds("Hello World", re"(\w+)", matches)
+doAssert first == 0
+doAssert last == 4
+doAssert matches[0] == (0, 4)
+ Source   +Edit   + +
+
+
+
proc findBounds(s: string; pattern: Regex; matches: var openArray[string];
+                start = 0): tuple[first, last: int] {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + returns the starting position and end position of pattern in s and the captured substrings in the array matches. If it does not match, nothing is written into matches and (-1,0) is returned.
Note: +The memory for matches needs to be allocated before this function is called, otherwise it will just remain empty.
+ +

Example:

+
var matches = newSeq[string](1)
+let (first, last) = findBounds("Hello World", re"(W\w+)", matches)
+doAssert first == 6
+doAssert last == 10
+doAssert matches[0] == "World"
+ Source   +Edit   + +
+
+
+
proc findBounds(s: string; pattern: Regex; start = 0): tuple[first, last: int] {.
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ +

returns the first and last position of pattern in s. If it does not match, (-1,0) is returned.

+

Note: there is a speed improvement if the matches do not need to be captured.

+ +

Example:

+
assert findBounds("01234abc89", re"abc") == (5,7)
+ Source   +Edit   + +
+
+ +
+
+
+
proc match(buf: cstring; pattern: Regex; matches: var openArray[string];
+           start = 0; bufSize: int): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + returns true if buf[start..<bufSize] matches the pattern and the captured substrings in the array matches. If it does not match, nothing is written into matches and false is returned. buf has length bufSize (not necessarily '\0' terminated).
Note: +The memory for matches needs to be allocated before this function is called, otherwise it will just remain empty.
+ + Source   +Edit   + +
+
+
+
proc match(s: string; pattern: Regex; matches: var openArray[string]; start = 0): bool {.
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ + returns true if s[start..] matches the pattern and the captured substrings in the array matches. If it does not match, nothing is written into matches and false is returned.
Note: +The memory for matches needs to be allocated before this function is called, otherwise it will just remain empty.
+ +

Example:

+
import std/sequtils
+var matches: array[2, string]
+if match("abcdefg", re"c(d)ef(g)", matches, 2):
+  doAssert toSeq(matches) == @["d", "g"]
+ Source   +Edit   + +
+
+
+
proc match(s: string; pattern: Regex; start = 0): bool {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + returns true if s[start..] matches the pattern. + Source   +Edit   + +
+
+ +
+
+
+
proc matchLen(buf: cstring; pattern: Regex; matches: var openArray[string];
+              start = 0; bufSize: int): int {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + the same as match, but it returns the length of the match, if there is no match, -1 is returned. Note that a match length of zero can happen.
Note: +The memory for matches needs to be allocated before this function is called, otherwise it will just remain empty.
+ + Source   +Edit   + +
+
+
+
proc matchLen(buf: cstring; pattern: Regex; start = 0; bufSize: int): int {.
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ + the same as match, but it returns the length of the match, if there is no match, -1 is returned. Note that a match length of zero can happen. + Source   +Edit   + +
+
+
+
proc matchLen(s: string; pattern: Regex; matches: var openArray[string];
+              start = 0): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + the same as match, but it returns the length of the match, if there is no match, -1 is returned. Note that a match length of zero can happen.
Note: +The memory for matches needs to be allocated before this function is called, otherwise it will just remain empty.
+ + Source   +Edit   + +
+
+
+
proc matchLen(s: string; pattern: Regex; start = 0): int {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + the same as match, but it returns the length of the match, if there is no match, -1 is returned. Note that a match length of zero can happen. +

Example:

+
doAssert matchLen("abcdefg", re"cde", 2) == 3
+doAssert matchLen("abcdefg", re"abcde") == 5
+doAssert matchLen("abcdefg", re"cde") == -1
+ Source   +Edit   + +
+
+ +
+
+
+
proc multiReplace(s: string;
+                  subs: openArray[tuple[pattern: Regex, repl: string]]): string {.
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ + Returns a modified copy of s with the substitutions in subs applied in parallel. + Source   +Edit   + +
+
+ +
+
+
+
proc re(s: string; flags = {reStudy}): Regex {....raises: [RegexError], tags: [],
+    forbids: [].}
+
+ +

Constructor of regular expressions.

+

Note that Nim's extended raw string literals support the syntax re"[abc]" as a short form for re(r"[abc]"). Also note that since this compiles the regular expression, which is expensive, you should avoid putting it directly in the arguments of the functions like the examples show below if you plan to use it a lot of times, as this will hurt performance immensely. (e.g. outside a loop, ...)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc replace(s: string; sub: Regex; by = ""): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + Replaces sub in s by the string by. Captures cannot be accessed in by. +

Example:

+
doAssert "var1=key; var2=key2".replace(re"(\w+)=(\w+)") == "; "
+doAssert "var1=key; var2=key2".replace(re"(\w+)=(\w+)", "?") == "?; ?"
+ Source   +Edit   + +
+
+ +
+
+
+
proc replacef(s: string; sub: Regex; by: string): string {....raises: [ValueError],
+    tags: [], forbids: [].}
+
+ + Replaces sub in s by the string by. Captures can be accessed in by with the notation $i and $# (see strutils.`%`). +

Example:

+
doAssert "var1=key; var2=key2".replacef(re"(\w+)=(\w+)", "$1<-$2$2") ==
+  "var1<-keykey; var2<-key2key2"
+ Source   +Edit   + +
+
+ +
+
+
+
proc rex(s: string; flags = {reStudy, reExtended}): Regex {.
+    ...raises: [RegexError], tags: [], forbids: [].}
+
+ +

Constructor for extended regular expressions.

+

The extended means that comments starting with # and whitespace are ignored.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc split(s: string; sep: Regex; maxsplit = -1): seq[string] {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Splits the string s into a seq of substrings.

+

The portion matched by sep is not returned.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc startsWith(s: string; prefix: Regex): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + returns true if s starts with the pattern prefix + Source   +Edit   + +
+
+ +
+
+
+
proc transformFile(infile, outfile: string;
+                   subs: openArray[tuple[pattern: Regex, repl: string]]) {.
+    ...raises: [IOError, ValueError], tags: [ReadIOEffect, WriteIOEffect],
+    forbids: [].}
+
+ + reads in the file infile, performs a parallel replacement (calls parallelReplace) and writes back to outfile. Raises IOError if an error occurs. This is supposed to be used for quick scripting. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator findAll(buf: cstring; pattern: Regex; start = 0; bufSize: int): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Yields all matching substrings of s that match pattern.

+

Note that since this is an iterator you should not modify the string you are iterating over: bad things could happen.

+ + Source   +Edit   + +
+
+
+
iterator findAll(s: string; pattern: Regex; start = 0): string {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Yields all matching substrings of s that match pattern.

+

Note that since this is an iterator you should not modify the string you are iterating over: bad things could happen.

+ + Source   +Edit   + +
+
+ +
+
+
+
iterator split(s: string; sep: Regex; maxsplit = -1): string {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Splits the string s into substrings.

+

Substrings are separated by the regular expression sep (and the portion matched by sep is not returned).

+ +

Example:

+
import std/sequtils
+doAssert toSeq(split("00232this02939is39an22example111", re"\d+")) ==
+  @["", "this", "is", "an", "example", ""]
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template `=~`(s: string; pattern: Regex): untyped
+
+ + This calls match with an implicit declared matches array that can be used in the scope of the =~ call: +

Example:

+
proc parse(line: string): string =
+  if line =~ re"\s*(\w+)\s*\=\s*(\w+)": # matches a key=value pair:
+    result = $(matches[0], matches[1])
+  elif line =~ re"\s*(\#.*)": # matches a comment
+    # note that the implicit `matches` array is different from 1st branch
+    result = $(matches[0],)
+  else: raiseAssert "unreachable"
+  doAssert not declared(matches)
+doAssert parse("NAME = LENA") == """("NAME", "LENA")"""
+doAssert parse("   # comment ... ") == """("# comment ... ",)"""
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/re.idx b/re.idx new file mode 100644 index 0000000000000..ef60ccb871575 --- /dev/null +++ b/re.idx @@ -0,0 +1,60 @@ +nimTitle re re.html module std/re 0 +nim MaxSubpatterns re.html#MaxSubpatterns const MaxSubpatterns 45 +nim reIgnoreCase re.html#reIgnoreCase RegexFlag.reIgnoreCase 50 +nim reMultiLine re.html#reMultiLine RegexFlag.reMultiLine 50 +nim reDotAll re.html#reDotAll RegexFlag.reDotAll 50 +nim reExtended re.html#reExtended RegexFlag.reExtended 50 +nim reStudy re.html#reStudy RegexFlag.reStudy 50 +nim RegexFlag re.html#RegexFlag enum RegexFlag 50 +nim Regex re.html#Regex type Regex 62 +nim RegexError re.html#RegexError object RegexError 64 +nim re re.html#re,string proc re(s: string; flags = {reStudy}): Regex 101 +nim rex re.html#rex,string proc rex(s: string; flags = {reStudy, reExtended}): Regex 126 +nim MaxReBufSize re.html#MaxReBufSize const MaxReBufSize 157 +nim findBounds re.html#findBounds,cstring,Regex,openArray[string],int,int proc findBounds(buf: cstring; pattern: Regex; matches: var openArray[string];\n start = 0; bufSize: int): tuple[first, last: int] 161 +nim findBounds re.html#findBounds,string,Regex,openArray[string],int proc findBounds(s: string; pattern: Regex; matches: var openArray[string]; start = 0): tuple[\n first, last: int] 184 +nim findBounds re.html#findBounds,cstring,Regex,openArray[tuple[int,int]],int,int proc findBounds(buf: cstring; pattern: Regex;\n matches: var openArray[tuple[first, last: int]]; start = 0;\n bufSize: int): tuple[first, last: int] 201 +nim findBounds re.html#findBounds,string,Regex,openArray[tuple[int,int]],int proc findBounds(s: string; pattern: Regex;\n matches: var openArray[tuple[first, last: int]]; start = 0): tuple[\n first, last: int] 224 +nim findBounds re.html#findBounds,cstring,Regex,int,int proc findBounds(buf: cstring; pattern: Regex; start = 0; bufSize: int): tuple[\n first, last: int] 254 +nim findBounds re.html#findBounds,string,Regex,int proc findBounds(s: string; pattern: Regex; start = 0): tuple[first, last: int] 267 +nim matchLen re.html#matchLen,string,Regex,openArray[string],int proc matchLen(s: string; pattern: Regex; matches: var openArray[string]; start = 0): int 287 +nim matchLen re.html#matchLen,cstring,Regex,openArray[string],int,int proc matchLen(buf: cstring; pattern: Regex; matches: var openArray[string];\n start = 0; bufSize: int): int 296 +nim matchLen re.html#matchLen,string,Regex,int proc matchLen(s: string; pattern: Regex; start = 0): int 305 +nim matchLen re.html#matchLen,cstring,Regex,int,int proc matchLen(buf: cstring; pattern: Regex; start = 0; bufSize: int): int 316 +nim match re.html#match,string,Regex,int proc match(s: string; pattern: Regex; start = 0): bool 322 +nim match re.html#match,string,Regex,openArray[string],int proc match(s: string; pattern: Regex; matches: var openArray[string]; start = 0): bool 326 +nim match re.html#match,cstring,Regex,openArray[string],int,int proc match(buf: cstring; pattern: Regex; matches: var openArray[string]; start = 0;\n bufSize: int): bool 341 +nim find re.html#find,cstring,Regex,openArray[string],int,int proc find(buf: cstring; pattern: Regex; matches: var openArray[string]; start = 0;\n bufSize: int): int 352 +nim find re.html#find,string,Regex,openArray[string],int proc find(s: string; pattern: Regex; matches: var openArray[string]; start = 0): int 373 +nim find re.html#find,cstring,Regex,int,int proc find(buf: cstring; pattern: Regex; start = 0; bufSize: int): int 382 +nim find re.html#find,string,Regex,int proc find(s: string; pattern: Regex; start = 0): int 394 +nim findAll re.html#findAll.i,string,Regex,int iterator findAll(s: string; pattern: Regex; start = 0): string 407 +nim findAll re.html#findAll.i,cstring,Regex,int,int iterator findAll(buf: cstring; pattern: Regex; start = 0; bufSize: int): string 426 +nim findAll re.html#findAll,string,Regex,int proc findAll(s: string; pattern: Regex; start = 0): seq[string] 447 +nim `=~` re.html#=~.t,string,Regex template `=~`(s: string; pattern: Regex): untyped 453 +nim contains re.html#contains,string,Regex,int proc contains(s: string; pattern: Regex; start = 0): bool 474 +nim contains re.html#contains,string,Regex,openArray[string],int proc contains(s: string; pattern: Regex; matches: var openArray[string]; start = 0): bool 478 +nim startsWith re.html#startsWith,string,Regex proc startsWith(s: string; prefix: Regex): bool 485 +nim endsWith re.html#endsWith,string,Regex proc endsWith(s: string; suffix: Regex): bool 489 +nim replace re.html#replace,string,Regex,string proc replace(s: string; sub: Regex; by = ""): string 494 +nim replacef re.html#replacef,string,Regex,string proc replacef(s: string; sub: Regex; by: string): string 515 +nim multiReplace re.html#multiReplace,string,openArray[tuple[Regex,string]] proc multiReplace(s: string; subs: openArray[tuple[pattern: Regex, repl: string]]): string 533 +nim transformFile re.html#transformFile,string,string,openArray[tuple[Regex,string]] proc transformFile(infile, outfile: string;\n subs: openArray[tuple[pattern: Regex, repl: string]]) 553 +nim split re.html#split.i,string,Regex,int iterator split(s: string; sep: Regex; maxsplit = -1): string 561 +nim split re.html#split,string,Regex,int proc split(s: string; sep: Regex; maxsplit = -1): seq[string] 594 +nim escapeRe re.html#escapeRe,string proc escapeRe(s: string): string 601 +heading Licence of the PCRE library re.html#licence-of-the-pcre-library Licence of the PCRE library 0 +heading Regular expression syntax and semantics re.html#regular-expression-syntax-and-semantics Regular expression syntax and semantics 0 +heading Backslash re.html#regular-expression-syntax-and-semantics-backslash Backslash 0 +idx backslash re.html#backslash_1 Backslash 0 +heading Non-printing characters re.html#regular-expression-syntax-and-semantics-nonminusprinting-characters Non-printing characters 0 +heading Generic character types re.html#regular-expression-syntax-and-semantics-generic-character-types Generic character types 0 +idx generic character types re.html#generic-character-types_1 Generic character types 0 +heading Simple assertions re.html#regular-expression-syntax-and-semantics-simple-assertions Simple assertions 0 +idx simple assertions re.html#simple-assertions_1 Simple assertions 0 +nimgrp findbounds re.html#findBounds-procs-all proc 161 +nimgrp contains re.html#contains-procs-all proc 474 +nimgrp match re.html#match-procs-all proc 322 +nimgrp find re.html#find-procs-all proc 352 +nimgrp matchlen re.html#matchLen-procs-all proc 287 +nimgrp findall re.html#findAll-iterators-all iterator 407 diff --git a/refc.html b/refc.html new file mode 100644 index 0000000000000..63905967fd01c --- /dev/null +++ b/refc.html @@ -0,0 +1,88 @@ + + + + + + + +doc/refc + + + + + + + + + + + + + + + + +
+
+

doc/refc

+ +

Tweaking the refc GC

+

Cycle collector

The cycle collector can be en-/disabled independently from the other parts of the garbage collector with GC_enableMarkAndSweep and GC_disableMarkAndSweep.

+ +

Soft real-time support

To enable real-time support, the symbol useRealtimeGC needs to be defined via --define:useRealtimeGC (you can put this into your config file as well). With this switch the garbage collector supports the following operations:

+

proc GC_setMaxPause*(maxPauseInUs: int)
+proc GC_step*(us: int, strongAdvice = false, stackSize = -1)

+

The unit of the parameters maxPauseInUs and us is microseconds.

+

These two procs are the two modus operandi of the real-time garbage collector:

+
  1. GC_SetMaxPause Mode

    +

    You can call GC_SetMaxPause at program startup and then each triggered garbage collector run tries to not take longer than maxPause time. However, it is possible (and common) that the work is nevertheless not evenly distributed as each call to new can trigger the garbage collector and thus take maxPause time.

    +
  2. +
  3. GC_step Mode

    +

    This allows the garbage collector to perform some work for up to us time. This is useful to call in the main loop to ensure the garbage collector can do its work. To bind all garbage collector activity to a GC_step call, deactivate the garbage collector with GC_disable at program startup. If strongAdvice is set to true, then the garbage collector will be forced to perform the collection cycle. Otherwise, the garbage collector may decide not to do anything, if there is not much garbage to collect. You may also specify the current stack size via stackSize parameter. It can improve performance when you know that there are no unique Nim references below a certain point on the stack. Make sure the size you specify is greater than the potential worst-case size.

    +

    It can improve performance when you know that there are no unique Nim references below a certain point on the stack. Make sure the size you specify is greater than the potential worst-case size.

    +
  4. +
+

These procs provide a "best effort" real-time guarantee; in particular the cycle collector is not aware of deadlines. Deactivate it to get more predictable real-time behaviour. Tests show that a 1ms max pause time will be met in almost all cases on modern CPUs (with the cycle collector disabled).

+ +

Time measurement with garbage collectors

The garbage collectors' way of measuring time uses (see lib/system/timers.nim for the implementation):

+
  1. QueryPerformanceCounter and QueryPerformanceFrequency on Windows.
  2. +
  3. mach_absolute_time on Mac OS X.
  4. +
  5. gettimeofday on Posix systems.
  6. +
+

As such it supports a resolution of nanoseconds internally; however, the API uses microseconds for convenience.

+

Define the symbol reportMissedDeadlines to make the garbage collector output whenever it missed a deadline. The reporting will be enhanced and supported by the API in later versions of the collector.

+ +

Tweaking the garbage collector

The collector checks whether there is still time left for its work after every workPackage'th iteration. This is currently set to 100 which means that up to 100 objects are traversed and freed before it checks again. Thus workPackage affects the timing granularity and may need to be tweaked in highly specialized environments or for older hardware.

+ +

Thread coordination

When the NimMain() function is called Nim initializes the garbage collector to the current thread, which is usually the main thread of your application. If your C code later spawns a different thread and calls Nim code, the garbage collector will fail to work properly and you will crash.

+

As long as you don't use the threadvar emulation Nim uses native thread variables, of which you get a fresh version whenever you create a thread. You can then attach a GC to this thread via

+

system.setupForeignThreadGc()

+

It is not safe to disable the garbage collector and enable it after the call from your background thread even if the code you are calling is short lived.

+

Before the thread exits, you should tear down the thread's GC to prevent memory leaks by calling

+

system.tearDownForeignThreadGc()

+ +

Keeping track of memory

If you need to pass around memory allocated by Nim to C, you can use the procs GC_ref and GC_unref to mark objects as referenced to avoid them being freed by the garbage collector. Other useful procs from system you can use to keep track of memory are:

+
  • getTotalMem() Returns the amount of total memory managed by the garbage collector.
  • +
  • getOccupiedMem() Bytes reserved by the garbage collector and used by objects.
  • +
  • getFreeMem() Bytes reserved by the garbage collector and not in use.
  • +
  • GC_getStatistics() Garbage collector statistics as a human-readable string.
  • +
+

These numbers are usually only for the running thread, not for the whole heap, with the exception of --mm:boehm and --mm:go.

+

In addition to GC_ref and GC_unref you can avoid the garbage collector by manually allocating memory with procs like alloc, alloc0, allocShared, allocShared0 or allocCStringArray. The garbage collector won't try to free them, you need to call their respective dealloc pairs (dealloc, deallocShared, deallocCStringArray, etc) when you are done with them or they will leak.

+ +

Heap dump

The heap dump feature is still in its infancy, but it already proved useful for us, so it might be useful for you. To get a heap dump, compile with -d:nimTypeNames and call dumpNumberOfInstances at a strategic place in your program. This produces a list of the used types in your program and for every type the total amount of object instances for this type as well as the total amount of bytes these instances take up.

+

The numbers count the number of objects in all garbage collector heaps, they refer to all running threads, not only to the current thread. (The current thread would be the thread that calls dumpNumberOfInstances.) This might change in later versions.

+ + + + +
+
+ + + + diff --git a/refc.idx b/refc.idx new file mode 100644 index 0000000000000..ee10c70a1106e --- /dev/null +++ b/refc.idx @@ -0,0 +1,10 @@ +markupTitle refc.md refc.html refc.md 0 +heading Tweaking the refc GC refc.html#tweaking-the-refc-gc Tweaking the refc GC 0 +heading Cycle collector refc.html#cycle-collector Cycle collector 0 +heading Soft real-time support refc.html#soft-realminustime-support Soft real-time support 0 +idx useRealtimeGC refc.html#userealtimegc_1 Soft real-time support 0 +heading Time measurement with garbage collectors refc.html#time-measurement-with-garbage-collectors Time measurement with garbage collectors 0 +heading Tweaking the garbage collector refc.html#tweaking-the-garbage-collector Tweaking the garbage collector 0 +heading Thread coordination refc.html#thread-coordination Thread coordination 0 +heading Keeping track of memory refc.html#keeping-track-of-memory Keeping track of memory 0 +heading Heap dump refc.html#heap-dump Heap dump 0 diff --git a/registry.html b/registry.html new file mode 100644 index 0000000000000..fba0613bb4d92 --- /dev/null +++ b/registry.html @@ -0,0 +1,199 @@ + + + + + + + +std/registry + + + + + + + + + + + + + + + + +
+
+

std/registry

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module is experimental and its interface may change.

+ +
+

Types

+
+
+
HKEY = uint
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
HKEY_CURRENT_USER = 2147483649'u
+
+ + + Source   +Edit   + +
+
+
+
HKEY_LOCAL_MACHINE = 2147483650'u
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc getUnicodeValue(path, key: string; handle: HKEY): string {.
+    ...raises: [OSError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setUnicodeValue(path, key, val: string; handle: HKEY) {....raises: [OSError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/registry.idx b/registry.idx new file mode 100644 index 0000000000000..125c9ee932c1f --- /dev/null +++ b/registry.idx @@ -0,0 +1,6 @@ +nimTitle registry registry.html module std/registry 0 +nim HKEY registry.html#HKEY type HKEY 18 +nim HKEY_LOCAL_MACHINE registry.html#HKEY_LOCAL_MACHINE const HKEY_LOCAL_MACHINE 21 +nim HKEY_CURRENT_USER registry.html#HKEY_CURRENT_USER const HKEY_CURRENT_USER 22 +nim getUnicodeValue registry.html#getUnicodeValue,string,string,HKEY proc getUnicodeValue(path, key: string; handle: HKEY): string 49 +nim setUnicodeValue registry.html#setUnicodeValue,string,string,string,HKEY proc setUnicodeValue(path, key, val: string; handle: HKEY) 77 diff --git a/repr_v2.html b/repr_v2.html new file mode 100644 index 0000000000000..842084d1a403a --- /dev/null +++ b/repr_v2.html @@ -0,0 +1,383 @@ + + + + + + + +system/repr_v2 + + + + + + + + + + + + + + + + +
+
+

system/repr_v2

+
+ +
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ formatfloat +
+
+
+

Procs

+
+
+
+
proc repr(p: pointer): string {....raises: [], tags: [], forbids: [].}
+
+ + repr of pointer as its hexadecimal value + Source   +Edit   + +
+
+
+
proc repr(p: proc | iterator {.closure.}): string
+
+ + repr of a proc as its address + Source   +Edit   + +
+
+
+
proc repr(x: bool): string {.magic: "BoolToStr", noSideEffect, ...raises: [],
+                             tags: [], forbids: [].}
+
+ + repr for a boolean argument. Returns x converted to the string "false" or "true". + Source   +Edit   + +
+
+
+
proc repr(x: char): string {.noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

repr for a character argument. Returns x converted to an escaped string.

+

assert repr('c') == "'c'"

+ + Source   +Edit   + +
+
+
+
proc repr(x: float): string {....raises: [], tags: [], forbids: [].}
+
+ + Same as $x + Source   +Edit   + +
+
+
+
proc repr(x: int): string {....raises: [], tags: [], forbids: [].}
+
+ + Same as $x + Source   +Edit   + +
+
+
+
proc repr(x: int64): string {....raises: [], tags: [], forbids: [].}
+
+ + Same as $x + Source   +Edit   + +
+
+
+
proc repr(x: NimNode): string {.magic: "Repr", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc repr(x: string | cstring): string {.noSideEffect, ...raises: [].}
+
+ + repr for a string argument. Returns x converted to a quoted and escaped string. + Source   +Edit   + +
+
+
+
proc repr(x: uint64): string {.noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + Same as $x + Source   +Edit   + +
+
+
+
proc repr[Enum: enum](x: Enum): string {.magic: "EnumToStr", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

repr for an enumeration argument. This works for any enumeration type thanks to compiler magic.

+

If a repr operator for a concrete enumeration is provided, this is used instead. (In other words: Overwriting is possible.)

+ + Source   +Edit   + +
+
+
+
proc repr[T, IDX](x: array[IDX, T]): string
+
+ + Generic repr operator for arrays that is lifted from the components. + Source   +Edit   + +
+
+
+
proc repr[T: tuple | object](x: T): string {.noSideEffect, ...raises: [].}
+
+ +

Generic repr operator for tuples that is lifted from the components of x. Example:

+

$(23, 45) == "(23, 45)"
+$(a: 23, b: 45) == "(a: 23, b: 45)"
+$() == "()"

+ + Source   +Edit   + +
+
+
+
proc repr[T](x: openArray[T]): string
+
+ +

Generic repr operator for openarrays that is lifted from the components of x. Example:

+

$(@[23, 45].toOpenArray(0, 1)) == "[23, 45]"

+ + Source   +Edit   + +
+
+
+
proc repr[T](x: ref T | ptr T): string {.noSideEffect, ...raises: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc repr[T](x: seq[T]): string
+
+ +

Generic repr operator for seqs that is lifted from the components of x. Example:

+

$(@[23, 45]) == "@[23, 45]"

+ + Source   +Edit   + +
+
+
+
proc repr[T](x: set[T]): string
+
+ +

Generic repr operator for sets that is lifted from the components of x. Example:

+

${23, 45} == "{23, 45}"

+ + Source   +Edit   + +
+
+
+
proc repr[T](x: UncheckedArray[T]): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc reprDiscriminant(e: int): string {.compilerproc, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template repr(t: typedesc): string
+
+ + + Source   +Edit   + +
+
+
+
template repr[T: distinct | (range and not enum)](x: T): string
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/repr_v2.idx b/repr_v2.idx new file mode 100644 index 0000000000000..86f2b80005796 --- /dev/null +++ b/repr_v2.idx @@ -0,0 +1,24 @@ +nimTitle repr_v2 repr_v2.html module system/repr_v2 0 +nim repr repr_v2.html#repr,NimNode proc repr(x: NimNode): string 15 +nim repr repr_v2.html#repr,int proc repr(x: int): string 17 +nim repr repr_v2.html#repr,int64 proc repr(x: int64): string 21 +nim repr repr_v2.html#repr,uint64 proc repr(x: uint64): string 25 +nim repr repr_v2.html#repr,float proc repr(x: float): string 29 +nim repr repr_v2.html#repr,bool proc repr(x: bool): string 33 +nim repr repr_v2.html#repr,char proc repr(x: char): string 37 +nim repr repr_v2.html#repr proc repr(x: string | cstring): string 54 +nim repr repr_v2.html#repr,Enum proc repr[Enum: enum](x: Enum): string 70 +nim reprDiscriminant repr_v2.html#reprDiscriminant,int proc reprDiscriminant(e: int): string 77 +nim repr repr_v2.html#repr,pointer proc repr(p: pointer): string 82 +nim repr repr_v2.html#repr_2 proc repr(p: proc | iterator {.closure.}): string 98 +nim repr repr_v2.html#repr.t,T template repr[T: distinct | (range and not enum)](x: T): string 102 +nim repr repr_v2.html#repr.t,typedesc template repr(t: typedesc): string 110 +nim repr repr_v2.html#repr,T proc repr[T: tuple | object](x: T): string 133 +nim repr repr_v2.html#repr_3 proc repr[T](x: ref T | ptr T): string 145 +nim repr repr_v2.html#repr,set[T] proc repr[T](x: set[T]): string 165 +nim repr repr_v2.html#repr,seq[T] proc repr[T](x: seq[T]): string 173 +nim repr repr_v2.html#repr,array[IDX,T] proc repr[T, IDX](x: array[IDX, T]): string 181 +nim repr repr_v2.html#repr,openArray[T] proc repr[T](x: openArray[T]): string 185 +nim repr repr_v2.html#repr,UncheckedArray[T] proc repr[T](x: UncheckedArray[T]): string 193 +nimgrp repr repr_v2.html#repr-procs-all proc 15 +nimgrp repr repr_v2.html#repr-templates-all template 102 diff --git a/reservedmem.html b/reservedmem.html new file mode 100644 index 0000000000000..4c38908e2e251 --- /dev/null +++ b/reservedmem.html @@ -0,0 +1,506 @@ + + + + + + + +std/reservedmem + + + + + + + + + + + + + + + + +
+
+

std/reservedmem

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
Authors:Zahary Karadjov

This module provides utilities for reserving portions of the address space of a program without consuming physical memory. It can be used to implement a dynamically resizable buffer that is guaranteed to remain in the same memory location. The buffer will be able to grow up to the size of the initially reserved portion of the address space.

+

Unstable API.

+

+ +
+

Types

+
+
+
MemAccessFlags = int
+
+ + + Source   +Edit   + +
+
+
+
ReservedMem = object
+
+ + + Source   +Edit   + +
+
+
+
ReservedMemSeq[T] = object
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Lets

+
+
+
memExec = MemAccessFlags(4'i32)
+
+ + + Source   +Edit   + +
+
+
+
memExecRead = MemAccessFlags(5'i32)
+
+ + + Source   +Edit   + +
+
+
+
memExecReadWrite = MemAccessFlags(7'i32)
+
+ + + Source   +Edit   + +
+
+
+
memRead = MemAccessFlags(1'i32)
+
+ + + Source   +Edit   + +
+
+
+
memReadWrite = MemAccessFlags(3'i32)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `[]`[T](s: ReservedMemSeq[T]; pos: Natural): lent T
+
+ + + Source   +Edit   + +
+
+
+
func `[]`[T](s: ReservedMemSeq[T]; rpos: BackwardsIndex): lent T
+
+ + + Source   +Edit   + +
+
+
+
func `[]`[T](s: var ReservedMemSeq[T]; pos: Natural): var T
+
+ + + Source   +Edit   + +
+
+
+
func `[]`[T](s: var ReservedMemSeq[T]; rpos: BackwardsIndex): var T
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc add[T](s: var ReservedMemSeq[T]; val: T)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func commitedLen(m: ReservedMem): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func commitedLen[T](s: ReservedMemSeq[T]): int
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc init(SeqType: type ReservedMemSeq; maxLen: Natural; initLen: Natural = 0;
+          initCommitLen: Natural = 0; memStart = pointer(nil);
+          accessFlags = memReadWrite; maxCommittedAndUnusedPages = 3): SeqType:type
+
+ + + Source   +Edit   + +
+
+
+
proc init(T: type ReservedMem; maxLen: Natural; initLen: Natural = 0;
+          initCommitLen = initLen; memStart = pointer(nil);
+          accessFlags = memReadWrite; maxCommittedAndUnusedPages = 3): ReservedMem
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func len(m: ReservedMem): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func len[T](s: ReservedMemSeq[T]): int
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func maxLen(m: ReservedMem): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func maxLen[T](s: ReservedMemSeq[T]): int
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pop[T](s: var ReservedMemSeq[T]): T
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setLen(m: var ReservedMem; newLen: int) {....raises: [OSError], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc setLen[T](s: var ReservedMemSeq[T]; newLen: int)
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template distance(lhs, rhs: pointer): int
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template shift(p: pointer; distance: int): pointer
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/reservedmem.idx b/reservedmem.idx new file mode 100644 index 0000000000000..91d3ab7eb0790 --- /dev/null +++ b/reservedmem.idx @@ -0,0 +1,33 @@ +nimTitle reservedmem reservedmem.html module std/reservedmem 0 +nim distance reservedmem.html#distance.t,pointer,pointer template distance(lhs, rhs: pointer): int 26 +nim shift reservedmem.html#shift.t,pointer,int template shift(p: pointer; distance: int): pointer 29 +nim MemAccessFlags reservedmem.html#MemAccessFlags type MemAccessFlags 33 +nim ReservedMem reservedmem.html#ReservedMem object ReservedMem 35 +nim ReservedMemSeq reservedmem.html#ReservedMemSeq object ReservedMemSeq 43 +nim memExec reservedmem.html#memExec let memExec 77 +nim memExecRead reservedmem.html#memExecRead let memExecRead 78 +nim memExecReadWrite reservedmem.html#memExecReadWrite let memExecReadWrite 79 +nim memRead reservedmem.html#memRead let memRead 80 +nim memReadWrite reservedmem.html#memReadWrite let memReadWrite 81 +nim init reservedmem.html#init,typeReservedMem,Natural,Natural,int proc init(T: type ReservedMem; maxLen: Natural; initLen: Natural = 0;\n initCommitLen = initLen; memStart = pointer(nil);\n accessFlags = memReadWrite; maxCommittedAndUnusedPages = 3): ReservedMem 105 +nim len reservedmem.html#len,ReservedMem proc len(m: ReservedMem): int 138 +nim commitedLen reservedmem.html#commitedLen,ReservedMem proc commitedLen(m: ReservedMem): int 141 +nim maxLen reservedmem.html#maxLen,ReservedMem proc maxLen(m: ReservedMem): int 144 +nim setLen reservedmem.html#setLen,ReservedMem,int proc setLen(m: var ReservedMem; newLen: int) 147 +nim init reservedmem.html#init,typeReservedMemSeq,Natural,Natural,Natural,int proc init(SeqType: type ReservedMemSeq; maxLen: Natural; initLen: Natural = 0;\n initCommitLen: Natural = 0; memStart = pointer(nil);\n accessFlags = memReadWrite; maxCommittedAndUnusedPages = 3): SeqType:type 175 +nim `[]` reservedmem.html#[],ReservedMemSeq[T],Natural proc `[]`[T](s: ReservedMemSeq[T]; pos: Natural): lent T 190 +nim `[]` reservedmem.html#[],ReservedMemSeq[T],Natural_2 proc `[]`[T](s: var ReservedMemSeq[T]; pos: Natural): var T 195 +nim `[]` reservedmem.html#[],ReservedMemSeq[T],BackwardsIndex proc `[]`[T](s: ReservedMemSeq[T]; rpos: BackwardsIndex): lent T 200 +nim `[]` reservedmem.html#[],ReservedMemSeq[T],BackwardsIndex_2 proc `[]`[T](s: var ReservedMemSeq[T]; rpos: BackwardsIndex): var T 203 +nim len reservedmem.html#len,ReservedMemSeq[T] proc len[T](s: ReservedMemSeq[T]): int 206 +nim setLen reservedmem.html#setLen,ReservedMemSeq[T],int proc setLen[T](s: var ReservedMemSeq[T]; newLen: int) 209 +nim add reservedmem.html#add,ReservedMemSeq[T],T proc add[T](s: var ReservedMemSeq[T]; val: T) 213 +nim pop reservedmem.html#pop,ReservedMemSeq[T] proc pop[T](s: var ReservedMemSeq[T]): T 218 +nim commitedLen reservedmem.html#commitedLen,ReservedMemSeq[T] proc commitedLen[T](s: ReservedMemSeq[T]): int 224 +nim maxLen reservedmem.html#maxLen,ReservedMemSeq[T] proc maxLen[T](s: ReservedMemSeq[T]): int 227 +nimgrp commitedlen reservedmem.html#commitedLen-procs-all proc 141 +nimgrp init reservedmem.html#init-procs-all proc 105 +nimgrp maxlen reservedmem.html#maxLen-procs-all proc 144 +nimgrp [] reservedmem.html#[]-procs-all proc 190 +nimgrp setlen reservedmem.html#setLen-procs-all proc 147 +nimgrp len reservedmem.html#len-procs-all proc 138 diff --git a/rlocks.html b/rlocks.html new file mode 100644 index 0000000000000..af8b078707a1c --- /dev/null +++ b/rlocks.html @@ -0,0 +1,244 @@ + + + + + + + +std/rlocks + + + + + + + + + + + + + + + + +
+
+

std/rlocks

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module contains Nim's support for reentrant locks.

+
+

Imports

+
+ syslocks +
+
+
+

Types

+
+
+
RLock = SysLock
+
+ + Nim lock, re-entrant + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc acquire(lock: var RLock) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Acquires the given lock. + Source   +Edit   + +
+
+ +
+
+
+
proc deinitRLock(lock: RLock) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Frees the resources associated with the lock. + Source   +Edit   + +
+
+ +
+
+
+
proc initRLock(lock: var RLock) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Initializes the given lock. + Source   +Edit   + +
+
+ +
+
+
+
proc release(lock: var RLock) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Releases the given lock. + Source   +Edit   + +
+
+ +
+
+
+
proc tryAcquire(lock: var RLock): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Tries to acquire the given lock. Returns true on success. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template withRLock(lock: RLock; code: untyped)
+
+ + Acquires the given lock and then executes the code. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/rlocks.idx b/rlocks.idx new file mode 100644 index 0000000000000..8d3f9a7ece0a5 --- /dev/null +++ b/rlocks.idx @@ -0,0 +1,8 @@ +nimTitle rlocks rlocks.html module std/rlocks 0 +nim RLock rlocks.html#RLock type RLock 22 +nim initRLock rlocks.html#initRLock,SysLockObj proc initRLock(lock: var RLock) 24 +nim deinitRLock rlocks.html#deinitRLock,SysLockObj proc deinitRLock(lock: RLock) 34 +nim tryAcquire rlocks.html#tryAcquire,SysLockObj proc tryAcquire(lock: var RLock): bool 38 +nim acquire rlocks.html#acquire,SysLockObj proc acquire(lock: var RLock) 42 +nim release rlocks.html#release,SysLockObj proc release(lock: var RLock) 46 +nim withRLock rlocks.html#withRLock.t,SysLockObj,untyped template withRLock(lock: RLock; code: untyped) 50 diff --git a/ropes.html b/ropes.html new file mode 100644 index 0000000000000..153fc00428036 --- /dev/null +++ b/ropes.html @@ -0,0 +1,541 @@ + + + + + + + +std/ropes + + + + + + + + + + + + + + + + +
+
+

std/ropes

+
+ +
+ Source   +Edit   + +
+ +

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). They are essentially concatenation trees that are only flattened when converting to a native Nim string. The empty string is represented by nil. Ropes are immutable and subtrees can be shared without copying. Leaves can be cached for better memory efficiency at the cost of runtime efficiency.

+ +
+

Types

+
+
+
Rope {.acyclic.} = ref object
+
+ + A rope data type. The empty rope is represented by nil. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(r: Rope): string {....gcsafe, extern: "nroToString", raises: [], tags: [],
+                            forbids: [].}
+
+ + Converts a rope back to a string. + Source   +Edit   + +
+
+ +
+
+
+
proc `%`(frmt: string; args: openArray[Rope]): Rope {....gcsafe,
+    extern: "nroFormat", raises: [ValueError], tags: [], forbids: [].}
+
+ + % substitution operator for ropes. Does not support the $identifier nor ${identifier} notations. +

Example:

+
let r1 = "$1 $2 $3" % [rope("Nim"), rope("is"), rope("a great language")]
+doAssert $r1 == "Nim is a great language"
+
+let r2 = "$# $# $#" % [rope("Nim"), rope("is"), rope("a great language")]
+doAssert $r2 == "Nim is a great language"
+
+let r3 = "${1} ${2} ${3}" % [rope("Nim"), rope("is"), rope("a great language")]
+doAssert $r3 == "Nim is a great language"
+ Source   +Edit   + +
+
+ +
+
+
+
proc `&`(a, b: Rope): Rope {....gcsafe, extern: "nroConcRopeRope", raises: [],
+                             tags: [], forbids: [].}
+
+ + The concatenation operator for ropes. +

Example:

+
let r = rope("Hello, ") & rope("Nim!")
+doAssert $r == "Hello, Nim!"
+ Source   +Edit   + +
+
+
+
proc `&`(a: openArray[Rope]): Rope {....gcsafe, extern: "nroConcOpenArray",
+                                     raises: [], tags: [], forbids: [].}
+
+ + The concatenation operator for an openArray of ropes. +

Example:

+
let r = &[rope("Hello, "), rope("Nim"), rope("!")]
+doAssert $r == "Hello, Nim!"
+ Source   +Edit   + +
+
+
+
proc `&`(a: Rope; b: string): Rope {....gcsafe, extern: "nroConcRopeStr",
+                                     raises: [], tags: [], forbids: [].}
+
+ + The concatenation operator for ropes. +

Example:

+
let r = rope("Hello, ") & "Nim!"
+doAssert $r == "Hello, Nim!"
+ Source   +Edit   + +
+
+
+
proc `&`(a: string; b: Rope): Rope {....gcsafe, extern: "nroConcStrRope",
+                                     raises: [], tags: [], forbids: [].}
+
+ + The concatenation operator for ropes. +

Example:

+
let r = "Hello, " & rope("Nim!")
+doAssert $r == "Hello, Nim!"
+ Source   +Edit   + +
+
+ +
+
+
+
proc `[]`(r: Rope; i: int): char {....gcsafe, extern: "nroCharAt", raises: [],
+                                   tags: [], forbids: [].}
+
+ + Returns the character at position i in the rope r. This is quite expensive! Worst-case: O(n). If i >= r.len or i < 0, \0 is returned. +

Example:

+
let r = rope("Hello, Nim!")
+
+doAssert r[0] == 'H'
+doAssert r[7] == 'N'
+doAssert r[22] == '\0'
+ Source   +Edit   + +
+
+ +
+
+
+
proc add(a: var Rope; b: Rope) {....gcsafe, extern: "nro$1Rope", raises: [],
+                                 tags: [], forbids: [].}
+
+ + Adds b to the rope a. +

Example:

+
var r = rope("Hello, ")
+r.add(rope("Nim!"))
+doAssert $r == "Hello, Nim!"
+ Source   +Edit   + +
+
+
+
proc add(a: var Rope; b: string) {....gcsafe, extern: "nro$1Str", raises: [],
+                                   tags: [], forbids: [].}
+
+ + Adds b to the rope a. +

Example:

+
var r = rope("Hello, ")
+r.add("Nim!")
+doAssert $r == "Hello, Nim!"
+ Source   +Edit   + +
+
+ +
+
+
+
proc addf(c: var Rope; frmt: string; args: openArray[Rope]) {....gcsafe,
+    extern: "nro$1", raises: [ValueError], tags: [], forbids: [].}
+
+ + Shortcut for add(c, frmt % args). +

Example:

+
var r = rope("Dash: ")
+r.addf "$1 $2 $3", [rope("Nim"), rope("is"), rope("a great language")]
+doAssert $r == "Dash: Nim is a great language"
+ Source   +Edit   + +
+
+ +
+
+
+
proc disableCache() {....gcsafe, extern: "nro$1", raises: [], tags: [], forbids: [].}
+
+ + The cache is discarded and disabled. The GC will reuse its used memory. + Source   +Edit   + +
+
+ +
+
+
+
proc enableCache() {....gcsafe, extern: "nro$1", raises: [], tags: [], forbids: [].}
+
+ + Enables the caching of leaves. This reduces the memory footprint at the cost of runtime efficiency. + Source   +Edit   + +
+
+ +
+
+
+
proc equalsFile(r: Rope; f: File): bool {....gcsafe, extern: "nro$1File",
+    raises: [IOError], tags: [ReadIOEffect], forbids: [].}
+
+ + Returns true if the contents of the file f equal r. + Source   +Edit   + +
+
+
+
proc equalsFile(r: Rope; filename: string): bool {....gcsafe, extern: "nro$1Str",
+    raises: [IOError], tags: [ReadIOEffect], forbids: [].}
+
+ + Returns true if the contents of the file f equal r. If f does not exist, false is returned. + Source   +Edit   + +
+
+ +
+
+
+
proc len(a: Rope): int {....gcsafe, extern: "nro$1", raises: [], tags: [],
+                         forbids: [].}
+
+ + The rope's length. + Source   +Edit   + +
+
+ +
+
+
+
proc rope(f: BiggestFloat): Rope {....gcsafe, extern: "nro$1BiggestFloat",
+                                   raises: [], tags: [], forbids: [].}
+
+ + Converts a float to a rope. +

Example:

+
let r = rope(4.29)
+doAssert $r == "4.29"
+ Source   +Edit   + +
+
+
+
proc rope(i: BiggestInt): Rope {....gcsafe, extern: "nro$1BiggestInt", raises: [],
+                                 tags: [], forbids: [].}
+
+ + Converts an int to a rope. +

Example:

+
let r = rope(429)
+doAssert $r == "429"
+ Source   +Edit   + +
+
+
+
proc rope(s: string = ""): Rope {....gcsafe, extern: "nro$1Str", raises: [],
+                                  tags: [], forbids: [].}
+
+ + Converts a string to a rope. +

Example:

+
let r = rope("I'm a rope")
+doAssert $r == "I'm a rope"
+ Source   +Edit   + +
+
+ +
+
+
+
proc write(f: File; r: Rope) {....gcsafe, extern: "nro$1", raises: [IOError],
+                               tags: [WriteIOEffect], forbids: [].}
+
+ + Writes a rope to a file. + Source   +Edit   + +
+
+
+
proc write(s: Stream; r: Rope) {....gcsafe, extern: "nroWriteStream",
+                                 raises: [IOError, OSError],
+                                 tags: [WriteIOEffect], forbids: [].}
+
+ + Writes a rope to a stream. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator items(r: Rope): char {....raises: [], tags: [], forbids: [].}
+
+ + Iterates over any character in the rope r. + Source   +Edit   + +
+
+ +
+
+
+
iterator leaves(r: Rope): string {....raises: [], tags: [], forbids: [].}
+
+ + Iterates over any leaf string in the rope r. +

Example:

+
let r = rope("Hello") & rope(", Nim!")
+let s = ["Hello", ", Nim!"]
+var index = 0
+for leave in r.leaves:
+  doAssert leave == s[index]
+  inc(index)
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/ropes.idx b/ropes.idx new file mode 100644 index 0000000000000..7cf9b92928573 --- /dev/null +++ b/ropes.idx @@ -0,0 +1,30 @@ +nimTitle ropes ropes.html module std/ropes 0 +nim Rope ropes.html#Rope type Rope 35 +nim len ropes.html#len,Rope proc len(a: Rope): int 49 +nim rope ropes.html#rope,string proc rope(s: string = ""): Rope 130 +nim rope ropes.html#rope,BiggestInt proc rope(i: BiggestInt): Rope 149 +nim rope ropes.html#rope,BiggestFloat proc rope(f: BiggestFloat): Rope 157 +nim enableCache ropes.html#enableCache proc enableCache() 165 +nim disableCache ropes.html#disableCache proc disableCache() 170 +nim `&` ropes.html#&,Rope,Rope proc `&`(a, b: Rope): Rope 175 +nim `&` ropes.html#&,Rope,string proc `&`(a: Rope; b: string): Rope 191 +nim `&` ropes.html#&,string,Rope proc `&`(a: string; b: Rope): Rope 199 +nim `&` ropes.html#&,openArray[Rope] proc `&`(a: openArray[Rope]): Rope 207 +nim add ropes.html#add,Rope,Rope proc add(a: var Rope; b: Rope) 215 +nim add ropes.html#add,Rope,string proc add(a: var Rope; b: string) 224 +nim `[]` ropes.html#[],Rope,int proc `[]`(r: Rope; i: int): char 233 +nim leaves ropes.html#leaves.i,Rope iterator leaves(r: Rope): string 257 +nim items ropes.html#items.i,Rope iterator items(r: Rope): char 278 +nim write ropes.html#write,File,Rope proc write(f: File; r: Rope) 283 +nim write ropes.html#write,Stream,Rope proc write(s: Stream; r: Rope) 287 +nim `$` ropes.html#$,Rope proc `$`(r: Rope): string 291 +nim `%` ropes.html#%,string,openArray[Rope] proc `%`(frmt: string; args: openArray[Rope]): Rope 296 +nim addf ropes.html#addf,Rope,string,openArray[Rope] proc addf(c: var Rope; frmt: string; args: openArray[Rope]) 349 +nim equalsFile ropes.html#equalsFile,Rope,File proc equalsFile(r: Rope; f: File): bool 362 +nim equalsFile ropes.html#equalsFile,Rope,string proc equalsFile(r: Rope; filename: string): bool 389 +idx rope ropes.html#rope_1 Module ropes 0 +nimgrp rope ropes.html#rope-procs-all proc 130 +nimgrp write ropes.html#write-procs-all proc 283 +nimgrp & ropes.html#&-procs-all proc 175 +nimgrp add ropes.html#add-procs-all proc 215 +nimgrp equalsfile ropes.html#equalsFile-procs-all proc 362 diff --git a/rst.html b/rst.html new file mode 100644 index 0000000000000..e913718cb0c65 --- /dev/null +++ b/rst.html @@ -0,0 +1,740 @@ + + + + + + + +packages/docutils/rst + + + + + + + + + + + + + + + + +
+
+

packages/docutils/rst

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a reStructuredText (RST) and Markdown parser. User's manual on supported markup syntax and command line usage can be found in Nim-flavored Markdown and reStructuredText.

+

Choice between Markdown and RST as well as optional additional features are turned on by passing options: RstParseOptions to proc rstParse.

+

+ +
+

Types

+
+
+
EParseError = object of ValueError
+
+ + + Source   +Edit   + +
+
+
+
FindFileHandler = proc (filename: string): string {.closure, ...gcsafe.}
+
+ + + Source   +Edit   + +
+
+
+
FindRefFileHandler = proc (targetRelPath: string): tuple[targetPath: string,
+    linkRelPath: string] {.closure, ...gcsafe.}
+
+ + returns where .html or .idx file should be found by its relative path; linkRelPath is a prefix to be added before a link anchor from such file + Source   +Edit   + +
+
+
+
MsgClass = enum
+  mcHint = "Hint", mcWarning = "Warning", mcError = "Error"
+
+ + + Source   +Edit   + +
+
+
+
MsgHandler = proc (filename: string; line, col: int; msgKind: MsgKind;
+                   arg: string) {.closure, ...gcsafe.}
+
+ + what to do in case of an error + Source   +Edit   + +
+
+
+
MsgKind = enum
+  meCannotOpenFile = "cannot open \'$1\'", meExpected = "\'$1\' expected",
+  meMissingClosing = "$1",
+  meGridTableNotImplemented = "grid table is not implemented",
+  meMarkdownIllformedTable = "illformed delimiter row of a Markdown table",
+  meIllformedTable = "Illformed table: $1",
+  meNewSectionExpected = "new section expected $1",
+  meGeneralParseError = "general parse error",
+  meInvalidDirective = "invalid directive: \'$1\'",
+  meInvalidField = "invalid field: $1",
+  meFootnoteMismatch = "mismatch in number of footnotes and their refs: $1",
+  mwRedefinitionOfLabel = "redefinition of label \'$1\'",
+  mwUnknownSubstitution = "unknown substitution \'$1\'",
+  mwAmbiguousLink = "ambiguous doc link $1",
+  mwBrokenLink = "broken link \'$1\'",
+  mwUnsupportedLanguage = "language \'$1\' not supported",
+  mwUnsupportedField = "field \'$1\' not supported",
+  mwRstStyle = "RST style: $1",
+  mwUnusedImportdoc = "importdoc for \'$1\' is not used",
+  meSandboxedDirective = "disabled directive: \'$1\'"
+
+ + the possible messages + Source   +Edit   + +
+
+
+
PRstSharedState = ref RstSharedState
+
+ + + Source   +Edit   + +
+
+
+
RstFileTable = object
+  filenameToIdx*: Table[string, FileIndex]
+  idxToFilename*: seq[string]
+
+ + + Source   +Edit   + +
+
+
+
RstParseOption = enum
+  roSupportSmilies,         ## make the RST parser support smilies like ``:)``
+  roSupportRawDirective,    ## support the ``raw`` directive (don't support
+                             ## it for sandboxing)
+  roSupportMarkdown,        ## support additional features of Markdown
+  roPreferMarkdown,         ## parse as Markdown (keeping RST as "extension"
+                             ## to Markdown) -- implies `roSupportMarkdown`
+  roNimFile,                ## set for Nim files where default interpreted
+                             ## text role should be :nim:
+  roSandboxDisabled          ## this option enables certain options
+                             ## (e.g. raw, include, importdoc)
+                             ## which are disabled by default as they can
+                             ## enable users to read arbitrary data and
+                             ## perform XSS if the parser is used in a web
+                             ## app.
+
+ + options for the RST parser + Source   +Edit   + +
+
+
+
RstParseOptions = set[RstParseOption]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
ColRstInit = 0
+
+ + Initial column number for standalone RST text (Nim global reporting adds ColOffset=1) + Source   +Edit   + +
+
+
+
ColRstOffset = 1
+
+ + 1: a replica of ColOffset for internal use + Source   +Edit   + +
+
+
+
LineRstInit = 1
+
+ + Initial line number for standalone RST text + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc addAnchorNim(s: var PRstSharedState; external: bool; refn: string;
+                  tooltip: string; langSym: LangSymbol; priority: int;
+                  info: TLineInfo; module: FileIndex) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Adds an anchor refn, which follows the rule arNim (i.e. a symbol in *.nim file) + Source   +Edit   + +
+
+ +
+
+
+
proc addFilename(s: PRstSharedState; file1: string): FileIndex {....raises: [],
+    tags: [], forbids: [].}
+
+ + Returns index of filename, adding it if it has not been used before + Source   +Edit   + +
+
+ +
+
+
+
proc addNodes(n: PRstNode): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc completePass2(s: PRstSharedState) {....raises: [ValueError, Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc defaultFindFile(filename: string): string {....raises: [],
+    tags: [ReadDirEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc defaultFindRefFile(filename: string): (string, string) {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc defaultMsgHandler(filename: string; line, col: int; msgkind: MsgKind;
+                       arg: string) {....raises: [ValueError, EParseError, IOError],
+                                      tags: [WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getArgument(n: PRstNode): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getFieldValue(n: PRstNode): string {....raises: [], tags: [], forbids: [].}
+
+ +

Returns the value of a specific rnField node.

+

This proc will assert if the node is not of the expected type. The empty string will be returned as a minimum. Any value in the rst will be stripped form leading/trailing whitespace.

+ + Source   +Edit   + +
+
+
+
proc getFieldValue(n: PRstNode; fieldname: string): string {....gcsafe, raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newRstSharedState(options: RstParseOptions; filename: string;
+                       findFile: FindFileHandler;
+                       findRefFile: FindRefFileHandler; msgHandler: MsgHandler;
+                       hasToc: bool): PRstSharedState {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc preparePass2(s: var PRstSharedState; mainNode: PRstNode; importdoc = true) {.
+    ...raises: [Exception, ValueError, KeyError], tags: [RootEffect, ReadIOEffect],
+    forbids: [].}
+
+ + Records titles in node mainNode and orders footnotes. + Source   +Edit   + +
+
+ +
+
+
+
proc resolveSubs(s: PRstSharedState; n: PRstNode): PRstNode {.
+    ...raises: [ValueError, Exception, KeyError],
+    tags: [ReadEnvEffect, RootEffect], forbids: [].}
+
+ + Makes pass 2 of RST parsing. Resolves substitutions and anchor aliases, groups footnotes. Takes input node n and returns the same node with recursive substitutions in n.sons to result. + Source   +Edit   + +
+
+ +
+
+
+
proc rstMessage(filenames: RstFileTable; f: MsgHandler; info: TLineInfo;
+                msgKind: MsgKind; arg: string) {.
+    ...raises: [ValueError, Exception], tags: [RootEffect], forbids: [].}
+
+ + Print warnings using info, i.e. in 2nd-pass warnings for footnotes/substitutions/references or from rstgen.nim. + Source   +Edit   + +
+
+ +
+
+
+
proc rstnodeToRefname(n: PRstNode): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rstParse(text, filename: string; line, column: int;
+              options: RstParseOptions; findFile: FindFileHandler = nil;
+              findRefFile: FindRefFileHandler = nil;
+              msgHandler: MsgHandler = nil): tuple[node: PRstNode,
+    filenames: RstFileTable, hasToc: bool] {.
+    ...raises: [Exception, ValueError, KeyError],
+    tags: [RootEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + Parses the whole text. The result is ready for rstgen.renderRstToOut, note that 2nd tuple element should be fed to initRstGenerator argument filenames (it is being filled here at least with filename and possibly with other files from RST .. include:: statement). + Source   +Edit   + +
+
+ +
+
+
+
proc rstParsePass1(fragment: string; line, column: int;
+                   sharedState: PRstSharedState): PRstNode {.
+    ...raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}
+
+ + Parses an RST fragment. The result should be further processed by preparePass2 and resolveSubs (which is pass 2). + Source   +Edit   + +
+
+ +
+
+
+
proc safeProtocol(linkStr: var string): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setCurrFilename(s: PRstSharedState; file1: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc whichMsgClass(k: MsgKind): MsgClass {....raises: [], tags: [], forbids: [].}
+
+ + returns which message class k belongs to. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/rst.idx b/rst.idx new file mode 100644 index 0000000000000..d9ff7e39ff285 --- /dev/null +++ b/rst.idx @@ -0,0 +1,66 @@ +nimTitle rst rst.html module packages/docutils/rst 0 +nim roSupportSmilies rst.html#roSupportSmilies RstParseOption.roSupportSmilies 35 +nim roSupportRawDirective rst.html#roSupportRawDirective RstParseOption.roSupportRawDirective 35 +nim roSupportMarkdown rst.html#roSupportMarkdown RstParseOption.roSupportMarkdown 35 +nim roPreferMarkdown rst.html#roPreferMarkdown RstParseOption.roPreferMarkdown 35 +nim roNimFile rst.html#roNimFile RstParseOption.roNimFile 35 +nim roSandboxDisabled rst.html#roSandboxDisabled RstParseOption.roSandboxDisabled 35 +nim RstParseOption rst.html#RstParseOption enum RstParseOption 35 +nim RstParseOptions rst.html#RstParseOptions type RstParseOptions 51 +nim mcHint rst.html#mcHint MsgClass.mcHint 53 +nim mcWarning rst.html#mcWarning MsgClass.mcWarning 53 +nim mcError rst.html#mcError MsgClass.mcError 53 +nim MsgClass rst.html#MsgClass enum MsgClass 53 +nim meCannotOpenFile rst.html#meCannotOpenFile MsgKind.meCannotOpenFile 59 +nim meExpected rst.html#meExpected MsgKind.meExpected 59 +nim meMissingClosing rst.html#meMissingClosing MsgKind.meMissingClosing 59 +nim meGridTableNotImplemented rst.html#meGridTableNotImplemented MsgKind.meGridTableNotImplemented 59 +nim meMarkdownIllformedTable rst.html#meMarkdownIllformedTable MsgKind.meMarkdownIllformedTable 59 +nim meIllformedTable rst.html#meIllformedTable MsgKind.meIllformedTable 59 +nim meNewSectionExpected rst.html#meNewSectionExpected MsgKind.meNewSectionExpected 59 +nim meGeneralParseError rst.html#meGeneralParseError MsgKind.meGeneralParseError 59 +nim meInvalidDirective rst.html#meInvalidDirective MsgKind.meInvalidDirective 59 +nim meInvalidField rst.html#meInvalidField MsgKind.meInvalidField 59 +nim meFootnoteMismatch rst.html#meFootnoteMismatch MsgKind.meFootnoteMismatch 59 +nim mwRedefinitionOfLabel rst.html#mwRedefinitionOfLabel MsgKind.mwRedefinitionOfLabel 59 +nim mwUnknownSubstitution rst.html#mwUnknownSubstitution MsgKind.mwUnknownSubstitution 59 +nim mwAmbiguousLink rst.html#mwAmbiguousLink MsgKind.mwAmbiguousLink 59 +nim mwBrokenLink rst.html#mwBrokenLink MsgKind.mwBrokenLink 59 +nim mwUnsupportedLanguage rst.html#mwUnsupportedLanguage MsgKind.mwUnsupportedLanguage 59 +nim mwUnsupportedField rst.html#mwUnsupportedField MsgKind.mwUnsupportedField 59 +nim mwRstStyle rst.html#mwRstStyle MsgKind.mwRstStyle 59 +nim mwUnusedImportdoc rst.html#mwUnusedImportdoc MsgKind.mwUnusedImportdoc 59 +nim meSandboxedDirective rst.html#meSandboxedDirective MsgKind.meSandboxedDirective 59 +nim MsgKind rst.html#MsgKind enum MsgKind 59 +nim MsgHandler rst.html#MsgHandler type MsgHandler 81 +nim FindFileHandler rst.html#FindFileHandler type FindFileHandler 83 +nim FindRefFileHandler rst.html#FindRefFileHandler type FindRefFileHandler 84 +nim rstnodeToRefname rst.html#rstnodeToRefname,PRstNode proc rstnodeToRefname(n: PRstNode): string 90 +nim addNodes rst.html#addNodes,PRstNode proc addNodes(n: PRstNode): string 91 +nim getFieldValue rst.html#getFieldValue,PRstNode,string proc getFieldValue(n: PRstNode; fieldname: string): string 92 +nim getArgument rst.html#getArgument,PRstNode proc getArgument(n: PRstNode): string 93 +nim RstFileTable rst.html#RstFileTable object RstFileTable 386 +nim PRstSharedState rst.html#PRstSharedState type PRstSharedState 428 +nim EParseError rst.html#EParseError object EParseError 446 +nim LineRstInit rst.html#LineRstInit const LineRstInit 450 +nim ColRstInit rst.html#ColRstInit const ColRstInit 451 +nim ColRstOffset rst.html#ColRstOffset const ColRstOffset 453 +nim whichMsgClass rst.html#whichMsgClass,MsgKind proc whichMsgClass(k: MsgKind): MsgClass 459 +nim defaultMsgHandler rst.html#defaultMsgHandler,string,int,int,MsgKind,string proc defaultMsgHandler(filename: string; line, col: int; msgkind: MsgKind;\n arg: string) 467 +nim defaultFindFile rst.html#defaultFindFile,string proc defaultFindFile(filename: string): string 477 +nim defaultFindRefFile rst.html#defaultFindRefFile,string proc defaultFindRefFile(filename: string): (string, string) 481 +nim addFilename rst.html#addFilename,PRstSharedState,string proc addFilename(s: PRstSharedState; file1: string): FileIndex 507 +nim setCurrFilename rst.html#setCurrFilename,PRstSharedState,string proc setCurrFilename(s: PRstSharedState; file1: string) 515 +nim newRstSharedState rst.html#newRstSharedState,RstParseOptions,string,FindFileHandler,FindRefFileHandler,MsgHandler,bool proc newRstSharedState(options: RstParseOptions; filename: string;\n findFile: FindFileHandler; findRefFile: FindRefFileHandler;\n msgHandler: MsgHandler; hasToc: bool): PRstSharedState 533 +nim rstMessage rst.html#rstMessage,RstFileTable,MsgHandler,TLineInfo,MsgKind,string proc rstMessage(filenames: RstFileTable; f: MsgHandler; info: TLineInfo;\n msgKind: MsgKind; arg: string) 575 +nim addAnchorNim rst.html#addAnchorNim,PRstSharedState,bool,string,string,LangSymbol,int,TLineInfo,FileIndex proc addAnchorNim(s: var PRstSharedState; external: bool; refn: string;\n tooltip: string; langSym: LangSymbol; priority: int;\n info: TLineInfo; module: FileIndex) 863 +nim safeProtocol rst.html#safeProtocol,string proc safeProtocol(linkStr: var string): string 1254 +nim getFieldValue rst.html#getFieldValue,PRstNode proc getFieldValue(n: PRstNode): string 2076 +nim rstParsePass1 rst.html#rstParsePass1,string,int,int,PRstSharedState proc rstParsePass1(fragment: string; line, column: int; sharedState: PRstSharedState): PRstNode 3559 +nim preparePass2 rst.html#preparePass2,PRstSharedState,PRstNode proc preparePass2(s: var PRstSharedState; mainNode: PRstNode; importdoc = true) 3648 +nim resolveSubs rst.html#resolveSubs,PRstSharedState,PRstNode proc resolveSubs(s: PRstSharedState; n: PRstNode): PRstNode 3767 +nim completePass2 rst.html#completePass2,PRstSharedState proc completePass2(s: PRstSharedState) 3862 +nim rstParse rst.html#rstParse,string,string,int,int,RstParseOptions,FindFileHandler,FindRefFileHandler,MsgHandler proc rstParse(text, filename: string; line, column: int; options: RstParseOptions;\n findFile: FindFileHandler = nil; findRefFile: FindRefFileHandler = nil;\n msgHandler: MsgHandler = nil): tuple[node: PRstNode,\n filenames: RstFileTable, hasToc: bool] 3868 +idx reStructuredText rst.html#restructuredtext_1 Module rst 0 +idx Markdown rst.html#markdown_1 Module rst 0 +nimgrp getfieldvalue rst.html#getFieldValue-procs-all proc 92 diff --git a/rstast.html b/rstast.html new file mode 100644 index 0000000000000..e18cf2dd6987f --- /dev/null +++ b/rstast.html @@ -0,0 +1,524 @@ + + + + + + + +packages/docutils/rstast + + + + + + + + + + + + + + + + +
+
+

packages/docutils/rstast

+
+ +
+ Source   +Edit   + +
+ +

This module implements an AST for the reStructuredText parser.

+ +
+

Types

+
+
+
FileIndex = distinct int32
+
+ + + Source   +Edit   + +
+
+
+
PRstNode = ref RstNode
+
+ + an RST node + Source   +Edit   + +
+
+
+
RstNode {.acyclic, final.} = object
+  case kind*: RstNodeKind    ## the node's kind
+  of rnLeaf, rnSmiley:
+    text*: string            ## string that is expected to be displayed
+  of rnEnumList:
+    labelFmt*: string        ## label format like "(1)"
+  of rnLineBlockItem:
+    lineIndent*: string      ## a few spaces or newline at the line beginning
+  of rnAdmonition:
+    adType*: string          ## admonition type: "note", "caution", etc. This
+                             ## text will set the style and also be displayed
+  of rnOverline, rnHeadline, rnMarkdownHeadline:
+    level*: int              ## level of headings starting from 1 (main
+                             ## chapter) to larger ones (minor sub-sections)
+                             ## level=0 means it's document title or subtitle
+  of rnFootnote, rnCitation, rnOptionListItem:
+    order*: int              ## footnote order (for auto-symbol footnotes and
+                             ## auto-numbered ones without a label)
+  of rnMarkdownBlockQuoteItem:
+    quotationDepth*: int     ## number of characters in line prefix
+  of rnRstRef, rnPandocRef, rnSubstitutionReferences, rnInterpretedText,
+     rnField, rnInlineCode, rnCodeBlock, rnFootnoteRef:
+    info*: TLineInfo         ## To have line/column info for warnings at
+                             ## nodes that are post-processed after parsing
+  of rnNimdocRef:
+    tooltip*: string
+  of rnTable, rnGridTable, rnMarkdownTable:
+    colCount*: int           ## Number of (not-united) cells in the table
+  of rnTableRow:
+    endsHeader*: bool        ## Is last row in the header of table?
+  of rnTableHeaderCell, rnTableDataCell:
+    span*: int               ## Number of table columns that the cell occupies
+  else:
+    nil
+  anchor*: string            ## anchor, internal link target
+                             ## (aka HTML id tag, aka Latex label/hypertarget)
+  sons*: RstNodeSeq          ## the node's sons
+
+ + AST node (result of RST parsing) + Source   +Edit   + +
+
+
+
RstNodeKind = enum
+  rnInner, rnHeadline, rnOverline, rnMarkdownHeadline, rnTransition,
+  rnParagraph, rnBulletList, rnBulletItem, rnEnumList, rnEnumItem, rnDefList,
+  rnMdDefList, rnDefItem, rnDefName, rnDefBody, rnFieldList, rnField,
+  rnFieldName, rnFieldBody, rnOptionList, rnOptionListItem, rnOptionGroup,
+  rnOption, rnOptionString, rnOptionArgument, rnDescription, rnLiteralBlock,
+  rnMarkdownBlockQuote, rnMarkdownBlockQuoteItem, rnLineBlock, rnLineBlockItem,
+  rnBlockQuote, rnTable, rnGridTable, rnMarkdownTable, rnTableRow,
+  rnTableHeaderCell, rnTableDataCell, rnFootnote, rnCitation, rnFootnoteGroup,
+  rnStandaloneHyperlink, rnHyperlink, rnRstRef, rnPandocRef, rnInternalRef,
+  rnFootnoteRef, rnNimdocRef, rnDirective, rnDirArg, rnRaw, rnTitle, rnContents,
+  rnImage, rnFigure, rnCodeBlock, rnAdmonition, rnRawHtml, rnRawLatex,
+  rnContainer, rnIndex, rnSubstitutionDef, rnInlineCode, rnCodeFragment,
+  rnUnknownRole, rnSub, rnSup, rnIdx, rnEmphasis, rnStrongEmphasis,
+  rnTripleEmphasis, rnInterpretedText, rnInlineLiteral, rnInlineTarget,
+  rnSubstitutionReferences, rnSmiley, rnDefaultRole, rnLeaf
+
+ + the possible node kinds of an PRstNode + Source   +Edit   + +
+
+
+
RstNodeSeq = seq[PRstNode]
+
+ + + Source   +Edit   + +
+
+
+
TLineInfo = object
+  line*: uint16
+  col*: int16
+  fileIndex*: FileIndex
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `==`(a, b: FileIndex): bool {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc add(father, son: PRstNode) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc add(father: PRstNode; s: string) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc addIfNotNil(father, son: PRstNode) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lastSon(n: PRstNode): PRstNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc len(n: PRstNode): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newRstLeaf(s: string): PRstNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newRstNode(kind: RstNodeKind; info: TLineInfo; sons: seq[PRstNode] = @[]): PRstNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newRstNode(kind: RstNodeKind; s: string): PRstNode {....deprecated,
+    raises: [], tags: [], forbids: [].}
+
+
+ Deprecated +
+ + + Source   +Edit   + +
+
+
+
proc newRstNode(kind: RstNodeKind; sons: seq[PRstNode] = @[]; anchor = ""): PRstNode {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc renderRstToJson(node: PRstNode): string {....raises: [], tags: [], forbids: [].}
+
+ + Writes the given RST node as JSON that is in the form
{
+  "kind":string node.kind,
+  "text":optional string node.text,
+  "level":optional int node.level,
+  "sons":optional node array
+}
+ + Source   +Edit   + +
+
+ +
+
+
+
proc renderRstToRst(n: PRstNode; result: var string) {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + renders n into its string representation and appends to result. + Source   +Edit   + +
+
+ +
+
+
+
proc renderRstToText(node: PRstNode): string {....raises: [], tags: [], forbids: [].}
+
+ + minimal text representation of markup node + Source   +Edit   + +
+
+ +
+
+
+
proc treeRepr(node: PRstNode; indent = 0): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + Writes the parsed RST node into an AST tree with compact string representation in the format (one line per every sub-node): indent - kind - [text|level|order|adType] - anchor (if non-zero) (suitable for debugging of RST parsing). + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/rstast.idx b/rstast.idx new file mode 100644 index 0000000000000..f56a0ea193d2e --- /dev/null +++ b/rstast.idx @@ -0,0 +1,102 @@ +nimTitle rstast rstast.html module packages/docutils/rstast 0 +nim rnInner rstast.html#rnInner RstNodeKind.rnInner 19 +nim rnHeadline rstast.html#rnHeadline RstNodeKind.rnHeadline 19 +nim rnOverline rstast.html#rnOverline RstNodeKind.rnOverline 19 +nim rnMarkdownHeadline rstast.html#rnMarkdownHeadline RstNodeKind.rnMarkdownHeadline 19 +nim rnTransition rstast.html#rnTransition RstNodeKind.rnTransition 19 +nim rnParagraph rstast.html#rnParagraph RstNodeKind.rnParagraph 19 +nim rnBulletList rstast.html#rnBulletList RstNodeKind.rnBulletList 19 +nim rnBulletItem rstast.html#rnBulletItem RstNodeKind.rnBulletItem 19 +nim rnEnumList rstast.html#rnEnumList RstNodeKind.rnEnumList 19 +nim rnEnumItem rstast.html#rnEnumItem RstNodeKind.rnEnumItem 19 +nim rnDefList rstast.html#rnDefList RstNodeKind.rnDefList 19 +nim rnMdDefList rstast.html#rnMdDefList RstNodeKind.rnMdDefList 19 +nim rnDefItem rstast.html#rnDefItem RstNodeKind.rnDefItem 19 +nim rnDefName rstast.html#rnDefName RstNodeKind.rnDefName 19 +nim rnDefBody rstast.html#rnDefBody RstNodeKind.rnDefBody 19 +nim rnFieldList rstast.html#rnFieldList RstNodeKind.rnFieldList 19 +nim rnField rstast.html#rnField RstNodeKind.rnField 19 +nim rnFieldName rstast.html#rnFieldName RstNodeKind.rnFieldName 19 +nim rnFieldBody rstast.html#rnFieldBody RstNodeKind.rnFieldBody 19 +nim rnOptionList rstast.html#rnOptionList RstNodeKind.rnOptionList 19 +nim rnOptionListItem rstast.html#rnOptionListItem RstNodeKind.rnOptionListItem 19 +nim rnOptionGroup rstast.html#rnOptionGroup RstNodeKind.rnOptionGroup 19 +nim rnOption rstast.html#rnOption RstNodeKind.rnOption 19 +nim rnOptionString rstast.html#rnOptionString RstNodeKind.rnOptionString 19 +nim rnOptionArgument rstast.html#rnOptionArgument RstNodeKind.rnOptionArgument 19 +nim rnDescription rstast.html#rnDescription RstNodeKind.rnDescription 19 +nim rnLiteralBlock rstast.html#rnLiteralBlock RstNodeKind.rnLiteralBlock 19 +nim rnMarkdownBlockQuote rstast.html#rnMarkdownBlockQuote RstNodeKind.rnMarkdownBlockQuote 19 +nim rnMarkdownBlockQuoteItem rstast.html#rnMarkdownBlockQuoteItem RstNodeKind.rnMarkdownBlockQuoteItem 19 +nim rnLineBlock rstast.html#rnLineBlock RstNodeKind.rnLineBlock 19 +nim rnLineBlockItem rstast.html#rnLineBlockItem RstNodeKind.rnLineBlockItem 19 +nim rnBlockQuote rstast.html#rnBlockQuote RstNodeKind.rnBlockQuote 19 +nim rnTable rstast.html#rnTable RstNodeKind.rnTable 19 +nim rnGridTable rstast.html#rnGridTable RstNodeKind.rnGridTable 19 +nim rnMarkdownTable rstast.html#rnMarkdownTable RstNodeKind.rnMarkdownTable 19 +nim rnTableRow rstast.html#rnTableRow RstNodeKind.rnTableRow 19 +nim rnTableHeaderCell rstast.html#rnTableHeaderCell RstNodeKind.rnTableHeaderCell 19 +nim rnTableDataCell rstast.html#rnTableDataCell RstNodeKind.rnTableDataCell 19 +nim rnFootnote rstast.html#rnFootnote RstNodeKind.rnFootnote 19 +nim rnCitation rstast.html#rnCitation RstNodeKind.rnCitation 19 +nim rnFootnoteGroup rstast.html#rnFootnoteGroup RstNodeKind.rnFootnoteGroup 19 +nim rnStandaloneHyperlink rstast.html#rnStandaloneHyperlink RstNodeKind.rnStandaloneHyperlink 19 +nim rnHyperlink rstast.html#rnHyperlink RstNodeKind.rnHyperlink 19 +nim rnRstRef rstast.html#rnRstRef RstNodeKind.rnRstRef 19 +nim rnPandocRef rstast.html#rnPandocRef RstNodeKind.rnPandocRef 19 +nim rnInternalRef rstast.html#rnInternalRef RstNodeKind.rnInternalRef 19 +nim rnFootnoteRef rstast.html#rnFootnoteRef RstNodeKind.rnFootnoteRef 19 +nim rnNimdocRef rstast.html#rnNimdocRef RstNodeKind.rnNimdocRef 19 +nim rnDirective rstast.html#rnDirective RstNodeKind.rnDirective 19 +nim rnDirArg rstast.html#rnDirArg RstNodeKind.rnDirArg 19 +nim rnRaw rstast.html#rnRaw RstNodeKind.rnRaw 19 +nim rnTitle rstast.html#rnTitle RstNodeKind.rnTitle 19 +nim rnContents rstast.html#rnContents RstNodeKind.rnContents 19 +nim rnImage rstast.html#rnImage RstNodeKind.rnImage 19 +nim rnFigure rstast.html#rnFigure RstNodeKind.rnFigure 19 +nim rnCodeBlock rstast.html#rnCodeBlock RstNodeKind.rnCodeBlock 19 +nim rnAdmonition rstast.html#rnAdmonition RstNodeKind.rnAdmonition 19 +nim rnRawHtml rstast.html#rnRawHtml RstNodeKind.rnRawHtml 19 +nim rnRawLatex rstast.html#rnRawLatex RstNodeKind.rnRawLatex 19 +nim rnContainer rstast.html#rnContainer RstNodeKind.rnContainer 19 +nim rnIndex rstast.html#rnIndex RstNodeKind.rnIndex 19 +nim rnSubstitutionDef rstast.html#rnSubstitutionDef RstNodeKind.rnSubstitutionDef 19 +nim rnInlineCode rstast.html#rnInlineCode RstNodeKind.rnInlineCode 19 +nim rnCodeFragment rstast.html#rnCodeFragment RstNodeKind.rnCodeFragment 19 +nim rnUnknownRole rstast.html#rnUnknownRole RstNodeKind.rnUnknownRole 19 +nim rnSub rstast.html#rnSub RstNodeKind.rnSub 19 +nim rnSup rstast.html#rnSup RstNodeKind.rnSup 19 +nim rnIdx rstast.html#rnIdx RstNodeKind.rnIdx 19 +nim rnEmphasis rstast.html#rnEmphasis RstNodeKind.rnEmphasis 19 +nim rnStrongEmphasis rstast.html#rnStrongEmphasis RstNodeKind.rnStrongEmphasis 19 +nim rnTripleEmphasis rstast.html#rnTripleEmphasis RstNodeKind.rnTripleEmphasis 19 +nim rnInterpretedText rstast.html#rnInterpretedText RstNodeKind.rnInterpretedText 19 +nim rnInlineLiteral rstast.html#rnInlineLiteral RstNodeKind.rnInlineLiteral 19 +nim rnInlineTarget rstast.html#rnInlineTarget RstNodeKind.rnInlineTarget 19 +nim rnSubstitutionReferences rstast.html#rnSubstitutionReferences RstNodeKind.rnSubstitutionReferences 19 +nim rnSmiley rstast.html#rnSmiley RstNodeKind.rnSmiley 19 +nim rnDefaultRole rstast.html#rnDefaultRole RstNodeKind.rnDefaultRole 19 +nim rnLeaf rstast.html#rnLeaf RstNodeKind.rnLeaf 19 +nim RstNodeKind rstast.html#RstNodeKind enum RstNodeKind 19 +nim FileIndex rstast.html#FileIndex type FileIndex 88 +nim TLineInfo rstast.html#TLineInfo object TLineInfo 89 +nim PRstNode rstast.html#PRstNode type PRstNode 94 +nim RstNodeSeq rstast.html#RstNodeSeq type RstNodeSeq 95 +nim RstNode rstast.html#RstNode object RstNode 96 +nim `==` rstast.html#==,FileIndex,FileIndex proc `==`(a, b: FileIndex): bool 134 +nim len rstast.html#len,PRstNode proc len(n: PRstNode): int 136 +nim newRstNode rstast.html#newRstNode,RstNodeKind,seq[PRstNode],string proc newRstNode(kind: RstNodeKind; sons: seq[PRstNode] = @[]; anchor = ""): PRstNode 139 +nim newRstNode rstast.html#newRstNode,RstNodeKind,TLineInfo,seq[PRstNode] proc newRstNode(kind: RstNodeKind; info: TLineInfo; sons: seq[PRstNode] = @[]): PRstNode 143 +nim newRstNode rstast.html#newRstNode,RstNodeKind,string proc newRstNode(kind: RstNodeKind; s: string): PRstNode 148 +nim newRstLeaf rstast.html#newRstLeaf,string proc newRstLeaf(s: string): PRstNode 153 +nim lastSon rstast.html#lastSon,PRstNode proc lastSon(n: PRstNode): PRstNode 157 +nim add rstast.html#add,PRstNode,PRstNode proc add(father, son: PRstNode) 160 +nim add rstast.html#add,PRstNode,string proc add(father: PRstNode; s: string) 163 +nim addIfNotNil rstast.html#addIfNotNil,PRstNode,PRstNode proc addIfNotNil(father, son: PRstNode) 166 +nim renderRstToRst rstast.html#renderRstToRst,PRstNode,string proc renderRstToRst(n: PRstNode; result: var string) 359 +nim renderRstToJson rstast.html#renderRstToJson,PRstNode proc renderRstToJson(node: PRstNode): string 378 +nim renderRstToText rstast.html#renderRstToText,PRstNode proc renderRstToText(node: PRstNode): string 389 +nim treeRepr rstast.html#treeRepr,PRstNode,int proc treeRepr(node: PRstNode; indent = 0): string 405 +idx reStructuredText rstast.html#restructuredtext_1 Module rstast 0 +nimgrp newrstnode rstast.html#newRstNode-procs-all proc 139 +nimgrp add rstast.html#add-procs-all proc 160 diff --git a/rstgen.html b/rstgen.html new file mode 100644 index 0000000000000..1bf8bf04fdc1a --- /dev/null +++ b/rstgen.html @@ -0,0 +1,676 @@ + + + + + + + +packages/docutils/rstgen + + + + + + + + + + + + + + + + +
+
+

packages/docutils/rstgen

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a generator of HTML/Latex from reStructuredText (see https://docutils.sourceforge.net/rst.html for information on this markup syntax) and is used by the compiler's docgen tools.

+

You can generate HTML output through the convenience proc rstToHtml, which provided an input string with rst markup returns a string with the generated HTML. The final output is meant to be embedded inside a full document you provide yourself, so it won't contain the usual <header> or <body> parts.

+

You can also create a RstGenerator structure and populate it with the other lower level methods to finally build complete documents. This requires many options and tweaking, but you are not limited to snippets and can generate LaTeX documents too.

+

Docutils configuration files are not supported. Instead HTML generation can be tweaked by editing file config/nimdoc.cfg.

+

There are stylistic difference between how this module renders some elements and how original Python Docutils does:

+
  • Backreferences to TOC in section headings are not generated. In HTML each section is also a link that points to the section itself: this is done for user to be able to copy the link into clipboard.
  • +
  • The same goes for footnotes/citations links: they point to themselves. No backreferences are generated since finding all references of a footnote can be done by simply searching for [footnoteName].
  • +
+

+ +
+

Types

+
+
+
EscapeMode = enum
+  emText, emOption, emUrl
+
+ + + Source   +Edit   + +
+
+
+
IndexedDocs = Table[IndexEntry, seq[IndexEntry]]
+
+ +

+Contains the index sequences for doc types.

+

The key is a fake IndexEntry which will contain the title of the document in the keyword field and link will contain the html filename for the document. linkTitle and linkDesc will be empty.

+

The value indexed by this IndexEntry is a sequence with the real index entries found in the .idx file.

+ + Source   +Edit   + +
+
+
+
MetaEnum = enum
+  metaNone, metaTitleRaw, metaTitle, metaSubtitle, metaAuthor, metaVersion
+
+ + + Source   +Edit   + +
+
+
+
OutputTarget = enum
+  outHtml, outLatex
+
+ + which document type to generate + Source   +Edit   + +
+
+
+
RstGenerator = object of RootObj
+  target*: OutputTarget
+  config*: StringTableRef
+  splitAfter*: int
+  listingCounter*: int
+  tocPart*: seq[PRstNode]
+  hasToc*: bool
+  findFile*: FindFileHandler
+  msgHandler*: MsgHandler
+  outDir*: string            ## output directory, initialized by docgen.nim
+  destFile*: string          ## output (HTML) file, initialized by docgen.nim
+  filenames*: RstFileTable
+  filename*: string          ## source Nim or Rst file
+  meta*: array[MetaEnum, string]
+  ## \
+  ## Stores the empty string or the last headline/overline found in the rst
+  ## document, so it can be used as a prettier name for term index generation.
+  ## \
+  ## Keeps count of same text index terms to generate different identifiers
+  ## for hyperlinks. See renderIndexTerm proc for details.
+  id*: int                   ## A counter useful for generating IDs.
+  onTestSnippet*: proc (d: var RstGenerator; filename, cmd: string; status: int;
+                        content: string) {....gcsafe.}
+  escMode*: EscapeMode
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
IndexExt = ".idx"
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc defaultConfig(): StringTableRef {....raises: [], tags: [], forbids: [].}
+
+ +

Returns a default configuration for embedded HTML generation.

+

The returned StringTableRef contains the parameters used by the HTML engine to build the final output. For information on what these parameters are and their purpose, please look up the file config/nimdoc.cfg bundled with the compiler.

+

The only difference between the contents of that file and the values provided by this proc is the doc.file variable. The doc.file variable of the configuration file contains HTML to build standalone pages, while this proc returns just the content for procs like rstToHtml to generate the bare minimum HTML.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc esc(target: OutputTarget; s: string; splitAfter = -1; escMode = emText): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Escapes the HTML. + Source   +Edit   + +
+
+ +
+
+
+
proc escChar(target: OutputTarget; dest: var string; c: char;
+             escMode: EscapeMode) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc formatNamedVars(frmt: string; varnames: openArray[string];
+                     varvalues: openArray[string]): string {.
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initRstGenerator(g: var RstGenerator; target: OutputTarget;
+                      config: StringTableRef; filename: string;
+                      findFile: FindFileHandler = nil;
+                      msgHandler: MsgHandler = nil;
+                      filenames = default(RstFileTable); hasToc = false) {.
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ +

Initializes a RstGenerator.

+

You need to call this before using a RstGenerator with any other procs in this module. Pass a non nil StringTableRef value as config with parameters used by the HTML output generator. If you don't know what to use, pass the results of the defaultConfig() <#defaultConfig>_ proc.

+

The filename parameter will be used for error reporting and creating index hyperlinks to the file, but you can pass an empty string here if you are parsing a stream in memory. If filename ends with the .nim extension, the title for the document will be set by default to Module filename. This default title can be overridden by the embedded rst, but it helps to prettify the generated index if no title is found.

+

The RstParseOptions, FindFileHandler and MsgHandler types are defined in the packages/docutils/rst module. options selects the behaviour of the rst parser.

+

findFile is a proc used by the rst include directive among others. The purpose of this proc is to mangle or filter paths. It receives paths specified in the rst document and has to return a valid path to existing files or the empty string otherwise. If you pass nil, a default proc will be used which given a path returns the input path only if the file exists. One use for this proc is to transform relative paths found in the document to absolute path, useful if the rst file and the resources it references are not in the same directory as the current working directory.

+

The msgHandler is a proc used for user error reporting. It will be called with the filename, line, col, and type of any error found during parsing. If you pass nil, a default message handler will be used which writes the messages to the standard output.

+

Example:

+

import packages/docutils/rstgen
+
+var gen: RstGenerator
+gen.initRstGenerator(outHtml, defaultConfig(), "filename", {})

+ + Source   +Edit   + +
+
+ +
+
+
+
proc mergeIndexes(dir: string): string {....raises: [OSError, IOError, ValueError],
+    tags: [ReadDirEffect, ReadIOEffect], forbids: [].}
+
+ +

Merges all index files in dir and returns the generated index as HTML.

+

This proc will first scan dir for index files with the .idx extension previously created by commands like nim doc|rst2html which use the --index:on switch. These index files are the result of calls to setIndexTerm() and writeIndexFile(), so they are simple tab separated files.

+

As convention this proc will split index files into two categories: documentation and API. API indices will be all joined together into a single big sorted index, making the bulk of the final index. This is good for API documentation because many symbols are repeated in different modules. On the other hand, documentation indices are essentially table of contents plus a few special markers. These documents will be rendered in a separate section which tries to maintain the order and hierarchy of the symbols in the index file.

+

To differentiate between a documentation and API file a convention is used: indices which contain one entry without the HTML hash character (#) will be considered documentation, since this hash-less entry is the explicit title of the document. Indices without this explicit entry will be considered generated API extracted out of a source .nim file.

+

Returns the merged and sorted indices into a single HTML block which can be further embedded into nimdoc templates.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc nextSplitPoint(s: string; start: int): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
proc readIndexDir(dir: string): tuple[modules: seq[string],
+                                      symbols: seq[IndexEntry],
+                                      docs: IndexedDocs] {.
+    ...raises: [OSError, IOError, ValueError], tags: [ReadDirEffect, ReadIOEffect],
+    forbids: [].}
+
+ +

Walks dir reading .idx files converting them in IndexEntry items.

+

Returns the list of found module names, the list of free symbol entries and the different documentation indexes. The list of modules is sorted. See the documentation of mergeIndexes for details.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc renderCodeLang(result: var string; lang: SourceLanguage; code: string;
+                    target: OutputTarget) {....raises: [ValueError], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc renderIndexTerm(d: PDoc; n: PRstNode; result: var string) {.
+    ...raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}
+
+ +

Renders the string decorated within `foobar`:idx: markers.

+

Additionally adds the enclosed text to the index as a term. Since we are interested in different instances of the same term to have different entries, a table is used to keep track of the amount of times a term has previously appeared to give a different identifier value for each.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc renderNimCode(result: var string; code: string; target: OutputTarget) {.
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc renderRstToOut(d: var RstGenerator; n: PRstNode; result: var string) {.
+    ...gcsafe, raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}
+
+ +

Writes into result the rst ast n using the d configuration.

+

Before using this proc you need to initialise a RstGenerator with initRstGenerator and parse a rst file with rstParse from the packages/docutils/rst module. Example:

+

# ...configure gen and rst vars...
+var generatedHtml = ""
+renderRstToOut(gen, rst, generatedHtml)
+echo generatedHtml

+ + Source   +Edit   + +
+
+ +
+
+
+
proc renderTocEntries(d: var RstGenerator; j: var int; lvl: int;
+                      result: var string) {....raises: [Exception, ValueError],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rstToHtml(s: string; options: RstParseOptions; config: StringTableRef;
+               msgHandler: MsgHandler = rst.defaultMsgHandler): string {....gcsafe,
+    raises: [Exception, ValueError, KeyError],
+    tags: [RootEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ +

Converts an input rst string into embeddable HTML.

+

This convenience proc parses any input string using rst markup (it doesn't have to be a full document!) and returns an embeddable piece of HTML. The proc is meant to be used in online environments without access to a meaningful filesystem, and therefore rst include like directives won't work. For an explanation of the config parameter see the initRstGenerator proc. Example:

+

import packages/docutils/rstgen, strtabs
+
+echo rstToHtml("*Hello* **world**!", {},
+  newStringTable(modeStyleInsensitive))
+# --> <em>Hello</em> <strong>world</strong>!

+

If you need to allow the rst include directive or tweak the generated output you have to create your own RstGenerator with initRstGenerator and related procs.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc rstToLatex(rstSource: string; options: RstParseOptions): string {.inline,
+    ...raises: [Exception, ValueError, KeyError],
+    tags: [RootEffect, ReadIOEffect, ReadEnvEffect], forbids: [].}
+
+ + Convenience proc for renderRstToOut and initRstGenerator. +

Example:

+
doAssert rstToLatex("*Hello* **world**", {}) == """\emph{Hello} \textbf{world}"""
+ Source   +Edit   + +
+
+ +
+
+
+
proc setIndexTerm(d: var RstGenerator; k: IndexEntryKind;
+                  htmlFile, id, term: string; linkTitle, linkDesc = ""; line = 0) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Adds a term to the index using the specified hyperlink identifier.

+

A new entry will be added to the index using the format term<tab>file#id. The file part will come from the htmlFile parameter.

+

The id will be appended with a hash character only if its length is not zero, otherwise no specific anchor will be generated. In general you should only pass an empty id value for the title of standalone rst documents (they are special for the mergeIndexes() proc, see Index (idx) file format for more information). Unlike other index terms, title entries are inserted at the beginning of the accumulated buffer to maintain a logical order of entries.

+

If linkTitle or linkDesc are not the empty string, two additional columns with their contents will be added.

+

The index won't be written to disk unless you call writeIndexFile(). The purpose of the index is documented in the docgen tools guide.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc traverseForIndex(d: PDoc; n: PRstNode) {....raises: [Exception, ValueError],
+    tags: [RootEffect], forbids: [].}
+
+ + A version of renderRstToOut that only fills entries for .idx files. + Source   +Edit   + +
+
+ +
+
+
+
proc writeIndexFile(g: var RstGenerator; outfile: string) {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ +

Writes the current index buffer to the specified output file.

+

You previously need to add entries to the index with the setIndexTerm() proc. If the index is empty the file won't be created.

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/rstgen.idx b/rstgen.idx new file mode 100644 index 0000000000000..46599e23ce9b6 --- /dev/null +++ b/rstgen.idx @@ -0,0 +1,38 @@ +nimTitle rstgen rstgen.html module packages/docutils/rstgen 0 +nim IndexExt rstgen.html#IndexExt const IndexExt 55 +nim outHtml rstgen.html#outHtml OutputTarget.outHtml 58 +nim outLatex rstgen.html#outLatex OutputTarget.outLatex 58 +nim OutputTarget rstgen.html#OutputTarget enum OutputTarget 58 +nim metaNone rstgen.html#metaNone MetaEnum.metaNone 62 +nim metaTitleRaw rstgen.html#metaTitleRaw MetaEnum.metaTitleRaw 62 +nim metaTitle rstgen.html#metaTitle MetaEnum.metaTitle 62 +nim metaSubtitle rstgen.html#metaSubtitle MetaEnum.metaSubtitle 62 +nim metaAuthor rstgen.html#metaAuthor MetaEnum.metaAuthor 62 +nim metaVersion rstgen.html#metaVersion MetaEnum.metaVersion 62 +nim MetaEnum rstgen.html#MetaEnum enum MetaEnum 62 +nim emText rstgen.html#emText EscapeMode.emText 65 +nim emOption rstgen.html#emOption EscapeMode.emOption 65 +nim emUrl rstgen.html#emUrl EscapeMode.emUrl 65 +nim EscapeMode rstgen.html#EscapeMode enum EscapeMode 65 +nim RstGenerator rstgen.html#RstGenerator object RstGenerator 69 +nim prettyLink rstgen.html#prettyLink,string proc prettyLink(file: string): string 107 +nim initRstGenerator rstgen.html#initRstGenerator,RstGenerator,OutputTarget,StringTableRef,string,FindFileHandler,MsgHandler proc initRstGenerator(g: var RstGenerator; target: OutputTarget;\n config: StringTableRef; filename: string;\n findFile: FindFileHandler = nil; msgHandler: MsgHandler = nil;\n filenames = default(RstFileTable); hasToc = false) 116 +nim writeIndexFile rstgen.html#writeIndexFile,RstGenerator,string proc writeIndexFile(g: var RstGenerator; outfile: string) 186 +nim escChar rstgen.html#escChar,OutputTarget,string,char,EscapeMode proc escChar(target: OutputTarget; dest: var string; c: char; escMode: EscapeMode) 229 +nim nextSplitPoint rstgen.html#nextSplitPoint,string,int proc nextSplitPoint(s: string; start: int): int 240 +nim esc rstgen.html#esc,OutputTarget,string,int proc esc(target: OutputTarget; s: string; splitAfter = -1; escMode = emText): string 252 +nim renderRstToOut rstgen.html#renderRstToOut,RstGenerator,PRstNode,string proc renderRstToOut(d: var RstGenerator; n: PRstNode; result: var string) 287 +nim setIndexTerm rstgen.html#setIndexTerm,RstGenerator,IndexEntryKind,string,string,string,string,string,int proc setIndexTerm(d: var RstGenerator; k: IndexEntryKind; htmlFile, id, term: string;\n linkTitle, linkDesc = ""; line = 0) 325 +nim renderIndexTerm rstgen.html#renderIndexTerm,PDoc,PRstNode,string proc renderIndexTerm(d: PDoc; n: PRstNode; result: var string) 372 +nim IndexedDocs rstgen.html#IndexedDocs type IndexedDocs 394 +nim readIndexDir rstgen.html#readIndexDir,string proc readIndexDir(dir: string): tuple[modules: seq[string], symbols: seq[IndexEntry],\n docs: IndexedDocs] 577 +nim mergeIndexes rstgen.html#mergeIndexes,string proc mergeIndexes(dir: string): string 624 +nim renderTocEntries rstgen.html#renderTocEntries,RstGenerator,int,int,string proc renderTocEntries(d: var RstGenerator; j: var int; lvl: int; result: var string) 732 +nim renderCodeLang rstgen.html#renderCodeLang,string,SourceLanguage,string,OutputTarget proc renderCodeLang(result: var string; lang: SourceLanguage; code: string;\n target: OutputTarget) 919 +nim renderNimCode rstgen.html#renderNimCode,string,string,OutputTarget proc renderNimCode(result: var string; code: string; target: OutputTarget) 935 +nim traverseForIndex rstgen.html#traverseForIndex,PDoc,PRstNode proc traverseForIndex(d: PDoc; n: PRstNode) 1108 +nim formatNamedVars rstgen.html#formatNamedVars,string,openArray[string],openArray[string] proc formatNamedVars(frmt: string; varnames: openArray[string];\n varvalues: openArray[string]): string 1384 +nim defaultConfig rstgen.html#defaultConfig proc defaultConfig(): StringTableRef 1445 +nim rstToHtml rstgen.html#rstToHtml,string,RstParseOptions,StringTableRef,MsgHandler proc rstToHtml(s: string; options: RstParseOptions; config: StringTableRef;\n msgHandler: MsgHandler = rst.defaultMsgHandler): string 1513 +nim rstToLatex rstgen.html#rstToLatex,string,RstParseOptions proc rstToLatex(rstSource: string; options: RstParseOptions): string 1555 +idx reStructuredText rstgen.html#restructuredtext_1 Module rstgen 0 diff --git a/rstidx.html b/rstidx.html new file mode 100644 index 0000000000000..3ed43dda897f1 --- /dev/null +++ b/rstidx.html @@ -0,0 +1,303 @@ + + + + + + + +packages/docutils/rstidx + + + + + + + + + + + + + + + + +
+
+

packages/docutils/rstidx

+
+ +
+ Source   +Edit   + +
+ +

Nim idx file format related definitions.

+ +
+

Types

+
+
+
IndexEntry = object
+  kind*: IndexEntryKind      ## 0.
+  keyword*: string           ## 1.
+  link*: string              ## 2.
+  linkTitle*: string         ## 3. contains a prettier text for the href
+  linkDesc*: string          ## 4. the title attribute of the final href
+  line*: int                 ## 5.
+  module*: string            ## origin file, NOT a field in ``.idx`` file
+  aux*: string               ## auxuliary field, NOT a field in ``.idx`` file
+
+ + + Source   +Edit   + +
+
+
+
IndexEntryKind = enum
+  ieMarkupTitle = "markupTitle", ## RST/Markdown title, text in `keyword` +
+                                  ## HTML text in `linkTitle`
+  ieNimTitle = "nimTitle",  ## Nim title
+  ieHeading = "heading",    ## RST/Markdown markup heading, escaped
+  ieIdxRole = "idx",        ## RST :idx: definition, escaped
+  ieNim = "nim",            ## Nim symbol, unescaped
+  ieNimGroup = "nimgrp"      ## Nim overload group, unescaped
+
+ + discriminator tag + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(e: IndexEntry): string {....raises: [ValueError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cmp(a, b: IndexEntry): int {....raises: [], tags: [], forbids: [].}
+
+ + Sorts two IndexEntry first by keyword field, then by link. + Source   +Edit   + +
+
+ +
+
+
+
proc formatIndexEntry(kind: IndexEntryKind;
+                      htmlFile, id, term, linkTitle, linkDesc: string; line: int): tuple[
+    entry: string, isTitle: bool] {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hash(x: IndexEntry): Hash {....raises: [], tags: [], forbids: [].}
+
+ +

Returns the hash for the combined fields of the type.

+

The hash is computed as the chained hash of the individual string hashes.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc isDocumentationTitle(hyperlink: string): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Returns true if the hyperlink is actually a documentation title.

+

Documentation titles lack the hash. See mergeIndexes() for a more detailed explanation.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc parseIdxFile(path: string): tuple[fileEntries: seq[IndexEntry],
+                                       title: IndexEntry] {.
+    ...raises: [IOError, ValueError], tags: [ReadIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc unquoteIndexColumn(text: string): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + Returns the unquoted version generated by quoteIndexColumn. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/rstidx.idx b/rstidx.idx new file mode 100644 index 0000000000000..9ca26f835b450 --- /dev/null +++ b/rstidx.idx @@ -0,0 +1,17 @@ +nimTitle rstidx rstidx.html module packages/docutils/rstidx 0 +nim ieMarkupTitle rstidx.html#ieMarkupTitle IndexEntryKind.ieMarkupTitle 14 +nim ieNimTitle rstidx.html#ieNimTitle IndexEntryKind.ieNimTitle 14 +nim ieHeading rstidx.html#ieHeading IndexEntryKind.ieHeading 14 +nim ieIdxRole rstidx.html#ieIdxRole IndexEntryKind.ieIdxRole 14 +nim ieNim rstidx.html#ieNim IndexEntryKind.ieNim 14 +nim ieNimGroup rstidx.html#ieNimGroup IndexEntryKind.ieNimGroup 14 +nim IndexEntryKind rstidx.html#IndexEntryKind enum IndexEntryKind 14 +nim IndexEntry rstidx.html#IndexEntry object IndexEntry 24 +nim isDocumentationTitle rstidx.html#isDocumentationTitle,string proc isDocumentationTitle(hyperlink: string): bool 34 +nim `$` rstidx.html#$,IndexEntry proc `$`(e: IndexEntry): string 41 +nim unquoteIndexColumn rstidx.html#unquoteIndexColumn,string proc unquoteIndexColumn(text: string): string 64 +nim formatIndexEntry rstidx.html#formatIndexEntry,IndexEntryKind,string,string,string,string,string,int proc formatIndexEntry(kind: IndexEntryKind;\n htmlFile, id, term, linkTitle, linkDesc: string; line: int): tuple[\n entry: string, isTitle: bool] 68 +nim parseIdxFile rstidx.html#parseIdxFile,string proc parseIdxFile(path: string): tuple[fileEntries: seq[IndexEntry],\n title: IndexEntry] 97 +nim cmp rstidx.html#cmp,IndexEntry,IndexEntry proc cmp(a, b: IndexEntry): int 128 +nim hash rstidx.html#hash,IndexEntry proc hash(x: IndexEntry): Hash 134 +idx idx rstidx.html#idx_1 Module rstidx 0 diff --git a/rtarrays.html b/rtarrays.html new file mode 100644 index 0000000000000..4a2c07a1aca42 --- /dev/null +++ b/rtarrays.html @@ -0,0 +1,154 @@ + + + + + + + +std/rtarrays + + + + + + + + + + + + + + + + +
+
+

std/rtarrays

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Module that implements a fixed length array whose size is determined at runtime. Note: This is not ready for other people to use!

+

Unstable API.

+

+
+

Types

+
+
+
RtArray[T] = object
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc getRawData[T](x: var RtArray[T]): ptr UncheckedArray[T]
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initRtArray[T](len: Natural): RtArray[T]
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/rtarrays.idx b/rtarrays.idx new file mode 100644 index 0000000000000..f89638886e8cf --- /dev/null +++ b/rtarrays.idx @@ -0,0 +1,4 @@ +nimTitle rtarrays rtarrays.html module std/rtarrays 0 +nim RtArray rtarrays.html#RtArray object RtArray 20 +nim initRtArray rtarrays.html#initRtArray,Natural proc initRtArray[T](len: Natural): RtArray[T] 27 +nim getRawData rtarrays.html#getRawData,RtArray[T] proc getRawData[T](x: var RtArray[T]): ptr UncheckedArray[T] 32 diff --git a/schubfach.html b/schubfach.html new file mode 100644 index 0000000000000..2832bfc09047a --- /dev/null +++ b/schubfach.html @@ -0,0 +1,142 @@ + + + + + + + +std/private/schubfach + + + + + + + + + + + + + + + + +
+
+

std/private/schubfach

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Copyright 2020 Alexander Bolz

+

Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)

+

This file contains an implementation of the Schubfach algorithm as described in

+

[1] Raffaello Giulietti, "The Schubfach way to render doubles", https://drive.google.com/open?id=1luHhyQF9zKlM8yJ1nebU0OgVYhfC6CBN

+

Returns floor(x / 2^n).

+

Technically, right-shift of negative integers is implementation defined... Should easily be optimized into SAR (or equivalent) instruction.

+

Returns floor(log_10(2^e))

+

static inline int32_t FloorLog10Pow2(int32_t e)
+{
+    SF_ASSERT(e >= -1500);
+    SF_ASSERT(e <=  1500);
+    return FloorDivPow2(e * 1262611, 22);
+}
Returns floor(log_10(3/4 2^e))

+

static inline int32_t FloorLog10ThreeQuartersPow2(int32_t e)
+{
+    SF_ASSERT(e >= -1500);
+    SF_ASSERT(e <=  1500);
+    return FloorDivPow2(e * 1262611 - 524031, 22);
+}
Returns floor(log_2(10^e))

+Returns whether value is divisible by 2^e2

ToChars

+ +
+

Procs

+
+
+
+
proc float32ToChars(buffer: var openArray[char]; v: float32;
+                    forceTrailingDotZero = false): int {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/schubfach.idx b/schubfach.idx new file mode 100644 index 0000000000000..49a33c023c9df --- /dev/null +++ b/schubfach.idx @@ -0,0 +1,3 @@ +nimTitle schubfach schubfach.html module std/private/schubfach 0 +nim float32ToChars schubfach.html#float32ToChars,openArray[char],float32 proc float32ToChars(buffer: var openArray[char]; v: float32;\n forceTrailingDotZero = false): int 403 +heading ToChars schubfach.html#tochars ToChars 0 diff --git a/segfaults.html b/segfaults.html new file mode 100644 index 0000000000000..bc446d5aab3f3 --- /dev/null +++ b/segfaults.html @@ -0,0 +1,90 @@ + + + + + + + +std/segfaults + + + + + + + + + + + + + + + + +
+
+

std/segfaults

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This modules registers a signal handler that turns access violations / segfaults into a NilAccessDefect exception. To be able to catch a NilAccessDefect all you have to do is to import this module.

+

Tested on these OSes: Linux, Windows, OSX

+

+
+

Imports

+
+ posix +
+
+ +
+
+ + +
+
+ + + + diff --git a/segfaults.idx b/segfaults.idx new file mode 100644 index 0000000000000..713ee0febf0e8 --- /dev/null +++ b/segfaults.idx @@ -0,0 +1 @@ +nimTitle segfaults segfaults.html module std/segfaults 0 diff --git a/selectors.html b/selectors.html new file mode 100644 index 0000000000000..c833b3e2e846b --- /dev/null +++ b/selectors.html @@ -0,0 +1,672 @@ + + + + + + + +std/selectors + + + + + + + + + + + + + + + + +
+
+

std/selectors

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module allows high-level and efficient I/O multiplexing.

+

Supported OS primitives: epoll, kqueue, poll and Windows select.

+

To use threadsafe version of this module, it needs to be compiled with both -d:threadsafe and --threads:on options.

+

Supported features: files, sockets, pipes, timers, processes, signals and user events.

+

Fully supported OS: MacOSX, FreeBSD, OpenBSD, NetBSD, Linux (except for Android).

+

Partially supported OS: Windows (only sockets and user events), Solaris (files, sockets, handles and user events). Android (files, sockets, handles and user events).

+

TODO: /dev/poll, event ports and filesystem events.

+

+ +
+

Types

+
+
+
Event {.pure.} = enum
+  Read,                     ## Descriptor is available for read
+  Write,                    ## Descriptor is available for write
+  Timer,                    ## Timer descriptor is completed
+  Signal,                   ## Signal is raised
+  Process,                  ## Process is finished
+  Vnode,                    ## BSD specific file change
+  User,                     ## User event is raised
+  Error,                    ## Error occurred while waiting for descriptor
+  VnodeWrite,               ## NOTE_WRITE (BSD specific, write to file occurred)
+  VnodeDelete,              ## NOTE_DELETE (BSD specific, unlink of file occurred)
+  VnodeExtend,              ## NOTE_EXTEND (BSD specific, file extended)
+  VnodeAttrib,              ## NOTE_ATTRIB (BSD specific, file attributes changed)
+  VnodeLink,                ## NOTE_LINK (BSD specific, file link count changed)
+  VnodeRename,              ## NOTE_RENAME (BSD specific, file renamed)
+  VnodeRevoke                ## NOTE_REVOKE (BSD specific, file revoke occurred)
+
+ + An enum which hold event types + Source   +Edit   + +
+
+
+
IOSelectorsException = object of CatchableError
+
+ + Exception that is raised if an IOSelectors error occurs. + Source   +Edit   + +
+
+
+
ReadyKey = object
+  fd*: int                   ## file/socket descriptor
+  events*: set[Event]        ## set of events
+  errorCode*: OSErrorCode    ## additional error code information for
+                             ## Error events
+
+ + An object which holds result for descriptor + Source   +Edit   + +
+
+
+
SelectEvent = object
+
+ + An object which holds user defined event + Source   +Edit   + +
+
+
+
Selector[T] = ref object
+
+ + An object which holds descriptors to be checked for read/write status + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
ioselSupportedPlatform = true
+
+ + This constant is used to determine whether the destination platform is fully supported by ioselectors module. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc close(ev: SelectEvent) {....raises: [], tags: [], forbids: [].}
+
+ + Closes user-defined event ev. + Source   +Edit   + +
+
+
+
proc close[T](s: Selector[T])
+
+ + Closes the selector. + Source   +Edit   + +
+
+ +
+
+
+
proc contains[T](s: Selector[T]; fd: SocketHandle | int): bool {.inline.}
+
+ + Determines whether selector contains a file descriptor. + Source   +Edit   + +
+
+ +
+
+
+
proc getData[T](s: Selector[T]; fd: SocketHandle | int): var T
+
+ + Retrieves application-defined data associated with descriptor fd. If specified descriptor fd is not registered, empty/default value will be returned. + Source   +Edit   + +
+
+ +
+
+
+
proc getFd[T](s: Selector[T]): int
+
+ +

Retrieves the underlying selector's file descriptor.

+

For poll and select selectors -1 is returned.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newSelectEvent(): SelectEvent {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new user-defined event. + Source   +Edit   + +
+
+ +
+
+
+
proc newSelector[T](): Selector[T]
+
+ + Creates a new selector + Source   +Edit   + +
+
+ +
+
+
+
proc registerEvent[T](s: Selector[T]; ev: SelectEvent; data: T)
+
+ +

Registers selector event ev in selector s.

+

The data is application-defined data, which will be passed when ev happens.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc registerHandle[T](s: Selector[T]; fd: int | SocketHandle;
+                       events: set[Event]; data: T)
+
+ + Registers file/socket descriptor fd to selector s with events set in events. The data is application-defined data, which will be passed when an event is triggered. + Source   +Edit   + +
+
+ +
+
+
+
proc registerProcess[T](s: Selector[T]; pid: int; data: T): int {.discardable.}
+
+ +

Registers a process id (pid) notification (when process has exited) in selector s.

+

The data is application-defined data, which will be passed when process with pid has exited.

+

Returns the file descriptor for the registered signal.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc registerSignal[T](s: Selector[T]; signal: int; data: T): int {.discardable.}
+
+ +

Registers Unix signal notification with signal to selector s.

+

The data is application-defined data, which will be passed when signal raises.

+

Returns the file descriptor for the registered signal.

+

Note: This function is not supported on Windows.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc registerTimer[T](s: Selector[T]; timeout: int; oneshot: bool; data: T): int {.
+    discardable.}
+
+ +

Registers timer notification with timeout (in milliseconds) to selector s.

+

If oneshot is true, timer will be notified only once.

+

Set oneshot to false if you want periodic notifications.

+

The data is application-defined data, which will be passed, when the timer is triggered.

+

Returns the file descriptor for the registered timer.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc registerVnode[T](s: Selector[T]; fd: cint; events: set[Event]; data: T)
+
+ +

Registers selector BSD/MacOSX specific vnode events for file descriptor fd and events events. data application-defined data, which to be passed, when vnode event happens.

+

Note: This function is supported only by BSD and MacOSX.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc select[T](s: Selector[T]; timeout: int): seq[ReadyKey]
+
+ +

Waits for events registered in selector s.

+

The timeout argument specifies the maximum number of milliseconds the function will be blocked for if no events are ready. Specifying a timeout of -1 causes the function to block indefinitely.

+

Returns a list of triggered events.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc selectInto[T](s: Selector[T]; timeout: int;
+                   results: var openArray[ReadyKey]): int
+
+ +

Waits for events registered in selector s.

+

The timeout argument specifies the maximum number of milliseconds the function will be blocked for if no events are ready. Specifying a timeout of -1 causes the function to block indefinitely. All available events will be stored in results array.

+

Returns number of triggered events.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc setData[T](s: Selector[T]; fd: SocketHandle | int; data: var T): bool
+
+ +

Associate application-defined data with descriptor fd.

+

Returns true, if data was successfully updated, false otherwise.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc trigger(ev: SelectEvent) {....raises: [], tags: [], forbids: [].}
+
+ + Trigger event ev. + Source   +Edit   + +
+
+ +
+
+
+
proc unregister[T](s: Selector[T]; ev: SelectEvent)
+
+ + Unregisters user-defined event ev from selector s. + Source   +Edit   + +
+
+
+
proc unregister[T](s: Selector[T]; fd: int | SocketHandle | cint)
+
+ + Unregisters file/socket descriptor fd from selector s. + Source   +Edit   + +
+
+ +
+
+
+
proc updateHandle[T](s: Selector[T]; fd: int | SocketHandle; events: set[Event])
+
+ + Update file/socket descriptor fd, registered in selector s with new events set event. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template isEmpty[T](s: Selector[T]): bool
+
+ + Returns true, if there are no registered events or descriptors in selector. + Source   +Edit   + +
+
+ +
+
+
+
template withData[T](s: Selector[T]; fd: SocketHandle | int;
+                     value, body1, body2: untyped)
+
+ +

Retrieves the application-data assigned with descriptor fd to value. This value can be modified in the scope of the withData call.

+

s.withData(fd, value) do:
+  # block is executed only if `fd` registered in selector `s`.
+  value.uid = 1000
+do:
+  # block is executed if `fd` not registered in selector `s`.
+  raise

+ + Source   +Edit   + +
+
+
+
template withData[T](s: Selector[T]; fd: SocketHandle | int;
+                     value, body: untyped)
+
+ +

Retrieves the application-data assigned with descriptor fd to value. This value can be modified in the scope of the withData call.

+

s.withData(fd, value) do:
+  # block is executed only if `fd` registered in selector `s`
+  value.uid = 1000

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/selectors.idx b/selectors.idx new file mode 100644 index 0000000000000..22802f61ec243 --- /dev/null +++ b/selectors.idx @@ -0,0 +1,33 @@ +nimTitle selectors selectors.html module std/selectors 0 +nim ioselSupportedPlatform selectors.html#ioselSupportedPlatform const ioselSupportedPlatform 38 +nim Selector selectors.html#Selector type Selector 51 +nim IOSelectorsException selectors.html#IOSelectorsException object IOSelectorsException 54 +nim Event selectors.html#Event enum Event 57 +nim ReadyKey selectors.html#ReadyKey object ReadyKey 75 +nim SelectEvent selectors.html#SelectEvent object SelectEvent 82 +nim newSelector selectors.html#newSelector proc newSelector[T](): Selector[T] 85 +nim close selectors.html#close,Selector[T] proc close[T](s: Selector[T]) 88 +nim registerHandle selectors.html#registerHandle,Selector[T],,set[Event],T proc registerHandle[T](s: Selector[T]; fd: int | SocketHandle; events: set[Event];\n data: T) 91 +nim updateHandle selectors.html#updateHandle,Selector[T],,set[Event] proc updateHandle[T](s: Selector[T]; fd: int | SocketHandle; events: set[Event]) 97 +nim registerTimer selectors.html#registerTimer,Selector[T],int,bool,T proc registerTimer[T](s: Selector[T]; timeout: int; oneshot: bool; data: T): int 102 +nim registerSignal selectors.html#registerSignal,Selector[T],int,T proc registerSignal[T](s: Selector[T]; signal: int; data: T): int 116 +nim registerProcess selectors.html#registerProcess,Selector[T],int,T proc registerProcess[T](s: Selector[T]; pid: int; data: T): int 128 +nim registerEvent selectors.html#registerEvent,Selector[T],SelectEvent,T proc registerEvent[T](s: Selector[T]; ev: SelectEvent; data: T) 138 +nim registerVnode selectors.html#registerVnode,Selector[T],cint,set[Event],T proc registerVnode[T](s: Selector[T]; fd: cint; events: set[Event]; data: T) 144 +nim newSelectEvent selectors.html#newSelectEvent proc newSelectEvent(): SelectEvent 153 +nim trigger selectors.html#trigger,SelectEvent proc trigger(ev: SelectEvent) 156 +nim close selectors.html#close,SelectEvent proc close(ev: SelectEvent) 159 +nim unregister selectors.html#unregister,Selector[T],SelectEvent proc unregister[T](s: Selector[T]; ev: SelectEvent) 162 +nim unregister selectors.html#unregister,Selector[T], proc unregister[T](s: Selector[T]; fd: int | SocketHandle | cint) 165 +nim selectInto selectors.html#selectInto,Selector[T],int,openArray[ReadyKey] proc selectInto[T](s: Selector[T]; timeout: int; results: var openArray[ReadyKey]): int 168 +nim select selectors.html#select,Selector[T],int proc select[T](s: Selector[T]; timeout: int): seq[ReadyKey] 179 +nim getData selectors.html#getData,Selector[T], proc getData[T](s: Selector[T]; fd: SocketHandle | int): var T 188 +nim setData selectors.html#setData,Selector[T],,T proc setData[T](s: Selector[T]; fd: SocketHandle | int; data: var T): bool 193 +nim isEmpty selectors.html#isEmpty.t,Selector[T] template isEmpty[T](s: Selector[T]): bool 198 +nim withData selectors.html#withData.t,Selector[T],,untyped,untyped template withData[T](s: Selector[T]; fd: SocketHandle | int; value, body: untyped) 202 +nim withData selectors.html#withData.t,Selector[T],,untyped,untyped,untyped template withData[T](s: Selector[T]; fd: SocketHandle | int; value, body1, body2: untyped) 214 +nim contains selectors.html#contains,Selector[T], proc contains[T](s: Selector[T]; fd: SocketHandle | int): bool 229 +nim getFd selectors.html#getFd,Selector[T] proc getFd[T](s: Selector[T]): int 232 +nimgrp close selectors.html#close-procs-all proc 88 +nimgrp unregister selectors.html#unregister-procs-all proc 162 +nimgrp withdata selectors.html#withData-templates-all template 202 diff --git a/sequtils.html b/sequtils.html new file mode 100644 index 0000000000000..6fbd5e9e24cc5 --- /dev/null +++ b/sequtils.html @@ -0,0 +1,1233 @@ + + + + + + + +std/sequtils + + + + + + + + + + + + + + + + +
+
+

std/sequtils

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Although this module has seq in its name, it implements operations not only for the seq type, but for three built-in container types under the openArray umbrella:

  • sequences
  • +
  • strings
  • +
  • array
  • +
+

The system module defines several common functions, such as:

+
  • newSeq[T] for creating new sequences of type T
  • +
  • @ for converting arrays and strings to sequences
  • +
  • add for adding new elements to strings and sequences
  • +
  • & for string and seq concatenation
  • +
  • in (alias for contains) and notin for checking if an item is in a container
  • +
+

This module builds upon that, providing additional functionality in form of procs, iterators and templates inspired by functional programming languages.

+

For functional style programming you have different options at your disposal:

+ +

Chaining of functions is possible thanks to the method call syntax.

+ +

Example:

+
import std/sequtils
+import std/sugar
+
+# Creating a sequence from 1 to 10, multiplying each member by 2,
+# keeping only the members which are not divisible by 6.
+let
+  foo = toSeq(1..10).map(x => x * 2).filter(x => x mod 6 != 0)
+  bar = toSeq(1..10).mapIt(it * 2).filterIt(it mod 6 != 0)
+  baz = collect:
+    for i in 1..10:
+      let j = 2 * i
+      if j mod 6 != 0:
+        j
+
+doAssert foo == bar
+doAssert foo == baz
+doAssert foo == @[2, 4, 8, 10, 14, 16, 20]
+
+doAssert foo.any(x => x > 17)
+doAssert not bar.allIt(it < 20)
+doAssert foo.foldl(a + b) == 74 # sum of all members
+

Example:

+
import std/sequtils
+from std/strutils import join
+
+let
+  vowels = @"aeiou"
+  foo = "sequtils is an awesome module"
+
+doAssert (vowels is seq[char]) and (vowels == @['a', 'e', 'i', 'o', 'u'])
+doAssert foo.filterIt(it notin vowels).join == "sqtls s n wsm mdl"
+

See also

+

+ +
+

Procs

+
+
+
+
func addUnique[T](s: var seq[T]; x: sink T)
+
+ + Adds x to the container s if it is not already present. Uses == to check if the item is already present. +

Example:

+
var a = @[1, 2, 3]
+a.addUnique(4)
+a.addUnique(4)
+assert a == @[1, 2, 3, 4]
+ Source   +Edit   + +
+
+ +
+
+
+
proc all[T](s: openArray[T]; pred: proc (x: T): bool {.closure.}): bool {.
+    effectsOf: pred.}
+
+ +

Iterates through a container and checks if every item fulfills the predicate.

+

See also:

+ + +

Example:

+
let numbers = @[1, 4, 5, 8, 9, 7, 4]
+assert all(numbers, proc (x: int): bool = x < 10) == true
+assert all(numbers, proc (x: int): bool = x < 9) == false
+ Source   +Edit   + +
+
+ +
+
+
+
proc any[T](s: openArray[T]; pred: proc (x: T): bool {.closure.}): bool {.
+    effectsOf: pred.}
+
+ +

Iterates through a container and checks if at least one item fulfills the predicate.

+

See also:

+ + +

Example:

+
let numbers = @[1, 4, 5, 8, 9, 7, 4]
+assert any(numbers, proc (x: int): bool = x > 8) == true
+assert any(numbers, proc (x: int): bool = x > 9) == false
+ Source   +Edit   + +
+
+ +
+
+
+
proc apply[T](s: openArray[T]; op: proc (x: T) {.closure.}) {.inline,
+    effectsOf: op.}
+
+ + Same as apply but for a proc that does not return anything and does not mutate s directly. +

Example:

+
var message: string
+apply([0, 1, 2, 3, 4], proc(item: int) = message.addInt item)
+assert message == "01234"
+ Source   +Edit   + +
+
+
+
proc apply[T](s: var openArray[T]; op: proc (x: T): T {.closure.}) {.inline,
+    effectsOf: op.}
+
+ +

Applies op to every item in s modifying it directly.

+

Note that the container s must be declared as a var and it is required for your input and output types to be the same, since s is modified in-place. The parameter function takes and returns a T type variable.

+

See also:

+ + +

Example:

+
var a = @["1", "2", "3", "4"]
+apply(a, proc(x: string): string = x & "42")
+assert a == @["142", "242", "342", "442"]
+ Source   +Edit   + +
+
+
+
proc apply[T](s: var openArray[T]; op: proc (x: var T) {.closure.}) {.inline,
+    effectsOf: op.}
+
+ +

Applies op to every item in s, modifying it directly.

+

Note that the container s must be declared as a var, since s is modified in-place. The parameter function takes a var T type parameter.

+

See also:

+ + +

Example:

+
var a = @["1", "2", "3", "4"]
+apply(a, proc(x: var string) = x &= "42")
+assert a == @["142", "242", "342", "442"]
+ Source   +Edit   + +
+
+ +
+
+
+
func concat[T](seqs: varargs[seq[T]]): seq[T]
+
+ +

Takes several sequences' items and returns them inside a new sequence. All sequences must be of the same type.

+

See also:

+ + +

Example:

+
let
+  s1 = @[1, 2, 3]
+  s2 = @[4, 5]
+  s3 = @[6, 7]
+  total = concat(s1, s2, s3)
+assert total == @[1, 2, 3, 4, 5, 6, 7]
+ Source   +Edit   + +
+
+ +
+
+
+
func count[T](s: openArray[T]; x: T): int
+
+ + Returns the number of occurrences of the item x in the container s. +

Example:

+
let
+  a = @[1, 2, 2, 3, 2, 4, 2]
+  b = "abracadabra"
+assert count(a, 2) == 4
+assert count(a, 99) == 0
+assert count(b, 'r') == 2
+ Source   +Edit   + +
+
+ +
+
+
+
func cycle[T](s: openArray[T]; n: Natural): seq[T]
+
+ + Returns a new sequence with the items of the container s repeated n times. n must be a non-negative number (zero or more). +

Example:

+
let
+  s = @[1, 2, 3]
+  total = s.cycle(3)
+assert total == @[1, 2, 3, 1, 2, 3, 1, 2, 3]
+ Source   +Edit   + +
+
+ +
+
+
+
func deduplicate[T](s: openArray[T]; isSorted: bool = false): seq[T]
+
+ +

Returns a new sequence without duplicates.

+

Setting the optional argument isSorted to true (default: false) uses a faster algorithm for deduplication.

+ +

Example:

+
let
+  dup1 = @[1, 1, 3, 4, 2, 2, 8, 1, 4]
+  dup2 = @["a", "a", "c", "d", "d"]
+  unique1 = deduplicate(dup1)
+  unique2 = deduplicate(dup2, isSorted = true)
+assert unique1 == @[1, 3, 4, 2, 8]
+assert unique2 == @["a", "c", "d"]
+ Source   +Edit   + +
+
+ +
+
+
+
func delete[T](s: var seq[T]; first, last: Natural) {.
+    ...deprecated: "use `delete(s, first..last)`".}
+
+
+ Deprecated: use `delete(s, first..last)` +
+ + Deletes the items of a sequence s at positions first..last (including both ends of the range). This modifies s itself, it does not return a copy. +

Example: cmd: --warning:deprecated:off

+
let outcome = @[1, 1, 1, 1, 1, 1, 1, 1]
+var dest = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
+dest.delete(3, 8)
+assert outcome == dest
+ Source   +Edit   + +
+
+
+
func delete[T](s: var seq[T]; slice: Slice[int])
+
+ +

Deletes the items s[slice], raising IndexDefect if the slice contains elements out of range.

+

This operation moves all elements after s[slice] in linear time.

+ +

Example:

+
var a = @[10, 11, 12, 13, 14]
+doAssertRaises(IndexDefect): a.delete(4..5)
+assert a == @[10, 11, 12, 13, 14]
+a.delete(4..4)
+assert a == @[10, 11, 12, 13]
+a.delete(1..2)
+assert a == @[10, 13]
+a.delete(1..<1) # empty slice
+assert a == @[10, 13]
+ Source   +Edit   + +
+
+ +
+
+
+
func distribute[T](s: seq[T]; num: Positive; spread = true): seq[seq[T]]
+
+ +

Splits and distributes a sequence s into num sub-sequences.

+

Returns a sequence of num sequences. For some input values this is the inverse of the concat func. The input sequence s can be empty, which will produce num empty sequences.

+

If spread is false and the length of s is not a multiple of num, the func will max out the first sub-sequence with 1 + len(s) div num entries, leaving the remainder of elements to the last sequence.

+

On the other hand, if spread is true, the func will distribute evenly the remainder of the division across all sequences, which makes the result more suited to multithreading where you are passing equal sized work units to a thread pool and want to maximize core usage.

+ +

Example:

+
let numbers = @[1, 2, 3, 4, 5, 6, 7]
+assert numbers.distribute(3) == @[@[1, 2, 3], @[4, 5], @[6, 7]]
+assert numbers.distribute(3, false) == @[@[1, 2, 3], @[4, 5, 6], @[7]]
+assert numbers.distribute(6)[0] == @[1, 2]
+assert numbers.distribute(6)[1] == @[3]
+ Source   +Edit   + +
+
+ +
+
+
+
proc filter[T](s: openArray[T]; pred: proc (x: T): bool {.closure.}): seq[T] {.
+    inline, effectsOf: pred.}
+
+ +

Returns a new sequence with all the items of s that fulfill the predicate pred (a function that returns a bool).

+

Instead of using map and filter, consider using the collect macro from the sugar module.

+

See also:

+ + +

Example:

+
let
+  colors = @["red", "yellow", "black"]
+  f1 = filter(colors, proc(x: string): bool = x.len < 6)
+  f2 = filter(colors, proc(x: string): bool = x.contains('y'))
+assert f1 == @["red", "black"]
+assert f2 == @["yellow"]
+ Source   +Edit   + +
+
+ +
+
+
+
func insert[T](dest: var seq[T]; src: openArray[T]; pos = 0)
+
+ +

Inserts items from src into dest at position pos. This modifies dest itself, it does not return a copy.

+

Note that the elements of src and dest must be of the same type.

+ +

Example:

+
var dest = @[1, 1, 1, 1, 1, 1, 1, 1]
+let
+  src = @[2, 2, 2, 2, 2, 2]
+  outcome = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
+dest.insert(src, 3)
+assert dest == outcome
+ Source   +Edit   + +
+
+ +
+
+
+
proc keepIf[T](s: var seq[T]; pred: proc (x: T): bool {.closure.}) {.inline,
+    effectsOf: pred.}
+
+ +

Keeps the items in the passed sequence s if they fulfill the predicate pred (a function that returns a bool).

+

Note that s must be declared as a var.

+

Similar to the filter proc, but modifies the sequence directly.

+

See also:

+ + +

Example:

+
var floats = @[13.0, 12.5, 5.8, 2.0, 6.1, 9.9, 10.1]
+keepIf(floats, proc(x: float): bool = x > 10)
+assert floats == @[13.0, 12.5, 10.1]
+ Source   +Edit   + +
+
+ +
+
+
+
proc map[T, S](s: openArray[T]; op: proc (x: T): S {.closure.}): seq[S] {.
+    inline, effectsOf: op.}
+
+ +

Returns a new sequence with the results of the op proc applied to every item in the container s.

+

Since the input is not modified, you can use it to transform the type of the elements in the input container.

+

Instead of using map and filter, consider using the collect macro from the sugar module.

+

See also:

+ + +

Example:

+
let
+  a = @[1, 2, 3, 4]
+  b = map(a, proc(x: int): string = $x)
+assert b == @["1", "2", "3", "4"]
+ Source   +Edit   + +
+
+ +
+
+
+
func maxIndex[T](s: openArray[T]): int
+
+ + Returns the index of the maximum value of s. T needs to have a < operator. +

Example:

+
let
+  a = @[1, 2, 3, 4]
+  b = @[6, 5, 4, 3]
+  c = [2, -7, 8, -5]
+  d = "ziggy"
+assert maxIndex(a) == 3
+assert maxIndex(b) == 0
+assert maxIndex(c) == 2
+assert maxIndex(d) == 0
+ Source   +Edit   + +
+
+ +
+
+
+
func minIndex[T](s: openArray[T]): int
+
+ + Returns the index of the minimum value of s. T needs to have a < operator. +

Example:

+
let
+  a = @[1, 2, 3, 4]
+  b = @[6, 5, 4, 3]
+  c = [2, -7, 8, -5]
+  d = "ziggy"
+assert minIndex(a) == 0
+assert minIndex(b) == 3
+assert minIndex(c) == 1
+assert minIndex(d) == 2
+ Source   +Edit   + +
+
+ +
+
+
+
func minmax[T](x: openArray[T]): (T, T)
+
+ + The minimum and maximum values of x. T needs to have a < operator. + Source   +Edit   + +
+
+ +
+
+
+
proc repeat[T](x: T; n: Natural): seq[T]
+
+ + Returns a new sequence with the item x repeated n times. n must be a non-negative number (zero or more). +

Example:

+
let
+  total = repeat(5, 3)
+assert total == @[5, 5, 5]
+ Source   +Edit   + +
+
+ +
+
+
+
proc unzip[S, T](s: openArray[(S, T)]): (seq[S], seq[T])
+
+ + Returns a tuple of two sequences split out from a sequence of 2-field tuples. +

Example:

+
let
+  zipped = @[(1, 'a'), (2, 'b'), (3, 'c')]
+  unzipped1 = @[1, 2, 3]
+  unzipped2 = @['a', 'b', 'c']
+assert zipped.unzip() == (unzipped1, unzipped2)
+assert zip(unzipped1, unzipped2).unzip() == (unzipped1, unzipped2)
+ Source   +Edit   + +
+
+ +
+
+
+
proc zip[S, T](s1: openArray[S]; s2: openArray[T]): seq[(S, T)]
+
+ +

Returns a new sequence with a combination of the two input containers.

+

The input containers can be of different types. If one container is shorter, the remaining items in the longer container are discarded.

+

Note: For Nim 1.0.x and older version, zip returned a seq of named tuples with fields a and b. For Nim versions 1.1.x and newer, zip returns a seq of unnamed tuples.

+ +

Example:

+
let
+  short = @[1, 2, 3]
+  long = @[6, 5, 4, 3, 2, 1]
+  words = @["one", "two", "three"]
+  letters = "abcd"
+  zip1 = zip(short, long)
+  zip2 = zip(short, words)
+assert zip1 == @[(1, 6), (2, 5), (3, 4)]
+assert zip2 == @[(1, "one"), (2, "two"), (3, "three")]
+assert zip1[2][0] == 3
+assert zip2[1][1] == "two"
+when (NimMajor, NimMinor) <= (1, 0):
+  let
+    zip3 = zip(long, letters)
+  assert zip3 == @[(a: 6, b: 'a'), (5, 'b'), (4, 'c'), (3, 'd')]
+  assert zip3[0].b == 'a'
+else:
+  let
+    zip3: seq[tuple[num: int, letter: char]] = zip(long, letters)
+  assert zip3 == @[(6, 'a'), (5, 'b'), (4, 'c'), (3, 'd')]
+  assert zip3[0].letter == 'a'
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator filter[T](s: openArray[T]; pred: proc (x: T): bool {.closure.}): T {.
+    effectsOf: pred.}
+
+ +

Iterates through a container s and yields every item that fulfills the predicate pred (a function that returns a bool).

+

Instead of using map and filter, consider using the collect macro from the sugar module.

+

See also:

+ + +

Example:

+
let numbers = @[1, 4, 5, 8, 9, 7, 4]
+var evens = newSeq[int]()
+for n in filter(numbers, proc (x: int): bool = x mod 2 == 0):
+  evens.add(n)
+assert evens == @[4, 8, 4]
+ Source   +Edit   + +
+
+ +
+
+
+
iterator items[T](xs: iterator (): T): T
+
+ + Iterates over each element yielded by a closure iterator. This may not seem particularly useful on its own, but this allows closure iterators to be used by the mapIt, filterIt, allIt, anyIt, etc. templates. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro mapLiterals(constructor, op: untyped; nested = true): untyped
+
+ + Applies op to each of the atomic literals like 3 or "abc" in the specified constructor AST. This can be used to map every array element to some target type: +

Example:

+
let x = mapLiterals([0.1, 1.2, 2.3, 3.4], int)
+doAssert x is array[4, int]
+doAssert x == [int(0.1), int(1.2), int(2.3), int(3.4)]
If nested is true (which is the default), the literals are replaced everywhere in the constructor AST, otherwise only the first level is considered: +

Example:

+
let a = mapLiterals((1.2, (2.3, 3.4), 4.8), int)
+let b = mapLiterals((1.2, (2.3, 3.4), 4.8), int, nested=false)
+assert a == (1, (2, 3), 4)
+assert b == (1, (2.3, 3.4), 4)
+
+let c = mapLiterals((1, (2, 3), 4, (5, 6)), `$`)
+let d = mapLiterals((1, (2, 3), 4, (5, 6)), `$`, nested=false)
+assert c == ("1", ("2", "3"), "4", ("5", "6"))
+assert d == ("1", (2, 3), "4", (5, 6))
There are no constraints for the constructor AST, it works for nested tuples of arrays of sets etc. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template allIt(s, pred: untyped): bool
+
+ +

Iterates through a container and checks if every item fulfills the predicate.

+

Unlike the all proc, the predicate needs to be an expression using the it variable for testing, like: allIt("abba", it == 'a').

+

See also:

+ + +

Example:

+
let numbers = @[1, 4, 5, 8, 9, 7, 4]
+assert numbers.allIt(it < 10) == true
+assert numbers.allIt(it < 9) == false
+ Source   +Edit   + +
+
+ +
+
+
+
template anyIt(s, pred: untyped): bool
+
+ +

Iterates through a container and checks if at least one item fulfills the predicate.

+

Unlike the any proc, the predicate needs to be an expression using the it variable for testing, like: anyIt("abba", it == 'a').

+

See also:

+ + +

Example:

+
let numbers = @[1, 4, 5, 8, 9, 7, 4]
+assert numbers.anyIt(it > 8) == true
+assert numbers.anyIt(it > 9) == false
+ Source   +Edit   + +
+
+ +
+
+
+
template applyIt(varSeq, op: untyped)
+
+ +

Convenience template around the mutable apply proc to reduce typing.

+

The template injects the it variable which you can use directly in an expression. The expression has to return the same type as the elements of the sequence you are mutating.

+

See also:

+ + +

Example:

+
var nums = @[1, 2, 3, 4]
+nums.applyIt(it * 3)
+assert nums[0] + nums[3] == 15
+ Source   +Edit   + +
+
+ +
+
+
+
template countIt(s, pred: untyped): int
+
+ +

Returns a count of all the items that fulfill the predicate.

+

The predicate needs to be an expression using the it variable for testing, like: countIt(@[1, 2, 3], it > 2).

+ +

Example:

+
let numbers = @[-3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
+iterator iota(n: int): int =
+  for i in 0..<n: yield i
+assert numbers.countIt(it < 0) == 3
+assert countIt(iota(10), it < 2) == 2
+ Source   +Edit   + +
+
+ +
+
+
+
template filterIt(s, pred: untyped): untyped
+
+ +

Returns a new sequence with all the items of s that fulfill the predicate pred.

+

Unlike the filter proc and filter iterator, the predicate needs to be an expression using the it variable for testing, like: filterIt("abcxyz", it == 'x').

+

Instead of using mapIt and filterIt, consider using the collect macro from the sugar module.

+

See also:

+ + +

Example:

+
let
+  temperatures = @[-272.15, -2.0, 24.5, 44.31, 99.9, -113.44]
+  acceptable = temperatures.filterIt(it < 50 and it > -10)
+  notAcceptable = temperatures.filterIt(it > 50 or it < -10)
+assert acceptable == @[-2.0, 24.5, 44.31]
+assert notAcceptable == @[-272.15, 99.9, -113.44]
+ Source   +Edit   + +
+
+ +
+
+
+
template foldl(sequence, operation, first): untyped
+
+ +

Template to fold a sequence from left to right, returning the accumulation.

+

This version of foldl gets a starting parameter. This makes it possible to accumulate the sequence into a different type than the sequence elements.

+

The operation parameter should be an expression which uses the variables a and b for each step of the fold. The first parameter is the start value (the first a) and therefore defines the type of the result.

+

See also:

+ + +

Example:

+
let
+  numbers = @[0, 8, 1, 5]
+  digits = foldl(numbers, a & (chr(b + ord('0'))), "")
+assert digits == "0815"
+ Source   +Edit   + +
+
+
+
template foldl(sequence, operation: untyped): untyped
+
+ +

Template to fold a sequence from left to right, returning the accumulation.

+

The sequence is required to have at least a single element. Debug versions of your program will assert in this situation but release versions will happily go ahead. If the sequence has a single element it will be returned without applying operation.

+

The operation parameter should be an expression which uses the variables a and b for each step of the fold. Since this is a left fold, for non associative binary operations like subtraction think that the sequence of numbers 1, 2 and 3 will be parenthesized as (((1) - 2) - 3).

+

See also:

+ + +

Example:

+
let
+  numbers = @[5, 9, 11]
+  addition = foldl(numbers, a + b)
+  subtraction = foldl(numbers, a - b)
+  multiplication = foldl(numbers, a * b)
+  words = @["nim", "is", "cool"]
+  concatenation = foldl(words, a & b)
+  procs = @["proc", "Is", "Also", "Fine"]
+
+
+func foo(acc, cur: string): string =
+  result = acc & cur
+
+assert addition == 25, "Addition is (((5)+9)+11)"
+assert subtraction == -15, "Subtraction is (((5)-9)-11)"
+assert multiplication == 495, "Multiplication is (((5)*9)*11)"
+assert concatenation == "nimiscool"
+assert foldl(procs, foo(a, b)) == "procIsAlsoFine"
+ Source   +Edit   + +
+
+ +
+
+
+
template foldr(sequence, operation: untyped): untyped
+
+ +

Template to fold a sequence from right to left, returning the accumulation.

+

The sequence is required to have at least a single element. Debug versions of your program will assert in this situation but release versions will happily go ahead. If the sequence has a single element it will be returned without applying operation.

+

The operation parameter should be an expression which uses the variables a and b for each step of the fold. Since this is a right fold, for non associative binary operations like subtraction think that the sequence of numbers 1, 2 and 3 will be parenthesized as (1 - (2 - (3))).

+

See also:

+ + +

Example:

+
let
+  numbers = @[5, 9, 11]
+  addition = foldr(numbers, a + b)
+  subtraction = foldr(numbers, a - b)
+  multiplication = foldr(numbers, a * b)
+  words = @["nim", "is", "cool"]
+  concatenation = foldr(words, a & b)
+assert addition == 25, "Addition is (5+(9+(11)))"
+assert subtraction == 7, "Subtraction is (5-(9-(11)))"
+assert multiplication == 495, "Multiplication is (5*(9*(11)))"
+assert concatenation == "nimiscool"
+ Source   +Edit   + +
+
+ +
+
+
+
template keepItIf(varSeq: seq; pred: untyped)
+
+ +

Keeps the items in the passed sequence (must be declared as a var) if they fulfill the predicate.

+

Unlike the keepIf proc, the predicate needs to be an expression using the it variable for testing, like: keepItIf("abcxyz", it == 'x').

+

See also:

+ + +

Example:

+
var candidates = @["foo", "bar", "baz", "foobar"]
+candidates.keepItIf(it.len == 3 and it[0] == 'b')
+assert candidates == @["bar", "baz"]
+ Source   +Edit   + +
+
+ +
+
+
+
template mapIt(s: typed; op: untyped): untyped
+
+ +

Returns a new sequence with the results of the op proc applied to every item in the container s.

+

Since the input is not modified you can use it to transform the type of the elements in the input container.

+

The template injects the it variable which you can use directly in an expression.

+

Instead of using mapIt and filterIt, consider using the collect macro from the sugar module.

+

See also:

+ + +

Example:

+
let
+  nums = @[1, 2, 3, 4]
+  strings = nums.mapIt($(4 * it))
+assert strings == @["4", "8", "12", "16"]
+ Source   +Edit   + +
+
+ +
+
+
+
template newSeqWith(len: int; init: untyped): untyped
+
+ +

Creates a new seq of length len, calling init to initialize each value of the seq.

+

Useful for creating "2D" seqs - seqs containing other seqs or to populate fields of the created seq.

+ +

Example:

+
## Creates a seq containing 5 bool seqs, each of length of 3.
+var seq2D = newSeqWith(5, newSeq[bool](3))
+assert seq2D.len == 5
+assert seq2D[0].len == 3
+assert seq2D[4][2] == false
+
+## Creates a seq with random numbers
+import std/random
+var seqRand = newSeqWith(20, rand(1.0))
+assert seqRand[0] != seqRand[1]
+ Source   +Edit   + +
+
+ +
+
+
+
template toSeq(iter: untyped): untyped
+
+ + Transforms any iterable (anything that can be iterated over, e.g. with a for-loop) into a sequence. +

Example:

+
let
+  myRange = 1..5
+  mySet: set[int8] = {5'i8, 3, 1}
+assert typeof(myRange) is HSlice[system.int, system.int]
+assert typeof(mySet) is set[int8]
+
+let
+  mySeq1 = toSeq(myRange)
+  mySeq2 = toSeq(mySet)
+assert mySeq1 == @[1, 2, 3, 4, 5]
+assert mySeq2 == @[1'i8, 3, 5]
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/sequtils.idx b/sequtils.idx new file mode 100644 index 0000000000000..5a5fe1584930d --- /dev/null +++ b/sequtils.idx @@ -0,0 +1,44 @@ +nimTitle sequtils sequtils.html module std/sequtils 0 +nim concat sequtils.html#concat,varargs[seq[T]] proc concat[T](seqs: varargs[seq[T]]): seq[T] 119 +nim addUnique sequtils.html#addUnique,seq[T],sinkT proc addUnique[T](s: var seq[T]; x: sink T) 144 +nim count sequtils.html#count,openArray[T],T proc count[T](s: openArray[T]; x: T): int 160 +nim cycle sequtils.html#cycle,openArray[T],Natural proc cycle[T](s: openArray[T]; n: Natural): seq[T] 175 +nim repeat sequtils.html#repeat,T,Natural proc repeat[T](x: T; n: Natural): seq[T] 193 +nim deduplicate sequtils.html#deduplicate,openArray[T],bool proc deduplicate[T](s: openArray[T]; isSorted: bool = false): seq[T] 206 +nim minIndex sequtils.html#minIndex,openArray[T] proc minIndex[T](s: openArray[T]): int 234 +nim maxIndex sequtils.html#maxIndex,openArray[T] proc maxIndex[T](s: openArray[T]): int 251 +nim minmax sequtils.html#minmax,openArray[T] proc minmax[T](x: openArray[T]): (T, T) 268 +nim zip sequtils.html#zip,, proc zip[S, T](s1: openArray[S]; s2: openArray[T]): seq[(S, T)] 320 +nim unzip sequtils.html#unzip,openArray[] proc unzip[S, T](s: openArray[(S, T)]): (seq[S], seq[T]) 322 +nim distribute sequtils.html#distribute,seq[T],Positive proc distribute[T](s: seq[T]; num: Positive; spread = true): seq[seq[T]] 336 +nim map sequtils.html#map,openArray[T],proc(T) proc map[T, S](s: openArray[T]; op: proc (x: T): S {.closure.}): seq[S] 392 +nim apply sequtils.html#apply,openArray[T],proc(T) proc apply[T](s: var openArray[T]; op: proc (x: var T) {.closure.}) 418 +nim apply sequtils.html#apply,openArray[T],proc(T)_2 proc apply[T](s: var openArray[T]; op: proc (x: T): T {.closure.}) 437 +nim apply sequtils.html#apply,openArray[T],proc(T)_3 proc apply[T](s: openArray[T]; op: proc (x: T) {.closure.}) 457 +nim filter sequtils.html#filter.i,openArray[T],proc(T) iterator filter[T](s: openArray[T]; pred: proc (x: T): bool {.closure.}): T 466 +nim filter sequtils.html#filter,openArray[T],proc(T) proc filter[T](s: openArray[T]; pred: proc (x: T): bool {.closure.}): seq[T] 489 +nim keepIf sequtils.html#keepIf,seq[T],proc(T) proc keepIf[T](s: var seq[T]; pred: proc (x: T): bool {.closure.}) 516 +nim delete sequtils.html#delete,seq[T],Slice[int] proc delete[T](s: var seq[T]; slice: Slice[int]) 546 +nim delete sequtils.html#delete,seq[T],Natural,Natural proc delete[T](s: var seq[T]; first, last: Natural) 586 +nim insert sequtils.html#insert,seq[T],openArray[T],int proc insert[T](dest: var seq[T]; src: openArray[T]; pos = 0) 610 +nim filterIt sequtils.html#filterIt.t,untyped,untyped template filterIt(s, pred: untyped): untyped 644 +nim keepItIf sequtils.html#keepItIf.t,seq,untyped template keepItIf(varSeq: seq; pred: untyped) 674 +nim countIt sequtils.html#countIt.t,untyped,untyped template countIt(s, pred: untyped): int 704 +nim all sequtils.html#all,openArray[T],proc(T) proc all[T](s: openArray[T]; pred: proc (x: T): bool {.closure.}): bool 722 +nim allIt sequtils.html#allIt.t,untyped,untyped template allIt(s, pred: untyped): bool 740 +nim any sequtils.html#any,openArray[T],proc(T) proc any[T](s: openArray[T]; pred: proc (x: T): bool {.closure.}): bool 764 +nim anyIt sequtils.html#anyIt.t,untyped,untyped template anyIt(s, pred: untyped): bool 782 +nim toSeq sequtils.html#toSeq.t,untyped template toSeq(iter: untyped): untyped 847 +nim foldl sequtils.html#foldl.t,untyped,untyped template foldl(sequence, operation: untyped): untyped 885 +nim foldl sequtils.html#foldl.t,,, template foldl(sequence, operation, first): untyped 934 +nim foldr sequtils.html#foldr.t,untyped,untyped template foldr(sequence, operation: untyped): untyped 961 +nim mapIt sequtils.html#mapIt.t,typed,untyped template mapIt(s: typed; op: untyped): untyped 1003 +nim applyIt sequtils.html#applyIt.t,untyped,untyped template applyIt(varSeq, op: untyped) 1068 +nim newSeqWith sequtils.html#newSeqWith.t,int,untyped template newSeqWith(len: int; init: untyped): untyped 1089 +nim mapLiterals sequtils.html#mapLiterals.m,untyped,untyped macro mapLiterals(constructor, op: untyped; nested = true): untyped 1130 +nim items sequtils.html#items.i iterator items[T](xs: iterator (): T): T 1156 +idx seq sequtils.html#seq_1 Module sequtils 0 +heading See also sequtils.html#see-also See also 0 +nimgrp apply sequtils.html#apply-procs-all proc 418 +nimgrp delete sequtils.html#delete-procs-all proc 546 +nimgrp foldl sequtils.html#foldl-templates-all template 885 diff --git a/sets.html b/sets.html new file mode 100644 index 0000000000000..32dd8ebfc4842 --- /dev/null +++ b/sets.html @@ -0,0 +1,1418 @@ + + + + + + + +std/sets + + + + + + + + + + + + + + + + +
+
+

std/sets

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

The sets module implements an efficient hash set and ordered hash set.

+

Hash sets are different from the built in set type. Sets allow you to store any value that can be hashed and they don't contain duplicate entries.

+

Common usages of sets:

+ +

Examples:

+

echo toHashSet([9, 5, 1])     # {9, 1, 5}
+echo toOrderedSet([9, 5, 1])  # {9, 5, 1}
+
+let
+  s1 = toHashSet([9, 5, 1])
+  s2 = toHashSet([3, 5, 7])
+
+echo s1 + s2    # {9, 1, 3, 5, 7}
+echo s1 - s2    # {1, 9}
+echo s1 * s2    # {5}
+echo s1 -+- s2  # {9, 1, 3, 7}

+

Note: The data types declared here have value semantics: This means that = performs a copy of the set.

+

See also:

+ +

+ +
+

Types

+
+
+
HashSet[A] {..} = object
+
+ +

+A generic hash set.

+

Use init proc or initHashSet proc before calling other procs on it.

+ + Source   +Edit   + +
+
+
+
OrderedSet[A] {..} = object
+
+ +

+A generic hash set that remembers insertion order.

+

Use init proc or initOrderedSet proc before calling other procs on it.

+ + Source   +Edit   + +
+
+
+
SomeSet[A] = HashSet[A] | OrderedSet[A]
+
+ + Type union representing HashSet or OrderedSet. + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
defaultInitialSize = 64
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`[A](s: HashSet[A]): string
+
+ +

Converts the set s to a string, mostly for logging and printing purposes.

+

Don't use this proc for serialization, the representation may change at any moment and values are not escaped.

+

Examples:

+

echo toHashSet([2, 4, 5])
+# --> {2, 4, 5}
+echo toHashSet(["no", "esc'aping", "is \" provided"])
+# --> {no, esc'aping, is " provided}

+ + Source   +Edit   + +
+
+
+
proc `$`[A](s: OrderedSet[A]): string
+
+ +

Converts the ordered hash set s to a string, mostly for logging and printing purposes.

+

Don't use this proc for serialization, the representation may change at any moment and values are not escaped.

+

Examples:

+

echo toOrderedSet([2, 4, 5])
+# --> {2, 4, 5}
+echo toOrderedSet(["no", "esc'aping", "is \" provided"])
+# --> {no, esc'aping, is " provided}

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `*`[A](s1, s2: HashSet[A]): HashSet[A] {.inline.}
+
+ + Alias for intersection(s1, s2). + Source   +Edit   + +
+
+ +
+
+
+
proc `+`[A](s1, s2: HashSet[A]): HashSet[A] {.inline.}
+
+ + Alias for union(s1, s2). + Source   +Edit   + +
+
+ +
+
+
+
proc `-`[A](s1, s2: HashSet[A]): HashSet[A] {.inline.}
+
+ + Alias for difference(s1, s2). + Source   +Edit   + +
+
+ +
+
+
+
proc `-+-`[A](s1, s2: HashSet[A]): HashSet[A] {.inline.}
+
+ + Alias for symmetricDifference(s1, s2). + Source   +Edit   + +
+
+ +
+
+
+
proc `<`[A](s, t: HashSet[A]): bool
+
+ +

Returns true if s is a strict or proper subset of t.

+

A strict or proper subset s has all of its members in t but t has more elements than s.

+ +

Example:

+
let
+  a = toHashSet(["a", "b"])
+  b = toHashSet(["b", "c"])
+  c = intersection(a, b)
+assert c < a and c < b
+assert(not (a < a))
+ Source   +Edit   + +
+
+ +
+
+
+
proc `<=`[A](s, t: HashSet[A]): bool
+
+ +

Returns true if s is a subset of t.

+

A subset s has all of its members in t and t doesn't necessarily have more members than s. That is, s can be equal to t.

+ +

Example:

+
let
+  a = toHashSet(["a", "b"])
+  b = toHashSet(["b", "c"])
+  c = intersection(a, b)
+assert c <= a and c <= b
+assert a <= a
+ Source   +Edit   + +
+
+ +
+
+
+
proc `==`[A](s, t: HashSet[A]): bool
+
+ + Returns true if both s and t have the same members and set size. +

Example:

+
var
+  a = toHashSet([1, 2])
+  b = toHashSet([2, 1])
+assert a == b
+ Source   +Edit   + +
+
+
+
proc `==`[A](s, t: OrderedSet[A]): bool
+
+ + Equality for ordered sets. +

Example:

+
let
+  a = toOrderedSet([1, 2])
+  b = toOrderedSet([2, 1])
+assert(not (a == b))
+ Source   +Edit   + +
+
+ +
+
+
+
proc `[]`[A](s: var HashSet[A]; key: A): var A
+
+ +

Returns the element that is actually stored in s which has the same value as key or raises the KeyError exception.

+

This is useful when one overloaded hash and == but still needs reference semantics for sharing.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc card[A](s: HashSet[A]): int
+
+ +

Alias for len().

+

Card stands for the cardinality of a set.

+ + Source   +Edit   + +
+
+
+
proc card[A](s: OrderedSet[A]): int {.inline.}
+
+ +

Alias for len().

+

Card stands for the cardinality of a set.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc clear[A](s: var HashSet[A])
+
+ +

Clears the HashSet back to an empty state, without shrinking any of the existing storage.

+

O(n) operation, where n is the size of the hash bucket.

+

See also:

+ + +

Example:

+
var s = toHashSet([3, 5, 7])
+clear(s)
+assert len(s) == 0
+ Source   +Edit   + +
+
+
+
proc clear[A](s: var OrderedSet[A])
+
+ +

Clears the OrderedSet back to an empty state, without shrinking any of the existing storage.

+

O(n) operation where n is the size of the hash bucket.

+ +

Example:

+
var s = toOrderedSet([3, 5, 7])
+clear(s)
+assert len(s) == 0
+ Source   +Edit   + +
+
+ +
+
+
+
proc contains[A](s: HashSet[A]; key: A): bool
+
+ +

Returns true if key is in s.

+

This allows the usage of in operator.

+

See also:

+ + +

Example:

+
var values = initHashSet[int]()
+assert(not values.contains(2))
+assert 2 notin values
+
+values.incl(2)
+assert values.contains(2)
+assert 2 in values
+ Source   +Edit   + +
+
+
+
proc contains[A](s: OrderedSet[A]; key: A): bool
+
+ +

Returns true if key is in s.

+

This allows the usage of in operator.

+

See also:

+ + +

Example:

+
var values = initOrderedSet[int]()
+assert(not values.contains(2))
+assert 2 notin values
+
+values.incl(2)
+assert values.contains(2)
+assert 2 in values
+ Source   +Edit   + +
+
+ +
+
+
+
proc containsOrIncl[A](s: var HashSet[A]; key: A): bool
+
+ +

Includes key in the set s and tells if key was already in s.

+

The difference with regards to the incl proc is that this proc returns true if s already contained key. The proc will return false if key was added as a new value to s during this call.

+

See also:

+ + +

Example:

+
var values = initHashSet[int]()
+assert values.containsOrIncl(2) == false
+assert values.containsOrIncl(2) == true
+assert values.containsOrIncl(3) == false
+ Source   +Edit   + +
+
+
+
proc containsOrIncl[A](s: var OrderedSet[A]; key: A): bool
+
+ +

Includes key in the set s and tells if key was already in s.

+

The difference with regards to the incl proc is that this proc returns true if s already contained key. The proc will return false if key was added as a new value to s during this call.

+

See also:

+ + +

Example:

+
var values = initOrderedSet[int]()
+assert values.containsOrIncl(2) == false
+assert values.containsOrIncl(2) == true
+assert values.containsOrIncl(3) == false
+ Source   +Edit   + +
+
+ +
+
+
+
proc difference[A](s1, s2: HashSet[A]): HashSet[A]
+
+ +

Returns the difference of the sets s1 and s2.

+

The same as s1 - s2.

+

The difference of two sets is represented mathematically as A ∖ B and is the set of all objects that are members of s1 and not members of s2.

+

See also:

+ + +

Example:

+
let
+  a = toHashSet(["a", "b"])
+  b = toHashSet(["b", "c"])
+  c = difference(a, b)
+assert c == toHashSet(["a"])
+ Source   +Edit   + +
+
+ +
+
+
+
proc disjoint[A](s1, s2: HashSet[A]): bool
+
+ + Returns true if the sets s1 and s2 have no items in common. +

Example:

+
let
+  a = toHashSet(["a", "b"])
+  b = toHashSet(["b", "c"])
+assert disjoint(a, b) == false
+assert disjoint(a, b - a) == true
+ Source   +Edit   + +
+
+ +
+
+
+
proc excl[A](s: var HashSet[A]; key: A)
+
+ +

Excludes key from the set s.

+

This doesn't do anything if key is not found in s.

+

See also:

+ + +

Example:

+
var s = toHashSet([2, 3, 6, 7])
+s.excl(2)
+s.excl(2)
+assert s.len == 3
+ Source   +Edit   + +
+
+
+
proc excl[A](s: var HashSet[A]; other: HashSet[A])
+
+ +

Excludes all elements of other set from s.

+

This is the in-place version of s - other.

+

See also:

+ + +

Example:

+
var
+  numbers = toHashSet([1, 2, 3, 4, 5])
+  even = toHashSet([2, 4, 6, 8])
+numbers.excl(even)
+assert len(numbers) == 3
+## numbers == {1, 3, 5}
+ Source   +Edit   + +
+
+
+
proc excl[A](s: var OrderedSet[A]; key: A)
+
+ +

Excludes key from the set s. Efficiency: O(n).

+

This doesn't do anything if key is not found in s.

+

See also:

+ + +

Example:

+
var s = toOrderedSet([2, 3, 6, 7])
+s.excl(2)
+s.excl(2)
+assert s.len == 3
+ Source   +Edit   + +
+
+ +
+
+
+
proc hash[A](s: HashSet[A]): Hash
+
+ + Hashing of HashSet. + Source   +Edit   + +
+
+
+
proc hash[A](s: OrderedSet[A]): Hash
+
+ + Hashing of OrderedSet. + Source   +Edit   + +
+
+ +
+
+
+
proc incl[A](s: var HashSet[A]; key: A)
+
+ +

Includes an element key in s.

+

This doesn't do anything if key is already in s.

+

See also:

+ + +

Example:

+
var values = initHashSet[int]()
+values.incl(2)
+values.incl(2)
+assert values.len == 1
+ Source   +Edit   + +
+
+
+
proc incl[A](s: var HashSet[A]; other: HashSet[A])
+
+ +

Includes all elements from other set into s (must be declared as var).

+

This is the in-place version of s + other.

+

See also:

+ + +

Example:

+
var
+  values = toHashSet([1, 2, 3])
+  others = toHashSet([3, 4, 5])
+values.incl(others)
+assert values.len == 5
+ Source   +Edit   + +
+
+
+
proc incl[A](s: var HashSet[A]; other: OrderedSet[A])
+
+ +

Includes all elements from the OrderedSet other into HashSet s (must be declared as var).

+

See also:

+ + +

Example:

+
var
+  values = toHashSet([1, 2, 3])
+  others = toOrderedSet([3, 4, 5])
+values.incl(others)
+assert values.len == 5
+ Source   +Edit   + +
+
+
+
proc incl[A](s: var OrderedSet[A]; key: A)
+
+ +

Includes an element key in s.

+

This doesn't do anything if key is already in s.

+

See also:

+ + +

Example:

+
var values = initOrderedSet[int]()
+values.incl(2)
+values.incl(2)
+assert values.len == 1
+ Source   +Edit   + +
+
+ +
+
+
+
proc init[A](s: var HashSet[A]; initialSize = defaultInitialSize)
+
+ +

Initializes a hash set.

+

Starting from Nim v0.20, sets are initialized by default and it is not necessary to call this function explicitly.

+

You can call this proc on a previously initialized hash set, which will discard all its values. This might be more convenient than iterating over existing values and calling excl() on them.

+

See also:

+ + +

Example:

+
var a: HashSet[int]
+init(a)
+ Source   +Edit   + +
+
+
+
proc init[A](s: var OrderedSet[A]; initialSize = defaultInitialSize)
+
+ +

Initializes an ordered hash set.

+

Starting from Nim v0.20, sets are initialized by default and it is not necessary to call this function explicitly.

+

You can call this proc on a previously initialized hash set, which will discard all its values. This might be more convenient than iterating over existing values and calling excl() on them.

+

See also:

+ + +

Example:

+
var a: OrderedSet[int]
+init(a)
+ Source   +Edit   + +
+
+ +
+
+
+
proc initHashSet[A](initialSize = defaultInitialSize): HashSet[A]
+
+ +

Wrapper around init proc for initialization of hash sets.

+

Returns an empty hash set you can assign directly in var blocks in a single line.

+

Starting from Nim v0.20, sets are initialized by default and it is not necessary to call this function explicitly.

+

See also:

+ + +

Example:

+
var a = initHashSet[int]()
+a.incl(3)
+assert len(a) == 1
+ Source   +Edit   + +
+
+ +
+
+
+
proc initOrderedSet[A](initialSize = defaultInitialSize): OrderedSet[A]
+
+ +

Wrapper around init proc for initialization of ordered hash sets.

+

Returns an empty ordered hash set you can assign directly in var blocks in a single line.

+

Starting from Nim v0.20, sets are initialized by default and it is not necessary to call this function explicitly.

+

See also:

+ + +

Example:

+
var a = initOrderedSet[int]()
+a.incl(3)
+assert len(a) == 1
+ Source   +Edit   + +
+
+ +
+
+
+
proc initSet[A](initialSize = defaultInitialSize): HashSet[A] {.
+    ...deprecated: "Deprecated since v0.20, use \'initHashSet\'".}
+
+
+ Deprecated: Deprecated since v0.20, use 'initHashSet' +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc intersection[A](s1, s2: HashSet[A]): HashSet[A]
+
+ +

Returns the intersection of the sets s1 and s2.

+

The same as s1 * s2.

+

The intersection of two sets is represented mathematically as A ∩ B and is the set of all objects that are members of s1 and s2 at the same time.

+

See also:

+ + +

Example:

+
let
+  a = toHashSet(["a", "b"])
+  b = toHashSet(["b", "c"])
+  c = intersection(a, b)
+assert c == toHashSet(["b"])
+ Source   +Edit   + +
+
+ +
+
+
+
proc isValid[A](s: HashSet[A]): bool {....deprecated: "Deprecated since v0.20; sets are initialized by default".}
+
+
+ Deprecated: Deprecated since v0.20; sets are initialized by default +
+ + Returns true if the set has been initialized (with initHashSet proc or init proc). +

Example:

+
proc savePreferences(options: HashSet[string]) =
+  assert options.isValid, "Pass an initialized set!"
+  # Do stuff here, may crash in release builds!
+ Source   +Edit   + +
+
+ +
+
+
+
proc len[A](s: HashSet[A]): int
+
+ +

Returns the number of elements in s.

+

Due to an implementation detail you can call this proc on variables which have not been initialized yet. The proc will return zero as the length then.

+ +

Example:

+
var a: HashSet[string]
+assert len(a) == 0
+let s = toHashSet([3, 5, 7])
+assert len(s) == 3
+ Source   +Edit   + +
+
+
+
proc len[A](s: OrderedSet[A]): int {.inline.}
+
+ +

Returns the number of elements in s.

+

Due to an implementation detail you can call this proc on variables which have not been initialized yet. The proc will return zero as the length then.

+ +

Example:

+
var a: OrderedSet[string]
+assert len(a) == 0
+let s = toHashSet([3, 5, 7])
+assert len(s) == 3
+ Source   +Edit   + +
+
+ +
+
+
+
proc map[A, B](data: HashSet[A]; op: proc (x: A): B {.closure.}): HashSet[B] {.
+    effectsOf: op.}
+
+ +

Returns a new set after applying op proc on each of the elements of data set.

+

You can use this proc to transform the elements from a set.

+ +

Example:

+
let
+  a = toHashSet([1, 2, 3])
+  b = a.map(proc (x: int): string = $x)
+assert b == toHashSet(["1", "2", "3"])
+ Source   +Edit   + +
+
+ +
+
+
+
proc missingOrExcl[A](s: var HashSet[A]; key: A): bool
+
+ +

Excludes key in the set s and tells if key was already missing from s.

+

The difference with regards to the excl proc is that this proc returns true if key was missing from s. The proc will return false if key was in s and it was removed during this call.

+

See also:

+ + +

Example:

+
var s = toHashSet([2, 3, 6, 7])
+assert s.missingOrExcl(4) == true
+assert s.missingOrExcl(6) == false
+assert s.missingOrExcl(6) == true
+ Source   +Edit   + +
+
+
+
proc missingOrExcl[A](s: var OrderedSet[A]; key: A): bool
+
+ +

Excludes key in the set s and tells if key was already missing from s. Efficiency: O(n).

+

The difference with regards to the excl proc is that this proc returns true if key was missing from s. The proc will return false if key was in s and it was removed during this call.

+

See also:

+ + +

Example:

+
var s = toOrderedSet([2, 3, 6, 7])
+assert s.missingOrExcl(4) == true
+assert s.missingOrExcl(6) == false
+assert s.missingOrExcl(6) == true
+ Source   +Edit   + +
+
+ +
+
+
+
proc pop[A](s: var HashSet[A]): A
+
+ +

Removes and returns an arbitrary element from the set s.

+

Raises KeyError if the set s is empty.

+

See also:

+ + +

Example:

+
var s = toHashSet([2, 1])
+assert [s.pop, s.pop] in [[1, 2], [2,1]] # order unspecified
+doAssertRaises(KeyError, echo s.pop)
+ Source   +Edit   + +
+
+ +
+
+
+
proc symmetricDifference[A](s1, s2: HashSet[A]): HashSet[A]
+
+ +

Returns the symmetric difference of the sets s1 and s2.

+

The same as s1 -+- s2.

+

The symmetric difference of two sets is represented mathematically as A △ B or A ⊖ B and is the set of all objects that are members of s1 or s2 but not both at the same time.

+

See also:

+ + +

Example:

+
let
+  a = toHashSet(["a", "b"])
+  b = toHashSet(["b", "c"])
+  c = symmetricDifference(a, b)
+assert c == toHashSet(["a", "c"])
+ Source   +Edit   + +
+
+ +
+
+
+
proc toHashSet[A](keys: openArray[A]): HashSet[A]
+
+ +

Creates a new hash set that contains the members of the given collection (seq, array, or string) keys.

+

Duplicates are removed.

+

See also:

+ + +

Example:

+
let
+  a = toHashSet([5, 3, 2])
+  b = toHashSet("abracadabra")
+assert len(a) == 3
+## a == {2, 3, 5}
+assert len(b) == 5
+## b == {'a', 'b', 'c', 'd', 'r'}
+ Source   +Edit   + +
+
+ +
+
+
+
proc toOrderedSet[A](keys: openArray[A]): OrderedSet[A]
+
+ +

Creates a new hash set that contains the members of the given collection (seq, array, or string) keys.

+

Duplicates are removed.

+

See also:

+ + +

Example:

+
let
+  a = toOrderedSet([5, 3, 2])
+  b = toOrderedSet("abracadabra")
+assert len(a) == 3
+## a == {5, 3, 2} # different than in HashSet
+assert len(b) == 5
+## b == {'a', 'b', 'r', 'c', 'd'} # different than in HashSet
+ Source   +Edit   + +
+
+ +
+
+
+
proc toSet[A](keys: openArray[A]): HashSet[A] {.
+    ...deprecated: "Deprecated since v0.20, use \'toHashSet\'".}
+
+
+ Deprecated: Deprecated since v0.20, use 'toHashSet' +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc union[A](s1, s2: HashSet[A]): HashSet[A]
+
+ +

Returns the union of the sets s1 and s2.

+

The same as s1 + s2.

+

The union of two sets is represented mathematically as A ∪ B and is the set of all objects that are members of s1, s2 or both.

+

See also:

+ + +

Example:

+
let
+  a = toHashSet(["a", "b"])
+  b = toHashSet(["b", "c"])
+  c = union(a, b)
+assert c == toHashSet(["a", "b", "c"])
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator items[A](s: HashSet[A]): A
+
+ +

Iterates over elements of the set s.

+

If you need a sequence with the elements you can use sequtils.toSeq template.

+

type
+  pair = tuple[a, b: int]
+var
+  a, b = initHashSet[pair]()
+a.incl((2, 3))
+a.incl((3, 2))
+a.incl((2, 3))
+for x, y in a.items:
+  b.incl((x - 2, y + 1))
+assert a.len == 2
+echo b
+# --> {(a: 1, b: 3), (a: 0, b: 4)}

+ + Source   +Edit   + +
+
+
+
iterator items[A](s: OrderedSet[A]): A
+
+ +

Iterates over keys in the ordered set s in insertion order.

+

If you need a sequence with the elements you can use sequtils.toSeq template.

+

var a = initOrderedSet[int]()
+for value in [9, 2, 1, 5, 1, 8, 4, 2]:
+  a.incl(value)
+for value in a.items:
+  echo "Got ", value
+# --> Got 9
+# --> Got 2
+# --> Got 1
+# --> Got 5
+# --> Got 8
+# --> Got 4

+ + Source   +Edit   + +
+
+ +
+
+
+
iterator pairs[A](s: OrderedSet[A]): tuple[a: int, b: A]
+
+ + Iterates through (position, value) tuples of OrderedSet s. +

Example:

+
let a = toOrderedSet("abracadabra")
+var p = newSeq[(int, char)]()
+for x in pairs(a):
+  p.add(x)
+assert p == @[(0, 'a'), (1, 'b'), (2, 'r'), (3, 'c'), (4, 'd')]
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/sets.idx b/sets.idx new file mode 100644 index 0000000000000..368fb6714d222 --- /dev/null +++ b/sets.idx @@ -0,0 +1,70 @@ +nimTitle sets sets.html module std/sets 0 +nim HashSet sets.html#HashSet object HashSet 66 +nim OrderedSet sets.html#OrderedSet object OrderedSet 78 +nim SomeSet sets.html#SomeSet type SomeSet 85 +nim defaultInitialSize sets.html#defaultInitialSize const defaultInitialSize 89 +nim init sets.html#init,HashSet[A] proc init[A](s: var HashSet[A]; initialSize = defaultInitialSize) 98 +nim initHashSet sets.html#initHashSet proc initHashSet[A](initialSize = defaultInitialSize): HashSet[A] 117 +nim `[]` sets.html#[],HashSet[A],A proc `[]`[A](s: var HashSet[A]; key: A): var A 136 +nim contains sets.html#contains,HashSet[A],A proc contains[A](s: HashSet[A]; key: A): bool 151 +nim len sets.html#len,HashSet[A] proc len[A](s: HashSet[A]): int 172 +nim card sets.html#card,HashSet[A] proc card[A](s: HashSet[A]): int 186 +nim incl sets.html#incl,HashSet[A],A proc incl[A](s: var HashSet[A]; key: A) 193 +nim incl sets.html#incl,HashSet[A],HashSet[A] proc incl[A](s: var HashSet[A]; other: HashSet[A]) 210 +nim toHashSet sets.html#toHashSet,openArray[A] proc toHashSet[A](keys: openArray[A]): HashSet[A] 228 +nim items sets.html#items.i,HashSet[A] iterator items[A](s: HashSet[A]): A 248 +nim containsOrIncl sets.html#containsOrIncl,HashSet[A],A proc containsOrIncl[A](s: var HashSet[A]; key: A): bool 274 +nim excl sets.html#excl,HashSet[A],A proc excl[A](s: var HashSet[A]; key: A) 294 +nim excl sets.html#excl,HashSet[A],HashSet[A] proc excl[A](s: var HashSet[A]; other: HashSet[A]) 311 +nim missingOrExcl sets.html#missingOrExcl,HashSet[A],A proc missingOrExcl[A](s: var HashSet[A]; key: A): bool 330 +nim pop sets.html#pop,HashSet[A] proc pop[A](s: var HashSet[A]): A 350 +nim clear sets.html#clear,HashSet[A] proc clear[A](s: var HashSet[A]) 369 +nim union sets.html#union,HashSet[A],HashSet[A] proc union[A](s1, s2: HashSet[A]): HashSet[A] 390 +nim intersection sets.html#intersection,HashSet[A],HashSet[A] proc intersection[A](s1, s2: HashSet[A]): HashSet[A] 412 +nim difference sets.html#difference,HashSet[A],HashSet[A] proc difference[A](s1, s2: HashSet[A]): HashSet[A] 443 +nim symmetricDifference sets.html#symmetricDifference,HashSet[A],HashSet[A] proc symmetricDifference[A](s1, s2: HashSet[A]): HashSet[A] 467 +nim `+` sets.html#+,HashSet[A],HashSet[A] proc `+`[A](s1, s2: HashSet[A]): HashSet[A] 491 +nim `*` sets.html#*,HashSet[A],HashSet[A] proc `*`[A](s1, s2: HashSet[A]): HashSet[A] 495 +nim `-` sets.html#-,HashSet[A],HashSet[A] proc `-`[A](s1, s2: HashSet[A]): HashSet[A] 499 +nim `-+-` sets.html#-+-,HashSet[A],HashSet[A] proc `-+-`[A](s1, s2: HashSet[A]): HashSet[A] 503 +nim disjoint sets.html#disjoint,HashSet[A],HashSet[A] proc disjoint[A](s1, s2: HashSet[A]): bool 508 +nim `<` sets.html#<,HashSet[A],HashSet[A] proc `<`[A](s, t: HashSet[A]): bool 521 +nim `<=` sets.html#<=,HashSet[A],HashSet[A] proc `<=`[A](s, t: HashSet[A]): bool 536 +nim `==` sets.html#==,HashSet[A],HashSet[A] proc `==`[A](s, t: HashSet[A]): bool 557 +nim map sets.html#map,HashSet[A],proc(A) proc map[A, B](data: HashSet[A]; op: proc (x: A): B {.closure.}): HashSet[B] 567 +nim hash sets.html#hash,HashSet[A] proc hash[A](s: HashSet[A]): Hash 581 +nim `$` sets.html#$,HashSet[A] proc `$`[A](s: HashSet[A]): string 587 +nim initSet sets.html#initSet proc initSet[A](initialSize = defaultInitialSize): HashSet[A] 603 +nim toSet sets.html#toSet,openArray[A] proc toSet[A](keys: openArray[A]): HashSet[A] 606 +nim isValid sets.html#isValid,HashSet[A] proc isValid[A](s: HashSet[A]): bool 609 +nim init sets.html#init,OrderedSet[A] proc init[A](s: var OrderedSet[A]; initialSize = defaultInitialSize) 638 +nim initOrderedSet sets.html#initOrderedSet proc initOrderedSet[A](initialSize = defaultInitialSize): OrderedSet[A] 657 +nim toOrderedSet sets.html#toOrderedSet,openArray[A] proc toOrderedSet[A](keys: openArray[A]): OrderedSet[A] 676 +nim contains sets.html#contains,OrderedSet[A],A proc contains[A](s: OrderedSet[A]; key: A): bool 696 +nim incl sets.html#incl,OrderedSet[A],A proc incl[A](s: var OrderedSet[A]; key: A) 717 +nim incl sets.html#incl,HashSet[A],OrderedSet[A] proc incl[A](s: var HashSet[A]; other: OrderedSet[A]) 734 +nim containsOrIncl sets.html#containsOrIncl,OrderedSet[A],A proc containsOrIncl[A](s: var OrderedSet[A]; key: A): bool 750 +nim excl sets.html#excl,OrderedSet[A],A proc excl[A](s: var OrderedSet[A]; key: A) 769 +nim missingOrExcl sets.html#missingOrExcl,OrderedSet[A],A proc missingOrExcl[A](s: var OrderedSet[A]; key: A): bool 785 +nim clear sets.html#clear,OrderedSet[A] proc clear[A](s: var OrderedSet[A]) 805 +nim len sets.html#len,OrderedSet[A] proc len[A](s: OrderedSet[A]): int 825 +nim card sets.html#card,OrderedSet[A] proc card[A](s: OrderedSet[A]): int 839 +nim `==` sets.html#==,OrderedSet[A],OrderedSet[A] proc `==`[A](s, t: OrderedSet[A]): bool 846 +nim hash sets.html#hash,OrderedSet[A] proc hash[A](s: OrderedSet[A]): Hash 870 +nim `$` sets.html#$,OrderedSet[A] proc `$`[A](s: OrderedSet[A]): string 876 +nim items sets.html#items.i,OrderedSet[A] iterator items[A](s: OrderedSet[A]): A 894 +nim pairs sets.html#pairs.i,OrderedSet[A] iterator pairs[A](s: OrderedSet[A]): tuple[a: int, b: A] 918 +idx hash set sets.html#hash-set_1 Module sets 0 +nimgrp missingorexcl sets.html#missingOrExcl-procs-all proc 330 +nimgrp excl sets.html#excl-procs-all proc 294 +nimgrp containsorincl sets.html#containsOrIncl-procs-all proc 274 +nimgrp == sets.html#==-procs-all proc 557 +nimgrp $ sets.html#$-procs-all proc 587 +nimgrp card sets.html#card-procs-all proc 186 +nimgrp contains sets.html#contains-procs-all proc 151 +nimgrp init sets.html#init-procs-all proc 98 +nimgrp incl sets.html#incl-procs-all proc 193 +nimgrp clear sets.html#clear-procs-all proc 369 +nimgrp len sets.html#len-procs-all proc 172 +nimgrp hash sets.html#hash-procs-all proc 581 +nimgrp items sets.html#items-iterators-all iterator 248 diff --git a/setutils.html b/setutils.html new file mode 100644 index 0000000000000..e0ac6f7c63c37 --- /dev/null +++ b/setutils.html @@ -0,0 +1,278 @@ + + + + + + + +std/setutils + + + + + + + + + + + + + + + + +
+
+

std/setutils

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module adds functionality for the built-in set type. +

See also

+

+ +
+

Procs

+
+
+
+
proc `-+-`[T](x, y: set[T]): set[T] {.inline.}
+
+ + Operator alias for symmetricDifference. +

Example:

+
assert {1, 2, 3} -+- {2, 3, 4} == {1, 4}
+ Source   +Edit   + +
+
+ +
+
+
+
func `[]=`[T](t: var set[T]; key: T; val: bool) {.inline.}
+
+ + Syntax sugar for if val: t.incl key else: t.excl key +

Example:

+
type A = enum
+  a0, a1, a2, a3
+var s = {a0, a3}
+s[a0] = false
+s[a1] = false
+assert s == {a3}
+s[a2] = true
+s[a3] = true
+assert s == {a2, a3}
+ Source   +Edit   + +
+
+ +
+
+
+
func complement[T](s: set[T]): set[T] {.inline.}
+
+ + Returns the set complement of a. +

Example:

+
type Colors = enum
+  red, green = 3, blue
+assert complement({red, blue}) == {green}
+assert complement({red, green, blue}).card == 0
+assert complement({range[0..10](0), 1, 2, 3}) == {range[0..10](4), 5, 6, 7, 8, 9, 10}
+assert complement({'0'..'9'}) == {0.char..255.char} - {'0'..'9'}
+ Source   +Edit   + +
+
+ +
+
+
+
func fullSet[T](U: typedesc[T]): set[T] {.inline.}
+
+ + Returns a set containing all elements in U. +

Example:

+
assert bool.fullSet == {true, false}
+type A = range[1..3]
+assert A.fullSet == {1.A, 2, 3}
+assert int8.fullSet.len == 256
+ Source   +Edit   + +
+
+ +
+
+
+
func symmetricDifference[T](x, y: set[T]): set[T] {.magic: "XorSet", ...raises: [],
+    tags: [], forbids: [].}
+
+ + This operator computes the symmetric difference of two sets, equivalent to but more efficient than x + y - x * y or (x - y) + (y - x). +

Example:

+
assert symmetricDifference({1, 2, 3}, {2, 3, 4}) == {1, 4}
+ Source   +Edit   + +
+
+ +
+
+
+
proc toggle[T](x: var set[T]; y: set[T]) {.inline.}
+
+ + Toggles the existence of each value of y in x. If any element in y is also in x, it is excluded from x; otherwise it is included. Equivalent to x = symmetricDifference(x, y). +

Example:

+
var x = {1, 2, 3}
+x.toggle({2, 3, 4})
+assert x == {1, 4}
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template toSet(iter: untyped): untyped
+
+ + Returns a built-in set from the elements of the iterable iter. +

Example:

+
assert "helloWorld".toSet == {'W', 'd', 'e', 'h', 'l', 'o', 'r'}
+assert toSet([10u16, 20, 30]) == {10u16, 20, 30}
+assert [30u8, 100, 10].toSet == {10u8, 30, 100}
+assert toSet(@[1321i16, 321, 90]) == {90i16, 321, 1321}
+assert toSet([false]) == {false}
+assert toSet(0u8..10) == {0u8..10}
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/setutils.idx b/setutils.idx new file mode 100644 index 0000000000000..f73e12ab44526 --- /dev/null +++ b/setutils.idx @@ -0,0 +1,9 @@ +nimTitle setutils setutils.html module std/setutils 0 +nim toSet setutils.html#toSet.t,untyped template toSet(iter: untyped): untyped 24 +nim fullSet setutils.html#fullSet,typedesc[T] proc fullSet[T](U: typedesc[T]): set[T] 42 +nim complement setutils.html#complement,set[T] proc complement[T](s: set[T]): set[T] 54 +nim `[]=` setutils.html#[]=,set[T],T,bool proc `[]=`[T](t: var set[T]; key: T; val: bool) 65 +nim symmetricDifference setutils.html#symmetricDifference,set[T],set[T] proc symmetricDifference[T](x, y: set[T]): set[T] 80 +nim `-+-` setutils.html#-+-,set[T],set[T] proc `-+-`[T](x, y: set[T]): set[T] 90 +nim toggle setutils.html#toggle,set[T],set[T] proc toggle[T](x: var set[T]; y: set[T]) 96 +heading See also setutils.html#see-also See also 0 diff --git a/sexp.html b/sexp.html new file mode 100644 index 0000000000000..aaeecaa2b0da2 --- /dev/null +++ b/sexp.html @@ -0,0 +1,1019 @@ + + + + + + + +sexp + + + + + + + + + + + + + + + + +
+
+

sexp

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Note: Import nimsuggest/sexp to use this module

+
+

Types

+
+
+
SexpError = enum
+  errNone,                  ## no error
+  errInvalidToken,          ## invalid token
+  errParensRiExpected,      ## ``)`` expected
+  errQuoteExpected,         ## ``"`` expected
+  errEofExpected             ## EOF expected
+
+ + enumeration that lists all errors that can occur + Source   +Edit   + +
+
+
+
SexpEventKind = enum
+  sexpError,                ## an error occurred during parsing
+  sexpEof,                  ## end of file reached
+  sexpString,               ## a string literal
+  sexpSymbol,               ## a symbol
+  sexpInt,                  ## an integer literal
+  sexpFloat,                ## a float literal
+  sexpNil,                  ## the value ``nil``
+  sexpDot,                  ## the dot to separate car/cdr
+  sexpListStart,            ## start of a list: the ``(`` token
+  sexpListEnd                ## end of a list: the ``)`` token
+
+ + enumeration of all events that may occur when parsing + Source   +Edit   + +
+
+
+
SexpNode = ref SexpNodeObj
+
+ + SEXP node + Source   +Edit   + +
+
+
+
SexpNodeKind = enum
+  SNil, SInt, SFloat, SString, SSymbol, SList, SCons
+
+ + possible SEXP node types + Source   +Edit   + +
+
+
+
SexpNodeObj {.acyclic.} = object
+  case kind*: SexpNodeKind
+  of SString:
+    str*: string
+  of SSymbol:
+    symbol*: string
+  of SInt:
+    num*: BiggestInt
+  of SFloat:
+    fnum*: float
+  of SList:
+    elems*: seq[SexpNode]
+  of SCons:
+  of SNil:
+    nil
+
+ + + Source   +Edit   + +
+
+
+
SexpParser = object of BaseLexer
+
+ + the parser object. + Source   +Edit   + +
+
+
+
SexpParsingError = object of ValueError
+
+ + is raised for a SEXP error + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(node: SexpNode): string {....raises: [], tags: [], forbids: [].}
+
+ + Converts node to its SEXP Representation on one line. + Source   +Edit   + +
+
+ +
+
+
+
func `==`(a, b: SexpNode): bool {....raises: [Exception], tags: [RootEffect],
+                                  forbids: [].}
+
+ + Check two nodes for equality + Source   +Edit   + +
+
+ +
+
+
+
proc `[]`(node: SexpNode; index: int): SexpNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Gets the node at index in a List. Result is undefined if index is out of bounds + Source   +Edit   + +
+
+ +
+
+
+
proc add(father, child: SexpNode) {....raises: [], tags: [], forbids: [].}
+
+ + Adds child to a SList node father. + Source   +Edit   + +
+
+ +
+
+
+
proc close(my: var SexpParser) {.inline, ...raises: [IOError, OSError],
+                                 tags: [WriteIOEffect], forbids: [].}
+
+ + closes the parser my and its associated input stream. + Source   +Edit   + +
+
+ +
+
+
+
proc copy(p: SexpNode): SexpNode {....raises: [], tags: [], forbids: [].}
+
+ + Performs a deep copy of a. + Source   +Edit   + +
+
+ +
+
+
+
proc errorMsg(my: SexpParser): string {....raises: [ValueError], tags: [],
+                                        forbids: [].}
+
+ + returns a helpful error message for the event sexpError + Source   +Edit   + +
+
+ +
+
+
+
proc errorMsgExpected(my: SexpParser; e: string): string {....raises: [ValueError],
+    tags: [], forbids: [].}
+
+ + returns an error message "e expected" in the same format as the other error messages + Source   +Edit   + +
+
+ +
+
+
+
proc escapeJson(s: string): string {....raises: [], tags: [], forbids: [].}
+
+ + Converts a string s to its JSON representation. + Source   +Edit   + +
+
+ +
+
+
+
proc getColumn(my: SexpParser): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + get the current column the parser has arrived at. + Source   +Edit   + +
+
+ +
+
+
+
proc getCons(n: SexpNode; defaults: Cons = (newSNil(), newSNil())): Cons {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Retrieves the cons value of a SList SexpNode.

+

Returns default if n is not a SList.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getElems(n: SexpNode; default: seq[SexpNode] = @[]): seq[SexpNode] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Retrieves the int value of a SList SexpNode.

+

Returns default if n is not a SList.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getFloat(my: SexpParser): float {.inline, ...raises: [ValueError], tags: [],
+                                       forbids: [].}
+
+ + returns the number for the event: sexpFloat + Source   +Edit   + +
+
+ +
+
+
+
proc getFNum(n: SexpNode; default: float = 0.0): float {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Retrieves the float value of a SFloat SexpNode.

+

Returns default if n is not a SFloat.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getInt(my: SexpParser): BiggestInt {.inline, ...raises: [ValueError],
+    tags: [], forbids: [].}
+
+ + returns the number for the event: sexpInt + Source   +Edit   + +
+
+ +
+
+
+
proc getLine(my: SexpParser): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + get the current line the parser has arrived at. + Source   +Edit   + +
+
+ +
+
+
+
proc getNum(n: SexpNode; default: BiggestInt = 0): BiggestInt {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Retrieves the int value of a SInt SexpNode.

+

Returns default if n is not a SInt.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getStr(n: SexpNode; default: string = ""): string {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Retrieves the string value of a SString SexpNode.

+

Returns default if n is not a SString.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc getSymbol(n: SexpNode; default: string = ""): string {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Retrieves the int value of a SList SexpNode.

+

Returns default if n is not a SList.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc hash(n: SexpNode): Hash {....raises: [Exception], tags: [RootEffect],
+                               forbids: [].}
+
+ + Compute the hash for a SEXP node + Source   +Edit   + +
+
+ +
+
+
+
proc kind(my: SexpParser): SexpEventKind {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + returns the current event type for the SEXP parser + Source   +Edit   + +
+
+ +
+
+
+
proc len(n: SexpNode): int {....raises: [], tags: [], forbids: [].}
+
+ + If n is a SList, it returns the number of elements. If n is a JObject, it returns the number of pairs. Else it returns 0. + Source   +Edit   + +
+
+ +
+
+
+
proc newSCons(car, cdr: SexpNode): SexpNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new SCons SexpNode + Source   +Edit   + +
+
+ +
+
+
+
proc newSFloat(n: float): SexpNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new SFloat SexpNode. + Source   +Edit   + +
+
+ +
+
+
+
proc newSInt(n: BiggestInt): SexpNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new SInt SexpNode. + Source   +Edit   + +
+
+ +
+
+
+
proc newSList(): SexpNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new SList SexpNode + Source   +Edit   + +
+
+ +
+
+
+
proc newSNil(): SexpNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new SNil SexpNode. + Source   +Edit   + +
+
+ +
+
+
+
proc newSString(s: string): SexpNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new SString SexpNode. + Source   +Edit   + +
+
+ +
+
+
+
proc newSSymbol(s: string): SexpNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc open(my: var SexpParser; input: Stream) {....raises: [IOError, OSError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + initializes the parser with an input stream. + Source   +Edit   + +
+
+ +
+
+
+
proc parseSexp(buffer: string): SexpNode {.
+    ...raises: [IOError, OSError, ValueError, SexpParsingError],
+    tags: [ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + Parses Sexp from buffer. + Source   +Edit   + +
+
+
+
proc parseSexp(s: Stream): SexpNode {....raises: [IOError, OSError, ValueError,
+    SexpParsingError], tags: [ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + Parses from a buffer s into a SexpNode. + Source   +Edit   + +
+
+ +
+
+
+
proc pretty(node: SexpNode; indent = 2): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + Converts node to its Sexp Representation, with indentation and on multiple lines. + Source   +Edit   + +
+
+ +
+
+
+
proc raiseParseErr(p: SexpParser; msg: string) {.noinline, noreturn,
+    ...raises: [SexpParsingError, ValueError], tags: [], forbids: [].}
+
+ + raises an ESexpParsingError exception. + Source   +Edit   + +
+
+ +
+
+
+
proc sexp(b: bool): SexpNode {....raises: [], tags: [], forbids: [].}
+
+ + Generic constructor for SEXP data. Creates a new SSymbol SexpNode with value t or SNil SexpNode. + Source   +Edit   + +
+
+
+
proc sexp(elements: openArray[SexpNode]): SexpNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Generic constructor for SEXP data. Creates a new SList SexpNode + Source   +Edit   + +
+
+
+
proc sexp(n: BiggestInt): SexpNode {....raises: [], tags: [], forbids: [].}
+
+ + Generic constructor for SEXP data. Creates a new SInt SexpNode. + Source   +Edit   + +
+
+
+
proc sexp(n: float): SexpNode {....raises: [], tags: [], forbids: [].}
+
+ + Generic constructor for SEXP data. Creates a new SFloat SexpNode. + Source   +Edit   + +
+
+
+
proc sexp(s: SexpNode): SexpNode {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc sexp(s: string): SexpNode {....raises: [], tags: [], forbids: [].}
+
+ + Generic constructor for SEXP data. Creates a new SString SexpNode. + Source   +Edit   + +
+
+ +
+
+
+
proc str(my: SexpParser): string {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + returns the character data for the events: sexpInt, sexpFloat, sexpString + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator items(node: SexpNode): SexpNode {....raises: [], tags: [], forbids: [].}
+
+ + Iterator for the items of node. node has to be a SList. + Source   +Edit   + +
+
+ +
+
+
+
iterator mitems(node: var SexpNode): var SexpNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Iterator for the items of node. node has to be a SList. Items can be modified. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro convertSexp(x: untyped): untyped
+
+ + Convert an expression to a SexpNode directly, without having to specify % for every element. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/sexp.idx b/sexp.idx new file mode 100644 index 0000000000000..2543c2c132bb6 --- /dev/null +++ b/sexp.idx @@ -0,0 +1,76 @@ +nimTitle sexp sexp.html module sexp 0 +nim sexpError sexp.html#sexpError SexpEventKind.sexpError 21 +nim sexpEof sexp.html#sexpEof SexpEventKind.sexpEof 21 +nim sexpString sexp.html#sexpString SexpEventKind.sexpString 21 +nim sexpSymbol sexp.html#sexpSymbol SexpEventKind.sexpSymbol 21 +nim sexpInt sexp.html#sexpInt SexpEventKind.sexpInt 21 +nim sexpFloat sexp.html#sexpFloat SexpEventKind.sexpFloat 21 +nim sexpNil sexp.html#sexpNil SexpEventKind.sexpNil 21 +nim sexpDot sexp.html#sexpDot SexpEventKind.sexpDot 21 +nim sexpListStart sexp.html#sexpListStart SexpEventKind.sexpListStart 21 +nim sexpListEnd sexp.html#sexpListEnd SexpEventKind.sexpListEnd 21 +nim SexpEventKind sexp.html#SexpEventKind enum SexpEventKind 21 +nim errNone sexp.html#errNone SexpError.errNone 46 +nim errInvalidToken sexp.html#errInvalidToken SexpError.errInvalidToken 46 +nim errParensRiExpected sexp.html#errParensRiExpected SexpError.errParensRiExpected 46 +nim errQuoteExpected sexp.html#errQuoteExpected SexpError.errQuoteExpected 46 +nim errEofExpected sexp.html#errEofExpected SexpError.errEofExpected 46 +nim SexpError sexp.html#SexpError_2 enum SexpError 46 +nim SexpParser sexp.html#SexpParser object SexpParser 53 +nim close sexp.html#close,SexpParser proc close(my: var SexpParser) 79 +nim str sexp.html#str,SexpParser proc str(my: SexpParser): string 83 +nim getInt sexp.html#getInt,SexpParser proc getInt(my: SexpParser): BiggestInt 89 +nim getFloat sexp.html#getFloat,SexpParser proc getFloat(my: SexpParser): float 94 +nim kind sexp.html#kind,SexpParser proc kind(my: SexpParser): SexpEventKind 99 +nim getColumn sexp.html#getColumn,SexpParser proc getColumn(my: SexpParser): int 103 +nim getLine sexp.html#getLine,SexpParser proc getLine(my: SexpParser): int 107 +nim errorMsg sexp.html#errorMsg,SexpParser proc errorMsg(my: SexpParser): string 111 +nim errorMsgExpected sexp.html#errorMsgExpected,SexpParser,string proc errorMsgExpected(my: SexpParser; e: string): string 116 +nim SNil sexp.html#SNil SexpNodeKind.SNil 254 +nim SInt sexp.html#SInt SexpNodeKind.SInt 254 +nim SFloat sexp.html#SFloat SexpNodeKind.SFloat 254 +nim SString sexp.html#SString SexpNodeKind.SString 254 +nim SSymbol sexp.html#SSymbol SexpNodeKind.SSymbol 254 +nim SList sexp.html#SList SexpNodeKind.SList 254 +nim SCons sexp.html#SCons SexpNodeKind.SCons 254 +nim SexpNodeKind sexp.html#SexpNodeKind enum SexpNodeKind 254 +nim SexpNode sexp.html#SexpNode type SexpNode 263 +nim SexpNodeObj sexp.html#SexpNodeObj object SexpNodeObj 264 +nim SexpParsingError sexp.html#SexpParsingError object SexpParsingError 284 +nim raiseParseErr sexp.html#raiseParseErr,SexpParser,string proc raiseParseErr(p: SexpParser; msg: string) 286 +nim newSString sexp.html#newSString,string proc newSString(s: string): SexpNode 290 +nim newSInt sexp.html#newSInt,BiggestInt proc newSInt(n: BiggestInt): SexpNode 294 +nim newSFloat sexp.html#newSFloat,float proc newSFloat(n: float): SexpNode 298 +nim newSNil sexp.html#newSNil proc newSNil(): SexpNode 302 +nim newSCons sexp.html#newSCons,SexpNode,SexpNode proc newSCons(car, cdr: SexpNode): SexpNode 306 +nim newSList sexp.html#newSList proc newSList(): SexpNode 310 +nim newSSymbol sexp.html#newSSymbol,string proc newSSymbol(s: string): SexpNode 314 +nim getStr sexp.html#getStr,SexpNode,string proc getStr(n: SexpNode; default: string = ""): string 317 +nim getNum sexp.html#getNum,SexpNode,BiggestInt proc getNum(n: SexpNode; default: BiggestInt = 0): BiggestInt 324 +nim getFNum sexp.html#getFNum,SexpNode,float proc getFNum(n: SexpNode; default: float = 0.0): float 331 +nim getSymbol sexp.html#getSymbol,SexpNode,string proc getSymbol(n: SexpNode; default: string = ""): string 338 +nim getElems sexp.html#getElems,SexpNode,seq[SexpNode] proc getElems(n: SexpNode; default: seq[SexpNode] = @[]): seq[SexpNode] 345 +nim getCons sexp.html#getCons,SexpNode,Cons proc getCons(n: SexpNode; defaults: Cons = (newSNil(), newSNil())): Cons 353 +nim sexp sexp.html#sexp,string proc sexp(s: string): SexpNode 361 +nim sexp sexp.html#sexp,BiggestInt proc sexp(n: BiggestInt): SexpNode 365 +nim sexp sexp.html#sexp,float proc sexp(n: float): SexpNode 369 +nim sexp sexp.html#sexp,bool proc sexp(b: bool): SexpNode 373 +nim sexp sexp.html#sexp,openArray[SexpNode] proc sexp(elements: openArray[SexpNode]): SexpNode 381 +nim sexp sexp.html#sexp,SexpNode proc sexp(s: SexpNode): SexpNode 387 +nim convertSexp sexp.html#convertSexp.m,untyped macro convertSexp(x: untyped): untyped 402 +nim `==` sexp.html#==,SexpNode,SexpNode proc `==`(a, b: SexpNode): bool 407 +nim hash sexp.html#hash,SexpNode proc hash(n: SexpNode): Hash 431 +nim len sexp.html#len,SexpNode proc len(n: SexpNode): int 449 +nim `[]` sexp.html#[],SexpNode,int proc `[]`(node: SexpNode; index: int): SexpNode 457 +nim add sexp.html#add,SexpNode,SexpNode proc add(father, child: SexpNode) 464 +nim escapeJson sexp.html#escapeJson,string proc escapeJson(s: string): string 481 +nim copy sexp.html#copy,SexpNode proc copy(p: SexpNode): SexpNode 498 +nim pretty sexp.html#pretty,SexpNode,int proc pretty(node: SexpNode; indent = 2): string 561 +nim `$` sexp.html#$,SexpNode proc `$`(node: SexpNode): string 567 +nim items sexp.html#items.i,SexpNode iterator items(node: SexpNode): SexpNode 572 +nim mitems sexp.html#mitems.i,SexpNode iterator mitems(node: var SexpNode): var SexpNode 578 +nim open sexp.html#open,SexpParser,Stream proc open(my: var SexpParser; input: Stream) 624 +nim parseSexp sexp.html#parseSexp,Stream proc parseSexp(s: Stream): SexpNode 630 +nim parseSexp sexp.html#parseSexp,string proc parseSexp(buffer: string): SexpNode 638 +nimgrp sexp sexp.html#sexp-procs-all proc 361 +nimgrp parsesexp sexp.html#parseSexp-procs-all proc 630 diff --git a/sha1.html b/sha1.html new file mode 100644 index 0000000000000..108914e44f539 --- /dev/null +++ b/sha1.html @@ -0,0 +1,338 @@ + + + + + + + +src/checksums/sha1 + + + + + + + + + + + + + + + + +
+
+

src/checksums/sha1

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

Note: +In order to use this module, run nimble install checksums.
+

SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash function which takes an input and produces a 160-bit (20-byte) hash value known as a message digest.

+

Please note that SHA-1 has been formally deprecated since 2011 and it is strongly recommended to switch to stronger hash functions such as the SHA-2 or SHA-3 family.

+

Even though SHA-1 is formally deprecated, this module itself is not deprecated and will continue to be usable.

+ +

See also

+ +

Example:

+
import src/checksums/sha1
+let accessName = secureHash("John Doe")
+assert $accessName == "AE6E4D1209F17B460503904FAD297B31E9CF6362"
+

Example: cmd: -r:off

+
import src/checksums/sha1
+let
+  a = secureHashFile("myFile.nim")
+  b = parseSecureHash("10DFAEBF6BFDBC7939957068E2EFACEC4972933C")
+assert a == b, "files don't match"

+
+

Types

+
+
+
SecureHash = distinct Sha1Digest
+
+ + + +
+
+
+
Sha1Digest = array[0 .. 20 - 1, uint8]
+
+ + + +
+
+
+
Sha1State = object
+
+ + + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(self: SecureHash): string {....raises: [], tags: [], forbids: [].}
+
+ +

Returns the string representation of a SecureHash.

+

See also:

+ + +

Example:

+
let hash = secureHash("Hello World")
+assert $hash == "0A4D55A8D778E5022FAB701977C5D840BBC486D0"
+ +
+
+ +
+
+
+
proc `==`(a, b: SecureHash): bool {....raises: [], tags: [], forbids: [].}
+
+ + Checks if two SecureHash values are identical. +

Example:

+
let
+  a = secureHash("Hello World")
+  b = secureHash("Goodbye World")
+  c = parseSecureHash("0A4D55A8D778E5022FAB701977C5D840BBC486D0")
+assert a != b
+assert a == c
+ +
+
+ +
+
+
+
proc finalize(ctx: var Sha1State): Sha1Digest {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Finalizes the Sha1State and returns a Sha1Digest.

+

If you use the secureHash proc, there's no need to call this function explicitly.

+ + +
+
+ +
+
+
+
proc isValidSha1Hash(s: string): bool {....raises: [], tags: [], forbids: [].}
+
+ + Checks if a string is a valid sha1 hash sum. + +
+
+ +
+
+
+
proc newSha1State(): Sha1State {....raises: [], tags: [], forbids: [].}
+
+ +

Creates a Sha1State.

+

If you use the secureHash proc, there's no need to call this function explicitly.

+ + +
+
+ +
+
+
+
proc parseSecureHash(hash: string): SecureHash {....raises: [ValueError], tags: [],
+    forbids: [].}
+
+ +

Converts a string hash to a SecureHash.

+

See also:

+ + +

Example:

+
let
+  hashStr = "0A4D55A8D778E5022FAB701977C5D840BBC486D0"
+  secureHash = secureHash("Hello World")
+assert secureHash == parseSecureHash(hashStr)
+ +
+
+ +
+
+
+
proc secureHash(str: openArray[char]): SecureHash {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Generates a SecureHash from str.

+

See also:

+ + +

Example:

+
let hash = secureHash("Hello World")
+assert hash == parseSecureHash("0A4D55A8D778E5022FAB701977C5D840BBC486D0")
+ +
+
+ +
+
+
+
proc secureHashFile(filename: string): SecureHash {....raises: [IOError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ +

Generates a SecureHash from a file.

+

See also:

+ + + +
+
+ +
+
+
+
proc update(ctx: var Sha1State; data: openArray[char]) {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Updates the Sha1State with data.

+

If you use the secureHash proc, there's no need to call this function explicitly.

+ + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/sha1.idx b/sha1.idx new file mode 100644 index 0000000000000..f6e500884757f --- /dev/null +++ b/sha1.idx @@ -0,0 +1,14 @@ +nimTitle sha1 sha1.html module src/checksums/sha1 0 +nim Sha1Digest sha1.html#Sha1Digest type Sha1Digest 50 +nim SecureHash sha1.html#SecureHash type SecureHash 51 +nim Sha1State sha1.html#Sha1State object Sha1State 54 +nim newSha1State sha1.html#newSha1State proc newSha1State(): Sha1State 62 +nim update sha1.html#update,Sha1State,openArray[char] proc update(ctx: var Sha1State; data: openArray[char]) 159 +nim finalize sha1.html#finalize,Sha1State proc finalize(ctx: var Sha1State): Sha1Digest 194 +nim secureHash sha1.html#secureHash,openArray[char] proc secureHash(str: openArray[char]): SecureHash 216 +nim secureHashFile sha1.html#secureHashFile,string proc secureHashFile(filename: string): SecureHash 230 +nim `$` sha1.html#$,SecureHash proc `$`(self: SecureHash): string 253 +nim parseSecureHash sha1.html#parseSecureHash,string proc parseSecureHash(hash: string): SecureHash 266 +nim `==` sha1.html#==,SecureHash,SecureHash proc `==`(a, b: SecureHash): bool 281 +nim isValidSha1Hash sha1.html#isValidSha1Hash,string proc isValidSha1Hash(s: string): bool 294 +heading See also sha1.html#see-also See also 0 diff --git a/sha2.html b/sha2.html new file mode 100644 index 0000000000000..534e24d933184 --- /dev/null +++ b/sha2.html @@ -0,0 +1,437 @@ + + + + + + + +src/checksums/sha2 + + + + + + + + + + + + + + + + +
+
+

src/checksums/sha2

+
+ +
+ +
+ +

SHA-2 (Secure Hash Algorithm 2) is a cryptographic hash function which takes an input and produces a value known as a message digest.

+

It provides fixed size algorithms that generate a one-shot message digest of a determinate size.

+ +

Implemented Algorithms

Fixed size functions:

+
  • SHA-224
  • +
  • SHA-256
  • +
  • SHA-384
  • +
  • SHA-512
  • +
+

For convenience, this module provides output-length type checked functions for the implemented fixed size functions via initSha_224, initSha_256, initSha_384 and initSha_512. These functions provide a digest overload returning a correctly sized message digest array.

+

If more relaxed types are required, an "unchecked" Sha2State can be used, but care must be taken to provide digest with a correctly sized dest array.

+ +

Example:

+
import src/checksums/sha2
+var hasher = initSha_256()
+
+hasher.update("The quick brown fox ")
+hasher.update("jumps over the lazy dog")
+
+let digest = hasher.digest()
+
+assert $digest == "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"
+

Example:

+
import src/checksums/sha2
+var hasher = initSha_384()
+
+hasher.update("The quick brown fox ")
+hasher.update("jumps over the lazy dog")
+
+let digest = hasher.digest()
+
+assert $digest == "ca737f1014a48f4c0b6dd43cb177b0afd9e5169367544c494011e3317dbf9a509cb1e5dc1e85a941bbee3d7f2afbc9b1"

+
+

Imports

+
+ sha_utils +
+
+
+

Types

+
+
+
ShaDigest_224 = array[28, char]
+
+ + SHA-224 output digest. + +
+
+
+
ShaDigest_256 = array[32, char]
+
+ + SHA-256 output digest. + +
+
+
+
ShaDigest_384 = array[48, char]
+
+ + SHA-384 output digest. + +
+
+
+
ShaDigest_512 = array[64, char]
+
+ + SHA-512 output digest. + +
+
+
+
ShaInstance = enum
+  Sha_224,                  ## SHA-224 with an output size of 28 bytes (truncated from SHA-256)
+  Sha_256,                  ## SHA-256 with an output size of 32 bytes
+  Sha_384,                  ## SHA-384 with an output size of 48 bytes (truncated from SHA-512)
+  Sha_512                    ## SHA-512 with an output size of 64 bytes
+
+ + Selects a specific SHA instance with well known message digest lengths and properties. + +
+
+
+
ShaState = distinct ShaContext
+
+ +

An unchecked SHA state created from a specific ShaInstance.

+

Unchecked meaning the user has to make sure that the target buffer has enough room to store the resulting digest, otherwise digest will truncate the output.

+ + +
+
+
+
ShaStateStatic[instance] = distinct ShaState
+
+ + A statically checked SHA state created from a specific ShaInstance. + +
+
+ +
+
+
+

Procs

+
+
+
+
proc digest(state: var ShaState; dest: var openArray[char]): int {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Finishes, stores the completed message digest in dest and returns the number of bytes written in dest.

+

If dest is not big enough to contain the digest produced by the selected instance, everything that would overflow is truncated.

+ + +
+
+
+
proc digest(state: var ShaStateStatic[Sha_224]): ShaDigest_224 {....raises: [],
+    tags: [], forbids: [].}
+
+ + Finishes and returns the completed SHA-224 message digest. + +
+
+
+
proc digest(state: var ShaStateStatic[Sha_256]): ShaDigest_256 {....raises: [],
+    tags: [], forbids: [].}
+
+ + Finishes and returns the completed SHA-256 message digest. + +
+
+
+
proc digest(state: var ShaStateStatic[Sha_384]): ShaDigest_384 {....raises: [],
+    tags: [], forbids: [].}
+
+ + Finishes and returns the completed SHA-284 message digest. + +
+
+
+
proc digest(state: var ShaStateStatic[Sha_512]): ShaDigest_512 {....raises: [],
+    tags: [], forbids: [].}
+
+ + Finishes and returns the completed SHA-512 message digest. + +
+
+ +
+
+
+
func digestLength(instance: ShaInstance): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + Returns the message digest size for the selected SHA instance. + +
+
+ +
+
+
+
func initSha(instance: ShaInstance): ShaState {....raises: [], tags: [],
+    forbids: [].}
+
+ + Constructs a new unchecked SHA state for the selected instance instance. + +
+
+ +
+
+
+
func initSha_224(): ShaStateStatic[Sha_224] {....raises: [], tags: [], forbids: [].}
+
+ + Constructs a new statically checked state for the SHA-224 instance. + +
+
+ +
+
+
+
func initSha_256(): ShaStateStatic[Sha_256] {....raises: [], tags: [], forbids: [].}
+
+ + Constructs a new statically checked state for the SHA-256 instance. + +
+
+ +
+
+
+
func initSha_384(): ShaStateStatic[Sha_384] {....raises: [], tags: [], forbids: [].}
+
+ + Constructs a new statically checked state for the SHA-384 instance. + +
+
+ +
+
+
+
func initSha_512(): ShaStateStatic[Sha_512] {....raises: [], tags: [], forbids: [].}
+
+ + Constructs a new statically checked state for the SHA-512 instance. + +
+
+ +
+
+
+
func initShaStateStatic(instance: static ShaInstance): ShaStateStatic[instance]
+
+ + Constructs a new statically checked SHA state for the selected instance instance. + +
+
+ +
+
+
+
proc secureHash(instance: ShaInstance; data: openArray[char]): seq[char] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Convenience wrapper around the standard "init, update, digest" sequence with a runtime selected SHA instance. + +
+
+
+
proc secureHash(instance: static ShaInstance; data: openArray[char]): auto
+
+ + Convenience wrapper around the standard "init, update, digest" sequence with a statically selected SHA instance. + +
+
+ +
+
+
+
proc update(state: var ShaState; data: openArray[char]) {.borrow, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Updates the given ShaState with the provided buffer data. + +
+
+
+
proc update[instance: static ShaInstance](state: var ShaStateStatic[instance];
+    data: openArray[char])
+
+ + Updates the given ShaStateStatic with the provided buffer data. + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/sha2.idx b/sha2.idx new file mode 100644 index 0000000000000..af1fe82d5e438 --- /dev/null +++ b/sha2.idx @@ -0,0 +1,32 @@ +nimTitle sha2 sha2.html module src/checksums/sha2 0 +nim Sha_224 sha2.html#Sha_224 ShaInstance.Sha_224 404 +nim Sha_256 sha2.html#Sha_256 ShaInstance.Sha_256 404 +nim Sha_384 sha2.html#Sha_384 ShaInstance.Sha_384 404 +nim Sha_512 sha2.html#Sha_512 ShaInstance.Sha_512 404 +nim ShaInstance sha2.html#ShaInstance enum ShaInstance 404 +nim ShaDigest_224 sha2.html#ShaDigest_224 type ShaDigest_224 412 +nim ShaDigest_256 sha2.html#ShaDigest_256 type ShaDigest_256 413 +nim ShaDigest_384 sha2.html#ShaDigest_384 type ShaDigest_384 414 +nim ShaDigest_512 sha2.html#ShaDigest_512 type ShaDigest_512 415 +nim ShaState sha2.html#ShaState type ShaState 417 +nim ShaStateStatic sha2.html#ShaStateStatic type ShaStateStatic 423 +nim digestLength sha2.html#digestLength,ShaInstance proc digestLength(instance: ShaInstance): int 426 +nim initSha sha2.html#initSha,ShaInstance proc initSha(instance: ShaInstance): ShaState 434 +nim initShaStateStatic sha2.html#initShaStateStatic,staticShaInstance proc initShaStateStatic(instance: static ShaInstance): ShaStateStatic[instance] 438 +nim initSha_224 sha2.html#initSha_224 proc initSha_224(): ShaStateStatic[Sha_224] 442 +nim initSha_256 sha2.html#initSha_256 proc initSha_256(): ShaStateStatic[Sha_256] 445 +nim initSha_384 sha2.html#initSha_384 proc initSha_384(): ShaStateStatic[Sha_384] 448 +nim initSha_512 sha2.html#initSha_512 proc initSha_512(): ShaStateStatic[Sha_512] 451 +nim update sha2.html#update,ShaStateStatic[instance],openArray[char] proc update[instance: static ShaInstance](state: var ShaStateStatic[instance];\n data: openArray[char]) 455 +nim update sha2.html#update,ShaState,openArray[char] proc update(state: var ShaState; data: openArray[char]) 461 +nim digest sha2.html#digest,ShaStateStatic[ShaInstance] proc digest(state: var ShaStateStatic[Sha_224]): ShaDigest_224 468 +nim digest sha2.html#digest,ShaStateStatic[ShaInstance]_2 proc digest(state: var ShaStateStatic[Sha_256]): ShaDigest_256 472 +nim digest sha2.html#digest,ShaStateStatic[ShaInstance]_3 proc digest(state: var ShaStateStatic[Sha_384]): ShaDigest_384 476 +nim digest sha2.html#digest,ShaStateStatic[ShaInstance]_4 proc digest(state: var ShaStateStatic[Sha_512]): ShaDigest_512 480 +nim digest sha2.html#digest,ShaState,openArray[char] proc digest(state: var ShaState; dest: var openArray[char]): int 484 +nim secureHash sha2.html#secureHash,staticShaInstance,openArray[char] proc secureHash(instance: static ShaInstance; data: openArray[char]): auto 499 +nim secureHash sha2.html#secureHash,ShaInstance,openArray[char] proc secureHash(instance: ShaInstance; data: openArray[char]): seq[char] 507 +nimgrp securehash sha2.html#secureHash-procs-all proc 499 +nimgrp update sha2.html#update-procs-all proc 455 +nimgrp digest sha2.html#digest-procs-all proc 468 +heading Implemented Algorithms sha2.html#implemented-algorithms Implemented Algorithms 0 diff --git a/sha3.html b/sha3.html new file mode 100644 index 0000000000000..19be27b934b7b --- /dev/null +++ b/sha3.html @@ -0,0 +1,553 @@ + + + + + + + +src/checksums/sha3 + + + + + + + + + + + + + + + + +
+
+

src/checksums/sha3

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

SHA-3 (Secure Hash Algorithm 3) is a cryptographic hash function which takes an input and produces a value known as a message digest.

+

It provides both fixed size algorithms that generate a one-shot message digest of a determinate size as well as an extendable-output function (XOF) variant that can produce any message digest lengths desired.

+ +

Implemented Algorithms

Fixed size functions:

+
  • SHA3-224
  • +
  • SHA3-256
  • +
  • SHA3-384
  • +
  • SHA3-512
  • +
+

Extended-output functions:

+
  • SHAKE128
  • +
  • SHAKE256
  • +
  • SHAKE512
  • +
+

For convenience, this module provides output-length type checked functions for the implemented fixed size functions via initSha3_224, initSha3_256, initSha3_384 and initSha3_512. These functions provide a digest overload returning a correctly sized message digest array.

+

If more relaxed types are required, an "unchecked" Sha3State can be used, but care must be taken to provide digest with a correctly sized dest array.

+ +

Example:

+
import src/checksums/sha3
+var hasher = initSha3_256()
+
+hasher.update("The quick brown fox ")
+hasher.update("jumps over the lazy dog")
+
+let digest = hasher.digest()
+
+assert $digest == "69070dda01975c8c120c3aada1b282394e7f032fa9cf32f4cb2259a0897dfc04"
+

Example:

+
import src/checksums/sha3
+var xof = initShake(Shake128)
+
+xof.update("The quick brown fox ")
+xof.update("jumps over the lazy dog")
+xof.finalize()
+
+var digest: array[16, char]
+
+xof.shakeOut(digest)
+assert $digest == "f4202e3c5852f9182a0430fd8144f0a7"
+
+xof.shakeOut(digest)
+assert $digest == "4b95e7417ecae17db0f8cfeed0e3e66e"

+
+

Imports

+
+ sha_utils +
+
+
+

Types

+
+
+
Sha3Digest_224 = array[28, char]
+
+ + SHA3-224 output digest. + +
+
+
+
Sha3Digest_256 = array[32, char]
+
+ + SHA3-256 output digest. + +
+
+
+
Sha3Digest_384 = array[48, char]
+
+ + SHA3-384 output digest. + +
+
+
+
Sha3Digest_512 = array[64, char]
+
+ + SHA3-512 output digest. + +
+
+
+
Sha3Instance = enum
+  Sha3_224,                 ## SHA3-224 with an output size of 28 bytes
+  Sha3_256,                 ## SHA3-256 with an output size of 32 bytes
+  Sha3_384,                 ## SHA3-384 with an output size of 48 bytes
+  Sha3_512                   ## SHA3-512 with an output size of 64 bytes
+
+ + Selects a specific SHA3 instance with well known message digest lengths and properties. + +
+
+
+
Sha3State = distinct KeccakState
+
+ +

An unchecked SHA3 state created from a specific Sha3Instance.

+

Unchecked meaning the user has to make sure that the target buffer has enough room to store the resulting digest, otherwise digest will truncate the output.

+ + +
+
+
+
Sha3StateStatic[instance] = distinct Sha3State
+
+ + A statically checked SHA3 state created from a specific Sha3Instance. + +
+
+
+
ShakeInstance = enum
+  Shake128,                 ## Shake-128
+  Shake256,                 ## Shake-256
+  Shake512                   ## Shake-512 (Keccak proposal; not officially included in SHA3)
+
+ + Selects a specific Shake instance with well known properties. + +
+
+
+
ShakeState = distinct KeccakState
+
+ + A Shake state created from a specific ShakeInstance. + +
+
+ +
+
+
+

Procs

+
+
+
+
proc digest(state: var Sha3State; dest: var openArray[char]): int {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Finishes, stores the completed message digest in dest and returns the number of bytes written in dest.

+

If dest is not big enough to contain the digest produced by the selected instance, everything that would overflow is truncated.

+ + +
+
+
+
proc digest(state: var Sha3StateStatic[Sha3_224]): Sha3Digest_224 {....raises: [],
+    tags: [], forbids: [].}
+
+ + Finishes and returns the completed SHA3-224 message digest. + +
+
+
+
proc digest(state: var Sha3StateStatic[Sha3_256]): Sha3Digest_256 {....raises: [],
+    tags: [], forbids: [].}
+
+ + Finishes and returns the completed SHA3-256 message digest. + +
+
+
+
proc digest(state: var Sha3StateStatic[Sha3_384]): Sha3Digest_384 {....raises: [],
+    tags: [], forbids: [].}
+
+ + Finishes and returns the completed SHA3-284 message digest. + +
+
+
+
proc digest(state: var Sha3StateStatic[Sha3_512]): Sha3Digest_512 {....raises: [],
+    tags: [], forbids: [].}
+
+ + Finishes and returns the completed SHA3-512 message digest. + +
+
+ +
+
+
+
func digestLength(instance: Sha3Instance): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + Returns the message digest size for the selected SHA3 instance. + +
+
+
+
func digestLength(instance: ShakeInstance): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + Returns the message digest size for the selected Shake instance. + +
+
+ +
+
+
+
proc finalize(state: var ShakeState) {....raises: [], tags: [], forbids: [].}
+
+ + Finishes the input digestion state of the given ShakeState and readies it for message digest retrieval. + +
+
+ +
+
+
+
func initSha3(instance: Sha3Instance): Sha3State {....raises: [], tags: [],
+    forbids: [].}
+
+ + Constructs a new unchecked SHA3 state for the selected instance instance. + +
+
+ +
+
+
+
func initSha3_224(): Sha3StateStatic[Sha3_224] {....raises: [], tags: [],
+    forbids: [].}
+
+ + Constructs a new statically checked state for the SHA3-224 instance. + +
+
+ +
+
+
+
func initSha3_256(): Sha3StateStatic[Sha3_256] {....raises: [], tags: [],
+    forbids: [].}
+
+ + Constructs a new statically checked state for the SHA3-256 instance. + +
+
+ +
+
+
+
func initSha3_384(): Sha3StateStatic[Sha3_384] {....raises: [], tags: [],
+    forbids: [].}
+
+ + Constructs a new statically checked state for the SHA3-384 instance. + +
+
+ +
+
+
+
func initSha3_512(): Sha3StateStatic[Sha3_512] {....raises: [], tags: [],
+    forbids: [].}
+
+ + Constructs a new statically checked state for the SHA3-512 instance. + +
+
+ +
+
+
+
func initSha3StateStatic(instance: static Sha3Instance): Sha3StateStatic[
+    instance]
+
+ + Constructs a new statically checked SHA3 state for the selected instance instance. + +
+
+ +
+
+
+
func initShake(instance: ShakeInstance): ShakeState {....raises: [], tags: [],
+    forbids: [].}
+
+ + Constructs a new Shake state for the selected instance instance. + +
+
+ +
+
+
+
proc secureHash(instance: Sha3Instance; data: openArray[char]): seq[char] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Convenience wrapper around the standard "init, update, digest" sequence with a runtime selected SHA instance. + +
+
+
+
proc secureHash(instance: static Sha3Instance; data: openArray[char]): auto
+
+ + Convenience wrapper around the standard "init, update, digest" sequence with a statically selected SHA instance. + +
+
+ +
+
+
+
proc shakeOut(state: var ShakeState; dest: var openArray[char]) {....raises: [],
+    tags: [], forbids: [].}
+
+ +

"Shakes out" a part of the variable length Shake message digest. The ShakeState must be finalized before calling this procedure.

+

It can be invoked multiple times with user selectable buffer sizes. In particular, it is guaranteed that the same digest is extracted in both of the following examples, given the same state:

+

  var digest: array[32, byte]
+  
+  state.shakeOut(digestPart)

+

  var digestA: array[16, byte]
+  var digestB: array[16, byte]
+  
+  state.shakeOut(digestA)
+  state.shakeOut(digestB)

+ + +
+
+ +
+
+
+
proc update(state: var Sha3State; data: openArray[char]) {.borrow, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Updates the given Sha3State with the provided buffer data. + +
+
+
+
proc update(state: var ShakeState; data: openArray[char]) {.borrow, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Updates the given ShakeState with the provided buffer data. + +
+
+
+
proc update[instance: static Sha3Instance](state: var Sha3StateStatic[instance];
+    data: openArray[char])
+
+ + Updates the given Sha3StateStatic with the provided buffer data. + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/sha3.idx b/sha3.idx new file mode 100644 index 0000000000000..7bd87aea4e8e6 --- /dev/null +++ b/sha3.idx @@ -0,0 +1,43 @@ +nimTitle sha3 sha3.html module src/checksums/sha3 0 +nim Sha3_224 sha3.html#Sha3_224 Sha3Instance.Sha3_224 291 +nim Sha3_256 sha3.html#Sha3_256 Sha3Instance.Sha3_256 291 +nim Sha3_384 sha3.html#Sha3_384 Sha3Instance.Sha3_384 291 +nim Sha3_512 sha3.html#Sha3_512 Sha3Instance.Sha3_512 291 +nim Sha3Instance sha3.html#Sha3Instance enum Sha3Instance 291 +nim Sha3Digest_224 sha3.html#Sha3Digest_224 type Sha3Digest_224 299 +nim Sha3Digest_256 sha3.html#Sha3Digest_256 type Sha3Digest_256 300 +nim Sha3Digest_384 sha3.html#Sha3Digest_384 type Sha3Digest_384 301 +nim Sha3Digest_512 sha3.html#Sha3Digest_512 type Sha3Digest_512 302 +nim Sha3State sha3.html#Sha3State type Sha3State 304 +nim Sha3StateStatic sha3.html#Sha3StateStatic type Sha3StateStatic 310 +nim digestLength sha3.html#digestLength,Sha3Instance proc digestLength(instance: Sha3Instance): int 313 +nim initSha3 sha3.html#initSha3,Sha3Instance proc initSha3(instance: Sha3Instance): Sha3State 321 +nim initSha3StateStatic sha3.html#initSha3StateStatic,staticSha3Instance proc initSha3StateStatic(instance: static Sha3Instance): Sha3StateStatic[instance] 325 +nim initSha3_224 sha3.html#initSha3_224 proc initSha3_224(): Sha3StateStatic[Sha3_224] 329 +nim initSha3_256 sha3.html#initSha3_256 proc initSha3_256(): Sha3StateStatic[Sha3_256] 332 +nim initSha3_384 sha3.html#initSha3_384 proc initSha3_384(): Sha3StateStatic[Sha3_384] 335 +nim initSha3_512 sha3.html#initSha3_512 proc initSha3_512(): Sha3StateStatic[Sha3_512] 338 +nim update sha3.html#update,Sha3StateStatic[instance],openArray[char] proc update[instance: static Sha3Instance](state: var Sha3StateStatic[instance];\n data: openArray[char]) 342 +nim update sha3.html#update,Sha3State,openArray[char] proc update(state: var Sha3State; data: openArray[char]) 348 +nim digest sha3.html#digest,Sha3StateStatic[Sha3Instance] proc digest(state: var Sha3StateStatic[Sha3_224]): Sha3Digest_224 355 +nim digest sha3.html#digest,Sha3StateStatic[Sha3Instance]_2 proc digest(state: var Sha3StateStatic[Sha3_256]): Sha3Digest_256 360 +nim digest sha3.html#digest,Sha3StateStatic[Sha3Instance]_3 proc digest(state: var Sha3StateStatic[Sha3_384]): Sha3Digest_384 365 +nim digest sha3.html#digest,Sha3StateStatic[Sha3Instance]_4 proc digest(state: var Sha3StateStatic[Sha3_512]): Sha3Digest_512 370 +nim digest sha3.html#digest,Sha3State,openArray[char] proc digest(state: var Sha3State; dest: var openArray[char]): int 375 +nim Shake128 sha3.html#Shake128 ShakeInstance.Shake128 392 +nim Shake256 sha3.html#Shake256 ShakeInstance.Shake256 392 +nim Shake512 sha3.html#Shake512 ShakeInstance.Shake512 392 +nim ShakeInstance sha3.html#ShakeInstance enum ShakeInstance 392 +nim ShakeState sha3.html#ShakeState type ShakeState 399 +nim digestLength sha3.html#digestLength,ShakeInstance proc digestLength(instance: ShakeInstance): int 402 +nim initShake sha3.html#initShake,ShakeInstance proc initShake(instance: ShakeInstance): ShakeState 409 +nim update sha3.html#update,ShakeState,openArray[char] proc update(state: var ShakeState; data: openArray[char]) 413 +nim finalize sha3.html#finalize,ShakeState proc finalize(state: var ShakeState) 416 +nim shakeOut sha3.html#shakeOut,ShakeState,openArray[char] proc shakeOut(state: var ShakeState; dest: var openArray[char]) 421 +nim secureHash sha3.html#secureHash,staticSha3Instance,openArray[char] proc secureHash(instance: static Sha3Instance; data: openArray[char]): auto 445 +nim secureHash sha3.html#secureHash,Sha3Instance,openArray[char] proc secureHash(instance: Sha3Instance; data: openArray[char]): seq[char] 453 +nimgrp digestlength sha3.html#digestLength-procs-all proc 313 +nimgrp securehash sha3.html#secureHash-procs-all proc 445 +nimgrp update sha3.html#update-procs-all proc 342 +nimgrp digest sha3.html#digest-procs-all proc 355 +heading Implemented Algorithms sha3.html#implemented-algorithms Implemented Algorithms 0 diff --git a/sharedlist.html b/sharedlist.html new file mode 100644 index 0000000000000..e332ccde1390c --- /dev/null +++ b/sharedlist.html @@ -0,0 +1,252 @@ + + + + + + + +std/sharedlist + + + + + + + + + + + + + + + + +
+
+

std/sharedlist

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+
+ Deprecated +
+ +

Shared list support.

+

Unstable API.

+

+
+

Imports

+
+ locks +
+
+
+

Types

+
+
+
SharedList[A] = object
+  lock*: Lock
+
+ + generic shared list + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc add[A](x: var SharedList[A]; y: A)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc clear[A](t: var SharedList[A])
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc deinitSharedList[A](t: var SharedList[A])
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc init[A](t: var SharedList[A])
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc iterAndMutate[A](x: var SharedList[A]; action: proc (x: A): bool)
+
+ + Iterates over the list. If action returns true, the current item is removed from the list.
Warning: +It may not preserve the element order after some modifications.
+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator items[A](x: var SharedList[A]): A
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/sharedlist.idx b/sharedlist.idx new file mode 100644 index 0000000000000..528e63fcb49f6 --- /dev/null +++ b/sharedlist.idx @@ -0,0 +1,8 @@ +nimTitle sharedlist sharedlist.html module std/sharedlist 0 +nim SharedList sharedlist.html#SharedList object SharedList 30 +nim iterAndMutate sharedlist.html#iterAndMutate,SharedList[A],proc(A) proc iterAndMutate[A](x: var SharedList[A]; action: proc (x: A): bool) 39 +nim items sharedlist.html#items.i,SharedList[A] iterator items[A](x: var SharedList[A]): A 62 +nim add sharedlist.html#add,SharedList[A],A proc add[A](x: var SharedList[A]; y: A) 70 +nim init sharedlist.html#init,SharedList[A] proc init[A](t: var SharedList[A]) 86 +nim clear sharedlist.html#clear,SharedList[A] proc clear[A](t: var SharedList[A]) 91 +nim deinitSharedList sharedlist.html#deinitSharedList,SharedList[A] proc deinitSharedList[A](t: var SharedList[A]) 101 diff --git a/sharedtables.html b/sharedtables.html new file mode 100644 index 0000000000000..1cd9b39c285fe --- /dev/null +++ b/sharedtables.html @@ -0,0 +1,434 @@ + + + + + + + +std/sharedtables + + + + + + + + + + + + + + + + +
+
+

std/sharedtables

+
+ +
+ Source   +Edit   + +
+
+ Deprecated +
+ +

Shared table support for Nim. Use plain old non GC'ed keys and values or you'll be in trouble. Uses a single lock to protect the table, lockfree implementations welcome but if lock contention is so high that you need a lockfree hash table, you're doing it wrong.

+

Unstable API.

+

+ +
+

Types

+
+
+
SharedTable[A; B] = object
+
+ + generic hash SharedTable + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
defaultInitialSize = 32
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `[]=`[A, B](t: var SharedTable[A, B]; key: A; val: B)
+
+ + Puts a (key, value)-pair into t. + Source   +Edit   + +
+
+ +
+
+
+
proc add[A, B](t: var SharedTable[A, B]; key: A; val: B)
+
+ + Puts a new (key, value)-pair into t even if t[key] already exists. This can introduce duplicate keys into the table! + Source   +Edit   + +
+
+ +
+
+
+
proc deinitSharedTable[A, B](t: var SharedTable[A, B])
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc del[A, B](t: var SharedTable[A, B]; key: A)
+
+ + Deletes key from hash table t. + Source   +Edit   + +
+
+ +
+
+
+
proc hasKeyOrPut[A, B](t: var SharedTable[A, B]; key: A; val: B): bool
+
+ + Returns true if key is in the table, otherwise inserts value. + Source   +Edit   + +
+
+ +
+
+
+
proc init[A, B](t: var SharedTable[A, B]; initialSize = 32)
+
+ +

Creates a new hash table that is empty.

+

This proc must be called before any other usage of t.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc len[A, B](t: var SharedTable[A, B]): int
+
+ + Number of elements in t. + Source   +Edit   + +
+
+ +
+
+
+
proc mget[A, B](t: var SharedTable[A, B]; key: A): var B
+
+ + Retrieves the value at t[key]. The value can be modified. If key is not in t, the KeyError exception is raised. + Source   +Edit   + +
+
+ +
+
+
+
proc mgetOrPut[A, B](t: var SharedTable[A, B]; key: A; val: B): var B
+
+ + Retrieves value at t[key] or puts val if not present, either way returning a value which can be modified. Note: This is inherently unsafe in the context of multi-threading since it returns a pointer to B. + Source   +Edit   + +
+
+ +
+
+
+
proc withKey[A, B](t: var SharedTable[A, B]; key: A;
+                   mapper: proc (key: A; val: var B; pairExists: var bool))
+
+ +

Computes a new mapping for the key with the specified mapper procedure.

+

The mapper takes 3 arguments:

+
  1. key - the current key, if it exists, or the key passed to withKey otherwise;
  2. +
  3. val - the current value, if the key exists, or default value of the type otherwise;
  4. +
  5. pairExists - true if the key exists, false otherwise.
  6. +
+

The mapper can can modify val and pairExists values to change the mapping of the key or delete it from the table. When adding a value, make sure to set pairExists to true along with modifying the val.

+

The operation is performed atomically and other operations on the table will be blocked while the mapper is invoked, so it should be short and simple.

+

Example usage:

+

# If value exists, decrement it.
+# If it becomes zero or less, delete the key
+t.withKey(1'i64) do (k: int64, v: var int, pairExists: var bool):
+  if pairExists:
+    dec v
+    if v <= 0:
+      pairExists = false

+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template withValue[A, B](t: var SharedTable[A, B]; key: A;
+                         value, body1, body2: untyped)
+
+ + Retrieves the value at t[key]. value can be modified in the scope of the withValue call. +

Example:

+
var table: SharedTable[string, string]
+init(table)
+
+table["a"] = "x"
+table["b"] = "y"
+table["c"] = "z"
+
+
+table.withValue("a", value):
+  value[] = "m"
+
+var flag = false
+table.withValue("d", value):
+  discard value
+  doAssert false
+do: # if "d" notin table
+  flag = true
+
+if flag:
+  table["d"] = "n"
+
+assert table.mget("a") == "m"
+assert table.mget("d") == "n"
+ Source   +Edit   + +
+
+
+
template withValue[A, B](t: var SharedTable[A, B]; key: A; value, body: untyped)
+
+ + Retrieves the value at t[key]. value can be modified in the scope of the withValue call. +

Example:

+
var table: SharedTable[string, string]
+init(table)
+
+table["a"] = "x"
+table["b"] = "y"
+table["c"] = "z"
+
+table.withValue("a", value):
+  assert value[] == "x"
+
+table.withValue("b", value):
+  value[] = "modified"
+
+table.withValue("b", value):
+  assert value[] == "modified"
+
+table.withValue("nonexistent", value):
+  assert false # not called
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/sharedtables.idx b/sharedtables.idx new file mode 100644 index 0000000000000..c406f1bc8a67b --- /dev/null +++ b/sharedtables.idx @@ -0,0 +1,16 @@ +nimTitle sharedtables sharedtables.html module std/sharedtables 0 +nim SharedTable sharedtables.html#SharedTable object SharedTable 25 +nim defaultInitialSize sharedtables.html#defaultInitialSize const defaultInitialSize 15 +nim withValue sharedtables.html#withValue.t,SharedTable[A,B],A,untyped,untyped template withValue[A, B](t: var SharedTable[A, B]; key: A; value, body: untyped) 63 +nim withValue sharedtables.html#withValue.t,SharedTable[A,B],A,untyped,untyped,untyped template withValue[A, B](t: var SharedTable[A, B]; key: A; value, body1, body2: untyped) 97 +nim mget sharedtables.html#mget,SharedTable[A,B],A proc mget[A, B](t: var SharedTable[A, B]; key: A): var B 139 +nim mgetOrPut sharedtables.html#mgetOrPut,SharedTable[A,B],A,B proc mgetOrPut[A, B](t: var SharedTable[A, B]; key: A; val: B): var B 156 +nim hasKeyOrPut sharedtables.html#hasKeyOrPut,SharedTable[A,B],A,B proc hasKeyOrPut[A, B](t: var SharedTable[A, B]; key: A; val: B): bool 164 +nim withKey sharedtables.html#withKey,SharedTable[A,B],A,proc(A,B,bool) proc withKey[A, B](t: var SharedTable[A, B]; key: A;\n mapper: proc (key: A; val: var B; pairExists: var bool)) 173 +nim `[]=` sharedtables.html#[]=,SharedTable[A,B],A,B proc `[]=`[A, B](t: var SharedTable[A, B]; key: A; val: B) 221 +nim add sharedtables.html#add,SharedTable[A,B],A,B proc add[A, B](t: var SharedTable[A, B]; key: A; val: B) 226 +nim del sharedtables.html#del,SharedTable[A,B],A proc del[A, B](t: var SharedTable[A, B]; key: A) 232 +nim len sharedtables.html#len,SharedTable[A,B] proc len[A, B](t: var SharedTable[A, B]): int 237 +nim init sharedtables.html#init,SharedTable[A,B],int proc init[A, B](t: var SharedTable[A, B]; initialSize = 32) 242 +nim deinitSharedTable sharedtables.html#deinitSharedTable,SharedTable[A,B] proc deinitSharedTable[A, B](t: var SharedTable[A, B]) 253 +nimgrp withvalue sharedtables.html#withValue-templates-all template 63 diff --git a/since.html b/since.html new file mode 100644 index 0000000000000..baabca9b1e0e7 --- /dev/null +++ b/since.html @@ -0,0 +1,134 @@ + + + + + + + +std/private/since + + + + + + + + + + + + + + + + +
+
+

std/private/since

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

since is used to emulate older versions of nim stdlib, see tuse_version.nim.

+

If a symbol foo is added in version (1,3,5), use {.since: (1.3.5).}, not {.since: (1.4).}, so that it works in devel in between releases.

+

The emulation cannot be 100% faithful and to avoid adding too much complexity, since is not needed in those cases:

+
  • if a new module is added
  • +
  • if an overload is added
  • +
  • if an extra parameter to an existing routine is added
  • +
+

+
+

Templates

+
+
+
+
template since(version: (int, int); body: untyped) {.dirty.}
+
+ +

Evaluates body if the (NimMajor, NimMinor) is greater than or equal to version. Usage:

+

proc fun*() {.since: (1, 3).}
+since (1, 3): fun()

+ + Source   +Edit   + +
+
+
+
template since(version: (int, int, int); body: untyped) {.dirty.}
+
+ +

Evaluates body if (NimMajor, NimMinor, NimPatch) is greater than or equal to version. Usage:

+

proc fun*() {.since: (1, 3, 1).}
+since (1, 3, 1): fun()

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/since.idx b/since.idx new file mode 100644 index 0000000000000..d6012f419ce5d --- /dev/null +++ b/since.idx @@ -0,0 +1,4 @@ +nimTitle since since.html module std/private/since 0 +nim since since.html#since.t,,untyped template since(version: (int, int); body: untyped) 15 +nim since since.html#since.t,,untyped_2 template since(version: (int, int, int); body: untyped) 25 +nimgrp since since.html#since-templates-all template 15 diff --git a/smtp.html b/smtp.html new file mode 100644 index 0000000000000..c2b639c2e1a6f --- /dev/null +++ b/smtp.html @@ -0,0 +1,529 @@ + + + + + + + +src/smtp + + + + + + + + + + + + + + + + +
+
+

src/smtp

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

Note: +In order to use this module, run nimble install smtp.
+

This module implements the SMTP client protocol as specified by RFC 5321, this can be used to send mail to any SMTP Server.

+

This module also implements the protocol used to format messages, as specified by RFC 2822.

+

Example gmail use:

+
var msg = createMessage("Hello from Nim's SMTP",
+                        "Hello!.\n Is this awesome or what?",
+                        @["foo@gmail.com"])
+let smtpConn = newSmtp(useSsl = true, debug=true)
+smtpConn.connect("smtp.gmail.com", Port 465)
+smtpConn.auth("username", "password")
+smtpConn.sendmail("username@gmail.com", @["foo@gmail.com"], $msg)

Example for startTls use:

+
var msg = createMessage("Hello from Nim's SMTP",
+                        "Hello!.\n Is this awesome or what?",
+                        @["foo@gmail.com"])
+let smtpConn = newSmtp(debug=true)
+smtpConn.connect("smtp.mailtrap.io", Port 2525)
+smtpConn.startTls()
+smtpConn.auth("username", "password")
+smtpConn.sendmail("username@gmail.com", @["foo@gmail.com"], $msg)

For SSL support this module relies on OpenSSL. If you want to enable SSL, compile with -d:ssl.

+

+
+

Types

+
+
+
AsyncSmtp = SmtpBase[AsyncSocket]
+
+ + + +
+
+
+
Message = object
+
+ + + +
+
+
+
ReplyError = object of IOError
+
+ + + +
+
+
+
Smtp = SmtpBase[Socket]
+
+ + + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(msg: Message): string {....raises: [], tags: [], forbids: [].}
+
+ + stringify for Message. + +
+
+ +
+
+
+
proc auth(smtp: AsyncSmtp; username, password: string): owned(Future[void]) {.
+    ...stackTrace: false, raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + Sends an AUTH command to the server to login as the username using password. May fail with ReplyError. + +
+
+
+
proc auth(smtp: Smtp; username, password: string) {.
+    ...raises: [SslError, OSError, TimeoutError, ReplyError],
+    tags: [WriteIOEffect, ReadIOEffect, TimeEffect], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc checkReply(smtp: AsyncSmtp; reply: string): owned(Future[void]) {.
+    ...stackTrace: false, raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ +

Calls debugRecv and checks that the received data starts with reply. If the received data does not start with reply, then a QUIT command will be sent to the SMTP server and a ReplyError exception will be raised.

+

This is a lower level proc and not something that you typically would need to call when using this module. One exception to this is if you are implementing any SMTP extensions.

+ + +
+
+
+
proc checkReply(smtp: Smtp; reply: string) {.
+    ...raises: [TimeoutError, OSError, SslError, ReplyError],
+    tags: [ReadIOEffect, TimeEffect, WriteIOEffect], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc close(smtp: AsyncSmtp): owned(Future[void]) {....stackTrace: false,
+    raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + Disconnects from the SMTP server and closes the socket. + +
+
+
+
proc close(smtp: Smtp) {....raises: [SslError, OSError, LibraryError, Exception],
+                         tags: [WriteIOEffect, RootEffect], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc connect(smtp: AsyncSmtp; address: string; port: Port): owned(
+    Future[void]) {....stackTrace: false, raises: [Exception], tags: [RootEffect],
+                    forbids: [].}
+
+ + Establishes a connection with a SMTP server. May fail with ReplyError or with a socket error. + +
+
+
+
proc connect(smtp: Smtp; address: string; port: Port) {.
+    ...raises: [OSError, SslError, TimeoutError, ReplyError],
+    tags: [ReadIOEffect, RootEffect, TimeEffect, WriteIOEffect], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc createMessage(mSubject, mBody: string; mTo, mCc: seq[string] = @[]): Message {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Alternate version of the above.

+

You need to make sure that mSubject, mTo and mCc don't contain any newline characters. Failing to do so will raise AssertionDefect.

+ + +
+
+
+
proc createMessage(mSubject, mBody: string; mTo, mCc: seq[string];
+                   otherHeaders: openArray[tuple[name, value: string]]): Message {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new MIME compliant message.

+

You need to make sure that mSubject, mTo and mCc don't contain any newline characters. Failing to do so will raise AssertionDefect.

+ + +
+
+ +
+
+
+
proc debugRecv(smtp: AsyncSmtp): Future[string] {....stackTrace: false,
+    raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}
+
+ +

Receives a line of data from the socket connected to the SMTP server.

+

If the smtp object was created with debug enabled, debugRecv will invoke echo("S:" & result.string) after the data is received.

+

This is a lower level proc and not something that you typically would need to call when using this module. One exception to this is if you are implementing any SMTP extensions.

+

See checkReply(reply).

+ + +
+
+
+
proc debugRecv(smtp: Smtp): string {....raises: [TimeoutError, OSError, SslError],
+                                     tags: [ReadIOEffect, TimeEffect],
+                                     forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc debugSend(smtp: AsyncSmtp; cmd: string): owned(Future[void]) {.
+    ...stackTrace: false, raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ +

Sends cmd on the socket connected to the SMTP server.

+

If the smtp object was created with debug enabled, debugSend will invoke echo("C:" & cmd) before sending.

+

This is a lower level proc and not something that you typically would need to call when using this module. One exception to this is if you are implementing any SMTP extensions.

+ + +
+
+
+
proc debugSend(smtp: Smtp; cmd: string) {....raises: [SslError, OSError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc ehlo(smtp: AsyncSmtp): Future[bool] {....stackTrace: false,
+    raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}
+
+ + Sends EHLO request. + +
+
+
+
proc ehlo(smtp: Smtp): bool {....raises: [SslError, OSError, TimeoutError],
+                              tags: [WriteIOEffect, ReadIOEffect, TimeEffect],
+                              forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc helo(smtp: AsyncSmtp): owned(Future[void]) {....stackTrace: false,
+    raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + + +
+
+
+
proc helo(smtp: Smtp) {....raises: [SslError, OSError, TimeoutError, ReplyError],
+                        tags: [WriteIOEffect, ReadIOEffect, TimeEffect],
+                        forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc newAsyncSmtp(useSsl = false; debug = false; sslContext: SslContext = nil): AsyncSmtp {.
+    ...raises: [OSError, SslError, LibraryError, Exception, IOError],
+    tags: [RootEffect, ReadDirEffect, ReadEnvEffect], forbids: [].}
+
+ + Creates a new AsyncSmtp instance. + +
+
+ +
+
+
+
proc newSmtp(useSsl = false; debug = false; sslContext: SslContext = nil): Smtp {.
+    ...raises: [OSError, SslError, LibraryError, Exception, IOError],
+    tags: [RootEffect, ReadDirEffect, ReadEnvEffect], forbids: [].}
+
+ + Creates a new Smtp instance. + +
+
+ +
+
+
+
proc sendMail(smtp: AsyncSmtp; fromAddr: string; toAddrs: seq[string];
+              msg: string): owned(Future[void]) {....stackTrace: false,
+    raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ +

Sends msg from fromAddr to the addresses specified in toAddrs. Messages may be formed using createMessage by converting the Message into a string.

+

You need to make sure that fromAddr and toAddrs don't contain any newline characters. Failing to do so will raise AssertionDefect.

+ + +
+
+
+
proc sendMail(smtp: Smtp; fromAddr: string; toAddrs: seq[string]; msg: string) {.
+    ...raises: [SslError, OSError, TimeoutError, ReplyError],
+    tags: [WriteIOEffect, ReadIOEffect, TimeEffect], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc startTls(smtp: AsyncSmtp; sslContext: SslContext = nil): owned(
+    Future[void]) {....stackTrace: false, raises: [Exception],
+                    tags: [RootEffect, ReadDirEffect, ReadEnvEffect],
+                    forbids: [].}
+
+ + Put the SMTP connection in TLS (Transport Layer Security) mode. May fail with ReplyError + +
+
+
+
proc startTls(smtp: Smtp; sslContext: SslContext = nil) {....raises: [SslError,
+    OSError, TimeoutError, ReplyError, Exception, LibraryError, IOError], tags: [
+    WriteIOEffect, ReadIOEffect, TimeEffect, RootEffect, ReadDirEffect,
+    ReadEnvEffect], forbids: [].}
+
+ + + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/smtp.idx b/smtp.idx new file mode 100644 index 0000000000000..4b82ffa1f5707 --- /dev/null +++ b/smtp.idx @@ -0,0 +1,41 @@ +nimTitle smtp smtp.html module src/smtp 0 +nim Message smtp.html#Message object Message 57 +nim ReplyError smtp.html#ReplyError object ReplyError 64 +nim Smtp smtp.html#Smtp type Smtp 71 +nim AsyncSmtp smtp.html#AsyncSmtp type AsyncSmtp 72 +nim debugSend smtp.html#debugSend,AsyncSmtp,string proc debugSend(smtp: AsyncSmtp; cmd: string): owned(Future[void]) 79 +nim debugSend smtp.html#debugSend,Smtp,string proc debugSend(smtp: Smtp; cmd: string) 79 +nim debugRecv smtp.html#debugRecv,AsyncSmtp proc debugRecv(smtp: AsyncSmtp): Future[string] 94 +nim debugRecv smtp.html#debugRecv,Smtp proc debugRecv(smtp: Smtp): string 94 +nim createMessage smtp.html#createMessage,string,string,seq[string],seq[string],openArray[tuple[string,string]] proc createMessage(mSubject, mBody: string; mTo, mCc: seq[string];\n otherHeaders: openArray[tuple[name, value: string]]): Message 128 +nim createMessage smtp.html#createMessage,string,string,seq[string],seq[string] proc createMessage(mSubject, mBody: string; mTo, mCc: seq[string] = @[]): Message 147 +nim `$` smtp.html#$,Message proc `$`(msg: Message): string 163 +nim newSmtp smtp.html#newSmtp,SslContext proc newSmtp(useSsl = false; debug = false; sslContext: SslContext = nil): Smtp 178 +nim newAsyncSmtp smtp.html#newAsyncSmtp,SslContext proc newAsyncSmtp(useSsl = false; debug = false; sslContext: SslContext = nil): AsyncSmtp 192 +nim checkReply smtp.html#checkReply,AsyncSmtp,string proc checkReply(smtp: AsyncSmtp; reply: string): owned(Future[void]) 214 +nim checkReply smtp.html#checkReply,Smtp,string proc checkReply(smtp: Smtp; reply: string) 214 +nim helo smtp.html#helo,AsyncSmtp proc helo(smtp: AsyncSmtp): owned(Future[void]) 228 +nim helo smtp.html#helo,Smtp proc helo(smtp: Smtp) 228 +nim ehlo smtp.html#ehlo,AsyncSmtp proc ehlo(smtp: AsyncSmtp): Future[bool] 244 +nim ehlo smtp.html#ehlo,Smtp proc ehlo(smtp: Smtp): bool 244 +nim connect smtp.html#connect,AsyncSmtp,string,Port proc connect(smtp: AsyncSmtp; address: string; port: Port): owned(Future[void]) 249 +nim connect smtp.html#connect,Smtp,string,Port proc connect(smtp: Smtp; address: string; port: Port) 250 +nim startTls smtp.html#startTls,AsyncSmtp,SslContext proc startTls(smtp: AsyncSmtp; sslContext: SslContext = nil): owned(Future[void]) 260 +nim startTls smtp.html#startTls,Smtp,SslContext proc startTls(smtp: Smtp; sslContext: SslContext = nil) 260 +nim auth smtp.html#auth,AsyncSmtp,string,string proc auth(smtp: AsyncSmtp; username, password: string): owned(Future[void]) 276 +nim auth smtp.html#auth,Smtp,string,string proc auth(smtp: Smtp; username, password: string) 276 +nim sendMail smtp.html#sendMail,AsyncSmtp,string,seq[string],string proc sendMail(smtp: AsyncSmtp; fromAddr: string; toAddrs: seq[string]; msg: string): owned(\n Future[void]) 290 +nim sendMail smtp.html#sendMail,Smtp,string,seq[string],string proc sendMail(smtp: Smtp; fromAddr: string; toAddrs: seq[string]; msg: string) 291 +nim close smtp.html#close,AsyncSmtp proc close(smtp: AsyncSmtp): owned(Future[void]) 314 +nim close smtp.html#close,Smtp proc close(smtp: Smtp) 314 +nimgrp checkreply smtp.html#checkReply-procs-all proc 214 +nimgrp helo smtp.html#helo-procs-all proc 228 +nimgrp close smtp.html#close-procs-all proc 314 +nimgrp createmessage smtp.html#createMessage-procs-all proc 128 +nimgrp connect smtp.html#connect-procs-all proc 249 +nimgrp starttls smtp.html#startTls-procs-all proc 260 +nimgrp sendmail smtp.html#sendMail-procs-all proc 290 +nimgrp debugrecv smtp.html#debugRecv-procs-all proc 94 +nimgrp auth smtp.html#auth-procs-all proc 276 +nimgrp debugsend smtp.html#debugSend-procs-all proc 79 +nimgrp ehlo smtp.html#ehlo-procs-all proc 244 diff --git a/socketstreams.html b/socketstreams.html new file mode 100644 index 0000000000000..0a541fed028b9 --- /dev/null +++ b/socketstreams.html @@ -0,0 +1,256 @@ + + + + + + + +std/socketstreams + + + + + + + + + + + + + + + + +
+
+

std/socketstreams

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module provides an implementation of the streams interface for sockets. It contains two separate implementations, a ReadSocketStream and a WriteSocketStream.

+

The ReadSocketStream only supports reading, peeking, and seeking. It reads into a buffer, so even by seeking backwards it will only read the same position a single time from the underlying socket. To clear the buffer and free the data read into it you can call resetStream, this will also reset the position back to 0 but won't do anything to the underlying socket.

+

The WriteSocketStream allows both reading and writing, but it performs the reads on the internal buffer. So by writing to the buffer you can then read back what was written but without receiving anything from the socket. You can also set the position and overwrite parts of the buffer, and to send anything over the socket you need to call flush at which point you can't write anything to the buffer before the point of the flush (but it can still be read). Again to empty the underlying buffer you need to call resetStream.

+ +

Examples

import std/socketstreams
+
+var
+  socket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
+  stream = newReadSocketStream(socket)
+socket.sendTo("127.0.0.1", Port(12345), "SOME REQUEST")
+echo stream.readLine() # Will call `recv`
+stream.setPosition(0)
+echo stream.readLine() # Will return the read line from the buffer
+stream.resetStream() # Buffer is now empty, position is 0
+echo stream.readLine() # Will call `recv` again
+stream.close() # Closes the socket

+

import std/socketstreams
+
+var socket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
+socket.connect("127.0.0.1", Port(12345))
+var sendStream = newWriteSocketStream(socket)
+sendStream.write "NOM"
+sendStream.setPosition(1)
+echo sendStream.peekStr(2) # OM
+sendStream.write "I"
+sendStream.setPosition(0)
+echo sendStream.readStr(3) # NIM
+echo sendStream.getPosition() # 3
+sendStream.flush() # This actually performs the writing to the socket
+sendStream.setPosition(1)
+sendStream.write "I" # Throws an error as we can't write into an already sent buffer

+

+
+

Imports

+
+ net, streams +
+
+
+

Types

+
+
+
ReadSocketStream = ref ReadSocketStreamObj
+
+ + + Source   +Edit   + +
+
+
+
ReadSocketStreamObj = object of StreamObj
+
+ + + Source   +Edit   + +
+
+
+
WriteSocketStream = ref WriteSocketStreamObj
+
+ + + Source   +Edit   + +
+
+
+
WriteSocketStreamObj = object of ReadSocketStreamObj
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc newReadSocketStream(s: Socket): owned ReadSocketStream {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newWriteSocketStream(s: Socket): owned WriteSocketStream {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc resetStream(s: ReadSocketStream) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc resetStream(s: WriteSocketStream) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/socketstreams.idx b/socketstreams.idx new file mode 100644 index 0000000000000..b836b4df79a8e --- /dev/null +++ b/socketstreams.idx @@ -0,0 +1,11 @@ +nimTitle socketstreams socketstreams.html module std/socketstreams 0 +nim ReadSocketStream socketstreams.html#ReadSocketStream type ReadSocketStream 70 +nim ReadSocketStreamObj socketstreams.html#ReadSocketStreamObj object ReadSocketStreamObj 71 +nim WriteSocketStream socketstreams.html#WriteSocketStream type WriteSocketStream 75 +nim WriteSocketStreamObj socketstreams.html#WriteSocketStreamObj object WriteSocketStreamObj 76 +nim newReadSocketStream socketstreams.html#newReadSocketStream,Socket proc newReadSocketStream(s: Socket): owned ReadSocketStream 154 +nim resetStream socketstreams.html#resetStream,ReadSocketStream proc resetStream(s: ReadSocketStream) 164 +nim newWriteSocketStream socketstreams.html#newWriteSocketStream,Socket proc newWriteSocketStream(s: Socket): owned WriteSocketStream 168 +nim resetStream socketstreams.html#resetStream,WriteSocketStream proc resetStream(s: WriteSocketStream) 179 +heading Examples socketstreams.html#examples Examples 0 +nimgrp resetstream socketstreams.html#resetStream-procs-all proc 164 diff --git a/sqlite3.html b/sqlite3.html new file mode 100644 index 0000000000000..7622e57839015 --- /dev/null +++ b/sqlite3.html @@ -0,0 +1,2690 @@ + + + + + + + +src/db_connector/sqlite3 + + + + + + + + + + + + + + + + +
+
+

src/db_connector/sqlite3

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ +
+ +

+
+

Types

+
+
+
Callback = proc (para1: pointer; para2: int32; para3, para4: cstringArray): int32 {.
+    cdecl.}
+
+ + + +
+
+
+
Collation_needed_func = proc (para1: pointer; para2: PSqlite3; eTextRep: int32;
+                              para4: cstring) {.cdecl.}
+
+ + + +
+
+
+
Create_collation_func = proc (para1: pointer; para2: int32; para3: pointer;
+                              para4: int32; para5: pointer): int32 {.cdecl.}
+
+ + + +
+
+
+
Create_function_final_func = proc (para1: Pcontext) {.cdecl.}
+
+ + + +
+
+
+
Create_function_func_func = proc (para1: Pcontext; para2: int32;
+                                  para3: PValueArg) {.cdecl.}
+
+ + + +
+
+
+
Create_function_step_func = proc (para1: Pcontext; para2: int32;
+                                  para3: PValueArg) {.cdecl.}
+
+ + + +
+
+
+
Pcontext = ptr Context
+
+ + + +
+
+
+
PPSqlite3 = ptr PSqlite3
+
+ + + +
+
+
+
PPSqlite3_Backup = ptr PSqlite3_Backup
+
+ + + +
+
+
+
PSqlite3 = ptr Sqlite3
+
+ + + +
+
+
+
PSqlite3_Backup = ptr Sqlite3_Backup
+
+ + + +
+
+
+
PStmt = ptr TStmt
+
+ + + +
+
+
+
PValue = ptr Value
+
+ + + +
+
+
+
PValueArg = array[0 .. 127, PValue]
+
+ + + +
+
+
+
Result_func = proc (para1: pointer) {.cdecl.}
+
+ + + +
+
+
+
Tbind_destructor_func = proc (para1: pointer) {.cdecl, ...tags: [], gcsafe.}
+
+ + + +
+
+ +
+
+
+

Consts

+
+
+
SQLITE_ABORT = 4
+
+ + + +
+
+
+
SQLITE_ALTER_TABLE = 26
+
+ + + +
+
+
+
SQLITE_ANY = 5
+
+ + + +
+
+
+
SQLITE_ATTACH = 24
+
+ + + +
+
+
+
SQLITE_AUTH = 23
+
+ + + +
+
+
+
SQLITE_BLOB = 4
+
+ + + +
+
+
+
SQLITE_BUSY = 5
+
+ + + +
+
+
+
SQLITE_CANTOPEN = 14
+
+ + + +
+
+
+
SQLITE_CONSTRAINT = 19
+
+ + + +
+
+
+
SQLITE_COPY = 0
+
+ + + +
+
+
+
SQLITE_CORRUPT = 11
+
+ + + +
+
+
+
SQLITE_CREATE_INDEX = 1
+
+ + + +
+
+
+
SQLITE_CREATE_TABLE = 2
+
+ + + +
+
+
+
SQLITE_CREATE_TEMP_INDEX = 3
+
+ + + +
+
+
+
SQLITE_CREATE_TEMP_TABLE = 4
+
+ + + +
+
+
+
SQLITE_CREATE_TEMP_TRIGGER = 5
+
+ + + +
+
+
+
SQLITE_CREATE_TEMP_VIEW = 6
+
+ + + +
+
+
+
SQLITE_CREATE_TRIGGER = 7
+
+ + + +
+
+
+
SQLITE_CREATE_VIEW = 8
+
+ + + +
+
+
+
SQLITE_DELETE = 9
+
+ + + +
+
+
+
SQLITE_DENY = 1
+
+ + + +
+
+
+
SQLITE_DETACH = 25
+
+ + + +
+
+
+
SQLITE_DETERMINISTIC = 0x00000800
+
+ + + +
+
+
+
SQLITE_DONE = 101
+
+ + + +
+
+
+
SQLITE_DROP_INDEX = 10
+
+ + + +
+
+
+
SQLITE_DROP_TABLE = 11
+
+ + + +
+
+
+
SQLITE_DROP_TEMP_INDEX = 12
+
+ + + +
+
+
+
SQLITE_DROP_TEMP_TABLE = 13
+
+ + + +
+
+
+
SQLITE_DROP_TEMP_TRIGGER = 14
+
+ + + +
+
+
+
SQLITE_DROP_TEMP_VIEW = 15
+
+ + + +
+
+
+
SQLITE_DROP_TRIGGER = 16
+
+ + + +
+
+
+
SQLITE_DROP_VIEW = 17
+
+ + + +
+
+
+
SQLITE_EMPTY = 16
+
+ + + +
+
+
+
SQLITE_ERROR = 1
+
+ + + +
+
+
+
SQLITE_FLOAT = 2
+
+ + + +
+
+
+
SQLITE_FORMAT = 24
+
+ + + +
+
+
+
SQLITE_FULL = 13
+
+ + + +
+
+
+
SQLITE_IGNORE = 2
+
+ + + +
+
+
+
SQLITE_INSERT = 18
+
+ + + +
+
+
+
SQLITE_INTEGER = 1
+
+ + + +
+
+
+
SQLITE_INTERNAL = 2
+
+ + + +
+
+
+
SQLITE_INTERRUPT = 9
+
+ + + +
+
+
+
SQLITE_IOERR = 10
+
+ + + +
+
+
+
SQLITE_LOCKED = 6
+
+ + + +
+
+
+
SQLITE_MISMATCH = 20
+
+ + + +
+
+
+
SQLITE_MISUSE = 21
+
+ + + +
+
+
+
SQLITE_NOLFS = 22
+
+ + + +
+
+
+
SQLITE_NOMEM = 7
+
+ + + +
+
+
+
SQLITE_NOTADB = 26
+
+ + + +
+
+
+
SQLITE_NOTFOUND = 12
+
+ + + +
+
+
+
SQLITE_NULL = 5
+
+ + + +
+
+
+
SQLITE_OK = 0
+
+ + + +
+
+
+
SQLITE_PERM = 3
+
+ + + +
+
+
+
SQLITE_PRAGMA = 19
+
+ + + +
+
+
+
SQLITE_PROTOCOL = 15
+
+ + + +
+
+
+
SQLITE_RANGE = 25
+
+ + + +
+
+
+
SQLITE_READ = 20
+
+ + + +
+
+
+
SQLITE_READONLY = 8
+
+ + + +
+
+
+
SQLITE_REINDEX = 27
+
+ + + +
+
+
+
SQLITE_ROW = 100
+
+ + + +
+
+
+
SQLITE_SCHEMA = 17
+
+ + + +
+
+
+
SQLITE_SELECT = 21
+
+ + + +
+
+
+
SQLITE_STATIC = nil
+
+ + + +
+
+
+
SQLITE_TEXT = 3
+
+ + + +
+
+
+
SQLITE_TOOBIG = 18
+
+ + + +
+
+
+
SQLITE_TRANSACTION = 22
+
+ + + +
+
+
+
SQLITE_TRANSIENT = -1
+
+ + + +
+
+
+
SQLITE_UPDATE = 23
+
+ + + +
+
+
+
SQLITE_UTF8 = 1
+
+ + + +
+
+
+
SQLITE_UTF16 = 4
+
+ + + +
+
+
+
SQLITE_UTF16BE = 3
+
+ + + +
+
+
+
SQLITE_UTF16LE = 2
+
+ + + +
+
+ +
+
+
+

Procs

+
+
+
+
proc aggregate_context(para1: Pcontext; nBytes: int32): pointer {.cdecl,
+    dynlib: Lib, importc: "sqlite3_aggregate_context", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc aggregate_count(para1: Pcontext): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_aggregate_count", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc backup_finish(pBackup: PSqlite3_Backup): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_backup_finish", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc backup_init(pDest: PSqlite3; zDestName: cstring; pSource: PSqlite3;
+                 zSourceName: cstring): PSqlite3_Backup {.cdecl, dynlib: Lib,
+    importc: "sqlite3_backup_init", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc backup_pagecount(pBackup: PSqlite3_Backup): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_backup_pagecount", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc backup_remaining(pBackup: PSqlite3_Backup): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_backup_remaining", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc backup_step(pBackup: PSqlite3_Backup; nPage: int32): int32 {.cdecl,
+    dynlib: Lib, importc: "sqlite3_backup_step", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc bind_blob(para1: PStmt; para2: int32; para3: pointer; n: int32;
+               para5: Tbind_destructor_func): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_bind_blob", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+
+
proc bind_blob(para1: PStmt; para2: int32; para3: pointer; n: int32;
+               para5: int32): int32 {.cdecl, dynlib: Lib,
+                                      importc: "sqlite3_bind_blob", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc bind_double(para1: PStmt; para2: int32; para3: float64): int32 {.cdecl,
+    dynlib: Lib, importc: "sqlite3_bind_double", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc bind_int(para1: PStmt; para2: int32; para3: int32): int32 {.cdecl,
+    dynlib: Lib, importc: "sqlite3_bind_int", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc bind_int64(para1: PStmt; para2: int32; para3: int64): int32 {.cdecl,
+    dynlib: Lib, importc: "sqlite3_bind_int64", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc bind_null(para1: PStmt; para2: int32): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_bind_null", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc bind_parameter_count(para1: PStmt): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_bind_parameter_count", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc bind_parameter_index(para1: PStmt; zName: cstring): int32 {.cdecl,
+    dynlib: Lib, importc: "sqlite3_bind_parameter_index", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc bind_parameter_name(para1: PStmt; para2: int32): cstring {.cdecl,
+    dynlib: Lib, importc: "sqlite3_bind_parameter_name", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc bind_text(para1: PStmt; para2: int32; para3: cstring; n: int32;
+               para5: Tbind_destructor_func): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_bind_text", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+
+
proc bind_text(para1: PStmt; para2: int32; para3: cstring; n: int32;
+               para5: int32): int32 {.cdecl, dynlib: Lib,
+                                      importc: "sqlite3_bind_text", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc bind_text16(para1: PStmt; para2: int32; para3: pointer; para4: int32;
+                 para5: int32): int32 {.cdecl, dynlib: Lib,
+                                        importc: "sqlite3_bind_text16",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+
+
proc bind_text16(para1: PStmt; para2: int32; para3: pointer; para4: int32;
+                 para5: Tbind_destructor_func): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_bind_text16", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc busy_handler(para1: PSqlite3;
+                  para2: proc (para1: pointer; para2: int32): int32 {.cdecl.};
+                  para3: pointer): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_busy_handler", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc busy_timeout(para1: PSqlite3; ms: int32): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_busy_timeout", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc changes(para1: PSqlite3): int32 {.cdecl, dynlib: Lib,
+                                       importc: "sqlite3_changes", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc clear_bindings(para1: PStmt): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_clear_bindings", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc close(para1: PSqlite3): int32 {.cdecl, dynlib: Lib,
+                                     importc: "sqlite3_close", ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc collation_needed(para1: PSqlite3; para2: pointer;
+                      para3: Collation_needed_func): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_collation_needed", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc collation_needed16(para1: PSqlite3; para2: pointer;
+                        para3: Collation_needed_func): int32 {.cdecl,
+    dynlib: Lib, importc: "sqlite3_collation_needed16", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc column_blob(para1: PStmt; iCol: int32): pointer {.cdecl, dynlib: Lib,
+    importc: "sqlite3_column_blob", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc column_bytes(para1: PStmt; iCol: int32): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_column_bytes", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc column_bytes16(para1: PStmt; iCol: int32): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_column_bytes16", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc column_count(PStmt: PStmt): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_column_count", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc column_decltype(para1: PStmt; i: int32): cstring {.cdecl, dynlib: Lib,
+    importc: "sqlite3_column_decltype", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc column_decltype16(para1: PStmt; para2: int32): pointer {.cdecl,
+    dynlib: Lib, importc: "sqlite3_column_decltype16", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc column_double(para1: PStmt; iCol: int32): float64 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_column_double", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc column_int(para1: PStmt; iCol: int32): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_column_int", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc column_int64(para1: PStmt; iCol: int32): int64 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_column_int64", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc column_name(para1: PStmt; para2: int32): cstring {.cdecl, dynlib: Lib,
+    importc: "sqlite3_column_name", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc column_name16(para1: PStmt; para2: int32): pointer {.cdecl, dynlib: Lib,
+    importc: "sqlite3_column_name16", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc column_table_name(para1: PStmt; para2: int32): cstring {.cdecl,
+    dynlib: Lib, importc: "sqlite3_column_table_name", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc column_text(para1: PStmt; iCol: int32): cstring {.cdecl, dynlib: Lib,
+    importc: "sqlite3_column_text", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc column_text16(para1: PStmt; iCol: int32): pointer {.cdecl, dynlib: Lib,
+    importc: "sqlite3_column_text16", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc column_type(para1: PStmt; iCol: int32): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_column_type", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc commit_hook(para1: PSqlite3; para2: proc (para1: pointer): int32 {.cdecl.};
+                 para3: pointer): pointer {.cdecl, dynlib: Lib,
+    importc: "sqlite3_commit_hook", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc complete(sql: cstring): int32 {.cdecl, dynlib: Lib,
+                                     importc: "sqlite3_complete", ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc complete16(sql: pointer): int32 {.cdecl, dynlib: Lib,
+                                       importc: "sqlite3_complete16",
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc create_collation(para1: PSqlite3; zName: cstring; eTextRep: int32;
+                      para4: pointer; xCompare: Create_collation_func): int32 {.
+    cdecl, dynlib: Lib, importc: "sqlite3_create_collation", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc create_collation16(para1: PSqlite3; zName: cstring; eTextRep: int32;
+                        para4: pointer; xCompare: Create_collation_func): int32 {.
+    cdecl, dynlib: Lib, importc: "sqlite3_create_collation16", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc create_function(para1: PSqlite3; zFunctionName: cstring; nArg: int32;
+                     eTextRep: int32; para5: pointer;
+                     xFunc: Create_function_func_func;
+                     xStep: Create_function_step_func;
+                     xFinal: Create_function_final_func): int32 {.cdecl,
+    dynlib: Lib, importc: "sqlite3_create_function", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc create_function16(para1: PSqlite3; zFunctionName: pointer; nArg: int32;
+                       eTextRep: int32; para5: pointer;
+                       xFunc: Create_function_func_func;
+                       xStep: Create_function_step_func;
+                       xFinal: Create_function_final_func): int32 {.cdecl,
+    dynlib: Lib, importc: "sqlite3_create_function16", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc data_count(PStmt: PStmt): int32 {.cdecl, dynlib: Lib,
+                                       importc: "sqlite3_data_count",
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc errcode(db: PSqlite3): int32 {.cdecl, dynlib: Lib,
+                                    importc: "sqlite3_errcode", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc errmsg(para1: PSqlite3): cstring {.cdecl, dynlib: Lib,
+                                        importc: "sqlite3_errmsg", ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc errmsg16(para1: PSqlite3): pointer {.cdecl, dynlib: Lib,
+    importc: "sqlite3_errmsg16", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc exec(para1: PSqlite3; sql: cstring; para3: Callback; para4: pointer;
+          errmsg: var cstring): int32 {.cdecl, dynlib: Lib,
+                                        importc: "sqlite3_exec", ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc finalize(PStmt: PStmt): int32 {.cdecl, dynlib: Lib,
+                                     importc: "sqlite3_finalize", ...raises: [],
+                                     tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc free(z: cstring) {.cdecl, dynlib: Lib, importc: "sqlite3_free", ...raises: [],
+                        tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc free_table(result: cstringArray) {.cdecl, dynlib: Lib,
+                                        importc: "sqlite3_free_table",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc get_auxdata(para1: Pcontext; para2: int32): pointer {.cdecl, dynlib: Lib,
+    importc: "sqlite3_get_auxdata", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc get_table(para1: PSqlite3; sql: cstring; resultp: var cstringArray;
+               nrow, ncolumn: var cint; errmsg: ptr cstring): int32 {.cdecl,
+    dynlib: Lib, importc: "sqlite3_get_table", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc interrupt(para1: PSqlite3) {.cdecl, dynlib: Lib,
+                                  importc: "sqlite3_interrupt", ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc last_insert_rowid(para1: PSqlite3): int64 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_last_insert_rowid", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc libversion(): cstring {.cdecl, dynlib: Lib, importc: "sqlite3_libversion",
+                             ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc libversion_number(): int32 {.cdecl, dynlib: Lib,
+                                  importc: "sqlite3_libversion_number",
+                                  ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc mprintf(para1: cstring): cstring {.cdecl, varargs, dynlib: Lib,
+                                        importc: "sqlite3_mprintf", ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc open(filename: cstring; ppDb: var PSqlite3): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_open", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc open16(filename: pointer; ppDb: var PSqlite3): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_open16", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc prepare(db: PSqlite3; zSql: cstring; nBytes: int32; ppStmt: var PStmt;
+             pzTail: ptr cstring): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_prepare", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc prepare16(db: PSqlite3; zSql: pointer; nBytes: int32; ppStmt: var PStmt;
+               pzTail: var pointer): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_prepare16", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc prepare_v2(db: PSqlite3; zSql: cstring; nByte: cint; ppStmt: var PStmt;
+                pzTail: ptr cstring): cint {.importc: "sqlite3_prepare_v2",
+    cdecl, dynlib: Lib, ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc progress_handler(para1: PSqlite3; para2: int32;
+                      para3: proc (para1: pointer): int32 {.cdecl.};
+                      para4: pointer) {.cdecl, dynlib: Lib,
+                                        importc: "sqlite3_progress_handler",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc reset(PStmt: PStmt): int32 {.cdecl, dynlib: Lib, importc: "sqlite3_reset",
+                                  ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc result_blob(para1: Pcontext; para2: pointer; para3: int32;
+                 para4: Result_func) {.cdecl, dynlib: Lib,
+                                       importc: "sqlite3_result_blob",
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc result_double(para1: Pcontext; para2: float64) {.cdecl, dynlib: Lib,
+    importc: "sqlite3_result_double", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc result_error(para1: Pcontext; para2: cstring; para3: int32) {.cdecl,
+    dynlib: Lib, importc: "sqlite3_result_error", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc result_error16(para1: Pcontext; para2: pointer; para3: int32) {.cdecl,
+    dynlib: Lib, importc: "sqlite3_result_error16", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc result_int(para1: Pcontext; para2: int32) {.cdecl, dynlib: Lib,
+    importc: "sqlite3_result_int", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc result_int64(para1: Pcontext; para2: int64) {.cdecl, dynlib: Lib,
+    importc: "sqlite3_result_int64", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc result_null(para1: Pcontext) {.cdecl, dynlib: Lib,
+                                    importc: "sqlite3_result_null", ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc result_text(para1: Pcontext; para2: cstring; para3: int32;
+                 para4: Result_func) {.cdecl, dynlib: Lib,
+                                       importc: "sqlite3_result_text",
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc result_text16(para1: Pcontext; para2: pointer; para3: int32;
+                   para4: Result_func) {.cdecl, dynlib: Lib,
+    importc: "sqlite3_result_text16", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc result_text16be(para1: Pcontext; para2: pointer; para3: int32;
+                     para4: Result_func) {.cdecl, dynlib: Lib,
+    importc: "sqlite3_result_text16be", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc result_text16le(para1: Pcontext; para2: pointer; para3: int32;
+                     para4: Result_func) {.cdecl, dynlib: Lib,
+    importc: "sqlite3_result_text16le", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc result_value(para1: Pcontext; para2: PValue) {.cdecl, dynlib: Lib,
+    importc: "sqlite3_result_value", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc set_authorizer(para1: PSqlite3; xAuth: proc (para1: pointer; para2: int32;
+    para3: cstring; para4: cstring; para5: cstring; para6: cstring): int32 {.
+    cdecl.}; pUserData: pointer): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_set_authorizer", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc set_auxdata(para1: Pcontext; para2: int32; para3: pointer;
+                 para4: proc (para1: pointer) {.cdecl.}) {.cdecl, dynlib: Lib,
+    importc: "sqlite3_set_auxdata", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc snprintf(para1: int32; para2: cstring; para3: cstring): cstring {.cdecl,
+    dynlib: Lib, varargs, importc: "sqlite3_snprintf", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc sqlite3_sleep(t: int64): int64 {.cdecl, dynlib: Lib,
+                                      importc: "sqlite3_sleep", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc step(para1: PStmt): int32 {.cdecl, dynlib: Lib, importc: "sqlite3_step",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc total_changes(para1: PSqlite3): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_total_changes", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc trace(para1: PSqlite3;
+           xTrace: proc (para1: pointer; para2: cstring) {.cdecl.};
+           para3: pointer): pointer {.cdecl, dynlib: Lib,
+                                      importc: "sqlite3_trace", ...raises: [],
+                                      tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc user_data(para1: Pcontext): pointer {.cdecl, dynlib: Lib,
+    importc: "sqlite3_user_data", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc value_blob(para1: PValue): pointer {.cdecl, dynlib: Lib,
+    importc: "sqlite3_value_blob", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc value_bytes(para1: PValue): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_value_bytes", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc value_bytes16(para1: PValue): int32 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_value_bytes16", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc value_double(para1: PValue): float64 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_value_double", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc value_int(para1: PValue): int32 {.cdecl, dynlib: Lib,
+                                       importc: "sqlite3_value_int", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc value_int64(para1: PValue): int64 {.cdecl, dynlib: Lib,
+    importc: "sqlite3_value_int64", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc value_text(para1: PValue): cstring {.cdecl, dynlib: Lib,
+    importc: "sqlite3_value_text", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc value_text16(para1: PValue): pointer {.cdecl, dynlib: Lib,
+    importc: "sqlite3_value_text16", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc value_text16be(para1: PValue): pointer {.cdecl, dynlib: Lib,
+    importc: "sqlite3_value_text16be", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc value_text16le(para1: PValue): pointer {.cdecl, dynlib: Lib,
+    importc: "sqlite3_value_text16le", ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc value_type(para1: PValue): int32 {.cdecl, dynlib: Lib,
+                                        importc: "sqlite3_value_type",
+                                        ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+
+
+
proc version(): cstring {.cdecl, dynlib: Lib, importc: "sqlite3_libversion",
+                          ...raises: [], tags: [], forbids: [].}
+
+ + + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/ssl_certs.html b/ssl_certs.html new file mode 100644 index 0000000000000..2a850a527756a --- /dev/null +++ b/ssl_certs.html @@ -0,0 +1,122 @@ + + + + + + + +std/ssl_certs + + + + + + + + + + + + + + + + +
+
+

std/ssl_certs

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Scan for SSL/TLS CA certificates on disk The default locations can be overridden using the SSL_CERT_FILE and SSL_CERT_DIR environment variables.

+
+

Imports

+
+ os, strutils +
+
+
+

Iterators

+
+
+
+
iterator scanSSLCertificates(useEnvVars = false): string {....raises: [],
+    tags: [ReadEnvEffect, ReadDirEffect], forbids: [].}
+
+ +

Scan for SSL/TLS CA certificates on disk.

+

if useEnvVars is true, the SSL_CERT_FILE and SSL_CERT_DIR environment variables can be used to override the certificate directories to scan or specify a CA certificate file.

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/ssl_certs.idx b/ssl_certs.idx new file mode 100644 index 0000000000000..bdbdcd67a5033 --- /dev/null +++ b/ssl_certs.idx @@ -0,0 +1,2 @@ +nimTitle ssl_certs ssl_certs.html module std/ssl_certs 0 +nim scanSSLCertificates ssl_certs.html#scanSSLCertificates.i iterator scanSSLCertificates(useEnvVars = false): string 95 diff --git a/ssl_config.html b/ssl_config.html new file mode 100644 index 0000000000000..84725e1e3a86a --- /dev/null +++ b/ssl_config.html @@ -0,0 +1,163 @@ + + + + + + + +std/ssl_config + + + + + + + + + + + + + + + + +
+
+

std/ssl_config

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module contains SSL configuration parameters obtained from Mozilla OpSec.

+

The configuration file used to generate this module: https://ssl-config.mozilla.org/guidelines/5.4.json

+

+
+

Consts

+
+
+
CiphersIntermediate = "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384"
+
+ +

An OpenSSL-compatible list of secure ciphers for intermediate compatibility per Mozilla's recommendations.

+

Oldest clients supported by this list:

+
  • Firefox 27
  • +
  • Android 4.4.2
  • +
  • Chrome 31
  • +
  • Edge
  • +
  • IE 11 on Windows 7
  • +
  • Java 8u31
  • +
  • OpenSSL 1.0.1
  • +
  • Opera 20
  • +
  • Safari 9
  • +
+ + Source   +Edit   + +
+
+
+
CiphersModern = "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256"
+
+ +

An OpenSSL-compatible list of secure ciphers for modern compatibility per Mozilla's recommendations.

+

Oldest clients supported by this list:

+
  • Firefox 63
  • +
  • Android 10.0
  • +
  • Chrome 70
  • +
  • Edge 75
  • +
  • Java 11
  • +
  • OpenSSL 1.1.1
  • +
  • Opera 57
  • +
  • Safari 12.1
  • +
+ + Source   +Edit   + +
+
+
+
CiphersOld = "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA"
+
+ +

An OpenSSL-compatible list of secure ciphers for old compatibility per Mozilla's recommendations.

+

Oldest clients supported by this list:

+
  • Firefox 1
  • +
  • Android 2.3
  • +
  • Chrome 1
  • +
  • Edge 12
  • +
  • IE8 on Windows XP
  • +
  • Java 6
  • +
  • OpenSSL 0.9.8
  • +
  • Opera 5
  • +
  • Safari 1
  • +
+ + Source   +Edit   + +
+
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/ssl_config.idx b/ssl_config.idx new file mode 100644 index 0000000000000..fcecde49f8610 --- /dev/null +++ b/ssl_config.idx @@ -0,0 +1,4 @@ +nimTitle ssl_config ssl_config.html module std/ssl_config 0 +nim CiphersModern ssl_config.html#CiphersModern const CiphersModern 8 +nim CiphersIntermediate ssl_config.html#CiphersIntermediate const CiphersIntermediate 22 +nim CiphersOld ssl_config.html#CiphersOld const CiphersOld 37 diff --git a/stackframes.html b/stackframes.html new file mode 100644 index 0000000000000..3de35e6025c4d --- /dev/null +++ b/stackframes.html @@ -0,0 +1,144 @@ + + + + + + + +std/stackframes + + + + + + + + + + + + + + + + +
+
+

std/stackframes

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
+

Templates

+
+
+
+
template getPFrame(): PFrame
+
+ + avoids a function call (unlike getFrame()) + Source   +Edit   + +
+
+ +
+
+
+
template procName(): string
+
+ + returns current C/C++ function name + Source   +Edit   + +
+
+ +
+
+
+
template setFrameMsg(msg: string; prefix = " ")
+
+ + attach a msg to current PFrame. This can be called multiple times in a given PFrame. Noop unless passing --stacktraceMsgs and --stacktrace + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/stackframes.idx b/stackframes.idx new file mode 100644 index 0000000000000..0c5d815943ff2 --- /dev/null +++ b/stackframes.idx @@ -0,0 +1,4 @@ +nimTitle stackframes stackframes.html module std/stackframes 0 +nim procName stackframes.html#procName.t template procName(): string 4 +nim getPFrame stackframes.html#getPFrame.t template getPFrame(): PFrame 11 +nim setFrameMsg stackframes.html#setFrameMsg.t,string,string template setFrameMsg(msg: string; prefix = " ") 19 diff --git a/staticos.html b/staticos.html new file mode 100644 index 0000000000000..0c2621f164fa4 --- /dev/null +++ b/staticos.html @@ -0,0 +1,131 @@ + + + + + + + +std/staticos + + + + + + + + + + + + + + + + +
+
+

std/staticos

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements path handling like os module but works at only compile-time. This module works even when cross compiling to OS that is not supported by os module.

+
+

Procs

+
+
+
+
proc staticDirExists(dir: string): bool {.compileTime, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Returns true if the directory dir exists. If dir is a file, false is returned. Follows symlinks. + Source   +Edit   + +
+
+ +
+
+
+
proc staticFileExists(filename: string): bool {.compileTime, ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Returns true if filename exists and is a regular file or symlink.

+

Directories, device files, named pipes and sockets return false.

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/staticos.idx b/staticos.idx new file mode 100644 index 0000000000000..7690579f6956e --- /dev/null +++ b/staticos.idx @@ -0,0 +1,3 @@ +nimTitle staticos staticos.html module std/staticos 0 +nim staticFileExists staticos.html#staticFileExists,string proc staticFileExists(filename: string): bool 4 +nim staticDirExists staticos.html#staticDirExists,string proc staticDirExists(dir: string): bool 10 diff --git a/stats.html b/stats.html new file mode 100644 index 0000000000000..ab19751dfd843 --- /dev/null +++ b/stats.html @@ -0,0 +1,687 @@ + + + + + + + +std/stats + + + + + + + + + + + + + + + + +
+
+

std/stats

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Statistical analysis framework for performing basic statistical analysis of data. The data is analysed in a single pass, when it is pushed to a RunningStat or RunningRegress object.

+

RunningStat calculates for a single data set

+
  • n (data count)
  • +
  • min (smallest value)
  • +
  • max (largest value)
  • +
  • sum
  • +
  • mean
  • +
  • variance
  • +
  • varianceS (sample variance)
  • +
  • standardDeviation
  • +
  • standardDeviationS (sample standard deviation)
  • +
  • skewness (the third statistical moment)
  • +
  • kurtosis (the fourth statistical moment)
  • +
+

RunningRegress calculates for two sets of data

+
  • n (data count)
  • +
  • slope
  • +
  • intercept
  • +
  • correlation
  • +
+

Procs are provided to calculate statistics on openArrays.

+

However, if more than a single statistical calculation is required, it is more efficient to push the data once to a RunningStat object and then call the numerous statistical procs for the RunningStat object:

+ +

Example:

+
import std/stats
+from std/math import almostEqual
+
+template `~=`(a, b: float): bool = almostEqual(a, b)
+
+var statistics: RunningStat  # must be var
+statistics.push(@[1.0, 2.0, 1.0, 4.0, 1.0, 4.0, 1.0, 2.0])
+doAssert statistics.n == 8
+doAssert statistics.mean() ~= 2.0
+doAssert statistics.variance() ~= 1.5
+doAssert statistics.varianceS() ~= 1.714285714285715
+doAssert statistics.skewness() ~= 0.8164965809277261
+doAssert statistics.skewnessS() ~= 1.018350154434631
+doAssert statistics.kurtosis() ~= -1.0
+doAssert statistics.kurtosisS() ~= -0.7000000000000008

+ +
+

Types

+
+
+
RunningRegress = object
+  n*: int                    ## amount of pushed data
+  x_stats*: RunningStat      ## stats for the first set of data
+  y_stats*: RunningStat      ## stats for the second set of data
+  ## accumulated data for combined xy
+
+ + An accumulator for regression calculations. + Source   +Edit   + +
+
+
+
RunningStat = object
+  n*: int                    ## amount of pushed data
+  min*, max*, sum*: float    ## self-explaining
+  ## statistical moments, mom1 is mean
+
+ + An accumulator for statistical data. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(a: RunningStat): string {....raises: [], tags: [], forbids: [].}
+
+ + Produces a string representation of the RunningStat. The exact format is currently unspecified and subject to change. Currently it contains:
  • the number of probes
  • +
  • min, max values
  • +
  • sum, mean and standard deviation.
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
proc `+`(a, b: RunningRegress): RunningRegress {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Combines two RunningRegress objects.

+

Useful when performing parallel analysis of data series and needing to re-combine parallel result sets

+ + Source   +Edit   + +
+
+
+
proc `+`(a, b: RunningStat): RunningStat {....raises: [], tags: [], forbids: [].}
+
+ +

Combines two RunningStats.

+

Useful when performing parallel analysis of data series and needing to re-combine parallel result sets.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `+=`(a: var RunningRegress; b: RunningRegress) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Adds the RunningRegress b to a. + Source   +Edit   + +
+
+
+
proc `+=`(a: var RunningStat; b: RunningStat) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Adds the RunningStat b to a. + Source   +Edit   + +
+
+ +
+
+
+
proc clear(r: var RunningRegress) {....raises: [], tags: [], forbids: [].}
+
+ + Resets r. + Source   +Edit   + +
+
+
+
proc clear(s: var RunningStat) {....raises: [], tags: [], forbids: [].}
+
+ + Resets s. + Source   +Edit   + +
+
+ +
+
+
+
proc correlation(r: RunningRegress): float {....raises: [], tags: [], forbids: [].}
+
+ + Computes the current correlation of the two data sets pushed into r. + Source   +Edit   + +
+
+ +
+
+
+
proc intercept(r: RunningRegress): float {....raises: [], tags: [], forbids: [].}
+
+ + Computes the current intercept of r. + Source   +Edit   + +
+
+ +
+
+
+
proc kurtosis(s: RunningStat): float {....raises: [], tags: [], forbids: [].}
+
+ + Computes the current population kurtosis of s. + Source   +Edit   + +
+
+
+
proc kurtosis[T](x: openArray[T]): float
+
+ + Computes the population kurtosis of x. + Source   +Edit   + +
+
+ +
+
+
+
proc kurtosisS(s: RunningStat): float {....raises: [], tags: [], forbids: [].}
+
+ + Computes the current sample kurtosis of s. + Source   +Edit   + +
+
+
+
proc kurtosisS[T](x: openArray[T]): float
+
+ + Computes the sample kurtosis of x. + Source   +Edit   + +
+
+ +
+
+
+
proc mean(s: RunningStat): float {....raises: [], tags: [], forbids: [].}
+
+ + Computes the current mean of s. + Source   +Edit   + +
+
+
+
proc mean[T](x: openArray[T]): float
+
+ + Computes the mean of x. + Source   +Edit   + +
+
+ +
+
+
+
proc push(r: var RunningRegress; x, y: float) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Pushes two values x and y for processing. + Source   +Edit   + +
+
+
+
proc push(r: var RunningRegress; x, y: int) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Pushes two values x and y for processing.

+

x and y are converted to float and the other push operation is called.

+ + Source   +Edit   + +
+
+
+
proc push(r: var RunningRegress; x, y: openArray[float | int])
+
+ + Pushes two sets of values x and y for processing. + Source   +Edit   + +
+
+
+
proc push(s: var RunningStat; x: float) {....raises: [], tags: [], forbids: [].}
+
+ + Pushes a value x for processing. + Source   +Edit   + +
+
+
+
proc push(s: var RunningStat; x: int) {....raises: [], tags: [], forbids: [].}
+
+ +

Pushes a value x for processing.

+

x is simply converted to float and the other push operation is called.

+ + Source   +Edit   + +
+
+
+
proc push(s: var RunningStat; x: openArray[float | int])
+
+ +

Pushes all values of x for processing.

+

Int values of x are simply converted to float and the other push operation is called.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc skewness(s: RunningStat): float {....raises: [], tags: [], forbids: [].}
+
+ + Computes the current population skewness of s. + Source   +Edit   + +
+
+
+
proc skewness[T](x: openArray[T]): float
+
+ + Computes the population skewness of x. + Source   +Edit   + +
+
+ +
+
+
+
proc skewnessS(s: RunningStat): float {....raises: [], tags: [], forbids: [].}
+
+ + Computes the current sample skewness of s. + Source   +Edit   + +
+
+
+
proc skewnessS[T](x: openArray[T]): float
+
+ + Computes the sample skewness of x. + Source   +Edit   + +
+
+ +
+
+
+
proc slope(r: RunningRegress): float {....raises: [], tags: [], forbids: [].}
+
+ + Computes the current slope of r. + Source   +Edit   + +
+
+ +
+
+
+
proc standardDeviation(s: RunningStat): float {....raises: [], tags: [],
+    forbids: [].}
+
+ + Computes the current population standard deviation of s. + Source   +Edit   + +
+
+
+
proc standardDeviation[T](x: openArray[T]): float
+
+ + Computes the population standard deviation of x. + Source   +Edit   + +
+
+ +
+
+
+
proc standardDeviationS(s: RunningStat): float {....raises: [], tags: [],
+    forbids: [].}
+
+ + Computes the current sample standard deviation of s. + Source   +Edit   + +
+
+
+
proc standardDeviationS[T](x: openArray[T]): float
+
+ + Computes the sample standard deviation of x. + Source   +Edit   + +
+
+ +
+
+
+
proc variance(s: RunningStat): float {....raises: [], tags: [], forbids: [].}
+
+ + Computes the current population variance of s. + Source   +Edit   + +
+
+
+
proc variance[T](x: openArray[T]): float
+
+ + Computes the population variance of x. + Source   +Edit   + +
+
+ +
+
+
+
proc varianceS(s: RunningStat): float {....raises: [], tags: [], forbids: [].}
+
+ + Computes the current sample variance of s. + Source   +Edit   + +
+
+
+
proc varianceS[T](x: openArray[T]): float
+
+ + Computes the sample variance of x. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/stats.idx b/stats.idx new file mode 100644 index 0000000000000..bcd8b135d42e4 --- /dev/null +++ b/stats.idx @@ -0,0 +1,50 @@ +nimTitle stats stats.html module std/stats 0 +nim RunningStat stats.html#RunningStat object RunningStat 66 +nim RunningRegress stats.html#RunningRegress object RunningRegress 71 +nim clear stats.html#clear,RunningStat proc clear(s: var RunningStat) 79 +nim push stats.html#push,RunningStat,float proc push(s: var RunningStat; x: float) 90 +nim push stats.html#push,RunningStat,int proc push(s: var RunningStat; x: int) 112 +nim push stats.html#push,RunningStat,openArray[] proc push(s: var RunningStat; x: openArray[float | int]) 119 +nim mean stats.html#mean,RunningStat proc mean(s: RunningStat): float 127 +nim variance stats.html#variance,RunningStat proc variance(s: RunningStat): float 131 +nim varianceS stats.html#varianceS,RunningStat proc varianceS(s: RunningStat): float 135 +nim standardDeviation stats.html#standardDeviation,RunningStat proc standardDeviation(s: RunningStat): float 139 +nim standardDeviationS stats.html#standardDeviationS,RunningStat proc standardDeviationS(s: RunningStat): float 143 +nim skewness stats.html#skewness,RunningStat proc skewness(s: RunningStat): float 147 +nim skewnessS stats.html#skewnessS,RunningStat proc skewnessS(s: RunningStat): float 151 +nim kurtosis stats.html#kurtosis,RunningStat proc kurtosis(s: RunningStat): float 156 +nim kurtosisS stats.html#kurtosisS,RunningStat proc kurtosisS(s: RunningStat): float 160 +nim `+` stats.html#+,RunningStat,RunningStat proc `+`(a, b: RunningStat): RunningStat 165 +nim `+=` stats.html#+=,RunningStat,RunningStat proc `+=`(a: var RunningStat; b: RunningStat) 193 +nim `$` stats.html#$,RunningStat proc `$`(a: RunningStat): string 197 +nim mean stats.html#mean,openArray[T] proc mean[T](x: openArray[T]): float 216 +nim variance stats.html#variance,openArray[T] proc variance[T](x: openArray[T]): float 222 +nim varianceS stats.html#varianceS,openArray[T] proc varianceS[T](x: openArray[T]): float 228 +nim standardDeviation stats.html#standardDeviation,openArray[T] proc standardDeviation[T](x: openArray[T]): float 234 +nim standardDeviationS stats.html#standardDeviationS,openArray[T] proc standardDeviationS[T](x: openArray[T]): float 240 +nim skewness stats.html#skewness,openArray[T] proc skewness[T](x: openArray[T]): float 246 +nim skewnessS stats.html#skewnessS,openArray[T] proc skewnessS[T](x: openArray[T]): float 252 +nim kurtosis stats.html#kurtosis,openArray[T] proc kurtosis[T](x: openArray[T]): float 258 +nim kurtosisS stats.html#kurtosisS,openArray[T] proc kurtosisS[T](x: openArray[T]): float 264 +nim clear stats.html#clear,RunningRegress proc clear(r: var RunningRegress) 272 +nim push stats.html#push,RunningRegress,float,float proc push(r: var RunningRegress; x, y: float) 279 +nim push stats.html#push,RunningRegress,int,int proc push(r: var RunningRegress; x, y: int) 287 +nim push stats.html#push,RunningRegress,openArray[],openArray[] proc push(r: var RunningRegress; x, y: openArray[float | int]) 294 +nim slope stats.html#slope,RunningRegress proc slope(r: RunningRegress): float 300 +nim intercept stats.html#intercept,RunningRegress proc intercept(r: RunningRegress): float 305 +nim correlation stats.html#correlation,RunningRegress proc correlation(r: RunningRegress): float 309 +nim `+` stats.html#+,RunningRegress,RunningRegress proc `+`(a, b: RunningRegress): RunningRegress 315 +nim `+=` stats.html#+=,RunningRegress,RunningRegress proc `+=`(a: var RunningRegress; b: RunningRegress) 330 +nimgrp standarddeviations stats.html#standardDeviationS-procs-all proc 143 +nimgrp standarddeviation stats.html#standardDeviation-procs-all proc 139 +nimgrp skewnesss stats.html#skewnessS-procs-all proc 151 +nimgrp + stats.html#+-procs-all proc 165 +nimgrp mean stats.html#mean-procs-all proc 127 +nimgrp skewness stats.html#skewness-procs-all proc 147 +nimgrp kurtosis stats.html#kurtosis-procs-all proc 156 +nimgrp clear stats.html#clear-procs-all proc 79 +nimgrp variance stats.html#variance-procs-all proc 131 +nimgrp kurtosiss stats.html#kurtosisS-procs-all proc 160 +nimgrp += stats.html#+=-procs-all proc 193 +nimgrp variances stats.html#varianceS-procs-all proc 135 +nimgrp push stats.html#push-procs-all proc 90 diff --git a/strbasics.html b/strbasics.html new file mode 100644 index 0000000000000..742c85a32c669 --- /dev/null +++ b/strbasics.html @@ -0,0 +1,198 @@ + + + + + + + +std/strbasics + + + + + + + + + + + + + + + + +
+
+

std/strbasics

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module provides some high performance string operations.

+

Experimental API, subject to change.

+

+
+

Imports

+
+ assertions +
+
+
+

Procs

+
+
+
+
proc add(x: var string; y: openArray[char]) {....raises: [], tags: [], forbids: [].}
+
+ + Concatenates x and y in place. y must not overlap with x to allow future memcpy optimizations. + Source   +Edit   + +
+
+ +
+
+
+
func setSlice(s: var string; slice: Slice[int]) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Inplace version of substr. +

Example:

+
import std/sugar
+
+var a = "Hello, Nim!"
+doAssert a.dup(setSlice(7 .. 9)) == "Nim"
+doAssert a.dup(setSlice(0 .. 0)) == "H"
+doAssert a.dup(setSlice(0 .. 1)) == "He"
+doAssert a.dup(setSlice(0 .. 10)) == a
+doAssert a.dup(setSlice(1 .. 0)).len == 0
+doAssert a.dup(setSlice(20 .. -1)).len == 0
+
+
+doAssertRaises(AssertionDefect):
+  discard a.dup(setSlice(-1 .. 1))
+
+doAssertRaises(AssertionDefect):
+  discard a.dup(setSlice(1 .. 11))
+ Source   +Edit   + +
+
+ +
+
+
+
func strip(a: var string; leading = true; trailing = true;
+           chars: set[char] = whitespaces) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Inplace version of strip. Strips leading or trailing chars (default: whitespace characters).

+

If leading is true (default), leading chars are stripped. If trailing is true (default), trailing chars are stripped. If both are false, the string is unchanged.

+ +

Example:

+
var a = "  vhellov   "
+strip(a)
+assert a == "vhellov"
+
+a = "  vhellov   "
+a.strip(leading = false)
+assert a == "  vhellov"
+
+a = "  vhellov   "
+a.strip(trailing = false)
+assert a == "vhellov   "
+
+var c = "blaXbla"
+c.strip(chars = {'b', 'a'})
+assert c == "laXbl"
+c = "blaXbla"
+c.strip(chars = {'b', 'a', 'l'})
+assert c == "X"
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/strbasics.idx b/strbasics.idx new file mode 100644 index 0000000000000..9732246936cdc --- /dev/null +++ b/strbasics.idx @@ -0,0 +1,4 @@ +nimTitle strbasics strbasics.html module std/strbasics 0 +nim add strbasics.html#add,string,openArray[char] proc add(x: var string; y: openArray[char]) 20 +nim setSlice strbasics.html#setSlice,string,Slice[int] proc setSlice(s: var string; slice: Slice[int]) 47 +nim strip strbasics.html#strip,string,set[char] proc strip(a: var string; leading = true; trailing = true;\n chars: set[char] = whitespaces) 92 diff --git a/streams.html b/streams.html new file mode 100644 index 0000000000000..78f70a37ba67a --- /dev/null +++ b/streams.html @@ -0,0 +1,1912 @@ + + + + + + + +std/streams + + + + + + + + + + + + + + + + +
+
+

std/streams

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

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.

+
Warning: +Due to the use of pointer, the readData, peekData and
+

writeData interfaces are not available on the compile-time VM, and must be cast from a ptr string on the JS backend. However, readDataStr is available generally in place of readData.

+ +

Basic usage

The basic flow of using this module is:

+
  1. Open input stream
  2. +
  3. Read or write stream
  4. +
  5. Close stream
  6. +
+ +

StringStream example

import std/streams
+
+var strm = newStringStream("""The first line
+the second line
+the third line""")
+
+var line = ""
+
+while strm.readLine(line):
+  echo line
+
+# Output:
+# The first line
+# the second line
+# the third line
+
+strm.close()

+ +

FileStream example

Write file stream example:

+

import std/streams
+
+var strm = newFileStream("somefile.txt", fmWrite)
+var line = ""
+
+if not isNil(strm):
+  strm.writeLine("The first line")
+  strm.writeLine("the second line")
+  strm.writeLine("the third line")
+  strm.close()
+
+# Output (somefile.txt):
+# The first line
+# the second line
+# the third line

+

Read file stream example:

+

import std/streams
+
+var strm = newFileStream("somefile.txt", fmRead)
+var line = ""
+
+if not isNil(strm):
+  while strm.readLine(line):
+    echo line
+  strm.close()
+
+# Output:
+# The first line
+# the second line
+# the third line

+ +

See also

+

+
+

Imports

+
+ since, syncio +
+
+
+

Types

+
+
+
FileStream = ref FileStreamObj
+
+ +

A stream that encapsulates a File.

+

Note: Not available for JS backend.

+ + Source   +Edit   + +
+
+
+
FileStreamObj = object of Stream
+
+ +

A file stream object.

+

Note: Not available for JS backend.

+ + Source   +Edit   + +
+
+
+
Stream = ref StreamObj
+
+ + All procedures of this module use this type. Procedures don't directly use StreamObj. + Source   +Edit   + +
+
+
+
StreamObj = object of RootObj
+  closeImpl*: proc (s: Stream) {.nimcall, ...raises: [IOError, OSError],
+                                 tags: [WriteIOEffect], gcsafe.}
+  atEndImpl*: proc (s: Stream): bool {.nimcall,
+                                       ...raises: [Defect, IOError, OSError],
+                                       tags: [], gcsafe.}
+  setPositionImpl*: proc (s: Stream; pos: int) {.nimcall,
+      ...raises: [Defect, IOError, OSError], tags: [], gcsafe.}
+  getPositionImpl*: proc (s: Stream): int {.nimcall,
+      ...raises: [Defect, IOError, OSError], tags: [], gcsafe.}
+  readDataStrImpl*: proc (s: Stream; buffer: var string; slice: Slice[int]): int {.
+      nimcall, ...raises: [Defect, IOError, OSError], tags: [ReadIOEffect], gcsafe.}
+  readLineImpl*: proc (s: Stream; line: var string): bool {.nimcall,
+      ...raises: [Defect, IOError, OSError], tags: [ReadIOEffect], gcsafe.}
+  readDataImpl*: proc (s: Stream; buffer: pointer; bufLen: int): int {.nimcall,
+      ...raises: [Defect, IOError, OSError], tags: [ReadIOEffect], gcsafe.}
+  peekDataImpl*: proc (s: Stream; buffer: pointer; bufLen: int): int {.nimcall,
+      ...raises: [Defect, IOError, OSError], tags: [ReadIOEffect], gcsafe.}
+  writeDataImpl*: proc (s: Stream; buffer: pointer; bufLen: int) {.nimcall,
+      ...raises: [Defect, IOError, OSError], tags: [WriteIOEffect], gcsafe.}
+  flushImpl*: proc (s: Stream) {.nimcall, ...raises: [Defect, IOError, OSError],
+                                 tags: [WriteIOEffect], gcsafe.}
+
+ +

Stream interface that supports writing or reading.

+

Note:

+
  • That these fields here shouldn't be used directly. They are accessible so that a stream implementation can override them.
  • +
+ + Source   +Edit   + +
+
+
+
StringStream = ref StringStreamObj
+
+ + A stream that encapsulates a string. + Source   +Edit   + +
+
+
+
StringStreamObj = object of StreamObj
+  data*: string              ## A string data.
+                             ## This is updated when called `writeLine` etc.
+
+ + A string stream object. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc atEnd(s: Stream): bool {....raises: [IOError, OSError], tags: [], forbids: [].}
+
+ + Checks if more data can be read from s. Returns true if all data has been read. +

Example:

+
var strm = newStringStream("The first line\nthe second line\nthe third line")
+var line = ""
+doAssert strm.atEnd() == false
+while strm.readLine(line):
+  discard
+doAssert strm.atEnd() == true
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc close(s: Stream) {....raises: [IOError, OSError], tags: [WriteIOEffect],
+                        forbids: [].}
+
+ +

Closes the stream s.

+

See also:

+ + +

Example:

+
block:
+  let strm = newStringStream("The first line\nthe second line\nthe third line")
+  ## do something...
+  strm.close()
+  
+block:
+  let strm = newFileStream("amissingfile.txt")
+  # deferring works even if newFileStream fails
+  defer: strm.close()
+  if not isNil(strm):
+    ## do something...
+ Source   +Edit   + +
+
+ +
+
+
+
proc flush(s: Stream) {....raises: [IOError, OSError], tags: [WriteIOEffect],
+                        forbids: [].}
+
+ +

Flushes the buffers that the stream s might use.

+

This procedure causes any unwritten data for that stream to be delivered to the host environment to be written to the file.

+

See also:

+ + +

Example:

+
from std/os import removeFile
+
+var strm = newFileStream("somefile.txt", fmWrite)
+
+doAssert "Before write:" & readFile("somefile.txt") == "Before write:"
+strm.write("hello")
+doAssert "After  write:" & readFile("somefile.txt") == "After  write:"
+
+strm.flush()
+doAssert "After  flush:" & readFile("somefile.txt") == "After  flush:hello"
+strm.write("HELLO")
+strm.flush()
+doAssert "After  flush:" & readFile("somefile.txt") == "After  flush:helloHELLO"
+
+strm.close()
+doAssert "After  close:" & readFile("somefile.txt") == "After  close:helloHELLO"
+removeFile("somefile.txt")
+ Source   +Edit   + +
+
+ +
+
+
+
proc getPosition(s: Stream): int {....raises: [IOError, OSError], tags: [],
+                                   forbids: [].}
+
+ + Retrieves the current position in the stream s. +

Example:

+
var strm = newStringStream("The first line\nthe second line\nthe third line")
+doAssert strm.getPosition() == 0
+discard strm.readLine()
+doAssert strm.getPosition() == 15
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc newFileStream(f: File): owned FileStream {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Creates a new stream from the file f.

+

Note: Not available for JS backend.

+

See also:

+ + +

Example:

+
## Input (somefile.txt):
+## The first line
+## the second line
+## the third line
+var f: File
+if open(f, "somefile.txt", fmRead, -1):
+  var strm = newFileStream(f)
+  var line = ""
+  while strm.readLine(line):
+    echo line
+  ## Output:
+  ## The first line
+  ## the second line
+  ## the third line
+  strm.close()
+ Source   +Edit   + +
+
+
+
proc newFileStream(filename: string; mode: FileMode = fmRead; bufSize: int = -1): owned
+    FileStream {....raises: [], tags: [], forbids: [].}
+
+ +

Creates a new stream from the file named filename with the mode mode.

+

If the file cannot be opened, nil is returned. See the io module for a list of available FileMode enums.

+

Note:

+
  • This function returns nil in case of failure. To prevent unexpected behavior and ensure proper error handling, use openFileStream proc instead.
  • +
  • Not available for JS backend.
  • +
+

See also:

+ + +

Example:

+
from std/os import removeFile
+var strm = newFileStream("somefile.txt", fmWrite)
+if not isNil(strm):
+  strm.writeLine("The first line")
+  strm.writeLine("the second line")
+  strm.writeLine("the third line")
+  strm.close()
+  ## Output (somefile.txt)
+  ## The first line
+  ## the second line
+  ## the third line
+  removeFile("somefile.txt")
+ Source   +Edit   + +
+
+ +
+
+
+
proc newStringStream(s: sink string = ""): owned StringStream {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Creates a new stream from the string s.

+

See also:

+ + +

Example:

+
var strm = newStringStream("The first line\nthe second line\nthe third line")
+doAssert strm.readLine() == "The first line"
+doAssert strm.readLine() == "the second line"
+doAssert strm.readLine() == "the third line"
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc openFileStream(filename: string; mode: FileMode = fmRead; bufSize: int = -1): owned
+    FileStream {....raises: [IOError], tags: [], forbids: [].}
+
+ +

Creates a new stream from the file named filename with the mode mode. If the file cannot be opened, an IO exception is raised.

+

Note: Not available for JS backend.

+

See also:

+ + +

Example:

+
try:
+  ## Input (somefile.txt):
+  ## The first line
+  ## the second line
+  ## the third line
+  var strm = openFileStream("somefile.txt")
+  echo strm.readLine()
+  ## Output:
+  ## The first line
+  strm.close()
+except:
+  stderr.write getCurrentExceptionMsg()
+ Source   +Edit   + +
+
+ +
+
+
+
proc peek[T](s: Stream; result: var T)
+
+ +

Generic peek procedure. Peeks result from the stream s.

+

Note: Not available for JS backend. Use peekStr for now.

+ +

Example:

+
var strm = newStringStream("012")
+## peekInt
+var i: int8
+strm.peek(i)
+doAssert i == 48
+## peekData
+var buffer: array[2, char]
+strm.peek(buffer)
+doAssert buffer == ['0', '1']
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc peekBool(s: Stream): bool {....raises: [IOError, OSError],
+                                 tags: [ReadIOEffect], forbids: [].}
+
+ +

Peeks a bool from the stream s.

+

A bool is one byte long and it is true for every non-zero (0000_0000) value. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use peekStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(true)
+strm.write(false)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.peekBool() == true
+## not false
+doAssert strm.peekBool() == true
+doAssert strm.readBool() == true
+doAssert strm.peekBool() == false
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc peekChar(s: Stream): char {....raises: [IOError, OSError],
+                                 tags: [ReadIOEffect], forbids: [].}
+
+ + Peeks a char from the stream s. Raises IOError if an error occurred. Returns '\0' as an EOF marker. +

Example:

+
var strm = newStringStream("12\n3")
+doAssert strm.peekChar() == '1'
+doAssert strm.peekChar() == '1'
+discard strm.readAll()
+doAssert strm.peekChar() == '\x00'
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc peekData(s: Stream; buffer: pointer; bufLen: int): int {.
+    ...raises: [IOError, OSError], tags: [ReadIOEffect], forbids: [].}
+
+ +

Low level proc that reads data into an untyped buffer of bufLen size without moving stream position.

+

JS note: buffer is treated as a ptr string and written to between 0..<bufLen.

+ +

Example:

+
var strm = newStringStream("abcde")
+var buffer: array[6, char]
+doAssert strm.peekData(addr(buffer), 1024) == 5
+doAssert buffer == ['a', 'b', 'c', 'd', 'e', '\x00']
+doAssert strm.atEnd() == false
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc peekFloat32(s: Stream): float32 {....raises: [IOError, OSError],
+                                       tags: [ReadIOEffect], forbids: [].}
+
+ +

Peeks a float32 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use peekStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'f32)
+strm.write(2'f32)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.peekFloat32() == 1'f32
+## not 2'f32
+doAssert strm.peekFloat32() == 1'f32
+doAssert strm.readFloat32() == 1'f32
+doAssert strm.peekFloat32() == 2'f32
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc peekFloat64(s: Stream): float64 {....raises: [IOError, OSError],
+                                       tags: [ReadIOEffect], forbids: [].}
+
+ +

Peeks a float64 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use peekStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'f64)
+strm.write(2'f64)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.peekFloat64() == 1'f64
+## not 2'f64
+doAssert strm.peekFloat64() == 1'f64
+doAssert strm.readFloat64() == 1'f64
+doAssert strm.peekFloat64() == 2'f64
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc peekInt8(s: Stream): int8 {....raises: [IOError, OSError],
+                                 tags: [ReadIOEffect], forbids: [].}
+
+ +

Peeks an int8 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use peekStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'i8)
+strm.write(2'i8)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.peekInt8() == 1'i8
+## not 2'i8
+doAssert strm.peekInt8() == 1'i8
+doAssert strm.readInt8() == 1'i8
+doAssert strm.peekInt8() == 2'i8
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc peekInt16(s: Stream): int16 {....raises: [IOError, OSError],
+                                   tags: [ReadIOEffect], forbids: [].}
+
+ +

Peeks an int16 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use peekStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'i16)
+strm.write(2'i16)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.peekInt16() == 1'i16
+## not 2'i16
+doAssert strm.peekInt16() == 1'i16
+doAssert strm.readInt16() == 1'i16
+doAssert strm.peekInt16() == 2'i16
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc peekInt32(s: Stream): int32 {....raises: [IOError, OSError],
+                                   tags: [ReadIOEffect], forbids: [].}
+
+ +

Peeks an int32 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use peekStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'i32)
+strm.write(2'i32)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.peekInt32() == 1'i32
+## not 2'i32
+doAssert strm.peekInt32() == 1'i32
+doAssert strm.readInt32() == 1'i32
+doAssert strm.peekInt32() == 2'i32
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc peekInt64(s: Stream): int64 {....raises: [IOError, OSError],
+                                   tags: [ReadIOEffect], forbids: [].}
+
+ +

Peeks an int64 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use peekStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'i64)
+strm.write(2'i64)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.peekInt64() == 1'i64
+## not 2'i64
+doAssert strm.peekInt64() == 1'i64
+doAssert strm.readInt64() == 1'i64
+doAssert strm.peekInt64() == 2'i64
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc peekLine(s: Stream): string {....raises: [IOError, OSError],
+                                   tags: [ReadIOEffect], forbids: [].}
+
+ +

Peeks a line from a stream s. Raises IOError if an error occurred.

+

Note: This is not very efficient.

+

See also:

+ + +

Example:

+
var strm = newStringStream("The first line\nthe second line\nthe third line")
+doAssert strm.peekLine() == "The first line"
+## not "the second line"
+doAssert strm.peekLine() == "The first line"
+doAssert strm.readLine() == "The first line"
+doAssert strm.peekLine() == "the second line"
+strm.close()
+ Source   +Edit   + +
+
+
+
proc peekLine(s: Stream; line: var string): bool {....raises: [IOError, OSError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ +

Peeks a line of text from the stream s into line. line must not be nil! May throw an IO exception.

+

A line of text may be delimited by CR, LF or CRLF. The newline character(s) are not part of the returned string. Returns false if the end of the file has been reached, true otherwise. If false is returned line contains no new data.

+

See also:

+ + +

Example:

+
var strm = newStringStream("The first line\nthe second line\nthe third line")
+var line = ""
+doAssert strm.peekLine(line) == true
+doAssert line == "The first line"
+doAssert strm.peekLine(line) == true
+## not "the second line"
+doAssert line == "The first line"
+doAssert strm.readLine(line) == true
+doAssert line == "The first line"
+doAssert strm.peekLine(line) == true
+doAssert line == "the second line"
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc peekStr(s: Stream; length: int): string {....raises: [IOError, OSError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + Peeks a string of length length from the stream s. Raises IOError if an error occurred. +

Example:

+
var strm = newStringStream("abcde")
+doAssert strm.peekStr(2) == "ab"
+## not "cd
+doAssert strm.peekStr(2) == "ab"
+doAssert strm.readStr(2) == "ab"
+doAssert strm.peekStr(2) == "cd"
+strm.close()
+ Source   +Edit   + +
+
+
+
proc peekStr(s: Stream; length: int; str: var string) {.
+    ...raises: [IOError, OSError], tags: [ReadIOEffect], forbids: [].}
+
+ + Peeks a string of length length from the stream s. Raises IOError if an error occurred. + Source   +Edit   + +
+
+ +
+
+
+
proc peekUint8(s: Stream): uint8 {....raises: [IOError, OSError],
+                                   tags: [ReadIOEffect], forbids: [].}
+
+ +

Peeks an uint8 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use peekStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'u8)
+strm.write(2'u8)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.peekUint8() == 1'u8
+## not 2'u8
+doAssert strm.peekUint8() == 1'u8
+doAssert strm.readUint8() == 1'u8
+doAssert strm.peekUint8() == 2'u8
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc peekUint16(s: Stream): uint16 {....raises: [IOError, OSError],
+                                     tags: [ReadIOEffect], forbids: [].}
+
+ +

Peeks an uint16 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use peekStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'u16)
+strm.write(2'u16)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.peekUint16() == 1'u16
+## not 2'u16
+doAssert strm.peekUint16() == 1'u16
+doAssert strm.readUint16() == 1'u16
+doAssert strm.peekUint16() == 2'u16
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc peekUint32(s: Stream): uint32 {....raises: [IOError, OSError],
+                                     tags: [ReadIOEffect], forbids: [].}
+
+ +

Peeks an uint32 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use peekStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'u32)
+strm.write(2'u32)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.peekUint32() == 1'u32
+## not 2'u32
+doAssert strm.peekUint32() == 1'u32
+doAssert strm.readUint32() == 1'u32
+doAssert strm.peekUint32() == 2'u32
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc peekUint64(s: Stream): uint64 {....raises: [IOError, OSError],
+                                     tags: [ReadIOEffect], forbids: [].}
+
+ +

Peeks an uint64 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use peekStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'u64)
+strm.write(2'u64)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.peekUint64() == 1'u64
+## not 2'u64
+doAssert strm.peekUint64() == 1'u64
+doAssert strm.readUint64() == 1'u64
+doAssert strm.peekUint64() == 2'u64
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc read[T](s: Stream; result: var T)
+
+ +

Generic read procedure. Reads result from the stream s.

+

Note: Not available for JS backend. Use readStr for now.

+ +

Example:

+
var strm = newStringStream("012")
+## readInt
+var i: int8
+strm.read(i)
+doAssert i == 48
+## readData
+var buffer: array[2, char]
+strm.read(buffer)
+doAssert buffer == ['1', '2']
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readAll(s: Stream): string {....raises: [IOError, OSError],
+                                  tags: [ReadIOEffect], forbids: [].}
+
+ + Reads all available data. +

Example:

+
var strm = newStringStream("The first line\nthe second line\nthe third line")
+doAssert strm.readAll() == "The first line\nthe second line\nthe third line"
+doAssert strm.atEnd() == true
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readBool(s: Stream): bool {....raises: [IOError, OSError],
+                                 tags: [ReadIOEffect], forbids: [].}
+
+ +

Reads a bool from the stream s.

+

A bool is one byte long and it is true for every non-zero (0000_0000) value. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use readStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(true)
+strm.write(false)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.readBool() == true
+doAssert strm.readBool() == false
+doAssertRaises(IOError): discard strm.readBool()
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readChar(s: Stream): char {....raises: [IOError, OSError],
+                                 tags: [ReadIOEffect], forbids: [].}
+
+ +

Reads a char from the stream s.

+

Raises IOError if an error occurred. Returns '\0' as an EOF marker.

+ +

Example:

+
var strm = newStringStream("12\n3")
+doAssert strm.readChar() == '1'
+doAssert strm.readChar() == '2'
+doAssert strm.readChar() == '\n'
+doAssert strm.readChar() == '3'
+doAssert strm.readChar() == '\x00'
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readData(s: Stream; buffer: pointer; bufLen: int): int {.
+    ...raises: [IOError, OSError], tags: [ReadIOEffect], forbids: [].}
+
+ +

Low level proc that reads data into an untyped buffer of bufLen size.

+

JS note: buffer is treated as a ptr string and written to between 0..<bufLen.

+ +

Example:

+
var strm = newStringStream("abcde")
+var buffer: array[6, char]
+doAssert strm.readData(addr(buffer), 1024) == 5
+doAssert buffer == ['a', 'b', 'c', 'd', 'e', '\x00']
+doAssert strm.atEnd() == true
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readDataStr(s: Stream; buffer: var string; slice: Slice[int]): int {.
+    ...raises: [IOError, OSError], tags: [ReadIOEffect], forbids: [].}
+
+ + Low level proc that reads data into a string buffer at slice. +

Example:

+
var strm = newStringStream("abcde")
+var buffer = "12345"
+doAssert strm.readDataStr(buffer, 0..3) == 4
+doAssert buffer == "abcd5"
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readFloat32(s: Stream): float32 {....raises: [IOError, OSError],
+                                       tags: [ReadIOEffect], forbids: [].}
+
+ +

Reads a float32 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use readStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'f32)
+strm.write(2'f32)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.readFloat32() == 1'f32
+doAssert strm.readFloat32() == 2'f32
+doAssertRaises(IOError): discard strm.readFloat32()
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readFloat64(s: Stream): float64 {....raises: [IOError, OSError],
+                                       tags: [ReadIOEffect], forbids: [].}
+
+ +

Reads a float64 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use readStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'f64)
+strm.write(2'f64)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.readFloat64() == 1'f64
+doAssert strm.readFloat64() == 2'f64
+doAssertRaises(IOError): discard strm.readFloat64()
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readInt8(s: Stream): int8 {....raises: [IOError, OSError],
+                                 tags: [ReadIOEffect], forbids: [].}
+
+ +

Reads an int8 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use readStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'i8)
+strm.write(2'i8)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.readInt8() == 1'i8
+doAssert strm.readInt8() == 2'i8
+doAssertRaises(IOError): discard strm.readInt8()
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readInt16(s: Stream): int16 {....raises: [IOError, OSError],
+                                   tags: [ReadIOEffect], forbids: [].}
+
+ +

Reads an int16 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use readStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'i16)
+strm.write(2'i16)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.readInt16() == 1'i16
+doAssert strm.readInt16() == 2'i16
+doAssertRaises(IOError): discard strm.readInt16()
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readInt32(s: Stream): int32 {....raises: [IOError, OSError],
+                                   tags: [ReadIOEffect], forbids: [].}
+
+ +

Reads an int32 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use readStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'i32)
+strm.write(2'i32)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.readInt32() == 1'i32
+doAssert strm.readInt32() == 2'i32
+doAssertRaises(IOError): discard strm.readInt32()
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readInt64(s: Stream): int64 {....raises: [IOError, OSError],
+                                   tags: [ReadIOEffect], forbids: [].}
+
+ +

Reads an int64 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use readStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'i64)
+strm.write(2'i64)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.readInt64() == 1'i64
+doAssert strm.readInt64() == 2'i64
+doAssertRaises(IOError): discard strm.readInt64()
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readLine(s: Stream): string {....raises: [IOError, OSError],
+                                   tags: [ReadIOEffect], forbids: [].}
+
+ +

Reads a line from a stream s. Raises IOError if an error occurred.

+

Note: This is not very efficient.

+

See also:

+ + +

Example:

+
var strm = newStringStream("The first line\nthe second line\nthe third line")
+doAssert strm.readLine() == "The first line"
+doAssert strm.readLine() == "the second line"
+doAssert strm.readLine() == "the third line"
+doAssertRaises(IOError): discard strm.readLine()
+strm.close()
+ Source   +Edit   + +
+
+
+
proc readLine(s: Stream; line: var string): bool {....raises: [IOError, OSError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ +

Reads a line of text from the stream s into line. line must not be nil! May throw an IO exception.

+

A line of text may be delimited by LF or CRLF. The newline character(s) are not part of the returned string. Returns false if the end of the file has been reached, true otherwise. If false is returned line contains no new data.

+

See also:

+ + +

Example:

+
var strm = newStringStream("The first line\nthe second line\nthe third line")
+var line = ""
+doAssert strm.readLine(line) == true
+doAssert line == "The first line"
+doAssert strm.readLine(line) == true
+doAssert line == "the second line"
+doAssert strm.readLine(line) == true
+doAssert line == "the third line"
+doAssert strm.readLine(line) == false
+doAssert line == ""
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readStr(s: Stream; length: int): string {....raises: [IOError, OSError],
+    tags: [ReadIOEffect], forbids: [].}
+
+ + Reads a string of length length from the stream s. Raises IOError if an error occurred. +

Example:

+
var strm = newStringStream("abcde")
+doAssert strm.readStr(2) == "ab"
+doAssert strm.readStr(2) == "cd"
+doAssert strm.readStr(2) == "e"
+doAssert strm.readStr(2) == ""
+strm.close()
+ Source   +Edit   + +
+
+
+
proc readStr(s: Stream; length: int; str: var string) {.
+    ...raises: [IOError, OSError], tags: [ReadIOEffect], forbids: [].}
+
+ + Reads a string of length length from the stream s. Raises IOError if an error occurred. + Source   +Edit   + +
+
+ +
+
+
+
proc readUint8(s: Stream): uint8 {....raises: [IOError, OSError],
+                                   tags: [ReadIOEffect], forbids: [].}
+
+ +

Reads an uint8 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use readStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'u8)
+strm.write(2'u8)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.readUint8() == 1'u8
+doAssert strm.readUint8() == 2'u8
+doAssertRaises(IOError): discard strm.readUint8()
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readUint16(s: Stream): uint16 {....raises: [IOError, OSError],
+                                     tags: [ReadIOEffect], forbids: [].}
+
+ +

Reads an uint16 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use readStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'u16)
+strm.write(2'u16)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.readUint16() == 1'u16
+doAssert strm.readUint16() == 2'u16
+doAssertRaises(IOError): discard strm.readUint16()
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readUint32(s: Stream): uint32 {....raises: [IOError, OSError],
+                                     tags: [ReadIOEffect], forbids: [].}
+
+ +

Reads an uint32 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use readStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'u32)
+strm.write(2'u32)
+strm.flush()
+strm.setPosition(0)
+
+## get data
+doAssert strm.readUint32() == 1'u32
+doAssert strm.readUint32() == 2'u32
+doAssertRaises(IOError): discard strm.readUint32()
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc readUint64(s: Stream): uint64 {....raises: [IOError, OSError],
+                                     tags: [ReadIOEffect], forbids: [].}
+
+ +

Reads an uint64 from the stream s. Raises IOError if an error occurred.

+

Note: Not available for JS backend. Use readStr for now.

+ +

Example:

+
var strm = newStringStream()
+## setup for reading data
+strm.write(1'u64)
+strm.write(2'u64)
+strm.flush()
+strm.setPosition(0)
+## get data
+doAssert strm.readUint64() == 1'u64
+doAssert strm.readUint64() == 2'u64
+doAssertRaises(IOError): discard strm.readUint64()
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc setPosition(s: Stream; pos: int) {....raises: [IOError, OSError], tags: [],
+                                        forbids: [].}
+
+ + Sets the position pos of the stream s. +

Example:

+
var strm = newStringStream("The first line\nthe second line\nthe third line")
+strm.setPosition(4)
+doAssert strm.readLine() == "first line"
+strm.setPosition(0)
+doAssert strm.readLine() == "The first line"
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc write(s: Stream; args: varargs[string, `$`]) {....raises: [IOError, OSError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + Writes one or more strings to the the stream. No length fields or terminating zeros are written. +

Example:

+
var strm = newStringStream("")
+strm.write(1, 2, 3, 4)
+strm.setPosition(0)
+doAssert strm.readLine() == "1234"
+strm.close()
+ Source   +Edit   + +
+
+
+
proc write(s: Stream; x: string) {....raises: [IOError, OSError],
+                                   tags: [WriteIOEffect], forbids: [].}
+
+ + Writes the string x to the stream s. No length field or terminating zero is written. +

Example:

+
var strm = newStringStream("")
+strm.write("THE FIRST LINE")
+strm.setPosition(0)
+doAssert strm.readLine() == "THE FIRST LINE"
+strm.close()
+ Source   +Edit   + +
+
+
+
proc write[T](s: Stream; x: T)
+
+ +

Generic write procedure. Writes x to the stream s. Implementation:

+

Note: Not available for JS backend. Use write(Stream, string) for now.

+

s.writeData(s, unsafeAddr(x), sizeof(x))

+ +

Example:

+
var strm = newStringStream("")
+strm.write("abcde")
+strm.setPosition(0)
+doAssert strm.readAll() == "abcde"
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc writeData(s: Stream; buffer: pointer; bufLen: int) {.
+    ...raises: [IOError, OSError], tags: [WriteIOEffect], forbids: [].}
+
+ +

Low level proc that writes an untyped buffer of bufLen size to the stream s.

+

JS note: buffer is treated as a ptr string and read between 0..<bufLen.

+ +

Example:

+
## writeData
+var strm = newStringStream("")
+var buffer = ['a', 'b', 'c', 'd', 'e']
+strm.writeData(addr(buffer), sizeof(buffer))
+doAssert strm.atEnd() == true
+## readData
+strm.setPosition(0)
+var buffer2: array[6, char]
+doAssert strm.readData(addr(buffer2), sizeof(buffer2)) == 5
+doAssert buffer2 == ['a', 'b', 'c', 'd', 'e', '\x00']
+strm.close()
+ Source   +Edit   + +
+
+ +
+
+
+
proc writeLine(s: Stream; args: varargs[string, `$`]) {.
+    ...raises: [IOError, OSError], tags: [WriteIOEffect], forbids: [].}
+
+ + Writes one or more strings to the the stream s followed by a new line. No length field or terminating zero is written. +

Example:

+
var strm = newStringStream("")
+strm.writeLine(1, 2)
+strm.writeLine(3, 4)
+strm.setPosition(0)
+doAssert strm.readAll() == "12\n34\n"
+strm.close()
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator lines(s: Stream): string {....raises: [IOError, OSError],
+                                    tags: [ReadIOEffect], forbids: [].}
+
+ +

Iterates over every line in the stream. The iteration is based on readLine.

+

See also:

+ + +

Example:

+
var strm = newStringStream("The first line\nthe second line\nthe third line")
+var lines: seq[string]
+for line in strm.lines():
+  lines.add line
+doAssert lines == @["The first line", "the second line", "the third line"]
+strm.close()
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/streams.idx b/streams.idx new file mode 100644 index 0000000000000..573494b6ab3f0 --- /dev/null +++ b/streams.idx @@ -0,0 +1,70 @@ +nimTitle streams streams.html module std/streams 0 +nim Stream streams.html#Stream type Stream 113 +nim StreamObj streams.html#StreamObj object StreamObj 116 +nim flush streams.html#flush,Stream proc flush(s: Stream) 147 +nim close streams.html#close,Stream proc close(s: Stream) 176 +nim atEnd streams.html#atEnd,Stream proc atEnd(s: Stream): bool 197 +nim setPosition streams.html#setPosition,Stream,int proc setPosition(s: Stream; pos: int) 211 +nim getPosition streams.html#getPosition,Stream proc getPosition(s: Stream): int 223 +nim readData streams.html#readData,Stream,pointer,int proc readData(s: Stream; buffer: pointer; bufLen: int): int 234 +nim readDataStr streams.html#readDataStr,Stream,string,Slice[int] proc readDataStr(s: Stream; buffer: var string; slice: Slice[int]): int 249 +nim readAll streams.html#readAll,Stream proc readAll(s: Stream): string 280 +nim peekData streams.html#peekData,Stream,pointer,int proc peekData(s: Stream; buffer: pointer; bufLen: int): int 313 +nim writeData streams.html#writeData,Stream,pointer,int proc writeData(s: Stream; buffer: pointer; bufLen: int) 329 +nim write streams.html#write,Stream,T proc write[T](s: Stream; x: T) 350 +nim write streams.html#write,Stream,string proc write(s: Stream; x: string) 368 +nim write streams.html#write,Stream,varargs[string,] proc write(s: Stream; args: varargs[string, `$`]) 388 +nim writeLine streams.html#writeLine,Stream,varargs[string,] proc writeLine(s: Stream; args: varargs[string, `$`]) 400 +nim read streams.html#read,Stream,T proc read[T](s: Stream; result: var T) 414 +nim peek streams.html#peek,Stream,T proc peek[T](s: Stream; result: var T) 433 +nim readChar streams.html#readChar,Stream proc readChar(s: Stream): char 452 +nim peekChar streams.html#peekChar,Stream proc peekChar(s: Stream): char 473 +nim readBool streams.html#readBool,Stream proc readBool(s: Stream): bool 491 +nim peekBool streams.html#peekBool,Stream proc peekBool(s: Stream): bool 516 +nim readInt8 streams.html#readInt8,Stream proc readInt8(s: Stream): int8 543 +nim peekInt8 streams.html#peekInt8,Stream proc peekInt8(s: Stream): int8 562 +nim readInt16 streams.html#readInt16,Stream proc readInt16(s: Stream): int16 583 +nim peekInt16 streams.html#peekInt16,Stream proc peekInt16(s: Stream): int16 602 +nim readInt32 streams.html#readInt32,Stream proc readInt32(s: Stream): int32 623 +nim peekInt32 streams.html#peekInt32,Stream proc peekInt32(s: Stream): int32 642 +nim readInt64 streams.html#readInt64,Stream proc readInt64(s: Stream): int64 663 +nim peekInt64 streams.html#peekInt64,Stream proc peekInt64(s: Stream): int64 682 +nim readUint8 streams.html#readUint8,Stream proc readUint8(s: Stream): uint8 703 +nim peekUint8 streams.html#peekUint8,Stream proc peekUint8(s: Stream): uint8 722 +nim readUint16 streams.html#readUint16,Stream proc readUint16(s: Stream): uint16 743 +nim peekUint16 streams.html#peekUint16,Stream proc peekUint16(s: Stream): uint16 762 +nim readUint32 streams.html#readUint32,Stream proc readUint32(s: Stream): uint32 783 +nim peekUint32 streams.html#peekUint32,Stream proc peekUint32(s: Stream): uint32 803 +nim readUint64 streams.html#readUint64,Stream proc readUint64(s: Stream): uint64 824 +nim peekUint64 streams.html#peekUint64,Stream proc peekUint64(s: Stream): uint64 843 +nim readFloat32 streams.html#readFloat32,Stream proc readFloat32(s: Stream): float32 864 +nim peekFloat32 streams.html#peekFloat32,Stream proc peekFloat32(s: Stream): float32 883 +nim readFloat64 streams.html#readFloat64,Stream proc readFloat64(s: Stream): float64 904 +nim peekFloat64 streams.html#peekFloat64,Stream proc peekFloat64(s: Stream): float64 923 +nim readStr streams.html#readStr,Stream,int,string proc readStr(s: Stream; length: int; str: var string) 956 +nim readStr streams.html#readStr,Stream,int proc readStr(s: Stream; length: int): string 961 +nim peekStr streams.html#peekStr,Stream,int,string proc peekStr(s: Stream; length: int; str: var string) 982 +nim peekStr streams.html#peekStr,Stream,int proc peekStr(s: Stream; length: int): string 987 +nim readLine streams.html#readLine,Stream,string proc readLine(s: Stream; line: var string): bool 1001 +nim peekLine streams.html#peekLine,Stream,string proc peekLine(s: Stream; line: var string): bool 1044 +nim readLine streams.html#readLine,Stream proc readLine(s: Stream): string 1075 +nim peekLine streams.html#peekLine,Stream proc peekLine(s: Stream): string 1105 +nim lines streams.html#lines.i,Stream iterator lines(s: Stream): string 1127 +nim StringStream streams.html#StringStream type StringStream 1147 +nim StringStreamObj streams.html#StringStreamObj object StringStreamObj 1149 +nim newStringStream streams.html#newStringStream,sinkstring proc newStringStream(s: sink string = ""): owned StringStream 1286 +nim FileStream streams.html#FileStream type FileStream 1324 +nim FileStreamObj streams.html#FileStreamObj object FileStreamObj 1328 +nim newFileStream streams.html#newFileStream,File proc newFileStream(f: File): owned FileStream 1361 +nim newFileStream streams.html#newFileStream,string,FileMode,int proc newFileStream(filename: string; mode: FileMode = fmRead; bufSize: int = -1): owned\n FileStream 1404 +nim openFileStream streams.html#openFileStream,string,FileMode,int proc openFileStream(filename: string; mode: FileMode = fmRead; bufSize: int = -1): owned\n FileStream 1442 +heading Basic usage streams.html#basic-usage Basic usage 0 +heading StringStream example streams.html#basic-usage-stringstream-example StringStream example 0 +heading FileStream example streams.html#basic-usage-filestream-example FileStream example 0 +heading See also streams.html#see-also See also 0 +nimgrp peekstr streams.html#peekStr-procs-all proc 982 +nimgrp readstr streams.html#readStr-procs-all proc 956 +nimgrp peekline streams.html#peekLine-procs-all proc 1044 +nimgrp newfilestream streams.html#newFileStream-procs-all proc 1361 +nimgrp write streams.html#write-procs-all proc 350 +nimgrp readline streams.html#readLine-procs-all proc 1001 diff --git a/streamwrapper.html b/streamwrapper.html new file mode 100644 index 0000000000000..b6885d0656dcc --- /dev/null +++ b/streamwrapper.html @@ -0,0 +1,154 @@ + + + + + + + +std/streamwrapper + + + + + + + + + + + + + + + + +
+
+

std/streamwrapper

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements stream wrapper.

+

Since version 1.2.

+

+ +
+

Types

+
+
+
PipeOutStream[T] = ref object of T
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc newPipeOutStream[T](s: sink (ref T)): owned PipeOutStream[T]
+
+ +

Wrap pipe for reading with PipeOutStream so that you can use peek* procs and generate runtime error when setPosition/getPosition is called or write operation is performed.

+

Example:

+

import std/[osproc, streamwrapper]
+var
+  p = startProcess(exePath)
+  outStream = p.outputStream().newPipeOutStream()
+echo outStream.peekChar
+p.close()

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/streamwrapper.idx b/streamwrapper.idx new file mode 100644 index 0000000000000..f941a84879261 --- /dev/null +++ b/streamwrapper.idx @@ -0,0 +1,3 @@ +nimTitle streamwrapper streamwrapper.html module std/streamwrapper 0 +nim PipeOutStream streamwrapper.html#PipeOutStream type PipeOutStream 21 +nim newPipeOutStream streamwrapper.html#newPipeOutStream,sink proc newPipeOutStream[T](s: sink (ref T)): owned PipeOutStream[T] 89 diff --git a/strformat.html b/strformat.html new file mode 100644 index 0000000000000..bde17764b9bf9 --- /dev/null +++ b/strformat.html @@ -0,0 +1,515 @@ + + + + + + + +std/strformat + + + + + + + + + + + + + + + + +
+
+

std/strformat

+
+ +
+ Source   +Edit   + +
+ +

String interpolation / format inspired by Python's f-strings. +

fmt vs. &

You can use either fmt or the unary & operator for formatting. The difference between them is subtle but important.

+

The fmt"{expr}" syntax is more aesthetically pleasing, but it hides a small gotcha. The string is a generalized raw string literal. This has some surprising effects:

+ +

Example:

+
import std/strformat
+let msg = "hello"
+assert fmt"{msg}\n" == "hello\\n"

Because the literal is a raw string literal, the \n is not interpreted as an escape sequence.

+

There are multiple ways to get around this, including the use of the & operator:

+ +

Example:

+
import std/strformat
+let msg = "hello"
+
+assert &"{msg}\n" == "hello\n"
+
+assert fmt"{msg}{'\n'}" == "hello\n"
+assert fmt("{msg}\n") == "hello\n"
+assert "{msg}\n".fmt == "hello\n"
The choice of style is up to you. +

Formatting strings

+

Example:

+
import std/strformat
+assert &"""{"abc":>4}""" == " abc"
+assert &"""{"abc":<4}""" == "abc "
+

Formatting floats

+

Example:

+
import std/strformat
+assert fmt"{-12345:08}" == "-0012345"
+assert fmt"{-1:3}" == " -1"
+assert fmt"{-1:03}" == "-01"
+assert fmt"{16:#X}" == "0x10"
+
+assert fmt"{123.456}" == "123.456"
+assert fmt"{123.456:>9.3f}" == "  123.456"
+assert fmt"{123.456:9.3f}" == "  123.456"
+assert fmt"{123.456:9.4f}" == " 123.4560"
+assert fmt"{123.456:>9.0f}" == "     123."
+assert fmt"{123.456:<9.4f}" == "123.4560 "
+
+assert fmt"{123.456:e}" == "1.234560e+02"
+assert fmt"{123.456:>13e}" == " 1.234560e+02"
+assert fmt"{123.456:13e}" == " 1.234560e+02"
+

Expressions

+

Example:

+
import std/strformat
+let x = 3.14
+assert fmt"{(if x!=0: 1.0/x else: 0):.5}" == "0.31847"
+assert fmt"""{(block:
+    var res: string
+    for i in 1..15:
+      res.add (if i mod 15 == 0: "FizzBuzz"
+        elif i mod 5 == 0: "Buzz"
+        elif i mod 3 == 0: "Fizz"
+        else: $i) & " "
+    res)}""" == "1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz "
+

Debugging strings

fmt"{expr=}" expands to fmt"expr={expr}" namely the text of the expression, an equal sign and the results of evaluated expression.

+ +

Example:

+
import std/strformat
+assert fmt"{123.456=}" == "123.456=123.456"
+assert fmt"{123.456=:>9.3f}" == "123.456=  123.456"
+
+let x = "hello"
+assert fmt"{x=}" == "x=hello"
+assert fmt"{x =}" == "x =hello"
+
+let y = 3.1415926
+assert fmt"{y=:.2f}" == fmt"y={y:.2f}"
+assert fmt"{y=}" == fmt"y={y}"
+assert fmt"{y = : <8}" == fmt"y = 3.14159 "
+
+proc hello(a: string, b: float): int = 12
+assert fmt"{hello(x, y) = }" == "hello(x, y) = 12"
+assert fmt"{x.hello(y) = }" == "x.hello(y) = 12"
+assert fmt"{hello x, y = }" == "hello x, y = 12"
Note that it is space sensitive: +

Example:

+
import std/strformat
+let x = "12"
+assert fmt"{x=}" == "x=12"
+assert fmt"{x =:}" == "x =12"
+assert fmt"{x =}" == "x =12"
+assert fmt"{x= :}" == "x= 12"
+assert fmt"{x= }" == "x= 12"
+assert fmt"{x = :}" == "x = 12"
+assert fmt"{x = }" == "x = 12"
+assert fmt"{x   =  :}" == "x   =  12"
+assert fmt"{x   =  }" == "x   =  12"
+

Implementation details

An expression like &"{key} is {value:arg} {{z}}" is transformed into:

+

var temp = newStringOfCap(educatedCapGuess)
+temp.formatValue(key, "")
+temp.add(" is ")
+temp.formatValue(value, arg)
+temp.add(" {z}")
+temp

+

Parts of the string that are enclosed in the curly braces are interpreted as Nim code. To escape a { or }, double it.

+

Within a curly expression, however, {, }, must be escaped with a backslash.

+

To enable evaluating Nim expressions within curlies, colons inside parentheses do not need to be escaped.

+ +

Example:

+
import std/strformat
+let x = "hello"
+assert fmt"""{ "\{(" & x & ")\}" }""" == "{(hello)}"
+assert fmt"""{{({ x })}}""" == "{(hello)}"
+assert fmt"""{ $(\{x:1,"world":2\}) }""" == """[("hello", 1), ("world", 2)]"""

& delegates most of the work to an open overloaded set of formatValue procs. The required signature for a type T that supports formatting is usually proc formatValue(result: var string; x: T; specifier: string).

+

The subexpression after the colon (arg in &"{key} is {value:arg} {{z}}") is optional. It will be passed as the last argument to formatValue. When the colon with the subexpression it is left out, an empty string will be taken instead.

+

For strings and numeric types the optional argument is a so-called "standard format specifier".

+ +

Standard format specifiers for strings, integers and floats

The general form of a standard format specifier is:

+
[[fill]align][sign][#][0][minimumwidth][.precision][type]
+

The square brackets [] indicate an optional element.

+

The optional align flag can be one of the following:

+
<
+
Forces the field to be left-aligned within the available space. (This is the default for strings.)
+
>
+
Forces the field to be right-aligned within the available space. (This is the default for numbers.)
+
^
+
Forces the field to be centered within the available space.
+
+

Note that unless a minimum field width is defined, the field width will always be the same size as the data to fill it, so that the alignment option has no meaning in this case.

+

The optional fill character defines the character to be used to pad the field to the minimum width. The fill character, if present, must be followed by an alignment flag.

+

The sign option is only valid for numeric types, and can be one of the following:

+ + + + +
SignMeaning
+Indicates that a sign should be used for both positive as well as negative numbers.
-Indicates that a sign should be used only for negative numbers (this is the default behavior).
(space)Indicates that a leading space should be used on positive numbers.

If the # character is present, integers use the 'alternate form' for formatting. This means that binary, octal and hexadecimal output will be prefixed with 0b, 0o and 0x, respectively.

+

width is a decimal integer defining the minimum field width. If not specified, then the field width will be determined by the content.

+

If the width field is preceded by a zero (0) character, this enables zero-padding.

+

The precision is a decimal number indicating how many digits should be displayed after the decimal point in a floating point conversion. For non-numeric types the field indicates the maximum field size - in other words, how many characters will be used from the field content. The precision is ignored for integer conversions.

+

Finally, the type determines how the data should be presented.

+

The available integer presentation types are:

+ + + + + + + +
TypeResult
bBinary. Outputs the number in base 2.
dDecimal Integer. Outputs the number in base 10.
oOctal format. Outputs the number in base 8.
xHex format. Outputs the number in base 16, using lower-case letters for the digits above 9.
XHex format. Outputs the number in base 16, using uppercase letters for the digits above 9.
(None)The same as d.

The available floating point presentation types are:

+ + + + + + + + + +
TypeResult
eExponent notation. Prints the number in scientific notation using the letter e to indicate the exponent.
EExponent notation. Same as e except it converts the number to uppercase.
fFixed point. Displays the number as a fixed-point number.
FFixed point. Same as f except it converts the number to uppercase.
gGeneral format. This prints the number as a fixed-point number, unless the number is too large, in which case it switches to e exponent notation.
GGeneral format. Same as g except it switches to E if the number gets to large.
iComplex General format. This is only supported for complex numbers, which it prints using the mathematical (RE+IMj) format. The real and imaginary parts are printed using the general format g by default, but it is possible to combine this format with one of the other formats (e.g jf).
(None)Similar to g, except that it prints at least one digit after the decimal point.
+

Limitations

Because of the well defined order how templates and macros are expanded, strformat cannot expand template arguments:

+

template myTemplate(arg: untyped): untyped =
+  echo "arg is: ", arg
+  echo &"--- {arg} ---"
+
+let x = "abc"
+myTemplate(x)

+

First the template myTemplate is expanded, where every identifier arg is substituted with its argument. The arg inside the format string is not seen by this process, because it is part of a quoted string literal. It is not an identifier yet. Then the strformat macro creates the arg identifier from the string literal, an identifier that cannot be resolved anymore.

+

The workaround for this is to bind the template argument to a new local variable.

+

template myTemplate(arg: untyped): untyped =
+  block:
+    let arg1 {.inject.} = arg
+    echo "arg is: ", arg1
+    echo &"--- {arg1} ---"

+

The use of {.inject.} here is necessary again because of template expansion order and hygienic templates. But since we generally want to keep the hygiene of myTemplate, and we do not want arg1 to be injected into the context where myTemplate is expanded, everything is wrapped in a block.

+ +

Future directions

A curly expression with commas in it like {x, argA, argB} could be transformed to formatValue(result, x, argA, argB) in order to support formatters that do not need to parse a custom language within a custom language but instead prefer to use Nim's existing syntax. This would also help with readability, since there is only so much you can cram into single letter DSLs.

+

+ +
+

Types

+
+
+
StandardFormatSpecifier = object
+  fill*, align*: char        ## Desired fill and alignment.
+  sign*: char                ## Desired sign.
+  alternateForm*: bool       ## Whether to prefix binary, octal and hex numbers
+                             ## with `0b`, `0o`, `0x`.
+  padWithZero*: bool         ## Whether to pad with zeros rather than spaces.
+  minimumWidth*, precision*: int ## Desired minimum width and precision.
+  typ*: char                 ## Type like 'f', 'g' or 'd'.
+  endPosition*: int          ## End position in the format specifier after
+                             ## `parseStandardFormatSpecifier` returned.
+
+ + Type that describes "standard format specifiers". + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc alignString(s: string; minimumWidth: int; align = '\x00'; fill = ' '): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Aligns s using the fill char. This is only of interest if you want to write a custom format proc that should support the standard format specifiers. + Source   +Edit   + +
+
+ +
+
+
+
proc formatValue(result: var string; value: SomeFloat; specifier: static string)
+
+ + Standard format implementation for SomeFloat. It makes little sense to call this directly, but it is required to exist by the & macro. + Source   +Edit   + +
+
+
+
proc formatValue(result: var string; value: SomeFloat; specifier: string)
+
+ + Standard format implementation for SomeFloat. It makes little sense to call this directly, but it is required to exist by the & macro. + Source   +Edit   + +
+
+
+
proc formatValue(result: var string; value: string; specifier: static string)
+
+ + Standard format implementation for string. It makes little sense to call this directly, but it is required to exist by the & macro. + Source   +Edit   + +
+
+
+
proc formatValue(result: var string; value: string; specifier: string) {.
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ + Standard format implementation for string. It makes little sense to call this directly, but it is required to exist by the & macro. + Source   +Edit   + +
+
+
+
proc formatValue[T: SomeInteger](result: var string; value: T;
+                                 specifier: static string)
+
+ + Standard format implementation for SomeInteger. It makes little sense to call this directly, but it is required to exist by the & macro. + Source   +Edit   + +
+
+
+
proc formatValue[T: SomeInteger](result: var string; value: T; specifier: string)
+
+ + Standard format implementation for SomeInteger. It makes little sense to call this directly, but it is required to exist by the & macro. + Source   +Edit   + +
+
+ +
+
+
+
proc parseStandardFormatSpecifier(s: string; start = 0;
+                                  ignoreUnknownSuffix = false): StandardFormatSpecifier {.
+    ...raises: [ValueError], tags: [], forbids: [].}
+
+ + An exported helper proc that parses the "standard format specifiers", as specified by the grammar:
[[fill]align][sign][#][0][minimumwidth][.precision][type]
+

This is only of interest if you want to write a custom format proc that should support the standard format specifiers. If ignoreUnknownSuffix is true, an unknown suffix after the type field is not an error.

+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template `&`(pattern: string{lit}): string {.callsite.}
+
+ + &pattern is the same as pattern.fmt. For a specification of the & macro, see the module level documentation. +

Example:

+
let x = 7
+assert &"{x}\n" == "7\n" # regular string literal
+assert &"{x}\n" == "{x}\n".fmt # `fmt` can be used instead
+assert &"{x}\n" != fmt"{x}\n" # see `fmt` docs, this would use a raw string literal
+ Source   +Edit   + +
+
+ +
+
+
+
template fmt(pattern: static string): untyped {.callsite.}
+
+ + Alias for fmt(pattern, '{', '}'). + Source   +Edit   + +
+
+
+
template fmt(pattern: static string; openChar: static char;
+             closeChar: static char): string {.callsite.}
+
+ + Interpolates pattern using symbols in scope. +

Example:

+
let x = 7
+assert "var is {x * 2}".fmt == "var is 14"
+assert "var is {{x}}".fmt == "var is {x}" # escape via doubling
+const s = "foo: {x}"
+assert s.fmt == "foo: 7" # also works with const strings
+
+assert fmt"\n" == r"\n" # raw string literal
+assert "\n".fmt == "\n" # regular literal (likewise with `fmt("\n")` or `fmt "\n"`)
+

Example:

+
# custom `openChar`, `closeChar`
+let x = 7
+assert "<x>".fmt('<', '>') == "7"
+assert "<<<x>>>".fmt('<', '>') == "<7>"
+assert "`x`".fmt('`', '`') == "7"
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/strformat.idx b/strformat.idx new file mode 100644 index 0000000000000..1940e38674cf8 --- /dev/null +++ b/strformat.idx @@ -0,0 +1,26 @@ +nimTitle strformat strformat.html module std/strformat 0 +nim alignString strformat.html#alignString,string,int,char,char proc alignString(s: string; minimumWidth: int; align = '\x00'; fill = ' '): string 339 +nim StandardFormatSpecifier strformat.html#StandardFormatSpecifier object StandardFormatSpecifier 359 +nim parseStandardFormatSpecifier strformat.html#parseStandardFormatSpecifier,string,int proc parseStandardFormatSpecifier(s: string; start = 0; ignoreUnknownSuffix = false): StandardFormatSpecifier 432 +nim formatValue strformat.html#formatValue,string,T,staticstring proc formatValue[T: SomeInteger](result: var string; value: T;\n specifier: static string) 495 +nim formatValue strformat.html#formatValue,string,T,string proc formatValue[T: SomeInteger](result: var string; value: T; specifier: string) 509 +nim formatValue strformat.html#formatValue,string,SomeFloat,staticstring proc formatValue(result: var string; value: SomeFloat; specifier: static string) 571 +nim formatValue strformat.html#formatValue,string,SomeFloat,string proc formatValue(result: var string; value: SomeFloat; specifier: string) 584 +nim formatValue strformat.html#formatValue,string,string,staticstring proc formatValue(result: var string; value: string; specifier: static string) 597 +nim formatValue strformat.html#formatValue,string,string,string proc formatValue(result: var string; value: string; specifier: string) 615 +nim fmt strformat.html#fmt.t,staticstring,staticchar,staticchar template fmt(pattern: static string; openChar: static char; closeChar: static char): string 755 +nim fmt strformat.html#fmt.t,staticstring template fmt(pattern: static string): untyped 774 +nim `&` strformat.html#&.t template `&`(pattern: string{lit}): string 778 +idx interpolation strformat.html#interpolation_1 Module strformat 0 +idx format strformat.html#format_1 Module strformat 0 +heading nimfmt vs. nim& strformat.html#nimfmt-vsdot-nimamp fmt vs. & 0 +heading Formatting strings strformat.html#formatting-strings Formatting strings 0 +heading Formatting floats strformat.html#formatting-floats Formatting floats 0 +heading Expressions strformat.html#expressions Expressions 0 +heading Debugging strings strformat.html#debugging-strings Debugging strings 0 +heading Implementation details strformat.html#implementation-details Implementation details 0 +heading Standard format specifiers for strings, integers and floats strformat.html#standard-format-specifiers-for-strings-integers-and-floats Standard format specifiers for strings, integers and floats 0 +heading Limitations strformat.html#limitations Limitations 0 +heading Future directions strformat.html#future-directions Future directions 0 +nimgrp formatvalue strformat.html#formatValue-procs-all proc 495 +nimgrp fmt strformat.html#fmt-templates-all template 755 diff --git a/strimpl.html b/strimpl.html new file mode 100644 index 0000000000000..8be6a842a2565 --- /dev/null +++ b/strimpl.html @@ -0,0 +1,249 @@ + + + + + + + +std/private/strimpl + + + + + + + + + + + + + + + + +
+
+

std/private/strimpl

+
+ +
+ Source   +Edit   + +
+ +

+
+

Procs

+
+
+
+
func cmpNimIdentifier[T: string | cstring](a, b: T): int
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func find(s, sub: cstring; start: Natural = 0; last = 0): int {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Searches for sub in s inside the range start..last (both ends included). If last is unspecified, it defaults to s.high (the last element).

+

Searching is case-sensitive. If sub is not in s, -1 is returned. Otherwise the index returned is relative to s[0], not start. Use s[start..last].find for a start-origin index.

+ + Source   +Edit   + +
+
+
+
func find(s: cstring; sub: char; start: Natural = 0; last = 0): int {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Searches for sub in s inside the range start..last (both ends included). If last is unspecified, it defaults to s.high (the last element).

+

Searching is case-sensitive. If sub is not in s, -1 is returned. Otherwise the index returned is relative to s[0], not start. Use s[start..last].rfind for a start-origin index.

+ + Source   +Edit   + +
+
+ +
+
+
+
func toLowerAscii(c: char): char {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template cmpIgnoreCaseImpl[T: string | cstring](a, b: T;
+    firstCharCaseSensitive: static bool = false)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template cmpIgnoreStyleImpl[T: string | cstring](a, b: T;
+    firstCharCaseSensitive: static bool = false)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template endsWithImpl[T: string | cstring](s, suffix: T)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template startsWithImpl[T: string | cstring](s, prefix: T)
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/strimpl.idx b/strimpl.idx new file mode 100644 index 0000000000000..9e2efd422d2d4 --- /dev/null +++ b/strimpl.idx @@ -0,0 +1,10 @@ +nimTitle strimpl strimpl.html module std/private/strimpl 0 +nim toLowerAscii strimpl.html#toLowerAscii,char proc toLowerAscii(c: char): char 1 +nim cmpIgnoreStyleImpl strimpl.html#cmpIgnoreStyleImpl.t,T,T,staticbool template cmpIgnoreStyleImpl[T: string | cstring](a, b: T; firstCharCaseSensitive: static\n bool = false) 12 +nim cmpIgnoreCaseImpl strimpl.html#cmpIgnoreCaseImpl.t,T,T,staticbool template cmpIgnoreCaseImpl[T: string | cstring](a, b: T; firstCharCaseSensitive: static\n bool = false) 40 +nim startsWithImpl strimpl.html#startsWithImpl.t,T,T template startsWithImpl[T: string | cstring](s, prefix: T) 55 +nim endsWithImpl strimpl.html#endsWithImpl.t,T,T template endsWithImpl[T: string | cstring](s, suffix: T) 64 +nim cmpNimIdentifier strimpl.html#cmpNimIdentifier,T,T proc cmpNimIdentifier[T: string | cstring](a, b: T): int 75 +nim find strimpl.html#find,cstring,char,Natural,int proc find(s: cstring; sub: char; start: Natural = 0; last = 0): int 84 +nim find strimpl.html#find,cstring,cstring,Natural,int proc find(s, sub: cstring; start: Natural = 0; last = 0): int 99 +nimgrp find strimpl.html#find-procs-all proc 84 diff --git a/strmisc.html b/strmisc.html new file mode 100644 index 0000000000000..f427f7b6e84e7 --- /dev/null +++ b/strmisc.html @@ -0,0 +1,180 @@ + + + + + + + +std/strmisc + + + + + + + + + + + + + + + + +
+
+

std/strmisc

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module contains various string utility routines that are uncommonly used in comparison to the ones in strutils.

+
+

Imports

+
+ strutils +
+
+
+

Procs

+
+
+
+
func expandTabs(s: string; tabSize: int = 8): string {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Expands tab characters in s, replacing them by spaces.

+

The amount of inserted spaces for each tab character is the difference between the current column number and the next tab position. Tab positions occur every tabSize characters. The column number starts at 0 and is increased with every single character and inserted space, except for newline, which resets the column number back to 0.

+ +

Example:

+
doAssert expandTabs("\t", 4) == "    "
+doAssert expandTabs("\tfoo\t", 4) == "    foo "
+doAssert expandTabs("a\tb\n\txy\t", 3) == "a  b\n   xy "
+ Source   +Edit   + +
+
+ +
+
+
+
func partition(s: string; sep: string; right: bool = false): (string, string,
+    string) {....raises: [], tags: [], forbids: [].}
+
+ +

Splits the string at the first (if right is false) or last (if right is true) occurrence of sep into a 3-tuple.

+

Returns a 3-tuple of strings, (beforeSep, sep, afterSep) or (s, "", "") if sep is not found and right is false or ("", "", s) if sep is not found and right is true.

+

See also:

+ + +

Example:

+
doAssert partition("foo:bar:baz", ":") == ("foo", ":", "bar:baz")
+doAssert partition("foo:bar:baz", ":", right = true) == ("foo:bar", ":", "baz")
+doAssert partition("foobar", ":") == ("foobar", "", "")
+doAssert partition("foobar", ":", right = true) == ("", "", "foobar")
+ Source   +Edit   + +
+
+ +
+
+
+
func rpartition(s: string; sep: string): (string, string, string) {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Splits the string at the last occurrence of sep into a 3-tuple.

+

Returns a 3-tuple of strings, (beforeSep, sep, afterSep) or ("", "", s) if sep is not found. This is the same as partition(s, sep, right = true).

+

See also:

+ + +

Example:

+
doAssert rpartition("foo:bar:baz", ":") == ("foo:bar", ":", "baz")
+doAssert rpartition("foobar", ":") == ("", "", "foobar")
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/strmisc.idx b/strmisc.idx new file mode 100644 index 0000000000000..48108fe2a16af --- /dev/null +++ b/strmisc.idx @@ -0,0 +1,4 @@ +nimTitle strmisc strmisc.html module std/strmisc 0 +nim expandTabs strmisc.html#expandTabs,string,int proc expandTabs(s: string; tabSize: int = 8): string 15 +nim partition strmisc.html#partition,string,string,bool proc partition(s: string; sep: string; right: bool = false): (string, string, string) 48 +nim rpartition strmisc.html#rpartition,string,string proc rpartition(s: string; sep: string): (string, string, string) 70 diff --git a/strscans.html b/strscans.html new file mode 100644 index 0000000000000..25f75dea7018e --- /dev/null +++ b/strscans.html @@ -0,0 +1,448 @@ + + + + + + + +std/strscans + + + + + + + + + + + + + + + + +
+
+

std/strscans

+
+ +
+ Source   +Edit   + +
+ +

This module contains a scanf macro that can be used for extracting substrings from an input string. This is often easier than regular expressions. Some examples as an appetizer:

+

# check if input string matches a triple of integers:
+const input = "(1,2,4)"
+var x, y, z: int
+if scanf(input, "($i,$i,$i)", x, y, z):
+  echo "matches and x is ", x, " y is ", y, " z is ", z
+
+# check if input string matches an ISO date followed by an identifier followed
+# by whitespace and a floating point number:
+var year, month, day: int
+var identifier: string
+var myfloat: float
+if scanf(input, "$i-$i-$i $w$s$f", year, month, day, identifier, myfloat):
+  echo "yes, we have a match!"

+

As can be seen from the examples, strings are matched verbatim except for substrings starting with $. These constructions are available:

+ + + + + + + + + + + + + + +
$bMatches a binary integer. This uses parseutils.parseBin.
$oMatches an octal integer. This uses parseutils.parseOct.
$iMatches a decimal integer. This uses parseutils.parseInt.
$hMatches a hex integer. This uses parseutils.parseHex.
$fMatches a floating-point number. Uses parseFloat.
$wMatches an ASCII identifier: [A-Za-z_][A-Za-z_0-9]*.
$cMatches a single ASCII character.
$sSkips optional whitespace.
$$Matches a single dollar sign.
$.Matches if the end of the input string has been reached.
$*Matches until the token following the $* was found. The match is allowed to be of 0 length.
$+Matches until the token following the $+ was found. The match must consist of at least one char.
${foo}User defined matcher. Uses the proc foo to perform the match. See below for more details.
$[foo]Call user defined proc foo to skip some optional parts in the input string. See below for more details.

Even though $* and $+ look similar to the regular expressions .* and .+, they work quite differently. There is no non-deterministic state machine involved and the matches are non-greedy. [$*] matches [xyz] via parseutils.parseUntil.

+

Furthermore no backtracking is performed, if parsing fails after a value has already been bound to a matched subexpression this value is not restored to its original value. This rarely causes problems in practice and if it does for you, it's easy enough to bind to a temporary variable first.

+ +

Startswith vs full match

scanf returns true if the input string starts with the specified pattern. If instead it should only return true if there is also nothing left in the input, append $. to your pattern.

+ +

User definable matchers

One very nice advantage over regular expressions is that scanf is extensible with ordinary Nim procs. The proc is either enclosed in ${} or in $[]. ${} matches and binds the result to a variable (that was passed to the scanf macro) while $[] merely matches optional tokens without any result binding.

+

In this example, we define a helper proc someSep that skips some separators which we then use in our scanf pattern to help us in the matching process:

+

proc someSep(input: string; start: int; seps: set[char] = {':','-','.'}): int =
+  # Note: The parameters and return value must match to what ``scanf`` requires
+  result = 0
+  while start+result < input.len and input[start+result] in seps: inc result
+
+if scanf(input, "$w$[someSep]$w", key, value):
+  ...

+

It is also possible to pass arguments to a user definable matcher:

+

proc ndigits(input: string; intVal: var int; start: int; n: int): int =
+  # matches exactly ``n`` digits. Matchers need to return 0 if nothing
+  # matched or otherwise the number of processed chars.
+  var x = 0
+  var i = 0
+  while i < n and i+start < input.len and input[i+start] in {'0'..'9'}:
+    x = x * 10 + input[i+start].ord - '0'.ord
+    inc i
+  # only overwrite if we had a match
+  if i == n:
+    result = n
+    intVal = x
+
+# match an ISO date extracting year, month, day at the same time.
+# Also ensure the input ends after the ISO date:
+var year, month, day: int
+if scanf("2013-01-03", "${ndigits(4)}-${ndigits(2)}-${ndigits(2)}$.", year, month, day):
+  ...

+ +

The scanp macro

This module also implements a scanp macro, which syntax somewhat resembles an EBNF or PEG grammar, except that it uses Nim's expression syntax and so has to use prefix instead of postfix operators.

+ + + + + + + + + + + + + +
(E)Grouping
*EZero or more
+EOne or more
?EZero or One
E{n,m}From n up to m times E
~ENot predicate
a ^* bShortcut for ?(a *(b a)). Usually used for separators.
a ^+ bShortcut for ?(a +(b a)). Usually used for separators.
'a'Matches a single character
{'a'..'b'}Matches a character set
"s"Matches a string
E -> aBind matching to some action
$_Access the currently matched character

Note that unordered or ordered choice operators (/, |) are not implemented.

+

Simple example that parses the /etc/passwd file line by line:

+

const
+  etc_passwd = """root:x:0:0:root:/root:/bin/bash
+daemon:x:1:1:daemon:/usr/sbin:/bin/sh
+bin:x:2:2:bin:/bin:/bin/sh
+sys:x:3:3:sys:/dev:/bin/sh
+nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
+messagebus:x:103:107::/var/run/dbus:/bin/false
+"""
+
+proc parsePasswd(content: string): seq[string] =
+  result = @[]
+  var idx = 0
+  while true:
+    var entry = ""
+    if scanp(content, idx, +(~{'\L', '\0'} -> entry.add($_)), '\L'):
+      result.add entry
+    else:
+      break

+

The scanp maps the grammar code into Nim code that performs the parsing. The parsing is performed with the help of 3 helper templates that that can be implemented for a custom type.

+

These templates need to be named atom and nxt. atom should be overloaded to handle both char and set[char].

+

import std/streams
+
+template atom(input: Stream; idx: int; c: char): bool =
+  ## Used in scanp for the matching of atoms (usually chars).
+  peekChar(input) == c
+
+template atom(input: Stream; idx: int; s: set[char]): bool =
+  peekChar(input) in s
+
+template nxt(input: Stream; idx, step: int = 1) =
+  inc(idx, step)
+  setPosition(input, idx)
+
+if scanp(content, idx, +( ~{'\L', '\0'} -> entry.add(peekChar($input))), '\L'):
+  result.add entry

+

Calling ordinary Nim procs inside the macro is possible:

+

proc digits(s: string; intVal: var int; start: int): int =
+  var x = 0
+  while result+start < s.len and s[result+start] in {'0'..'9'} and s[result+start] != ':':
+    x = x * 10 + s[result+start].ord - '0'.ord
+    inc result
+  intVal = x
+
+proc extractUsers(content: string): seq[string] =
+  # Extracts the username and home directory
+  # of each entry (with UID greater than 1000)
+  const
+    digits = {'0'..'9'}
+  result = @[]
+  var idx = 0
+  while true:
+    var login = ""
+    var uid = 0
+    var homedir = ""
+    if scanp(content, idx, *(~ {':', '\0'}) -> login.add($_), ':', * ~ ':', ':',
+            digits($input, uid, $index), ':', *`digits`, ':', * ~ ':', ':',
+            *('/', * ~{':', '/'}) -> homedir.add($_), ':', *('/', * ~{'\L', '/'}), '\L'):
+      if uid >= 1000:
+        result.add login & " " & homedir
+    else:
+      break

+

When used for matching, keep in mind that likewise scanf, no backtracking is performed.

+

proc skipUntil(s: string; until: string; unless = '\0'; start: int): int =
+  # Skips all characters until the string `until` is found. Returns 0
+  # if the char `unless` is found first or the end is reached.
+  var i = start
+  var u = 0
+  while true:
+    if i >= s.len or s[i] == unless:
+      return 0
+    elif s[i] == until[0]:
+      u = 1
+      while i+u < s.len and u < until.len and s[i+u] == until[u]:
+        inc u
+      if u >= until.len: break
+    inc(i)
+  result = i+u-start
+
+iterator collectLinks(s: string): string =
+  const quote = {'\'', '"'}
+  var idx, old = 0
+  var res = ""
+  while idx < s.len:
+    old = idx
+    if scanp(s, idx, "<a", skipUntil($input, "href=", '>', $index),
+            `quote`, *( ~`quote`) -> res.add($_)):
+      yield res
+      res = ""
+    idx = old + 1
+
+for r in collectLinks(body):
+  echo r

+

In this example both macros are combined seamlessly in order to maximise efficiency and perform different checks.

+

iterator parseIps*(soup: string): string =
+  ## ipv4 only!
+  const digits = {'0'..'9'}
+  var a, b, c, d: int
+  var buf = ""
+  var idx = 0
+  while idx < soup.len:
+    if scanp(soup, idx, (`digits`{1,3}, '.', `digits`{1,3}, '.',
+             `digits`{1,3}, '.', `digits`{1,3}) -> buf.add($_)):
+      discard buf.scanf("$i.$i.$i.$i", a, b, c, d)
+      if (a >= 0 and a <= 254) and
+         (b >= 0 and b <= 254) and
+         (c >= 0 and c <= 254) and
+         (d >= 0 and d <= 254):
+        yield buf
+    buf.setLen(0) # need to clear `buf` each time, cause it might contain garbage
+    idx.inc

+

+ +
+

Macros

+
+
+
+
macro scanf(input: string; pattern: static[string]; results: varargs[typed]): bool
+
+ + See top level documentation of this module about how scanf works. + Source   +Edit   + +
+
+ +
+
+
+
macro scanp(input, idx: typed; pattern: varargs[untyped]): bool
+
+ + See top level documentation of this module about how scanp works. + Source   +Edit   + +
+
+ +
+
+
+
macro scanTuple(input: untyped; pattern: static[string];
+                matcherTypes: varargs[untyped]): untyped
+
+ + Works identically as scanf, but instead of predeclaring variables it returns a tuple. Tuple is started with a bool which indicates if the scan was successful followed by the requested data. If using a user defined matcher, provide the types in order they appear after pattern: line.scanTuple("${yourMatcher()}", int) +

Example:

+
let (success, year, month, day, time) = scanTuple("1000-01-01 00:00:00", "$i-$i-$i$s$+")
+if success:
+  assert year == 1000
+  assert month == 1
+  assert day == 1
+  assert time == "00:00:00"
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template atom(input: string; idx: int; c: char): bool
+
+ + Used in scanp for the matching of atoms (usually chars). EOF is matched as '\0'. + Source   +Edit   + +
+
+
+
template atom(input: string; idx: int; s: set[char]): bool
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template hasNxt(input: string; idx: int): bool
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template nxt(input: string; idx, step: int = 1)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template success(x: int): bool
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/strscans.idx b/strscans.idx new file mode 100644 index 0000000000000..9c9549adb4ff6 --- /dev/null +++ b/strscans.idx @@ -0,0 +1,14 @@ +nimTitle strscans strscans.html module std/strscans 0 +nim scanf strscans.html#scanf.m,string,static[string],varargs[typed] macro scanf(input: string; pattern: static[string]; results: varargs[typed]): bool 316 +nim scanTuple strscans.html#scanTuple.m,untyped,static[string],varargs[untyped] macro scanTuple(input: untyped; pattern: static[string];\n matcherTypes: varargs[untyped]): untyped 473 +nim atom strscans.html#atom.t,string,int,char template atom(input: string; idx: int; c: char): bool 521 +nim atom strscans.html#atom.t,string,int,set[char] template atom(input: string; idx: int; s: set[char]): bool 526 +nim hasNxt strscans.html#hasNxt.t,string,int template hasNxt(input: string; idx: int): bool 529 +nim success strscans.html#success.t,int template success(x: int): bool 532 +nim nxt strscans.html#nxt.t,string,int,int template nxt(input: string; idx, step: int = 1) 534 +nim scanp strscans.html#scanp.m,typed,typed,varargs[untyped] macro scanp(input, idx: typed; pattern: varargs[untyped]): bool 536 +idx scanf strscans.html#scanf_1 Module strscans 0 +heading Startswith vs full match strscans.html#startswith-vs-full-match Startswith vs full match 0 +heading User definable matchers strscans.html#user-definable-matchers User definable matchers 0 +heading The scanp macro strscans.html#the-scanp-macro The scanp macro 0 +nimgrp atom strscans.html#atom-templates-all template 521 diff --git a/strtabs.html b/strtabs.html new file mode 100644 index 0000000000000..f0454be2d9fe6 --- /dev/null +++ b/strtabs.html @@ -0,0 +1,620 @@ + + + + + + + +std/strtabs + + + + + + + + + + + + + + + + +
+
+

std/strtabs

+
+ +
+ Source   +Edit   + +
+ +

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 mode. +

Example:

+
import std/strtabs
+var t = newStringTable()
+t["name"] = "John"
+t["city"] = "Monaco"
+doAssert t.len == 2
+doAssert t.hasKey "name"
+doAssert "name" in t
String tables can be created from a table constructor: +

Example:

+
import std/strtabs
+var t = {"name": "John", "city": "Monaco"}.newStringTable
When using the style insensitive mode (modeStyleInsensitive), all letters are compared case insensitively within the ASCII range and underscores are ignored. +

Example:

+
import std/strtabs
+var x = newStringTable(modeStyleInsensitive)
+x["first_name"] = "John"
+x["LastName"] = "Doe"
+
+doAssert x["firstName"] == "John"
+doAssert x["last_name"] == "Doe"
An efficient string substitution operator % for the string table is also provided. +

Example:

+
import std/strtabs
+var t = {"name": "John", "city": "Monaco"}.newStringTable
+doAssert "${name} lives in ${city}" % t == "John lives in Monaco"
See also: +

+ +
+

Types

+
+
+
FormatFlag = enum
+  useEnvironment,           ## Use environment variable if the ``$key``
+                             ## is not found in the table.
+                             ## Does nothing when using `js` target.
+  useEmpty,                 ## Use the empty string as a default, thus it
+                             ## won't throw an exception if ``$key`` is not
+                             ## in the table.
+  useKey                     ## Do not replace ``$key`` if it is not found
+                             ## in the table (or in the environment).
+
+ + Flags for the % operator. + Source   +Edit   + +
+
+
+
StringTableMode = enum
+  modeCaseSensitive,        ## the table is case sensitive
+  modeCaseInsensitive,      ## the table is case insensitive
+  modeStyleInsensitive       ## the table is style insensitive
+
+ + Describes the tables operation mode. + Source   +Edit   + +
+
+
+
StringTableObj = object of RootObj
+
+ + + Source   +Edit   + +
+
+
+
StringTableRef = ref StringTableObj
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(t: StringTableRef): string {....gcsafe, extern: "nstDollar", raises: [],
+                                      tags: [], forbids: [].}
+
+ + The $ operator for string tables. Used internally when calling echo on a table. + Source   +Edit   + +
+
+ +
+
+
+
proc `%`(f: string; t: StringTableRef; flags: set[FormatFlag] = {}): string {.
+    ...gcsafe, extern: "nstFormat", raises: [ValueError], tags: [ReadEnvEffect],
+    forbids: [].}
+
+ + The % operator for string tables. +

Example:

+
var t = {"name": "John", "city": "Monaco"}.newStringTable
+doAssert "${name} lives in ${city}" % t == "John lives in Monaco"
+ Source   +Edit   + +
+
+ +
+
+
+
proc `[]`(t: StringTableRef; key: string): var string {....gcsafe,
+    extern: "nstTake", raises: [KeyError], tags: [], forbids: [].}
+
+ +

Retrieves the location at t[key].

+

If key is not in t, the KeyError exception is raised. One can check with hasKey proc whether the key exists.

+

See also:

+ + +

Example:

+
var t = {"name": "John", "city": "Monaco"}.newStringTable
+doAssert t["name"] == "John"
+doAssertRaises(KeyError):
+  echo t["occupation"]
+ Source   +Edit   + +
+
+ +
+
+
+
proc `[]=`(t: StringTableRef; key, val: string) {....gcsafe, extern: "nstPut",
+    raises: [], tags: [], forbids: [].}
+
+ +

Inserts a (key, value) pair into t.

+

See also:

+
  • [] proc for retrieving a value of a key
  • +
  • del proc for removing a key from the table
  • +
+ +

Example:

+
var t = {"name": "John", "city": "Monaco"}.newStringTable
+t["occupation"] = "teacher"
+doAssert t.hasKey("occupation")
+ Source   +Edit   + +
+
+ +
+
+
+
proc clear(s: StringTableRef) {....raises: [], tags: [], forbids: [].}
+
+ + Resets a string table to be empty again without changing the mode. + Source   +Edit   + +
+
+
+
proc clear(s: StringTableRef; mode: StringTableMode) {....gcsafe, extern: "nst$1",
+    raises: [], tags: [], forbids: [].}
+
+ +

Resets a string table to be empty again, perhaps altering the mode.

+

See also:

+
  • del proc for removing a key from the table
  • +
+ +

Example:

+
var t = {"name": "John", "city": "Monaco"}.newStringTable
+clear(t, modeCaseSensitive)
+doAssert len(t) == 0
+doAssert "name" notin t
+doAssert "city" notin t
+ Source   +Edit   + +
+
+ +
+
+
+
proc contains(t: StringTableRef; key: string): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + Alias of hasKey proc for use with the in operator. +

Example:

+
var t = {"name": "John", "city": "Monaco"}.newStringTable
+doAssert "name" in t
+doAssert "occupation" notin t
+ Source   +Edit   + +
+
+ +
+
+
+
proc del(t: StringTableRef; key: string) {....raises: [], tags: [], forbids: [].}
+
+ +

Removes key from t.

+

See also:

+
  • clear proc for resetting a table to be empty
  • +
  • []= proc for inserting a new (key, value) pair in the table
  • +
+ +

Example:

+
var t = {"name": "John", "city": "Monaco"}.newStringTable
+t.del("name")
+doAssert len(t) == 1
+doAssert "name" notin t
+doAssert "city" in t
+ Source   +Edit   + +
+
+ +
+
+
+
proc getOrDefault(t: StringTableRef; key: string; default: string = ""): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Retrieves the location at t[key].

+

If key is not in t, the default value is returned (if not specified, it is an empty string ("")).

+

See also:

+
  • [] proc for retrieving a value of a key
  • +
  • hasKey proc for checking if a key is in the table
  • +
  • []= proc for inserting a new (key, value) pair in the table
  • +
+ +

Example:

+
var t = {"name": "John", "city": "Monaco"}.newStringTable
+doAssert t.getOrDefault("name") == "John"
+doAssert t.getOrDefault("occupation") == ""
+doAssert t.getOrDefault("occupation", "teacher") == "teacher"
+doAssert t.getOrDefault("name", "Paul") == "John"
+ Source   +Edit   + +
+
+ +
+
+
+
proc hasKey(t: StringTableRef; key: string): bool {....gcsafe, extern: "nst$1",
+    raises: [], tags: [], forbids: [].}
+
+ +

Returns true if key is in the table t.

+

See also:

+ + +

Example:

+
var t = {"name": "John", "city": "Monaco"}.newStringTable
+doAssert t.hasKey("name")
+doAssert not t.hasKey("occupation")
+ Source   +Edit   + +
+
+ +
+
+
+
proc len(t: StringTableRef): int {....gcsafe, extern: "nst$1", raises: [],
+                                   tags: [], forbids: [].}
+
+ + Returns the number of keys in t. + Source   +Edit   + +
+
+ +
+
+
+
proc mode(t: StringTableRef): StringTableMode {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newStringTable(keyValuePairs: varargs[string]; mode: StringTableMode): owned(
+    StringTableRef) {....gcsafe, extern: "nst$1WithPairs", noSideEffect,
+                      ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new string table with given key, value string pairs.

+

StringTableMode must be specified.

+ +

Example:

+
var mytab = newStringTable("key1", "val1", "key2", "val2",
+                           modeCaseInsensitive)
+ Source   +Edit   + +
+
+
+
proc newStringTable(keyValuePairs: varargs[tuple[key, val: string]];
+                    mode: StringTableMode = modeCaseSensitive): owned(
+    StringTableRef) {....gcsafe, extern: "nst$1WithTableConstr", noSideEffect,
+                      ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new string table with given (key, value) tuple pairs.

+

The default mode is case sensitive.

+ +

Example:

+
var
+  mytab1 = newStringTable({"key1": "val1", "key2": "val2"}, modeCaseInsensitive)
+  mytab2 = newStringTable([("key3", "val3"), ("key4", "val4")])
+ Source   +Edit   + +
+
+
+
proc newStringTable(mode: StringTableMode): owned(StringTableRef) {....gcsafe,
+    extern: "nst$1", noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new empty string table.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator keys(t: StringTableRef): string {....raises: [], tags: [], forbids: [].}
+
+ + Iterates over every key in the table t. + Source   +Edit   + +
+
+ +
+
+
+
iterator pairs(t: StringTableRef): tuple[key, value: string] {....raises: [],
+    tags: [], forbids: [].}
+
+ + Iterates over every (key, value) pair in the table t. + Source   +Edit   + +
+
+ +
+
+
+
iterator values(t: StringTableRef): string {....raises: [], tags: [], forbids: [].}
+
+ + Iterates over every value in the table t. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/strtabs.idx b/strtabs.idx new file mode 100644 index 0000000000000..544c523a2a2cb --- /dev/null +++ b/strtabs.idx @@ -0,0 +1,31 @@ +nimTitle strtabs strtabs.html module std/strtabs 0 +nim modeCaseSensitive strtabs.html#modeCaseSensitive StringTableMode.modeCaseSensitive 69 +nim modeCaseInsensitive strtabs.html#modeCaseInsensitive StringTableMode.modeCaseInsensitive 69 +nim modeStyleInsensitive strtabs.html#modeStyleInsensitive StringTableMode.modeStyleInsensitive 69 +nim StringTableMode strtabs.html#StringTableMode enum StringTableMode 69 +nim StringTableObj strtabs.html#StringTableObj object StringTableObj 75 +nim StringTableRef strtabs.html#StringTableRef type StringTableRef 80 +nim useEnvironment strtabs.html#useEnvironment FormatFlag.useEnvironment 82 +nim useEmpty strtabs.html#useEmpty FormatFlag.useEmpty 82 +nim useKey strtabs.html#useKey FormatFlag.useKey 82 +nim FormatFlag strtabs.html#FormatFlag enum FormatFlag 82 +nim mode strtabs.html#mode,StringTableRef proc mode(t: StringTableRef): StringTableMode 96 +nim pairs strtabs.html#pairs.i,StringTableRef iterator pairs(t: StringTableRef): tuple[key, value: string] 98 +nim keys strtabs.html#keys.i,StringTableRef iterator keys(t: StringTableRef): string 104 +nim values strtabs.html#values.i,StringTableRef iterator values(t: StringTableRef): string 110 +nim len strtabs.html#len,StringTableRef proc len(t: StringTableRef): int 151 +nim `[]` strtabs.html#[],StringTableRef,string proc `[]`(t: StringTableRef; key: string): var string 155 +nim getOrDefault strtabs.html#getOrDefault,StringTableRef,string,string proc getOrDefault(t: StringTableRef; key: string; default: string = ""): string 176 +nim hasKey strtabs.html#hasKey,StringTableRef,string proc hasKey(t: StringTableRef; key: string): bool 200 +nim contains strtabs.html#contains,StringTableRef,string proc contains(t: StringTableRef; key: string): bool 213 +nim `[]=` strtabs.html#[]=,StringTableRef,string,string proc `[]=`(t: StringTableRef; key, val: string) 237 +nim newStringTable strtabs.html#newStringTable,StringTableMode proc newStringTable(mode: StringTableMode): owned(StringTableRef) 257 +nim newStringTable strtabs.html#newStringTable,varargs[string],StringTableMode proc newStringTable(keyValuePairs: varargs[string]; mode: StringTableMode): owned(\n StringTableRef) 266 +nim newStringTable strtabs.html#newStringTable,varargs[tuple[string,string]],StringTableMode proc newStringTable(keyValuePairs: varargs[tuple[key, val: string]];\n mode: StringTableMode = modeCaseSensitive): owned(StringTableRef) 283 +nim clear strtabs.html#clear,StringTableRef,StringTableMode proc clear(s: StringTableRef; mode: StringTableMode) 313 +nim clear strtabs.html#clear,StringTableRef proc clear(s: StringTableRef) 331 +nim del strtabs.html#del,StringTableRef,string proc del(t: StringTableRef; key: string) 335 +nim `$` strtabs.html#$,StringTableRef proc `$`(t: StringTableRef): string 376 +nim `%` strtabs.html#%,string,StringTableRef,set[FormatFlag] proc `%`(f: string; t: StringTableRef; flags: set[FormatFlag] = {}): string 390 +nimgrp newstringtable strtabs.html#newStringTable-procs-all proc 257 +nimgrp clear strtabs.html#clear-procs-all proc 313 diff --git a/strutils.html b/strutils.html new file mode 100644 index 0000000000000..89611a3fa5aa8 --- /dev/null +++ b/strutils.html @@ -0,0 +1,3330 @@ + + + + + + + +std/strutils + + + + + + + + + + + + + + + + +
+
+

std/strutils

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

The system module defines several common functions for working with strings, such as:

  • $ for converting other data-types to strings
  • +
  • & for string concatenation
  • +
  • add for adding a new character or a string to the existing one
  • +
  • in (alias for contains) and notin for checking if a character is in a string
  • +
+

This module builds upon that, providing additional functionality in form of procedures, iterators and templates for strings.

+ +

Example:

+
import std/strutils
+let
+  numbers = @[867, 5309]
+  multiLineString = "first line\nsecond line\nthird line"
+
+let jenny = numbers.join("-")
+assert jenny == "867-5309"
+
+assert splitLines(multiLineString) ==
+       @["first line", "second line", "third line"]
+assert split(multiLineString) == @["first", "line", "second",
+                                   "line", "third", "line"]
+assert indent(multiLineString, 4) ==
+       "    first line\n    second line\n    third line"
+assert 'z'.repeat(5) == "zzzzz"
The chaining of functions is possible thanks to the method call syntax: +

Example:

+
import std/strutils
+from std/sequtils import map
+
+let jenny = "867-5309"
+assert jenny.split('-').map(parseInt) == @[867, 5309]
+
+assert "Beetlejuice".indent(1).repeat(3).strip ==
+       "Beetlejuice Beetlejuice Beetlejuice"
This module is available for the JavaScript target.
+

See also:

+
  • strformat module for string interpolation and formatting
  • +
  • unicode module for Unicode UTF-8 handling
  • +
  • sequtils module for operations on container types (including strings)
  • +
  • parsecsv module for a high-performance CSV parser
  • +
  • parseutils module for lower-level parsing of tokens, numbers, identifiers, etc.
  • +
  • parseopt module for command-line parsing
  • +
  • pegs module for PEG (Parsing Expression Grammar) support
  • +
  • strtabs module for efficient hash tables (dictionaries, in some programming languages) mapping from strings to strings
  • +
  • ropes module for rope data type, which can represent very long strings efficiently
  • +
  • re module for regular expression (regex) support
  • +
  • strscans for scanf and scanp macros, which offer easier substring extraction than regular expressions
  • +
+

+ +
+

Types

+
+
+
BinaryPrefixMode = enum
+  bpIEC, bpColloquial
+
+ + The different names for binary prefixes. + Source   +Edit   + +
+
+
+
FloatFormatMode = enum
+  ffDefault,                ## use the shorter floating point notation
+  ffDecimal,                ## use decimal floating point notation
+  ffScientific               ## use scientific notation (using `e` character)
+
+ + The different modes of floating point formatting. + Source   +Edit   + +
+
+
+
SkipTable = array[char, int]
+
+ + Character table for efficient substring search. + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
AllChars = {'\x00'..'\xFF'}
+
+ +

A set with all the possible characters.

+

Not very useful by its own, you can use it to create inverted sets to make the find func find invalid characters in strings. Example:

+

let invalid = AllChars - Digits
+doAssert "01234".find(invalid) == -1
+doAssert "01A34".find(invalid) == 2

+ + Source   +Edit   + +
+
+
+
Digits = {'0'..'9'}
+
+ + The set of digits. + Source   +Edit   + +
+
+
+
HexDigits = {'0'..'9', 'A'..'F', 'a'..'f'}
+
+ + The set of hexadecimal digits. + Source   +Edit   + +
+
+
+
IdentChars = {'a'..'z', 'A'..'Z', '0'..'9', '_'}
+
+ + The set of characters an identifier can consist of. + Source   +Edit   + +
+
+
+
IdentStartChars = {'a'..'z', 'A'..'Z', '_'}
+
+ + The set of characters an identifier can start with. + Source   +Edit   + +
+
+
+
Letters = {'A'..'Z', 'a'..'z'}
+
+ + The set of letters. + Source   +Edit   + +
+
+
+
LowercaseLetters = {'a'..'z'}
+
+ + The set of lowercase ASCII letters. + Source   +Edit   + +
+
+
+
Newlines = {'\r', '\n'}
+
+ + The set of characters a newline terminator can start with (carriage return, line feed). + Source   +Edit   + +
+
+
+
PrintableChars = {'\t'..'\r', ' '..'~'}
+
+ + The set of all printable ASCII characters (letters, digits, whitespace, and punctuation characters). + Source   +Edit   + +
+
+
+
PunctuationChars = {'!'..'/', ':'..'@', '['..'`', '{'..'~'}
+
+ + The set of all ASCII punctuation characters. + Source   +Edit   + +
+
+
+
UppercaseLetters = {'A'..'Z'}
+
+ + The set of uppercase ASCII letters. + Source   +Edit   + +
+
+
+
Whitespace = {' ', '\t', '\v', '\r', '\n', '\f'}
+
+ + All the characters that count as whitespace (space, tab, vertical tab, carriage return, new line, form feed). + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `%`(formatstr, a: string): string {....gcsafe, extern: "nsuFormatSingleElem",
+    raises: [ValueError], tags: [], forbids: [].}
+
+ + This is the same as formatstr % [a] (see % func). + Source   +Edit   + +
+
+
+
func `%`(formatstr: string; a: openArray[string]): string {....gcsafe,
+    extern: "nsuFormatOpenArray", raises: [ValueError], tags: [], forbids: [].}
+
+ +

Interpolates a format string with the values from a.

+

The substitution operator performs string substitutions in formatstr and returns a modified formatstr. This is often called string interpolation.

+

This is best explained by an example:

+

"$1 eats $2." % ["The cat", "fish"]

+

Results in:

+

"The cat eats fish."

+

The substitution variables (the thing after the $) are enumerated from 1 to a.len. To produce a verbatim $, use $$. The notation $# can be used to refer to the next substitution variable:

+

"$# eats $#." % ["The cat", "fish"]

+

Substitution variables can also be words (that is [A-Za-z_]+[A-Za-z0-9_]*) in which case the arguments in a with even indices are keys and with odd indices are the corresponding values. An example:

+

"$animal eats $food." % ["animal", "The cat", "food", "fish"]

+

Results in:

+

"The cat eats fish."

+

The variables are compared with cmpIgnoreStyle. ValueError is raised if an ill-formed format string has been passed to the % operator.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func abbrev(s: string; possibilities: openArray[string]): int {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Returns the index of the first item in possibilities which starts with s, if not ambiguous.

+

Returns -1 if no item has been found and -2 if multiple items match.

+ +

Example:

+
doAssert abbrev("fac", ["college", "faculty", "industry"]) == 1
+doAssert abbrev("foo", ["college", "faculty", "industry"]) == -1 # Not found
+doAssert abbrev("fac", ["college", "faculty", "faculties"]) == -2 # Ambiguous
+doAssert abbrev("college", ["college", "colleges", "industry"]) == 0
+ Source   +Edit   + +
+
+ +
+
+
+
func addf(s: var string; formatstr: string; a: varargs[string, `$`]) {....gcsafe,
+    extern: "nsuAddf", raises: [ValueError], tags: [], forbids: [].}
+
+ + The same as add(s, formatstr % a), but more efficient. + Source   +Edit   + +
+
+ +
+
+
+
func addSep(dest: var string; sep = ", "; startLen: Natural = 0) {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Adds a separator to dest only if its length is bigger than startLen.

+

A shorthand for:

+

if dest.len > startLen: add(dest, sep)

+

This is often useful for generating some code where the items need to be separated by sep. sep is only added if dest is longer than startLen. The following example creates a string describing an array of integers.

+ +

Example:

+
var arr = "["
+for x in items([2, 3, 5, 7, 11]):
+  addSep(arr, startLen = len("["))
+  add(arr, $x)
+add(arr, "]")
+doAssert arr == "[2, 3, 5, 7, 11]"
+ Source   +Edit   + +
+
+ +
+
+
+
func align(s: string; count: Natural; padding = ' '): string {....gcsafe,
+    extern: "nsuAlignString", raises: [], tags: [], forbids: [].}
+
+ +

Aligns a string s with padding, so that it is of length count.

+

padding characters (by default spaces) are added before s resulting in right alignment. If s.len >= count, no spaces are added and s is returned unchanged. If you need to left align a string use the alignLeft func.

+

See also:

+ + +

Example:

+
assert align("abc", 4) == " abc"
+assert align("a", 0) == "a"
+assert align("1232", 6) == "  1232"
+assert align("1232", 6, '#') == "##1232"
+ Source   +Edit   + +
+
+ +
+
+
+
func alignLeft(s: string; count: Natural; padding = ' '): string {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Left-Aligns a string s with padding, so that it is of length count.

+

padding characters (by default spaces) are added after s resulting in left alignment. If s.len >= count, no spaces are added and s is returned unchanged. If you need to right align a string use the align func.

+

See also:

+ + +

Example:

+
assert alignLeft("abc", 4) == "abc "
+assert alignLeft("a", 0) == "a"
+assert alignLeft("1232", 6) == "1232  "
+assert alignLeft("1232", 6, '#') == "1232##"
+ Source   +Edit   + +
+
+ +
+
+
+
func allCharsInSet(s: string; theSet: set[char]): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ + Returns true if every character of s is in the set theSet. +

Example:

+
doAssert allCharsInSet("aeea", {'a', 'e'}) == true
+doAssert allCharsInSet("", {'a', 'e'}) == true
+ Source   +Edit   + +
+
+ +
+
+
+
func capitalizeAscii(s: string): string {....gcsafe, extern: "nsuCapitalizeAscii",
+    raises: [], tags: [], forbids: [].}
+
+ +

Converts the first character of string s into upper case.

+

This works only for the letters A-Z. Use Unicode module for UTF-8 support.

+

See also:

+ + +

Example:

+
doAssert capitalizeAscii("foo") == "Foo"
+doAssert capitalizeAscii("-bar") == "-bar"
+ Source   +Edit   + +
+
+ +
+
+
+
func center(s: string; width: int; fillChar: char = ' '): string {....gcsafe,
+    extern: "nsuCenterString", raises: [], tags: [], forbids: [].}
+
+ +

Return the contents of s centered in a string width long using fillChar (default: space) as padding.

+

The original string is returned if width is less than or equal to s.len.

+

See also:

+ + +

Example:

+
let a = "foo"
+doAssert a.center(2) == "foo"
+doAssert a.center(5) == " foo "
+doAssert a.center(6) == " foo  "
+ Source   +Edit   + +
+
+ +
+
+
+
func cmpIgnoreCase(a, b: string): int {....gcsafe, extern: "nsuCmpIgnoreCase",
+                                        raises: [], tags: [], forbids: [].}
+
+ + Compares two strings in a case insensitive manner. Returns:

0 if a == b
< 0 if a < b
> 0 if a > b

+

Example:

+
doAssert cmpIgnoreCase("FooBar", "foobar") == 0
+doAssert cmpIgnoreCase("bar", "Foo") < 0
+doAssert cmpIgnoreCase("Foo5", "foo4") > 0
+ Source   +Edit   + +
+
+ +
+
+
+
func cmpIgnoreStyle(a, b: string): int {....gcsafe, extern: "nsuCmpIgnoreStyle",
+    raises: [], tags: [], forbids: [].}
+
+ +

Semantically the same as cmp(normalize(a), normalize(b)). It is just optimized to not allocate temporary strings. This should NOT be used to compare Nim identifier names. Use macros.eqIdent for that.

+

Returns:

+

0 if a == b
< 0 if a < b
> 0 if a > b

+

Example:

+
doAssert cmpIgnoreStyle("foo_bar", "FooBar") == 0
+doAssert cmpIgnoreStyle("foo_bar_5", "FooBar4") > 0
+ Source   +Edit   + +
+
+ +
+
+
+
func contains(s, sub: string): bool {....raises: [], tags: [], forbids: [].}
+
+ +

Same as find(s, sub) >= 0.

+

See also:

+ + + Source   +Edit   + +
+
+
+
func contains(s: string; chars: set[char]): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Same as find(s, chars) >= 0.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func continuesWith(s, substr: string; start: Natural): bool {....gcsafe,
+    extern: "nsuContinuesWith", raises: [], tags: [], forbids: [].}
+
+ +

Returns true if s continues with substr at position start.

+

If substr == "" true is returned.

+

See also:

+ + +

Example:

+
let a = "abracadabra"
+doAssert a.continuesWith("ca", 4) == true
+doAssert a.continuesWith("ca", 5) == false
+doAssert a.continuesWith("dab", 6) == true
+ Source   +Edit   + +
+
+ +
+
+
+
func count(s: string; sub: char): int {....gcsafe, extern: "nsuCountChar",
+                                        raises: [], tags: [], forbids: [].}
+
+ +

Counts the occurrences of the character sub in the string s.

+

See also:

+ + + Source   +Edit   + +
+
+
+
func count(s: string; sub: string; overlapping: bool = false): int {....gcsafe,
+    extern: "nsuCountString", raises: [], tags: [], forbids: [].}
+
+ +

Counts the occurrences of a substring sub in the string s. Overlapping occurrences of sub only count when overlapping is set to true (default: false).

+

See also:

+ + + Source   +Edit   + +
+
+
+
func count(s: string; subs: set[char]): int {....gcsafe, extern: "nsuCountCharSet",
+    raises: [], tags: [], forbids: [].}
+
+ +

Counts the occurrences of the group of character subs in the string s.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func countLines(s: string): int {....gcsafe, extern: "nsuCountLines", raises: [],
+                                  tags: [], forbids: [].}
+
+ +

Returns the number of lines in the string s.

+

This is the same as len(splitLines(s)), but much more efficient because it doesn't modify the string creating temporary objects. Every character literal newline combination (CR, LF, CR-LF) is supported.

+

In this context, a line is any string separated by a newline combination. A line can be an empty string.

+

See also:

+ + +

Example:

+
doAssert countLines("First line\l and second line.") == 2
+ Source   +Edit   + +
+
+ +
+
+
+
func dedent(s: string; count: Natural = indentation(s)): string {....gcsafe,
+    extern: "nsuDedent", raises: [], tags: [], forbids: [].}
+
+ +

Unindents each line in s by count amount of padding. The only difference between this and the unindent func is that this by default only cuts off the amount of indentation that all lines of s share as opposed to all indentation. It only supports spaces as padding.

+

Note: This does not preserve the new line characters used in s.

+

See also:

+ + +

Example:

+
let x = """
+      Hello
+        There
+    """.dedent()
+
+doAssert x == "Hello\n  There\n"
+ Source   +Edit   + +
+
+ +
+
+
+
func delete(s: var string; first, last: int) {....gcsafe, extern: "nsuDelete",
+    deprecated: "use `delete(s, first..last)`", raises: [], tags: [],
+    forbids: [].}
+
+
+ Deprecated: use `delete(s, first..last)` +
+ + Deletes in s the characters at positions first .. last (both ends included). +

Example: cmd: --warning:deprecated:off

+
var a = "abracadabra"
+
+a.delete(4, 5)
+doAssert a == "abradabra"
+
+a.delete(1, 6)
+doAssert a == "ara"
+
+a.delete(2, 999)
+doAssert a == "ar"
+ Source   +Edit   + +
+
+
+
func delete(s: var string; slice: Slice[int]) {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Deletes the items s[slice], raising IndexDefect if the slice contains elements out of range.

+

This operation moves all elements after s[slice] in linear time, and is the string analog to sequtils.delete.

+ +

Example:

+
var a = "abcde"
+doAssertRaises(IndexDefect): a.delete(4..5)
+assert a == "abcde"
+a.delete(4..4)
+assert a == "abcd"
+a.delete(1..2)
+assert a == "ad"
+a.delete(1..<1) # empty slice
+assert a == "ad"
+ Source   +Edit   + +
+
+ +
+
+
+
func endsWith(s, suffix: string): bool {....gcsafe, extern: "nsuEndsWith",
+    raises: [], tags: [], forbids: [].}
+
+ +

Returns true if s ends with suffix.

+

If suffix == "" true is returned.

+

See also:

+ + +

Example:

+
let a = "abracadabra"
+doAssert a.endsWith("abra") == true
+doAssert a.endsWith("dab") == false
+ Source   +Edit   + +
+
+
+
func endsWith(s: string; suffix: char): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Returns true if s ends with suffix.

+

See also:

+ + +

Example:

+
let a = "abracadabra"
+doAssert a.endsWith('a') == true
+doAssert a.endsWith('b') == false
+ Source   +Edit   + +
+
+ +
+
+
+
func escape(s: string; prefix = "\""; suffix = "\""): string {....gcsafe,
+    extern: "nsuEscape", raises: [], tags: [], forbids: [].}
+
+ + Escapes a string s.
Note: +The escaping scheme is different from system.addEscapedChar.
+
  • replaces '\0'..'\31' and '\127'..'\255' by \xHH where HH is its hexadecimal value
  • +
  • replaces \ by \\
  • +
  • replaces ' by \'
  • +
  • replaces " by \"
  • +
+

The resulting string is prefixed with prefix and suffixed with suffix. Both may be empty strings.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func find(a: SkipTable; s, sub: string; start: Natural = 0; last = -1): int {.
+    ...gcsafe, extern: "nsuFindStrA", raises: [], tags: [], forbids: [].}
+
+ +

Searches for sub in s inside range start..last using preprocessed table a. If last is unspecified, it defaults to s.high (the last element).

+

Searching is case-sensitive. If sub is not in s, -1 is returned.

+

See also:

+ + + Source   +Edit   + +
+
+
+
func find(s, sub: string; start: Natural = 0; last = -1): int {....gcsafe,
+    extern: "nsuFindStr", raises: [], tags: [], forbids: [].}
+
+ +

Searches for sub in s inside range start..last (both ends included). If last is unspecified or negative, it defaults to s.high (the last element).

+

Searching is case-sensitive. If sub is not in s, -1 is returned. Otherwise the index returned is relative to s[0], not start. Subtract start from the result for a start-origin index.

+

See also:

+ + + Source   +Edit   + +
+
+
+
func find(s: string; chars: set[char]; start: Natural = 0; last = -1): int {.
+    ...gcsafe, extern: "nsuFindCharSet", raises: [], tags: [], forbids: [].}
+
+ +

Searches for chars in s inside range start..last (both ends included). If last is unspecified or negative, it defaults to s.high (the last element).

+

If s contains none of the characters in chars, -1 is returned. Otherwise the index returned is relative to s[0], not start. Subtract start from the result for a start-origin index.

+

See also:

+ + + Source   +Edit   + +
+
+
+
func find(s: string; sub: char; start: Natural = 0; last = -1): int {....gcsafe,
+    extern: "nsuFindChar", raises: [], tags: [], forbids: [].}
+
+ +

Searches for sub in s inside range start..last (both ends included). If last is unspecified or negative, it defaults to s.high (the last element).

+

Searching is case-sensitive. If sub is not in s, -1 is returned. Otherwise the index returned is relative to s[0], not start. Subtract start from the result for a start-origin index.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func format(formatstr: string; a: varargs[string, `$`]): string {....gcsafe,
+    extern: "nsuFormatVarargs", raises: [ValueError], tags: [], forbids: [].}
+
+ +

This is the same as formatstr % a (see % func) except that it supports auto stringification.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func formatBiggestFloat(f: BiggestFloat; format: FloatFormatMode = ffDefault;
+                        precision: range[-1 .. 32] = 16; decimalSep = '.'): string {.
+    ...gcsafe, extern: "nsu$1", raises: [], tags: [], forbids: [].}
+
+ +

Converts a floating point value f to a string.

+

If format == ffDecimal then precision is the number of digits to be printed after the decimal point. If format == ffScientific then precision is the maximum number of significant digits to be printed. precision's default value is the maximum number of meaningful digits after the decimal point for Nim's biggestFloat type.

+

If precision == -1, it tries to format it nicely.

+ +

Example:

+
let x = 123.456
+doAssert x.formatBiggestFloat() == "123.4560000000000"
+doAssert x.formatBiggestFloat(ffDecimal, 4) == "123.4560"
+doAssert x.formatBiggestFloat(ffScientific, 2) == "1.23e+02"
+ Source   +Edit   + +
+
+ +
+
+
+
func formatEng(f: BiggestFloat; precision: range[0 .. 32] = 10;
+               trim: bool = true; siPrefix: bool = false; unit: string = "";
+               decimalSep = '.'; useUnitSpace = false): string {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Converts a floating point value f to a string using engineering notation.

+

Numbers in of the range -1000.0<f<1000.0 will be formatted without an exponent. Numbers outside of this range will be formatted as a significand in the range -1000.0<f<1000.0 and an exponent that will always be an integer multiple of 3, corresponding with the SI prefix scale k, M, G, T etc for numbers with an absolute value greater than 1 and m, μ, n, p etc for numbers with an absolute value less than 1.

+

The default configuration (trim=true and precision=10) shows the shortest form that precisely (up to a maximum of 10 decimal places) displays the value. For example, 4.100000 will be displayed as 4.1 (which is mathematically identical) whereas 4.1000003 will be displayed as 4.1000003.

+

If trim is set to true, trailing zeros will be removed; if false, the number of digits specified by precision will always be shown.

+

precision can be used to set the number of digits to be shown after the decimal point or (if trim is true) the maximum number of digits to be shown.

+

 formatEng(0, 2, trim=false) == "0.00"
+ formatEng(0, 2) == "0"
+ formatEng(0.053, 0) == "53e-3"
+ formatEng(52731234, 2) == "52.73e6"
+ formatEng(-52731234, 2) == "-52.73e6"

+

If siPrefix is set to true, the number will be displayed with the SI prefix corresponding to the exponent. For example 4100 will be displayed as "4.1 k" instead of "4.1e3". Note that u is used for micro- in place of the greek letter mu (μ) as per ISO 2955. Numbers with an absolute value outside of the range 1e-18<f<1000e18 (1a<f<1000E) will be displayed with an exponent rather than an SI prefix, regardless of whether siPrefix is true.

+

If useUnitSpace is true, the provided unit will be appended to the string (with a space as required by the SI standard). This behaviour is slightly different to appending the unit to the result as the location of the space is altered depending on whether there is an exponent.

+

 formatEng(4100, siPrefix=true, unit="V") == "4.1 kV"
+ formatEng(4.1, siPrefix=true, unit="V") == "4.1 V"
+ formatEng(4.1, siPrefix=true) == "4.1" # Note lack of space
+ formatEng(4100, siPrefix=true) == "4.1 k"
+ formatEng(4.1, siPrefix=true, unit="") == "4.1 " # Space with unit=""
+ formatEng(4100, siPrefix=true, unit="") == "4.1 k"
+ formatEng(4100) == "4.1e3"
+ formatEng(4100, unit="V") == "4.1e3 V"
+ formatEng(4100, unit="", useUnitSpace=true) == "4.1e3 " # Space with useUnitSpace=true

+

decimalSep is used as the decimal separator.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func formatFloat(f: float; format: FloatFormatMode = ffDefault;
+                 precision: range[-1 .. 32] = 16; decimalSep = '.'): string {.
+    ...gcsafe, extern: "nsu$1", raises: [], tags: [], forbids: [].}
+
+ +

Converts a floating point value f to a string.

+

If format == ffDecimal then precision is the number of digits to be printed after the decimal point. If format == ffScientific then precision is the maximum number of significant digits to be printed. precision's default value is the maximum number of meaningful digits after the decimal point for Nim's float type.

+

If precision == -1, it tries to format it nicely.

+ +

Example:

+
let x = 123.456
+doAssert x.formatFloat() == "123.4560000000000"
+doAssert x.formatFloat(ffDecimal, 4) == "123.4560"
+doAssert x.formatFloat(ffScientific, 2) == "1.23e+02"
+ Source   +Edit   + +
+
+ +
+
+
+
func formatSize(bytes: int64; decimalSep = '.'; prefix = bpIEC;
+                includeSpace = false): string {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Rounds and formats bytes.

+

By default, uses the IEC/ISO standard binary prefixes, so 1024 will be formatted as 1KiB. Set prefix to bpColloquial to use the colloquial names from the SI standard (e.g. k for 1000 being reused as 1024).

+

includeSpace can be set to true to include the (SI preferred) space between the number and the unit (e.g. 1 KiB).

+

See also:

+ + +

Example:

+
doAssert formatSize((1'i64 shl 31) + (300'i64 shl 20)) == "2.293GiB"
+doAssert formatSize((2.234*1024*1024).int) == "2.234MiB"
+doAssert formatSize(4096, includeSpace = true) == "4 KiB"
+doAssert formatSize(4096, prefix = bpColloquial, includeSpace = true) == "4 kB"
+doAssert formatSize(4096) == "4KiB"
+doAssert formatSize(5_378_934, prefix = bpColloquial, decimalSep = ',') == "5,13MB"
+ Source   +Edit   + +
+
+ +
+
+
+
func fromBin[T: SomeInteger](s: string): T
+
+ +

Parses a binary integer value from a string s.

+

If s is not a valid binary integer, ValueError is raised. s can have one of the following optional prefixes: 0b, 0B. Underscores within s are ignored.

+

Does not check for overflow. If the value represented by s is too big to fit into a return type, only the value of the rightmost binary digits of s is returned without producing an error.

+ +

Example:

+
let s = "0b_0100_1000_1000_1000_1110_1110_1001_1001"
+doAssert fromBin[int](s) == 1216933529
+doAssert fromBin[int8](s) == 0b1001_1001'i8
+doAssert fromBin[int8](s) == -103'i8
+doAssert fromBin[uint8](s) == 153
+doAssert s.fromBin[:int16] == 0b1110_1110_1001_1001'i16
+doAssert s.fromBin[:uint64] == 1216933529'u64
+ Source   +Edit   + +
+
+ +
+
+
+
func fromHex[T: SomeInteger](s: string): T
+
+ +

Parses a hex integer value from a string s.

+

If s is not a valid hex integer, ValueError is raised. s can have one of the following optional prefixes: 0x, 0X, #. Underscores within s are ignored.

+

Does not check for overflow. If the value represented by s is too big to fit into a return type, only the value of the rightmost hex digits of s is returned without producing an error.

+ +

Example:

+
let s = "0x_1235_8df6"
+doAssert fromHex[int](s) == 305499638
+doAssert fromHex[int8](s) == 0xf6'i8
+doAssert fromHex[int8](s) == -10'i8
+doAssert fromHex[uint8](s) == 246'u8
+doAssert s.fromHex[:int16] == -29194'i16
+doAssert s.fromHex[:uint64] == 305499638'u64
+ Source   +Edit   + +
+
+ +
+
+
+
func fromOct[T: SomeInteger](s: string): T
+
+ +

Parses an octal integer value from a string s.

+

If s is not a valid octal integer, ValueError is raised. s can have one of the following optional prefixes: 0o, 0O. Underscores within s are ignored.

+

Does not check for overflow. If the value represented by s is too big to fit into a return type, only the value of the rightmost octal digits of s is returned without producing an error.

+ +

Example:

+
let s = "0o_123_456_777"
+doAssert fromOct[int](s) == 21913087
+doAssert fromOct[int8](s) == 0o377'i8
+doAssert fromOct[int8](s) == -1'i8
+doAssert fromOct[uint8](s) == 255'u8
+doAssert s.fromOct[:int16] == 24063'i16
+doAssert s.fromOct[:uint64] == 21913087'u64
+ Source   +Edit   + +
+
+ +
+
+
+
func indent(s: string; count: Natural; padding: string = " "): string {....gcsafe,
+    extern: "nsuIndent", raises: [], tags: [], forbids: [].}
+
+ +

Indents each line in s by count amount of padding.

+

Note: This does not preserve the new line characters used in s.

+

See also:

+ + +

Example:

+
doAssert indent("First line\c\l and second line.", 2) ==
+         "  First line\l   and second line."
+ Source   +Edit   + +
+
+ +
+
+
+
func indentation(s: string): Natural {....raises: [], tags: [], forbids: [].}
+
+ + Returns the amount of indentation all lines of s have in common, ignoring lines that consist only of whitespace. + Source   +Edit   + +
+
+ +
+
+
+
func initSkipTable(a: var SkipTable; sub: string) {....gcsafe,
+    extern: "nsuInitSkipTable", raises: [], tags: [], forbids: [].}
+
+ +

Initializes table a for efficient search of substring sub.

+

See also:

+ + + Source   +Edit   + +
+
+
+
func initSkipTable(sub: string): SkipTable {.noinit, ...gcsafe,
+    extern: "nsuInitNewSkipTable", raises: [], tags: [], forbids: [].}
+
+ +

Returns a new table initialized for sub.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func insertSep(s: string; sep = '_'; digits = 3): string {....gcsafe,
+    extern: "nsuInsertSep", raises: [], tags: [], forbids: [].}
+
+ +

Inserts the separator sep after digits characters (default: 3) from right to left.

+

Even though the algorithm works with any string s, it is only useful if s contains a number.

+ +

Example:

+
doAssert insertSep("1000000") == "1_000_000"
+ Source   +Edit   + +
+
+ +
+
+
+
func intToStr(x: int; minchars: Positive = 1): string {....gcsafe,
+    extern: "nsuIntToStr", raises: [], tags: [], forbids: [].}
+
+ +

Converts x to its decimal representation.

+

The resulting string will be minimally minchars characters long. This is achieved by adding leading zeros.

+ +

Example:

+
doAssert intToStr(1984) == "1984"
+doAssert intToStr(1984, 6) == "001984"
+ Source   +Edit   + +
+
+ +
+
+
+
func isAlphaAscii(c: char): bool {....gcsafe, extern: "nsuIsAlphaAsciiChar",
+                                   raises: [], tags: [], forbids: [].}
+
+ +

Checks whether or not character c is alphabetical.

+

This checks a-z, A-Z ASCII characters only. Use Unicode module for UTF-8 support.

+ +

Example:

+
doAssert isAlphaAscii('e') == true
+doAssert isAlphaAscii('E') == true
+doAssert isAlphaAscii('8') == false
+ Source   +Edit   + +
+
+ +
+
+
+
func isAlphaNumeric(c: char): bool {....gcsafe, extern: "nsuIsAlphaNumericChar",
+                                     raises: [], tags: [], forbids: [].}
+
+ +

Checks whether or not c is alphanumeric.

+

This checks a-z, A-Z, 0-9 ASCII characters only.

+ +

Example:

+
doAssert isAlphaNumeric('n') == true
+doAssert isAlphaNumeric('8') == true
+doAssert isAlphaNumeric(' ') == false
+ Source   +Edit   + +
+
+ +
+
+
+
func isDigit(c: char): bool {....gcsafe, extern: "nsuIsDigitChar", raises: [],
+                              tags: [], forbids: [].}
+
+ +

Checks whether or not c is a number.

+

This checks 0-9 ASCII characters only.

+ +

Example:

+
doAssert isDigit('n') == false
+doAssert isDigit('8') == true
+ Source   +Edit   + +
+
+ +
+
+
+
func isEmptyOrWhitespace(s: string): bool {....gcsafe,
+    extern: "nsuIsEmptyOrWhitespace", raises: [], tags: [], forbids: [].}
+
+ + Checks if s is empty or consists entirely of whitespace characters. + Source   +Edit   + +
+
+ +
+
+
+
func isLowerAscii(c: char): bool {....gcsafe, extern: "nsuIsLowerAsciiChar",
+                                   raises: [], tags: [], forbids: [].}
+
+ +

Checks whether or not c is a lower case character.

+

This checks ASCII characters only. Use Unicode module for UTF-8 support.

+

See also:

+ + +

Example:

+
doAssert isLowerAscii('e') == true
+doAssert isLowerAscii('E') == false
+doAssert isLowerAscii('7') == false
+ Source   +Edit   + +
+
+ +
+
+
+
func isSpaceAscii(c: char): bool {....gcsafe, extern: "nsuIsSpaceAsciiChar",
+                                   raises: [], tags: [], forbids: [].}
+
+ + Checks whether or not c is a whitespace character. +

Example:

+
doAssert isSpaceAscii('n') == false
+doAssert isSpaceAscii(' ') == true
+doAssert isSpaceAscii('\t') == true
+ Source   +Edit   + +
+
+ +
+
+
+
func isUpperAscii(c: char): bool {....gcsafe, extern: "nsuIsUpperAsciiChar",
+                                   raises: [], tags: [], forbids: [].}
+
+ +

Checks whether or not c is an upper case character.

+

This checks ASCII characters only. Use Unicode module for UTF-8 support.

+

See also:

+ + +

Example:

+
doAssert isUpperAscii('e') == false
+doAssert isUpperAscii('E') == true
+doAssert isUpperAscii('7') == false
+ Source   +Edit   + +
+
+ +
+
+
+
func join(a: openArray[string]; sep: string = ""): string {....gcsafe,
+    extern: "nsuJoinSep", raises: [], tags: [], forbids: [].}
+
+ + Concatenates all strings in the container a, separating them with sep. +

Example:

+
doAssert join(["A", "B", "Conclusion"], " -> ") == "A -> B -> Conclusion"
+ Source   +Edit   + +
+
+
+
proc join[T: not string](a: openArray[T]; sep: string = ""): string
+
+ + Converts all elements in the container a to strings using $, and concatenates them with sep. +

Example:

+
doAssert join([1, 2, 3], " -> ") == "1 -> 2 -> 3"
+ Source   +Edit   + +
+
+ +
+
+
+
func multiReplace(s: string; replacements: varargs[(string, string)]): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Same as replace, but specialized for doing multiple replacements in a single pass through the input string.

+

multiReplace scans the input string from left to right and replaces the matching substrings in the same order as passed in the argument list.

+

The implications of the order of scanning the string and matching the replacements:

+
  • In case of multiple matches at a given position, the earliest replacement is applied.
  • +
  • Overlaps are not handled. After performing a replacement, the scan continues from the character after the matched substring. If the resulting string then contains a possible match starting in a newly placed substring, the additional replacement is not performed.
  • +
+

If the resulting string is not longer than the original input string, only a single memory allocation is required.

+ +

Example:

+
# Swapping occurrences of 'a' and 'b':
+doAssert multireplace("abba", [("a", "b"), ("b", "a")]) == "baab"
+
+# The second replacement ("ab") is matched and performed first, the scan then
+# continues from 'c', so the "bc" replacement is never matched and thus skipped.
+doAssert multireplace("abc", [("bc", "x"), ("ab", "_b")]) == "_bc"
+ Source   +Edit   + +
+
+ +
+
+
+
func nimIdentNormalize(s: string): string {....raises: [], tags: [], forbids: [].}
+
+ +

Normalizes the string s as a Nim identifier.

+

That means to convert to lower case and remove any '_' on all characters except first one.

+
Warning: +Backticks (`) are not handled: they remain as is and spaces are preserved. See nimIdentBackticksNormalize for an alternative approach.
+ +

Example:

+
doAssert nimIdentNormalize("Foo_bar") == "Foobar"
+ Source   +Edit   + +
+
+ +
+
+
+
func normalize(s: string): string {....gcsafe, extern: "nsuNormalize", raises: [],
+                                    tags: [], forbids: [].}
+
+ +

Normalizes the string s.

+

That means to convert it to lower case and remove any '_'. This should NOT be used to normalize Nim identifier names.

+

See also:

+ + +

Example:

+
doAssert normalize("Foo_bar") == "foobar"
+doAssert normalize("Foo Bar") == "foo bar"
+ Source   +Edit   + +
+
+ +
+
+
+
func parseBiggestInt(s: string): BiggestInt {....gcsafe,
+    extern: "nsuParseBiggestInt", raises: [ValueError], tags: [], forbids: [].}
+
+ +

Parses a decimal integer value contained in s.

+

If s is not a valid integer, ValueError is raised.

+ + Source   +Edit   + +
+
+ +
+
+
+
func parseBiggestUInt(s: string): BiggestUInt {....gcsafe,
+    extern: "nsuParseBiggestUInt", raises: [ValueError], tags: [], forbids: [].}
+
+ +

Parses a decimal unsigned integer value contained in s.

+

If s is not a valid integer, ValueError is raised.

+ + Source   +Edit   + +
+
+ +
+
+
+
func parseBinInt(s: string): int {....gcsafe, extern: "nsuParseBinInt",
+                                   raises: [ValueError], tags: [], forbids: [].}
+
+ +

Parses a binary integer value contained in s.

+

If s is not a valid binary integer, ValueError is raised. s can have one of the following optional prefixes: 0b, 0B. Underscores within s are ignored.

+ +

Example:

+
let
+  a = "0b11_0101"
+  b = "111"
+doAssert a.parseBinInt() == 53
+doAssert b.parseBinInt() == 7
+ Source   +Edit   + +
+
+ +
+
+
+
func parseBool(s: string): bool {....raises: [ValueError], tags: [], forbids: [].}
+
+ +

Parses a value into a bool.

+

If s is one of the following values: y, yes, true, 1, on, then returns true. If s is one of the following values: n, no, false, 0, off, then returns false. If s is something else a ValueError exception is raised.

+ +

Example:

+
let a = "n"
+doAssert parseBool(a) == false
+ Source   +Edit   + +
+
+ +
+
+
+
func parseEnum[T: enum](s: string): T
+
+ +

Parses an enum T. This errors at compile time, if the given enum type contains multiple fields with the same string value.

+

Raises ValueError for an invalid value in s. The comparison is done in a style insensitive way (first letter is still case-sensitive).

+ +

Example:

+
type
+  MyEnum = enum
+    first = "1st",
+    second,
+    third = "3rd"
+
+doAssert parseEnum[MyEnum]("1_st") == first
+doAssert parseEnum[MyEnum]("second") == second
+doAssertRaises(ValueError):
+  echo parseEnum[MyEnum]("third")
+ Source   +Edit   + +
+
+
+
func parseEnum[T: enum](s: string; default: T): T
+
+ +

Parses an enum T. This errors at compile time, if the given enum type contains multiple fields with the same string value.

+

Uses default for an invalid value in s. The comparison is done in a style insensitive way (first letter is still case-sensitive).

+ +

Example:

+
type
+  MyEnum = enum
+    first = "1st",
+    second,
+    third = "3rd"
+
+doAssert parseEnum[MyEnum]("1_st") == first
+doAssert parseEnum[MyEnum]("second") == second
+doAssert parseEnum[MyEnum]("last", third) == third
+ Source   +Edit   + +
+
+ +
+
+
+
func parseFloat(s: string): float {....gcsafe, extern: "nsuParseFloat",
+                                    raises: [ValueError], tags: [], forbids: [].}
+
+ +

Parses a decimal floating point value contained in s.

+

If s is not a valid floating point number, ValueError is raised. NAN, INF, -INF are also supported (case insensitive comparison).

+ +

Example:

+
doAssert parseFloat("3.14") == 3.14
+doAssert parseFloat("inf") == 1.0/0
+ Source   +Edit   + +
+
+ +
+
+
+
func parseHexInt(s: string): int {....gcsafe, extern: "nsuParseHexInt",
+                                   raises: [ValueError], tags: [], forbids: [].}
+
+ +

Parses a hexadecimal integer value contained in s.

+

If s is not a valid hex integer, ValueError is raised. s can have one of the following optional prefixes: 0x, 0X, #. Underscores within s are ignored.

+ + Source   +Edit   + +
+
+ +
+
+
+
func parseHexStr(s: string): string {....gcsafe, extern: "nsuParseHexStr",
+                                      raises: [ValueError], tags: [],
+                                      forbids: [].}
+
+ +

Converts hex-encoded string to byte string, e.g.:

+

Raises ValueError for an invalid hex values. The comparison is case-insensitive.

+

See also:

+ + +

Example:

+
let
+  a = "41"
+  b = "3161"
+  c = "00ff"
+doAssert parseHexStr(a) == "A"
+doAssert parseHexStr(b) == "1a"
+doAssert parseHexStr(c) == "\0\255"
+ Source   +Edit   + +
+
+ +
+
+
+
func parseInt(s: string): int {....gcsafe, extern: "nsuParseInt",
+                                raises: [ValueError], tags: [], forbids: [].}
+
+ +

Parses a decimal integer value contained in s.

+

If s is not a valid integer, ValueError is raised.

+ +

Example:

+
doAssert parseInt("-0042") == -42
+ Source   +Edit   + +
+
+ +
+
+
+
func parseOctInt(s: string): int {....gcsafe, extern: "nsuParseOctInt",
+                                   raises: [ValueError], tags: [], forbids: [].}
+
+ +

Parses an octal integer value contained in s.

+

If s is not a valid oct integer, ValueError is raised. s can have one of the following optional prefixes: 0o, 0O. Underscores within s are ignored.

+ + Source   +Edit   + +
+
+ +
+
+
+
func parseUInt(s: string): uint {....gcsafe, extern: "nsuParseUInt",
+                                  raises: [ValueError], tags: [], forbids: [].}
+
+ +

Parses a decimal unsigned integer value contained in s.

+

If s is not a valid integer, ValueError is raised.

+ + Source   +Edit   + +
+
+ +
+
+
+
func removePrefix(s: var string; c: char) {....gcsafe,
+    extern: "nsuRemovePrefixChar", raises: [], tags: [], forbids: [].}
+
+ +

Removes all occurrences of a single character (in-place) from the start of a string.

+

See also:

+ + +

Example:

+
var ident = "pControl"
+ident.removePrefix('p')
+doAssert ident == "Control"
+ Source   +Edit   + +
+
+
+
func removePrefix(s: var string; chars: set[char] = Newlines) {....gcsafe,
+    extern: "nsuRemovePrefixCharSet", raises: [], tags: [], forbids: [].}
+
+ +

Removes all characters from chars from the start of the string s (in-place).

+

See also:

+ + +

Example:

+
var userInput = "\r\n*~Hello World!"
+userInput.removePrefix
+doAssert userInput == "*~Hello World!"
+userInput.removePrefix({'~', '*'})
+doAssert userInput == "Hello World!"
+
+var otherInput = "?!?Hello!?!"
+otherInput.removePrefix({'!', '?'})
+doAssert otherInput == "Hello!?!"
+ Source   +Edit   + +
+
+
+
func removePrefix(s: var string; prefix: string) {....gcsafe,
+    extern: "nsuRemovePrefixString", raises: [], tags: [], forbids: [].}
+
+ +

Remove the first matching prefix (in-place) from a string.

+

See also:

+ + +

Example:

+
var answers = "yesyes"
+answers.removePrefix("yes")
+doAssert answers == "yes"
+ Source   +Edit   + +
+
+ +
+
+
+
func removeSuffix(s: var string; c: char) {....gcsafe,
+    extern: "nsuRemoveSuffixChar", raises: [], tags: [], forbids: [].}
+
+ +

Removes all occurrences of a single character (in-place) from the end of a string.

+

See also:

+ + +

Example:

+
var table = "users"
+table.removeSuffix('s')
+doAssert table == "user"
+
+var dots = "Trailing dots......."
+dots.removeSuffix('.')
+doAssert dots == "Trailing dots"
+ Source   +Edit   + +
+
+
+
func removeSuffix(s: var string; chars: set[char] = Newlines) {....gcsafe,
+    extern: "nsuRemoveSuffixCharSet", raises: [], tags: [], forbids: [].}
+
+ +

Removes all characters from chars from the end of the string s (in-place).

+

See also:

+ + +

Example:

+
var userInput = "Hello World!*~\r\n"
+userInput.removeSuffix
+doAssert userInput == "Hello World!*~"
+userInput.removeSuffix({'~', '*'})
+doAssert userInput == "Hello World!"
+
+var otherInput = "Hello!?!"
+otherInput.removeSuffix({'!', '?'})
+doAssert otherInput == "Hello"
+ Source   +Edit   + +
+
+
+
func removeSuffix(s: var string; suffix: string) {....gcsafe,
+    extern: "nsuRemoveSuffixString", raises: [], tags: [], forbids: [].}
+
+ +

Remove the first matching suffix (in-place) from a string.

+

See also:

+ + +

Example:

+
var answers = "yeses"
+answers.removeSuffix("es")
+doAssert answers == "yes"
+ Source   +Edit   + +
+
+ +
+
+
+
func repeat(c: char; count: Natural): string {....gcsafe, extern: "nsuRepeatChar",
+    raises: [], tags: [], forbids: [].}
+
+ + Returns a string of length count consisting only of the character c. +

Example:

+
let a = 'z'
+doAssert a.repeat(5) == "zzzzz"
+ Source   +Edit   + +
+
+
+
func repeat(s: string; n: Natural): string {....gcsafe, extern: "nsuRepeatStr",
+    raises: [], tags: [], forbids: [].}
+
+ + Returns string s concatenated n times. +

Example:

+
doAssert "+ foo +".repeat(3) == "+ foo ++ foo ++ foo +"
+ Source   +Edit   + +
+
+ +
+
+
+
func replace(s, sub: string; by = ""): string {....gcsafe, extern: "nsuReplaceStr",
+    raises: [], tags: [], forbids: [].}
+
+ +

Replaces every occurrence of the string sub in s with the string by.

+

See also:

+ + + Source   +Edit   + +
+
+
+
func replace(s: string; sub, by: char): string {....gcsafe,
+    extern: "nsuReplaceChar", raises: [], tags: [], forbids: [].}
+
+ +

Replaces every occurrence of the character sub in s with the character by.

+

Optimized version of replace for characters.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func replaceWord(s, sub: string; by = ""): string {....gcsafe,
+    extern: "nsuReplaceWord", raises: [], tags: [], forbids: [].}
+
+ +

Replaces every occurrence of the string sub in s with the string by.

+

Each occurrence of sub has to be surrounded by word boundaries (comparable to \b in regular expressions), otherwise it is not replaced.

+ + Source   +Edit   + +
+
+ +
+
+
+
func rfind(s, sub: string; start: Natural = 0; last = -1): int {....gcsafe,
+    extern: "nsuRFindStr", raises: [], tags: [], forbids: [].}
+
+ +

Searches for sub in s inside range start..last (both ends included) included) in reverse -- starting at high indexes and moving lower to the first character or start. If last is unspecified, it defaults to s.high (the last element).

+

Searching is case-sensitive. If sub is not in s, -1 is returned. Otherwise the index returned is relative to s[0], not start. Subtract start from the result for a start-origin index.

+

See also:

+ + + Source   +Edit   + +
+
+
+
func rfind(s: string; chars: set[char]; start: Natural = 0; last = -1): int {.
+    ...gcsafe, extern: "nsuRFindCharSet", raises: [], tags: [], forbids: [].}
+
+ +

Searches for chars in s inside range start..last (both ends included) in reverse -- starting at high indexes and moving lower to the first character or start. If last is unspecified, it defaults to s.high (the last element).

+

If s contains none of the characters in chars, -1 is returned. Otherwise the index returned is relative to s[0], not start. Subtract start from the result for a start-origin index.

+

See also:

+ + + Source   +Edit   + +
+
+
+
func rfind(s: string; sub: char; start: Natural = 0; last = -1): int {....gcsafe,
+    extern: "nsuRFindChar", raises: [], tags: [], forbids: [].}
+
+ +

Searches for sub in s inside range start..last (both ends included) in reverse -- starting at high indexes and moving lower to the first character or start. If last is unspecified, it defaults to s.high (the last element).

+

Searching is case-sensitive. If sub is not in s, -1 is returned. Otherwise the index returned is relative to s[0], not start. Subtract start from the result for a start-origin index.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func rsplit(s: string; sep: char; maxsplit: int = -1): seq[string] {....gcsafe,
+    extern: "nsuRSplitChar", raises: [], tags: [], forbids: [].}
+
+ +

The same as the rsplit iterator, but is a func that returns a sequence of substrings in original order.

+

A possible common use case for rsplit is path manipulation, particularly on systems that don't use a common delimiter.

+

For example, if a system had # as a delimiter, you could do the following to get the tail of the path:

+

var tailSplit = rsplit("Root#Object#Method#Index", '#', maxsplit=1)

+

Results in tailSplit containing:

+

@["Root#Object#Method", "Index"]

+

See also:

+ + + Source   +Edit   + +
+
+
+
func rsplit(s: string; sep: string; maxsplit: int = -1): seq[string] {....gcsafe,
+    extern: "nsuRSplitString", raises: [], tags: [], forbids: [].}
+
+ +

The same as the rsplit iterator, but is a func that returns a sequence of substrings in original order.

+

A possible common use case for rsplit is path manipulation, particularly on systems that don't use a common delimiter.

+

For example, if a system had # as a delimiter, you could do the following to get the tail of the path:

+

var tailSplit = rsplit("Root#Object#Method#Index", "#", maxsplit=1)

+

Results in tailSplit containing:

+

@["Root#Object#Method", "Index"]

+
Note: +Empty separator string results in returning an original string, following the interpretation "split by no element".
+

See also:

+ + +

Example:

+
doAssert "a  largely    spaced sentence".rsplit(" ", maxsplit = 1) == @[
+    "a  largely    spaced", "sentence"]
+doAssert "a,b,c".rsplit(",") == @["a", "b", "c"]
+doAssert "a man a plan a canal panama".rsplit("a ") == @["", "man ",
+    "plan ", "canal panama"]
+doAssert "".rsplit("Elon Musk") == @[""]
+doAssert "a  largely    spaced sentence".rsplit(" ") == @["a", "",
+    "largely", "", "", "", "spaced", "sentence"]
+doAssert "empty sep returns unsplit s".rsplit("") == @["empty sep returns unsplit s"]
+ Source   +Edit   + +
+
+
+
func rsplit(s: string; seps: set[char] = Whitespace; maxsplit: int = -1): seq[
+    string] {....gcsafe, extern: "nsuRSplitCharSet", raises: [], tags: [],
+              forbids: [].}
+
+ +

The same as the rsplit iterator, but is a func that returns a sequence of substrings in original order.

+

A possible common use case for rsplit is path manipulation, particularly on systems that don't use a common delimiter.

+

For example, if a system had # as a delimiter, you could do the following to get the tail of the path:

+

var tailSplit = rsplit("Root#Object#Method#Index", {'#'}, maxsplit=1)

+

Results in tailSplit containing:

+

@["Root#Object#Method", "Index"]

+
Note: +Empty separator set results in returning an original string, following the interpretation "split by no element".
+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func spaces(n: Natural): string {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Returns a string with n space characters. You can use this func to left align strings.

+

See also:

+ + +

Example:

+
let
+  width = 15
+  text1 = "Hello user!"
+  text2 = "This is a very long string"
+doAssert text1 & spaces(max(0, width - text1.len)) & "|" ==
+         "Hello user!    |"
+doAssert text2 & spaces(max(0, width - text2.len)) & "|" ==
+         "This is a very long string|"
+ Source   +Edit   + +
+
+ +
+
+
+
func split(s: string; sep: char; maxsplit: int = -1): seq[string] {....gcsafe,
+    extern: "nsuSplitChar", raises: [], tags: [], forbids: [].}
+
+ +

The same as the split iterator (see its documentation), but is a func that returns a sequence of substrings.

+

See also:

+ + +

Example:

+
doAssert "a,b,c".split(',') == @["a", "b", "c"]
+doAssert "".split(' ') == @[""]
+ Source   +Edit   + +
+
+
+
func split(s: string; sep: string; maxsplit: int = -1): seq[string] {....gcsafe,
+    extern: "nsuSplitString", raises: [], tags: [], forbids: [].}
+
+ +

Splits the string s into substrings using a string separator.

+

Substrings are separated by the string sep. This is a wrapper around the split iterator.

+
Note: +Empty separator string results in returning an original string, following the interpretation "split by no element".
+

See also:

+ + +

Example:

+
doAssert "a,b,c".split(",") == @["a", "b", "c"]
+doAssert "a man a plan a canal panama".split("a ") == @["", "man ", "plan ", "canal panama"]
+doAssert "".split("Elon Musk") == @[""]
+doAssert "a  largely    spaced sentence".split(" ") == @["a", "", "largely",
+    "", "", "", "spaced", "sentence"]
+doAssert "a  largely    spaced sentence".split(" ", maxsplit = 1) == @["a", " largely    spaced sentence"]
+doAssert "empty sep returns unsplit s".split("") == @["empty sep returns unsplit s"]
+ Source   +Edit   + +
+
+
+
func split(s: string; seps: set[char] = Whitespace; maxsplit: int = -1): seq[
+    string] {....gcsafe, extern: "nsuSplitCharSet", raises: [], tags: [],
+              forbids: [].}
+
+ + The same as the split iterator (see its documentation), but is a func that returns a sequence of substrings.
Note: +Empty separator set results in returning an original string, following the interpretation "split by no element".
+

See also:

+ + +

Example:

+
doAssert "a,b;c".split({',', ';'}) == @["a", "b", "c"]
+doAssert "".split({' '}) == @[""]
+doAssert "empty seps return unsplit s".split({}) == @["empty seps return unsplit s"]
+ Source   +Edit   + +
+
+ +
+
+
+
func splitLines(s: string; keepEol = false): seq[string] {....gcsafe,
+    extern: "nsuSplitLines", raises: [], tags: [], forbids: [].}
+
+ +

The same as the splitLines iterator (see its documentation), but is a func that returns a sequence of substrings.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func splitWhitespace(s: string; maxsplit: int = -1): seq[string] {....gcsafe,
+    extern: "nsuSplitWhitespace", raises: [], tags: [], forbids: [].}
+
+ +

The same as the splitWhitespace iterator (see its documentation), but is a func that returns a sequence of substrings.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
func startsWith(s, prefix: string): bool {....gcsafe, extern: "nsuStartsWith",
+    raises: [], tags: [], forbids: [].}
+
+ +

Returns true if s starts with string prefix.

+

If prefix == "" true is returned.

+

See also:

+ + +

Example:

+
let a = "abracadabra"
+doAssert a.startsWith("abra") == true
+doAssert a.startsWith("bra") == false
+ Source   +Edit   + +
+
+
+
func startsWith(s: string; prefix: char): bool {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Returns true if s starts with character prefix.

+

See also:

+ + +

Example:

+
let a = "abracadabra"
+doAssert a.startsWith('a') == true
+doAssert a.startsWith('b') == false
+ Source   +Edit   + +
+
+ +
+
+
+
func strip(s: string; leading = true; trailing = true;
+           chars: set[char] = Whitespace): string {....gcsafe, extern: "nsuStrip",
+    raises: [], tags: [], forbids: [].}
+
+ +

Strips leading or trailing chars (default: whitespace characters) from s and returns the resulting string.

+

If leading is true (default), leading chars are stripped. If trailing is true (default), trailing chars are stripped. If both are false, the string is returned unchanged.

+

See also:

+ + +

Example:

+
let a = "  vhellov   "
+let b = strip(a)
+doAssert b == "vhellov"
+
+doAssert a.strip(leading = false) == "  vhellov"
+doAssert a.strip(trailing = false) == "vhellov   "
+
+doAssert b.strip(chars = {'v'}) == "hello"
+doAssert b.strip(leading = false, chars = {'v'}) == "vhello"
+
+let c = "blaXbla"
+doAssert c.strip(chars = {'b', 'a'}) == "laXbl"
+doAssert c.strip(chars = {'b', 'a', 'l'}) == "X"
+ Source   +Edit   + +
+
+ +
+
+
+
func stripLineEnd(s: var string) {....raises: [], tags: [], forbids: [].}
+
+ + Strips one of these suffixes from s in-place: \r, \n, \r\n, \f, \v (at most once instance). For example, can be useful in conjunction with osproc.execCmdEx. aka: chomp +

Example:

+
var s = "foo\n\n"
+s.stripLineEnd
+doAssert s == "foo\n"
+s = "foo\r\n"
+s.stripLineEnd
+doAssert s == "foo"
+ Source   +Edit   + +
+
+ +
+
+
+
func toBin(x: BiggestInt; len: Positive): string {....gcsafe, extern: "nsuToBin",
+    raises: [], tags: [], forbids: [].}
+
+ +

Converts x into its binary representation.

+

The resulting string is always len characters long. No leading 0b prefix is generated.

+ +

Example:

+
let
+  a = 29
+  b = 257
+doAssert a.toBin(8) == "00011101"
+doAssert b.toBin(8) == "00000001"
+doAssert b.toBin(9) == "100000001"
+ Source   +Edit   + +
+
+ +
+
+
+
func toHex(s: string): string {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ +

Converts a bytes string to its hexadecimal representation.

+

The output is twice the input long. No prefix like 0x is generated.

+

See also:

+ + +

Example:

+
let
+  a = "1"
+  b = "A"
+  c = "\0\255"
+doAssert a.toHex() == "31"
+doAssert b.toHex() == "41"
+doAssert c.toHex() == "00FF"
+ Source   +Edit   + +
+
+
+
func toHex[T: SomeInteger](x: T): string
+
+ + Shortcut for toHex(x, T.sizeof * 2) +

Example:

+
doAssert toHex(1984'i64) == "00000000000007C0"
+doAssert toHex(1984'i16) == "07C0"
+ Source   +Edit   + +
+
+
+
func toHex[T: SomeInteger](x: T; len: Positive): string
+
+ +

Converts x to its hexadecimal representation.

+

The resulting string will be exactly len characters long. No prefix like 0x is generated. x is treated as an unsigned value.

+ +

Example:

+
let
+  a = 62'u64
+  b = 4097'u64
+doAssert a.toHex(3) == "03E"
+doAssert b.toHex(3) == "001"
+doAssert b.toHex(4) == "1001"
+doAssert toHex(62, 3) == "03E"
+doAssert toHex(-8, 6) == "FFFFF8"
+ Source   +Edit   + +
+
+ +
+
+
+
func toLowerAscii(c: char): char {....gcsafe, extern: "nsuToLowerAsciiChar",
+                                   raises: [], tags: [], forbids: [].}
+
+ +

Returns the lower case version of character c.

+

This works only for the letters A-Z. See unicode.toLower for a version that works for any Unicode character.

+

See also:

+ + +

Example:

+
doAssert toLowerAscii('A') == 'a'
+doAssert toLowerAscii('e') == 'e'
+ Source   +Edit   + +
+
+
+
func toLowerAscii(s: string): string {....gcsafe, extern: "nsuToLowerAsciiStr",
+                                       raises: [], tags: [], forbids: [].}
+
+ +

Converts string s into lower case.

+

This works only for the letters A-Z. See unicode.toLower for a version that works for any Unicode character.

+

See also:

+ + +

Example:

+
doAssert toLowerAscii("FooBar!") == "foobar!"
+ Source   +Edit   + +
+
+ +
+
+
+
func toOct(x: BiggestInt; len: Positive): string {....gcsafe, extern: "nsuToOct",
+    raises: [], tags: [], forbids: [].}
+
+ +

Converts x into its octal representation.

+

The resulting string is always len characters long. No leading 0o prefix is generated.

+

Do not confuse it with toOctal func.

+ +

Example:

+
let
+  a = 62
+  b = 513
+doAssert a.toOct(3) == "076"
+doAssert b.toOct(3) == "001"
+doAssert b.toOct(5) == "01001"
+ Source   +Edit   + +
+
+ +
+
+
+
func toOctal(c: char): string {....gcsafe, extern: "nsuToOctal", raises: [],
+                                tags: [], forbids: [].}
+
+ +

Converts a character c to its octal representation.

+

The resulting string may not have a leading zero. Its length is always exactly 3.

+

Do not confuse it with toOct func.

+ +

Example:

+
doAssert toOctal('1') == "061"
+doAssert toOctal('A') == "101"
+doAssert toOctal('a') == "141"
+doAssert toOctal('!') == "041"
+ Source   +Edit   + +
+
+ +
+
+
+
func toUpperAscii(c: char): char {....gcsafe, extern: "nsuToUpperAsciiChar",
+                                   raises: [], tags: [], forbids: [].}
+
+ +

Converts character c into upper case.

+

This works only for the letters A-Z. See unicode.toUpper for a version that works for any Unicode character.

+

See also:

+ + +

Example:

+
doAssert toUpperAscii('a') == 'A'
+doAssert toUpperAscii('E') == 'E'
+ Source   +Edit   + +
+
+
+
func toUpperAscii(s: string): string {....gcsafe, extern: "nsuToUpperAsciiStr",
+                                       raises: [], tags: [], forbids: [].}
+
+ +

Converts string s into upper case.

+

This works only for the letters A-Z. See unicode.toUpper for a version that works for any Unicode character.

+

See also:

+ + +

Example:

+
doAssert toUpperAscii("FooBar!") == "FOOBAR!"
+ Source   +Edit   + +
+
+ +
+
+
+
func trimZeros(x: var string; decimalSep = '.') {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Trim trailing zeros from a formatted floating point value x (must be declared as var).

+

This modifies x itself, it does not return a copy.

+ +

Example:

+
var x = "123.456000000"
+x.trimZeros()
+doAssert x == "123.456"
+ Source   +Edit   + +
+
+ +
+
+
+
func unescape(s: string; prefix = "\""; suffix = "\""): string {....gcsafe,
+    extern: "nsuUnescape", raises: [ValueError], tags: [], forbids: [].}
+
+ +

Unescapes a string s.

+

This complements escape func as it performs the opposite operations.

+

If s does not begin with prefix and end with suffix a ValueError exception will be raised.

+ + Source   +Edit   + +
+
+ +
+
+
+
func unindent(s: string; count: Natural = int.high; padding: string = " "): string {.
+    ...gcsafe, extern: "nsuUnindent", raises: [], tags: [], forbids: [].}
+
+ +

Unindents each line in s by count amount of padding.

+

Note: This does not preserve the new line characters used in s.

+

See also:

+ + +

Example:

+
let x = """
+      Hello
+        There
+    """.unindent()
+
+doAssert x == "Hello\nThere\n"
+ Source   +Edit   + +
+
+ +
+
+
+
func validIdentifier(s: string): bool {....gcsafe, extern: "nsuValidIdentifier",
+                                        raises: [], tags: [], forbids: [].}
+
+ +

Returns true if s is a valid identifier.

+

A valid identifier starts with a character of the set IdentStartChars and is followed by any number of characters of the set IdentChars.

+ +

Example:

+
doAssert "abc_def08".validIdentifier
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator rsplit(s: string; sep: char; maxsplit: int = -1): string {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Splits the string s into substrings from the right using a string separator. Works exactly the same as split iterator except in reverse order.

+

for piece in "foo:bar".rsplit(':'):
+  echo piece

+

Results in:

+

"bar"
+"foo"

+

Substrings are separated from the right by the char sep.

+

See also:

+ + + Source   +Edit   + +
+
+
+
iterator rsplit(s: string; sep: string; maxsplit: int = -1;
+                keepSeparators: bool = false): string {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Splits the string s into substrings from the right using a string separator. Works exactly the same as split iterator except in reverse order.

+

for piece in "foothebar".rsplit("the"):
+  echo piece

+

Results in:

+

"bar"
+"foo"

+

Substrings are separated from the right by the string sep

+
Note: +Empty separator string results in returning an original string, following the interpretation "split by no element".
+

See also:

+ + + Source   +Edit   + +
+
+
+
iterator rsplit(s: string; seps: set[char] = Whitespace; maxsplit: int = -1): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Splits the string s into substrings from the right using a string separator. Works exactly the same as split iterator except in reverse order.

+

for piece in "foo bar".rsplit(WhiteSpace):
+  echo piece

+

Results in:

+

"bar"
+"foo"

+

Substrings are separated from the right by the set of chars seps

+
Note: +Empty separator set results in returning an original string, following the interpretation "split by no element".
+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator split(s: string; sep: char; maxsplit: int = -1): string {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Splits the string s into substrings using a single separator.

+

Substrings are separated by the character sep. The code:

+

for word in split(";;this;is;an;;example;;;", ';'):
+  writeLine(stdout, word)

+

Results in:

+

""
+""
+"this"
+"is"
+"an"
+""
+"example"
+""
+""
+""

+

See also:

+ + + Source   +Edit   + +
+
+
+
iterator split(s: string; sep: string; maxsplit: int = -1): string {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Splits the string s into substrings using a string separator.

+

Substrings are separated by the string sep. The code:

+

for word in split("thisDATAisDATAcorrupted", "DATA"):
+  writeLine(stdout, word)

+

Results in:

+

"this"
+"is"
+"corrupted"

+
Note: +Empty separator string results in returning an original string, following the interpretation "split by no element".
+

See also:

+ + + Source   +Edit   + +
+
+
+
iterator split(s: string; seps: set[char] = Whitespace; maxsplit: int = -1): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Splits the string s into substrings using a group of separators.

+

Substrings are separated by a substring containing only seps.

+

for word in split("this\lis an\texample"):
+  writeLine(stdout, word)

+

...generates this output:

+

"this"
+"is"
+"an"
+"example"

+

And the following code:

+

for word in split("this:is;an$example", {';', ':', '$'}):
+  writeLine(stdout, word)

+

...produces the same output as the first example. The code:

+

let date = "2012-11-20T22:08:08.398990"
+let separators = {' ', '-', ':', 'T'}
+for number in split(date, separators):
+  writeLine(stdout, number)

+

...results in:

+

"2012"
+"11"
+"20"
+"22"
+"08"
+"08.398990"

+
Note: +Empty separator set results in returning an original string, following the interpretation "split by no element".
+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator splitLines(s: string; keepEol = false): string {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Splits the string s into its containing lines.

+

Every character literal newline combination (CR, LF, CR-LF) is supported. The result strings contain no trailing end of line characters unless the parameter keepEol is set to true.

+

Example:

+

for line in splitLines("\nthis\nis\nan\n\nexample\n"):
+  writeLine(stdout, line)

+

Results in:

+

""
+"this"
+"is"
+"an"
+""
+"example"
+""

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator splitWhitespace(s: string; maxsplit: int = -1): string {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Splits the string s at whitespace stripping leading and trailing whitespace if necessary. If maxsplit is specified and is positive, no more than maxsplit splits is made.

+

The following code:

+

let s = "  foo \t bar  baz  "
+for ms in [-1, 1, 2, 3]:
+  echo "------ maxsplit = ", ms, ":"
+  for item in s.splitWhitespace(maxsplit=ms):
+    echo '"', item, '"'

+

...results in:

+

------ maxsplit = -1:
+"foo"
+"bar"
+"baz"
+------ maxsplit = 1:
+"foo"
+"bar  baz  "
+------ maxsplit = 2:
+"foo"
+"bar"
+"baz  "
+------ maxsplit = 3:
+"foo"
+"bar"
+"baz"

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator tokenize(s: string; seps: set[char] = Whitespace): tuple[token: string,
+    isSep: bool] {....raises: [], tags: [], forbids: [].}
+
+ +

Tokenizes the string s into substrings.

+

Substrings are separated by a substring containing only seps. Example:

+

for word in tokenize("  this is an  example  "):
+  writeLine(stdout, word)

+

Results in:

+

("  ", true)
+("this", false)
+(" ", true)
+("is", false)
+(" ", true)
+("an", false)
+("  ", true)
+("example", false)
+("  ", true)

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/strutils.idx b/strutils.idx new file mode 100644 index 0000000000000..6023c298e2ecd --- /dev/null +++ b/strutils.idx @@ -0,0 +1,163 @@ +nimTitle strutils strutils.html module std/strutils 0 +nim Whitespace strutils.html#Whitespace const Whitespace 91 +nim Letters strutils.html#Letters const Letters 95 +nim UppercaseLetters strutils.html#UppercaseLetters const UppercaseLetters 98 +nim LowercaseLetters strutils.html#LowercaseLetters const LowercaseLetters 101 +nim PunctuationChars strutils.html#PunctuationChars const PunctuationChars 104 +nim Digits strutils.html#Digits const Digits 107 +nim HexDigits strutils.html#HexDigits const HexDigits 110 +nim IdentChars strutils.html#IdentChars const IdentChars 113 +nim IdentStartChars strutils.html#IdentStartChars const IdentStartChars 116 +nim Newlines strutils.html#Newlines const Newlines 119 +nim PrintableChars strutils.html#PrintableChars const PrintableChars 123 +nim AllChars strutils.html#AllChars const AllChars 126 +nim isAlphaAscii strutils.html#isAlphaAscii,char proc isAlphaAscii(c: char): bool 138 +nim isAlphaNumeric strutils.html#isAlphaNumeric,char proc isAlphaNumeric(c: char): bool 149 +nim isDigit strutils.html#isDigit,char proc isDigit(c: char): bool 159 +nim isSpaceAscii strutils.html#isSpaceAscii,char proc isSpaceAscii(c: char): bool 168 +nim isLowerAscii strutils.html#isLowerAscii,char proc isLowerAscii(c: char): bool 176 +nim isUpperAscii strutils.html#isUpperAscii,char proc isUpperAscii(c: char): bool 190 +nim toLowerAscii strutils.html#toLowerAscii,char proc toLowerAscii(c: char): char 204 +nim toLowerAscii strutils.html#toLowerAscii,string proc toLowerAscii(s: string): string 227 +nim toUpperAscii strutils.html#toUpperAscii,char proc toUpperAscii(c: char): char 240 +nim toUpperAscii strutils.html#toUpperAscii,string proc toUpperAscii(s: string): string 259 +nim capitalizeAscii strutils.html#capitalizeAscii,string proc capitalizeAscii(s: string): string 272 +nim nimIdentNormalize strutils.html#nimIdentNormalize,string proc nimIdentNormalize(s: string): string 286 +nim normalize strutils.html#normalize,string proc normalize(s: string): string 312 +nim cmpIgnoreCase strutils.html#cmpIgnoreCase,string,string proc cmpIgnoreCase(a, b: string): int 334 +nim cmpIgnoreStyle strutils.html#cmpIgnoreStyle,string,string proc cmpIgnoreStyle(a, b: string): int 349 +nim split strutils.html#split.i,string,char,int iterator split(s: string; sep: char; maxsplit: int = -1): string 421 +nim split strutils.html#split.i,string,set[char],int iterator split(s: string; seps: set[char] = Whitespace; maxsplit: int = -1): string 451 +nim split strutils.html#split.i,string,string,int iterator split(s: string; sep: string; maxsplit: int = -1): string 508 +nim rsplit strutils.html#rsplit.i,string,char,int iterator rsplit(s: string; sep: char; maxsplit: int = -1): string 564 +nim rsplit strutils.html#rsplit.i,string,set[char],int iterator rsplit(s: string; seps: set[char] = Whitespace; maxsplit: int = -1): string 591 +nim rsplit strutils.html#rsplit.i,string,string,int,bool iterator rsplit(s: string; sep: string; maxsplit: int = -1; keepSeparators: bool = false): string 621 +nim splitLines strutils.html#splitLines.i,string iterator splitLines(s: string; keepEol = false): string 653 +nim splitWhitespace strutils.html#splitWhitespace.i,string,int iterator splitWhitespace(s: string; maxsplit: int = -1): string 704 +nim split strutils.html#split,string,char,int proc split(s: string; sep: char; maxsplit: int = -1): seq[string] 746 +nim split strutils.html#split,string,set[char],int proc split(s: string; seps: set[char] = Whitespace; maxsplit: int = -1): seq[string] 761 +nim split strutils.html#split,string,string,int proc split(s: string; sep: string; maxsplit: int = -1): seq[string] 780 +nim rsplit strutils.html#rsplit,string,char,int proc rsplit(s: string; sep: char; maxsplit: int = -1): seq[string] 805 +nim rsplit strutils.html#rsplit,string,set[char],int proc rsplit(s: string; seps: set[char] = Whitespace; maxsplit: int = -1): seq[string] 834 +nim rsplit strutils.html#rsplit,string,string,int proc rsplit(s: string; sep: string; maxsplit: int = -1): seq[string] 867 +nim splitLines strutils.html#splitLines,string proc splitLines(s: string; keepEol = false): seq[string] 909 +nim splitWhitespace strutils.html#splitWhitespace,string,int proc splitWhitespace(s: string; maxsplit: int = -1): seq[string] 920 +nim toBin strutils.html#toBin,BiggestInt,Positive proc toBin(x: BiggestInt; len: Positive): string 930 +nim toOct strutils.html#toOct,BiggestInt,Positive proc toOct(x: BiggestInt; len: Positive): string 952 +nim toHex strutils.html#toHex,T,Positive proc toHex[T: SomeInteger](x: T; len: Positive): string 987 +nim toHex strutils.html#toHex,T proc toHex[T: SomeInteger](x: T): string 1009 +nim toHex strutils.html#toHex,string proc toHex(s: string): string 1022 +nim toOctal strutils.html#toOctal,char proc toOctal(c: char): string 1047 +nim fromBin strutils.html#fromBin,string proc fromBin[T: SomeInteger](s: string): T 1066 +nim fromOct strutils.html#fromOct,string proc fromOct[T: SomeInteger](s: string): T 1089 +nim fromHex strutils.html#fromHex,string proc fromHex[T: SomeInteger](s: string): T 1112 +nim intToStr strutils.html#intToStr,int,Positive proc intToStr(x: int; minchars: Positive = 1): string 1135 +nim parseInt strutils.html#parseInt,string proc parseInt(s: string): int 1150 +nim parseBiggestInt strutils.html#parseBiggestInt,string proc parseBiggestInt(s: string): BiggestInt 1161 +nim parseUInt strutils.html#parseUInt,string proc parseUInt(s: string): uint 1171 +nim parseBiggestUInt strutils.html#parseBiggestUInt,string proc parseBiggestUInt(s: string): BiggestUInt 1180 +nim parseFloat strutils.html#parseFloat,string proc parseFloat(s: string): float 1190 +nim parseBinInt strutils.html#parseBinInt,string proc parseBinInt(s: string): int 1203 +nim parseOctInt strutils.html#parseOctInt,string proc parseOctInt(s: string): int 1221 +nim parseHexInt strutils.html#parseHexInt,string proc parseHexInt(s: string): int 1232 +nim parseHexStr strutils.html#parseHexStr,string proc parseHexStr(s: string): string 1258 +nim parseBool strutils.html#parseBool,string proc parseBool(s: string): bool 1289 +nim parseEnum strutils.html#parseEnum,string proc parseEnum[T: enum](s: string): T 1305 +nim parseEnum strutils.html#parseEnum,string,T proc parseEnum[T: enum](s: string; default: T): T 1325 +nim repeat strutils.html#repeat,char,Natural proc repeat(c: char; count: Natural): string 1344 +nim repeat strutils.html#repeat,string,Natural proc repeat(s: string; n: Natural): string 1353 +nim spaces strutils.html#spaces,Natural proc spaces(n: Natural): string 1361 +nim align strutils.html#align,string,Natural,char proc align(s: string; count: Natural; padding = ' '): string 1381 +nim alignLeft strutils.html#alignLeft,string,Natural,char proc alignLeft(s: string; count: Natural; padding = ' '): string 1408 +nim center strutils.html#center,string,int,char proc center(s: string; width: int; fillChar: char = ' '): string 1435 +nim indent strutils.html#indent,string,Natural,string proc indent(s: string; count: Natural; padding: string = " "): string 1470 +nim unindent strutils.html#unindent,string,Natural,string proc unindent(s: string; count: Natural = int.high; padding: string = " "): string 1495 +nim indentation strutils.html#indentation,string proc indentation(s: string): Natural 1528 +nim dedent strutils.html#dedent,string,Natural proc dedent(s: string; count: Natural = indentation(s)): string 1541 +nim delete strutils.html#delete,string,Slice[int] proc delete(s: var string; slice: Slice[int]) 1566 +nim delete strutils.html#delete,string,int,int proc delete(s: var string; first, last: int) 1596 +nim startsWith strutils.html#startsWith,string,char proc startsWith(s: string; prefix: char): bool 1620 +nim startsWith strutils.html#startsWith,string,string proc startsWith(s, prefix: string): bool 1633 +nim endsWith strutils.html#endsWith,string,char proc endsWith(s: string; suffix: char): bool 1648 +nim endsWith strutils.html#endsWith,string,string proc endsWith(s, suffix: string): bool 1661 +nim continuesWith strutils.html#continuesWith,string,string,Natural proc continuesWith(s, substr: string; start: Natural): bool 1676 +nim removePrefix strutils.html#removePrefix,string,set[char] proc removePrefix(s: var string; chars: set[char] = Newlines) 1697 +nim removePrefix strutils.html#removePrefix,string,char proc removePrefix(s: var string; c: char) 1719 +nim removePrefix strutils.html#removePrefix,string,string proc removePrefix(s: var string; prefix: string) 1733 +nim removeSuffix strutils.html#removeSuffix,string,set[char] proc removeSuffix(s: var string; chars: set[char] = Newlines) 1747 +nim removeSuffix strutils.html#removeSuffix,string,char proc removeSuffix(s: var string; c: char) 1770 +nim removeSuffix strutils.html#removeSuffix,string,string proc removeSuffix(s: var string; suffix: string) 1789 +nim addSep strutils.html#addSep,string,string,Natural proc addSep(dest: var string; sep = ", "; startLen: Natural = 0) 1806 +nim allCharsInSet strutils.html#allCharsInSet,string,set[char] proc allCharsInSet(s: string; theSet: set[char]): bool 1829 +nim abbrev strutils.html#abbrev,string,openArray[string] proc abbrev(s: string; possibilities: openArray[string]): int 1839 +nim join strutils.html#join,openArray[string],string proc join(a: openArray[string]; sep: string = ""): string 1861 +nim join strutils.html#join,openArray[T],string proc join[T: not string](a: openArray[T]; sep: string = ""): string 1878 +nim SkipTable strutils.html#SkipTable type SkipTable 1891 +nim initSkipTable strutils.html#initSkipTable,SkipTable,string proc initSkipTable(a: var SkipTable; sub: string) 1893 +nim initSkipTable strutils.html#initSkipTable,string proc initSkipTable(sub: string): SkipTable 1907 +nim find strutils.html#find,SkipTable,string,string,Natural,int proc find(a: SkipTable; s, sub: string; start: Natural = 0; last = -1): int 1916 +nim find strutils.html#find,string,char,Natural,int proc find(s: string; sub: char; start: Natural = 0; last = -1): int 1956 +nim find strutils.html#find,string,set[char],Natural,int proc find(s: string; chars: set[char]; start: Natural = 0; last = -1): int 1988 +nim find strutils.html#find,string,string,Natural,int proc find(s, sub: string; start: Natural = 0; last = -1): int 2014 +nim rfind strutils.html#rfind,string,char,Natural,int proc rfind(s: string; sub: char; start: Natural = 0; last = -1): int 2048 +nim rfind strutils.html#rfind,string,set[char],Natural,int proc rfind(s: string; chars: set[char]; start: Natural = 0; last = -1): int 2066 +nim rfind strutils.html#rfind,string,string,Natural,int proc rfind(s, sub: string; start: Natural = 0; last = -1): int 2084 +nim count strutils.html#count,string,char proc count(s: string; sub: char): int 2114 +nim count strutils.html#count,string,set[char] proc count(s: string; subs: set[char]): int 2123 +nim count strutils.html#count,string,string,bool proc count(s: string; sub: string; overlapping: bool = false): int 2134 +nim countLines strutils.html#countLines,string proc countLines(s: string): int 2152 +nim contains strutils.html#contains,string,string proc contains(s, sub: string): bool 2179 +nim contains strutils.html#contains,string,set[char] proc contains(s: string; chars: set[char]): bool 2186 +nim replace strutils.html#replace,string,string,string proc replace(s, sub: string; by = ""): string 2193 +nim replace strutils.html#replace,string,char,char proc replace(s: string; sub, by: char): string 2234 +nim replaceWord strutils.html#replaceWord,string,string,string proc replaceWord(s, sub: string; by = ""): string 2253 +nim multiReplace strutils.html#multiReplace,string,varargs[] proc multiReplace(s: string; replacements: varargs[(string, string)]): string 2283 +nim insertSep strutils.html#insertSep,string,char,int proc insertSep(s: string; sep = '_'; digits = 3): string 2332 +nim escape strutils.html#escape,string,string,string proc escape(s: string; prefix = "\""; suffix = "\""): string 2366 +nim unescape strutils.html#unescape,string,string,string proc unescape(s: string; prefix = "\""; suffix = "\""): string 2398 +nim validIdentifier strutils.html#validIdentifier,string proc validIdentifier(s: string): bool 2441 +nim ffDefault strutils.html#ffDefault FloatFormatMode.ffDefault 2461 +nim ffDecimal strutils.html#ffDecimal FloatFormatMode.ffDecimal 2461 +nim ffScientific strutils.html#ffScientific FloatFormatMode.ffScientific 2461 +nim FloatFormatMode strutils.html#FloatFormatMode enum FloatFormatMode 2461 +nim formatBiggestFloat strutils.html#formatBiggestFloat,BiggestFloat,FloatFormatMode,range[],char proc formatBiggestFloat(f: BiggestFloat; format: FloatFormatMode = ffDefault;\n precision: range[-1 .. 32] = 16; decimalSep = '.'): string 2467 +nim formatFloat strutils.html#formatFloat,float,FloatFormatMode,range[],char proc formatFloat(f: float; format: FloatFormatMode = ffDefault;\n precision: range[-1 .. 32] = 16; decimalSep = '.'): string 2543 +nim trimZeros strutils.html#trimZeros,string,char proc trimZeros(x: var string; decimalSep = '.') 2564 +nim bpIEC strutils.html#bpIEC BinaryPrefixMode.bpIEC 2585 +nim bpColloquial strutils.html#bpColloquial BinaryPrefixMode.bpColloquial 2585 +nim BinaryPrefixMode strutils.html#BinaryPrefixMode enum BinaryPrefixMode 2585 +nim formatSize strutils.html#formatSize,int64,char proc formatSize(bytes: int64; decimalSep = '.'; prefix = bpIEC; includeSpace = false): string 2589 +nim formatEng strutils.html#formatEng,BiggestFloat,range[],bool,bool,string,char proc formatEng(f: BiggestFloat; precision: range[0 .. 32] = 10; trim: bool = true;\n siPrefix: bool = false; unit: string = ""; decimalSep = '.';\n useUnitSpace = false): string 2645 +nim addf strutils.html#addf,string,string,varargs[string,] proc addf(s: var string; formatstr: string; a: varargs[string, `$`]) 2796 +nim `%` strutils.html#%,string,openArray[string] proc `%`(formatstr: string; a: openArray[string]): string 2859 +nim `%` strutils.html#%,string,string proc `%`(formatstr, a: string): string 2912 +nim format strutils.html#format,string,varargs[string,] proc format(formatstr: string; a: varargs[string, `$`]): string 2919 +nim strip strutils.html#strip,string,set[char] proc strip(s: string; leading = true; trailing = true; chars: set[char] = Whitespace): string 2931 +nim stripLineEnd strutils.html#stripLineEnd,string proc stripLineEnd(s: var string) 2967 +nim tokenize strutils.html#tokenize.i,string,set[char] iterator tokenize(s: string; seps: set[char] = Whitespace): tuple[token: string,\n isSep: bool] 2993 +nim isEmptyOrWhitespace strutils.html#isEmptyOrWhitespace,string proc isEmptyOrWhitespace(s: string): bool 3029 +idx chomp strutils.html#chomp_1 Module strutils 0 +idx substitution strutils.html#substitution_1 Module strutils 0 +idx string interpolation strutils.html#string-interpolation_1 Module strutils 0 +nimgrp replace strutils.html#replace-procs-all proc 2193 +nimgrp tohex strutils.html#toHex-procs-all proc 987 +nimgrp removesuffix strutils.html#removeSuffix-procs-all proc 1747 +nimgrp toupperascii strutils.html#toUpperAscii-procs-all proc 240 +nimgrp endswith strutils.html#endsWith-procs-all proc 1648 +nimgrp removeprefix strutils.html#removePrefix-procs-all proc 1697 +nimgrp count strutils.html#count-procs-all proc 2114 +nimgrp find strutils.html#find-procs-all proc 1916 +nimgrp rsplit strutils.html#rsplit-procs-all proc 805 +nimgrp join strutils.html#join-procs-all proc 1861 +nimgrp rfind strutils.html#rfind-procs-all proc 2048 +nimgrp startswith strutils.html#startsWith-procs-all proc 1620 +nimgrp delete strutils.html#delete-procs-all proc 1566 +nimgrp tolowerascii strutils.html#toLowerAscii-procs-all proc 204 +nimgrp contains strutils.html#contains-procs-all proc 2179 +nimgrp % strutils.html#%-procs-all proc 2859 +nimgrp split strutils.html#split-procs-all proc 746 +nimgrp repeat strutils.html#repeat-procs-all proc 1344 +nimgrp parseenum strutils.html#parseEnum-procs-all proc 1305 +nimgrp initskiptable strutils.html#initSkipTable-procs-all proc 1893 +nimgrp split strutils.html#split-iterators-all iterator 421 +nimgrp rsplit strutils.html#rsplit-iterators-all iterator 564 diff --git a/sugar.html b/sugar.html new file mode 100644 index 0000000000000..8d7628fe7101d --- /dev/null +++ b/sugar.html @@ -0,0 +1,378 @@ + + + + + + + +std/sugar + + + + + + + + + + + + + + + + +
+
+

std/sugar

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements nice syntactic sugar based on Nim's macro system.

+ +
+

Macros

+
+
+
+
macro `->`(p, b: untyped): untyped
+
+ + Syntax sugar for procedure types. It also supports pragmas.
Warning: +Semicolons can not be used to separate procedure arguments.
+ +

Example:

+
proc passTwoAndTwo(f: (int, int) -> int): int = f(2, 2)
+# is the same as:
+# proc passTwoAndTwo(f: proc (x, y: int): int): int = f(2, 2)
+
+assert passTwoAndTwo((x, y) => x + y) == 4
+
+proc passOne(f: (int {.noSideEffect.} -> int)): int = f(1)
+# is the same as:
+# proc passOne(f: proc (x: int): int {.noSideEffect.}): int = f(1)
+
+assert passOne(x {.noSideEffect.} => x + 1) == 2
+ Source   +Edit   + +
+
+ +
+
+
+
macro `=>`(p, b: untyped): untyped
+
+ + Syntax sugar for anonymous procedures. It also supports pragmas.
Warning: +Semicolons can not be used to separate procedure arguments.
+ +

Example:

+
proc passTwoAndTwo(f: (int, int) -> int): int = f(2, 2)
+
+assert passTwoAndTwo((x, y) => x + y) == 4
+
+type
+  Bot = object
+    call: (string {.noSideEffect.} -> string)
+
+var myBot = Bot()
+
+myBot.call = (name: string) {.noSideEffect.} => "Hello " & name & ", I'm a bot."
+assert myBot.call("John") == "Hello John, I'm a bot."
+
+let f = () => (discard) # simplest proc that returns void
+f()
+ Source   +Edit   + +
+
+ +
+
+
+
macro capture(locals: varargs[typed]; body: untyped): untyped
+
+ + Useful when creating a closure in a loop to capture some local loop variables by their current iteration values. +

Example:

+
import std/strformat
+
+var myClosure: () -> string
+for i in 5..7:
+  for j in 7..9:
+    if i * j == 42:
+      capture i, j:
+        myClosure = () => fmt"{i} * {j} = 42"
+assert myClosure() == "6 * 7 = 42"
+ Source   +Edit   + +
+
+ +
+
+
+
macro collect(body: untyped): untyped
+
+ +

Same as collect but without an init parameter.

+

See also:

+ + +

Example:

+
import std/[sets, tables]
+let data = @["bird", "word"]
+
+# seq:
+let k = collect:
+  for i, d in data.pairs:
+    if i mod 2 == 0: d
+assert k == @["bird"]
+
+## HashSet:
+let n = collect:
+  for d in data.items: {d}
+assert n == data.toHashSet
+
+## Table:
+let m = collect:
+  for i, d in data.pairs: {i: d}
+assert m == {0: "bird", 1: "word"}.toTable
+ Source   +Edit   + +
+
+
+
macro collect(init, body: untyped): untyped
+
+ +

Comprehension for seqs/sets/tables.

+

The last expression of body has special syntax that specifies the collection's add operation. Use {e} for set's incl, {k: v} for table's []= and e for seq's add.

+ +

Example:

+
import std/[sets, tables]
+
+let data = @["bird", "word"]
+
+## seq:
+let k = collect(newSeq):
+  for i, d in data.pairs:
+    if i mod 2 == 0: d
+assert k == @["bird"]
+
+## seq with initialSize:
+let x = collect(newSeqOfCap(4)):
+  for i, d in data.pairs:
+    if i mod 2 == 0: d
+assert x == @["bird"]
+
+## HashSet:
+let y = collect(initHashSet()):
+  for d in data.items: {d}
+assert y == data.toHashSet
+
+## Table:
+let z = collect(initTable(2)):
+  for i, d in data.pairs: {i: d}
+assert z == {0: "bird", 1: "word"}.toTable
+ Source   +Edit   + +
+
+ +
+
+
+
macro dump(x: untyped): untyped
+
+ +

Dumps the content of an expression, useful for debugging. It accepts any expression and prints a textual representation of the tree representing the expression - as it would appear in source code - together with the value of the expression.

+

See also: dumpToString which is more convenient and useful since it expands intermediate templates/macros, returns a string instead of calling echo, and works with statements and expressions.

+ +

Example: cmd: -r:off

+
let
+  x = 10
+  y = 20
+dump(x + y) # prints: `x + y = 30`
+ Source   +Edit   + +
+
+ +
+
+
+
macro dumpToString(x: untyped): string
+
+ + Returns the content of a statement or expression x after semantic analysis, useful for debugging. +

Example:

+
const a = 1
+let x = 10
+assert dumpToString(a + 2) == "a + 2: 3 = 3"
+assert dumpToString(a + x) == "a + x: 1 + x = 11"
+template square(x): untyped = x * x
+assert dumpToString(square(x)) == "square(x): x * x = 100"
+assert not compiles dumpToString(1 + nonexistent)
+import std/strutils
+assert "failedAssertImpl" in dumpToString(assert true) # example with a statement
+ Source   +Edit   + +
+
+ +
+
+
+
macro dup[T](arg: T; calls: varargs[untyped]): T
+
+ +

Turns an in-place algorithm into one that works on a copy and returns this copy, without modifying its input.

+

This macro also allows for (otherwise in-place) function chaining.

+

Since: Version 1.2.

+ +

Example:

+
import std/algorithm
+
+let a = @[1, 2, 3, 4, 5, 6, 7, 8, 9]
+assert a.dup(sort) == sorted(a)
+
+# Chaining:
+var aCopy = a
+aCopy.insert(10)
+assert a.dup(insert(10), sort) == sorted(aCopy)
+
+let s1 = "abc"
+let s2 = "xyz"
+assert s1 & s2 == s1.dup(&= s2)
+
+# An underscore (_) can be used to denote the place of the argument you're passing:
+assert "".dup(addQuoted(_, "foo")) == "\"foo\""
+# but `_` is optional here since the substitution is in 1st position:
+assert "".dup(addQuoted("foo")) == "\"foo\""
+
+proc makePalindrome(s: var string) =
+  for i in countdown(s.len-2, 0):
+    s.add(s[i])
+
+let c = "xyz"
+
+# chaining:
+let d = dup c:
+  makePalindrome # xyzyx
+  sort(_, SortOrder.Descending) # zyyxx
+  makePalindrome # zyyxxxyyz
+assert d == "zyyxxxyyz"
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/sugar.idx b/sugar.idx new file mode 100644 index 0000000000000..4c4a4e6cc131c --- /dev/null +++ b/sugar.idx @@ -0,0 +1,11 @@ +nimTitle sugar sugar.html module std/sugar 0 +nim `=>` sugar.html#=>.m,untyped,untyped macro `=>`(p, b: untyped): untyped 55 +nim `->` sugar.html#->.m,untyped,untyped macro `->`(p, b: untyped): untyped 136 +nim dump sugar.html#dump.m,untyped macro dump(x: untyped): untyped 155 +nim dumpToString sugar.html#dumpToString.m,untyped macro dumpToString(x: untyped): string 183 +nim capture sugar.html#capture.m,varargs[typed],untyped macro capture(locals: varargs[typed]; body: untyped): untyped 216 +nim dup sugar.html#dup.m,T,varargs[untyped] macro dup[T](arg: T; calls: varargs[untyped]): T 254 +nim collect sugar.html#collect.m,untyped,untyped macro collect(init, body: untyped): untyped 366 +nim collect sugar.html#collect.m,untyped macro collect(body: untyped): untyped 403 +idx in-place sugar.html#inminusplace_1 Module sugar 0 +nimgrp collect sugar.html#collect-macros-all macro 366 diff --git a/symlinks.html b/symlinks.html new file mode 100644 index 0000000000000..07a822807965c --- /dev/null +++ b/symlinks.html @@ -0,0 +1,167 @@ + + + + + + + +std/symlinks + + + + + + + + + + + + + + + + +
+
+

std/symlinks

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements symlink (symbolic link) handling.

+ +
+

Procs

+
+ + +
+
+
proc symlinkExists(link: Path): bool {.inline, ...tags: [ReadDirEffect],
+                                       sideEffect, ...raises: [], forbids: [].}
+
+ + Returns true if the symlink link exists. Will return true regardless of whether the link points to a directory or file. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/symlinks.idx b/symlinks.idx new file mode 100644 index 0000000000000..2f369bfa00e3e --- /dev/null +++ b/symlinks.idx @@ -0,0 +1,4 @@ +nimTitle symlinks symlinks.html module std/symlinks 0 +nim symlinkExists symlinks.html#symlinkExists,Path proc symlinkExists(link: Path): bool 9 +nim createSymlink symlinks.html#createSymlink,Path,Path proc createSymlink(src, dest: Path) 14 +nim expandSymlink symlinks.html#expandSymlink,Path proc expandSymlink(symlinkPath: Path): Path 26 diff --git a/syncio.html b/syncio.html new file mode 100644 index 0000000000000..b240fa82f08e4 --- /dev/null +++ b/syncio.html @@ -0,0 +1,1013 @@ + + + + + + + +std/syncio + + + + + + + + + + + + + + + + +
+
+

std/syncio

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements various synchronized I/O operations.

+ +
+

Types

+
+
+
File = ptr CFile
+
+ + The type representing a file handle. + Source   +Edit   + +
+
+
+
FileHandle = cint
+
+ + The type that represents an OS file handle; this is useful for low-level file access. + Source   +Edit   + +
+
+
+
FileMode = enum
+  fmRead,                   ## Open the file for read access only.
+                             ## If the file does not exist, it will not
+                             ## be created.
+  fmWrite,                  ## Open the file for write access only.
+                             ## If the file does not exist, it will be
+                             ## created. Existing files will be cleared!
+  fmReadWrite,              ## Open the file for read and write access.
+                             ## If the file does not exist, it will be
+                             ## created. Existing files will be cleared!
+  fmReadWriteExisting,      ## Open the file for read and write access.
+                             ## If the file does not exist, it will not be
+                             ## created. The existing file will not be cleared.
+  fmAppend                   ## Open the file for writing only; append data
+                             ## at the end. If the file does not exist, it
+                             ## will be created.
+
+ + The file mode when opening a file. + Source   +Edit   + +
+
+
+
FileSeekPos = enum
+  fspSet,                   ## Seek to absolute value
+  fspCur,                   ## Seek relative to current position
+  fspEnd                     ## Seek relative to end
+
+ + Position relative to which seek should happen. + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
stderr {.importc: "stderr", header: "<stdio.h>".}: File
+
+ + The standard error stream. + Source   +Edit   + +
+
+
+
stdin {.importc: "stdin", header: "<stdio.h>".}: File
+
+ + The standard input stream. + Source   +Edit   + +
+
+
+
stdout {.importc: "stdout", header: "<stdio.h>".}: File
+
+ + The standard output stream. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc close(f: File) {....tags: [], gcsafe, sideEffect, ...raises: [], forbids: [].}
+
+ + Closes the file. + Source   +Edit   + +
+
+ +
+
+
+
proc endOfFile(f: File): bool {....tags: [], gcsafe, raises: [], forbids: [].}
+
+ + Returns true if f is at the end. + Source   +Edit   + +
+
+ +
+
+
+
proc flushFile(f: File) {....tags: [WriteIOEffect], raises: [], forbids: [].}
+
+ + Flushes f's buffer. + Source   +Edit   + +
+
+ +
+
+
+
proc getFileHandle(f: File): FileHandle {....raises: [], tags: [], forbids: [].}
+
+ + Returns the file handle of the file f. This is only useful for platform specific programming. Note that on Windows this doesn't return the Windows-specific handle, but the C library's notion of a handle, whatever that means. Use getOsFileHandle instead. + Source   +Edit   + +
+
+ +
+
+
+
proc getFilePos(f: File): int64 {....gcsafe, raises: [IOError], tags: [],
+                                  forbids: [].}
+
+ + Retrieves the current position of the file pointer that is used to read from the file f. The file's first byte has the index zero. + Source   +Edit   + +
+
+ +
+
+
+
proc getFileSize(f: File): int64 {....tags: [ReadIOEffect], gcsafe,
+                                   raises: [IOError], forbids: [].}
+
+ + Retrieves the file size (in bytes) of f. + Source   +Edit   + +
+
+ +
+
+
+
proc getOsFileHandle(f: File): FileHandle {....raises: [], tags: [], forbids: [].}
+
+ + Returns the OS file handle of the file f. This is only useful for platform specific programming. + Source   +Edit   + +
+
+ +
+
+
+
proc open(f: var File; filehandle: FileHandle; mode: FileMode = fmRead): bool {.
+    ...tags: [], raises: [], gcsafe, forbids: [].}
+
+ +

Creates a File from a filehandle with given mode.

+

Default mode is readonly. Returns true if the file could be opened.

+

The passed file handle will no longer be inheritable.

+ + Source   +Edit   + +
+
+
+
proc open(f: var File; filename: string; mode: FileMode = fmRead;
+          bufSize: int = -1): bool {....tags: [], raises: [], gcsafe, forbids: [].}
+
+ +

Opens a file named filename with given mode.

+

Default mode is readonly. Returns true if the file could be opened. This throws no exception if the file could not be opened.

+

The file handle associated with the resulting File is not inheritable.

+ + Source   +Edit   + +
+
+
+
proc open(filename: string; mode: FileMode = fmRead; bufSize: int = -1): File {.
+    ...raises: [IOError], tags: [], forbids: [].}
+
+ +

Opens a file named filename with given mode.

+

Default mode is readonly. Raises an IOError if the file could not be opened.

+

The file handle associated with the resulting File is not inheritable.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc readAll(file: File): string {....tags: [ReadIOEffect], gcsafe,
+                                   raises: [IOError], forbids: [].}
+
+ +

Reads all data from the stream file.

+

Raises an IO exception in case of an error. It is an error if the current file position is not at the beginning of the file.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc readBuffer(f: File; buffer: pointer; len: Natural): int {.
+    ...tags: [ReadIOEffect], gcsafe, raises: [IOError], forbids: [].}
+
+ + Reads len bytes into the buffer pointed to by buffer. Returns the actual number of bytes that have been read which may be less than len (if not as many bytes are remaining), but not greater. + Source   +Edit   + +
+
+ +
+
+
+
proc readBytes(f: File; a: var openArray[int8 | uint8]; start, len: Natural): int {.
+    ...tags: [ReadIOEffect], gcsafe.}
+
+ + Reads len bytes into the buffer a starting at a[start]. Returns the actual number of bytes that have been read which may be less than len (if not as many bytes are remaining), but not greater. + Source   +Edit   + +
+
+ +
+
+
+
proc readChar(f: File): char {....tags: [ReadIOEffect],
+                               raises: [IOError, EOFError], forbids: [].}
+
+ + Reads a single character from the stream f. Should not be used in performance sensitive code. + Source   +Edit   + +
+
+ +
+
+
+
proc readChars(f: File; a: var openArray[char]): int {....tags: [ReadIOEffect],
+    gcsafe, raises: [IOError], forbids: [].}
+
+ + Reads up to a.len bytes into the buffer a. Returns the actual number of bytes that have been read which may be less than a.len (if not as many bytes are remaining), but not greater. + Source   +Edit   + +
+
+
+
proc readChars(f: File; a: var openArray[char]; start, len: Natural): int {.
+    ...tags: [ReadIOEffect], gcsafe, deprecated: "use other `readChars` overload, possibly via: readChars(toOpenArray(buf, start, len-1))",
+    raises: [IOError], forbids: [].}
+
+
+ Deprecated: use other `readChars` overload, possibly via: readChars(toOpenArray(buf, start, len-1)) +
+ + Reads len bytes into the buffer a starting at a[start]. Returns the actual number of bytes that have been read which may be less than len (if not as many bytes are remaining), but not greater. + Source   +Edit   + +
+
+ +
+
+
+
proc readFile(filename: string): string {....tags: [ReadIOEffect], gcsafe,
+    raises: [IOError], forbids: [].}
+
+ + Opens a file named filename for reading, calls readAll and closes the file afterwards. Returns the string. Raises an IO exception in case of an error. If you need to call this inside a compile time macro you can use staticRead. + Source   +Edit   + +
+
+ +
+
+
+
proc readLine(f: File): string {....tags: [ReadIOEffect], gcsafe,
+                                 raises: [IOError, EOFError], forbids: [].}
+
+ + Reads a line of text from the file f. May throw an IO exception. A line of text may be delimited by LF or CRLF. The newline character(s) are not part of the returned string. + Source   +Edit   + +
+
+
+
proc readLine(f: File; line: var string): bool {....tags: [ReadIOEffect], gcsafe,
+    raises: [IOError], forbids: [].}
+
+ + Reads a line of text from the file f into line. May throw an IO exception. A line of text may be delimited by LF or CRLF. The newline character(s) are not part of the returned string. Returns false if the end of the file has been reached, true otherwise. If false is returned line contains no new data. + Source   +Edit   + +
+
+ +
+
+
+
proc readLines(filename: string; n: Natural): seq[string] {.
+    ...raises: [IOError, EOFError], tags: [ReadIOEffect], forbids: [].}
+
+ + Reads n lines from the file named filename. Raises an IO exception in case of an error. Raises EOF if file does not contain at least n lines. Available at compile time. A line of text may be delimited by LF or CRLF. The newline character(s) are not part of the returned strings. + Source   +Edit   + +
+
+ +
+
+
+
proc reopen(f: File; filename: string; mode: FileMode = fmRead): bool {.
+    ...tags: [], gcsafe, raises: [], forbids: [].}
+
+ +

Reopens the file f with given filename and mode. This is often used to redirect the stdin, stdout or stderr file variables.

+

Default mode is readonly. Returns true if the file could be reopened.

+

The file handle associated with f won't be inheritable.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc setFilePos(f: File; pos: int64; relativeTo: FileSeekPos = fspSet) {....gcsafe,
+    sideEffect, ...raises: [IOError], tags: [], forbids: [].}
+
+ + Sets the position of the file pointer that is used for read/write operations. The file's first byte has the index zero. + Source   +Edit   + +
+
+ +
+
+
+
proc setInheritable(f: FileHandle; inheritable: bool): bool {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Controls whether a file handle can be inherited by child processes. Returns true on success. This requires the OS file handle, which can be retrieved via getOsFileHandle.

+

This procedure is not guaranteed to be available for all platforms. Test for availability with declared().

+ + Source   +Edit   + +
+
+ +
+
+
+
proc setStdIoUnbuffered() {....tags: [], gcsafe, raises: [], forbids: [].}
+
+ + Configures stdin, stdout and stderr to be unbuffered. + Source   +Edit   + +
+
+ +
+
+
+
proc write(f: File; a: varargs[string, `$`]) {....tags: [WriteIOEffect], gcsafe,
+    raises: [IOError], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc write(f: File; b: bool) {....tags: [WriteIOEffect], gcsafe, raises: [IOError],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc write(f: File; c: char) {....tags: [WriteIOEffect], gcsafe, raises: [],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc write(f: File; c: cstring) {....tags: [WriteIOEffect], gcsafe,
+                                  raises: [IOError], forbids: [].}
+
+ + Writes a value to the file f. May throw an IO exception. + Source   +Edit   + +
+
+
+
proc write(f: File; i: BiggestInt) {....tags: [WriteIOEffect], gcsafe,
+                                     raises: [IOError], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc write(f: File; i: int) {....tags: [WriteIOEffect], gcsafe, raises: [IOError],
+                              forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc write(f: File; r: BiggestFloat) {....tags: [WriteIOEffect], gcsafe,
+                                       raises: [IOError], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc write(f: File; r: float32) {....tags: [WriteIOEffect], gcsafe,
+                                  raises: [IOError], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc write(f: File; s: string) {....tags: [WriteIOEffect], gcsafe,
+                                 raises: [IOError], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc writeBuffer(f: File; buffer: pointer; len: Natural): int {.
+    ...tags: [WriteIOEffect], gcsafe, raises: [IOError], forbids: [].}
+
+ + Writes the bytes of buffer pointed to by the parameter buffer to the file f. Returns the number of actual written bytes, which may be less than len in case of an error. + Source   +Edit   + +
+
+ +
+
+
+
proc writeBytes(f: File; a: openArray[int8 | uint8]; start, len: Natural): int {.
+    ...tags: [WriteIOEffect], gcsafe.}
+
+ + Writes the bytes of a[start..start+len-1] to the file f. Returns the number of actual written bytes, which may be less than len in case of an error. + Source   +Edit   + +
+
+ +
+
+
+
proc writeChars(f: File; a: openArray[char]; start, len: Natural): int {.
+    ...tags: [WriteIOEffect], gcsafe, raises: [IOError], forbids: [].}
+
+ + Writes the bytes of a[start..start+len-1] to the file f. Returns the number of actual written bytes, which may be less than len in case of an error. + Source   +Edit   + +
+
+ +
+
+
+
proc writeFile(filename, content: string) {....tags: [WriteIOEffect], gcsafe,
+    raises: [IOError], forbids: [].}
+
+ + Opens a file named filename for writing. Then writes the content completely to the file and closes the file afterwards. Raises an IO exception in case of an error. + Source   +Edit   + +
+
+
+
proc writeFile(filename: string; content: openArray[byte]) {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + Opens a file named filename for writing. Then writes the content completely to the file and closes the file afterwards. Raises an IO exception in case of an error. + Source   +Edit   + +
+
+ +
+
+
+
proc writeLine[Ty](f: File; x: varargs[Ty, `$`]) {.inline,
+    ...tags: [WriteIOEffect], gcsafe.}
+
+ + Writes the values x to f and then writes "\n". May throw an IO exception. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator lines(f: File): string {....tags: [ReadIOEffect], raises: [IOError],
+                                  forbids: [].}
+
+ +

Iterates over any line in the file f.

+

The trailing newline character(s) are removed from the iterated lines.

+ +

Example:

+
proc countZeros(filename: File): tuple[lines, zeros: int] =
+  for line in filename.lines:
+    for letter in line:
+      if letter == '0':
+        result.zeros += 1
+    result.lines += 1
+ Source   +Edit   + +
+
+
+
iterator lines(filename: string): string {....tags: [ReadIOEffect],
+    raises: [IOError, IOError], forbids: [].}
+
+ +

Iterates over any line in the file named filename.

+

If the file does not exist IOError is raised. The trailing newline character(s) are removed from the iterated lines. Example:

+ +

Example:

+
import std/strutils
+
+proc transformLetters(filename: string) =
+  var buffer = ""
+  for line in filename.lines:
+    buffer.add(line.replace("a", "0") & '\n')
+  writeFile(filename, buffer)
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template `&=`(f: File; x: typed)
+
+ + An alias for write. + Source   +Edit   + +
+
+ +
+
+
+
template readLines(filename: string): seq[string] {.
+    ...deprecated: "use readLines with two arguments".}
+
+
+ Deprecated: use readLines with two arguments +
+ + + Source   +Edit   + +
+
+ +
+
+
+
template stdmsg(): File
+
+ + Template which expands to either stdout or stderr depending on useStdoutAsStdmsg compile-time switch. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/syncio.idx b/syncio.idx new file mode 100644 index 0000000000000..a454fa7515bc4 --- /dev/null +++ b/syncio.idx @@ -0,0 +1,66 @@ +nimTitle syncio syncio.html module std/syncio 0 +nim File syncio.html#File type File 22 +nim fmRead syncio.html#fmRead FileMode.fmRead 24 +nim fmWrite syncio.html#fmWrite FileMode.fmWrite 24 +nim fmReadWrite syncio.html#fmReadWrite FileMode.fmReadWrite 24 +nim fmReadWriteExisting syncio.html#fmReadWriteExisting FileMode.fmReadWriteExisting 24 +nim fmAppend syncio.html#fmAppend FileMode.fmAppend 24 +nim FileMode syncio.html#FileMode enum FileMode 24 +nim FileHandle syncio.html#FileHandle type FileHandle 41 +nim fspSet syncio.html#fspSet FileSeekPos.fspSet 44 +nim fspCur syncio.html#fspCur FileSeekPos.fspCur 44 +nim fspEnd syncio.html#fspEnd FileSeekPos.fspEnd 44 +nim FileSeekPos syncio.html#FileSeekPos enum FileSeekPos 44 +nim stdin syncio.html#stdin var stdin 61 +nim stdout syncio.html#stdout var stdout 63 +nim stderr syncio.html#stderr var stderr 65 +nim stdmsg syncio.html#stdmsg.t template stdmsg(): File 71 +nim readBuffer syncio.html#readBuffer,File,pointer,Natural proc readBuffer(f: File; buffer: pointer; len: Natural): int 178 +nim readBytes syncio.html#readBytes,File,openArray[],Natural,Natural proc readBytes(f: File; a: var openArray[int8 | uint8]; start, len: Natural): int 186 +nim readChars syncio.html#readChars,File,openArray[char] proc readChars(f: File; a: var openArray[char]): int 194 +nim readChars syncio.html#readChars,File,openArray[char],Natural,Natural proc readChars(f: File; a: var openArray[char]; start, len: Natural): int 200 +nim write syncio.html#write,File,cstring proc write(f: File; c: cstring) 210 +nim writeBuffer syncio.html#writeBuffer,File,pointer,Natural proc writeBuffer(f: File; buffer: pointer; len: Natural): int 215 +nim writeBytes syncio.html#writeBytes,File,openArray[],Natural,Natural proc writeBytes(f: File; a: openArray[int8 | uint8]; start, len: Natural): int 223 +nim writeChars syncio.html#writeChars,File,openArray[char],Natural,Natural proc writeChars(f: File; a: openArray[char]; start, len: Natural): int 231 +nim write syncio.html#write,File,string proc write(f: File; s: string) 261 +nim close syncio.html#close,File proc close(f: File) 339 +nim readChar syncio.html#readChar,File proc readChar(f: File): char 343 +nim flushFile syncio.html#flushFile,File proc flushFile(f: File) 352 +nim getFileHandle syncio.html#getFileHandle,File proc getFileHandle(f: File): FileHandle 356 +nim getOsFileHandle syncio.html#getOsFileHandle,File proc getOsFileHandle(f: File): FileHandle 364 +nim setInheritable syncio.html#setInheritable,FileHandle,bool proc setInheritable(f: FileHandle; inheritable: bool): bool 373 +nim readLine syncio.html#readLine,File,string proc readLine(f: File; line: var string): bool 394 +nim readLine syncio.html#readLine,File proc readLine(f: File): string 516 +nim write syncio.html#write,File,int proc write(f: File; i: int) 523 +nim write syncio.html#write,File,BiggestInt proc write(f: File; i: BiggestInt) 529 +nim write syncio.html#write,File,bool proc write(f: File; b: bool) 535 +nim write syncio.html#write,File,float32 proc write(f: File; r: float32) 539 +nim write syncio.html#write,File,BiggestFloat proc write(f: File; r: BiggestFloat) 544 +nim write syncio.html#write,File,char proc write(f: File; c: char) 549 +nim write syncio.html#write,File,varargs[string,] proc write(f: File; a: varargs[string, `$`]) 552 +nim endOfFile syncio.html#endOfFile,File proc endOfFile(f: File): bool 576 +nim readAll syncio.html#readAll,File proc readAll(file: File): string 600 +nim writeLine syncio.html#writeLine,File,varargs[Ty,] proc writeLine[Ty](f: File; x: varargs[Ty, `$`]) 617 +nim open syncio.html#open,File,string,FileMode,int proc open(f: var File; filename: string; mode: FileMode = fmRead; bufSize: int = -1): bool 708 +nim reopen syncio.html#reopen,File,string,FileMode proc reopen(f: File; filename: string; mode: FileMode = fmRead): bool 741 +nim open syncio.html#open,File,FileHandle,FileMode proc open(f: var File; filehandle: FileHandle; mode: FileMode = fmRead): bool 758 +nim open syncio.html#open,string,FileMode,int proc open(filename: string; mode: FileMode = fmRead; bufSize: int = -1): File 773 +nim setFilePos syncio.html#setFilePos,File,int64,FileSeekPos proc setFilePos(f: File; pos: int64; relativeTo: FileSeekPos = fspSet) 784 +nim getFilePos syncio.html#getFilePos,File proc getFilePos(f: File): int64 790 +nim getFileSize syncio.html#getFileSize,File proc getFileSize(f: File): int64 796 +nim setStdIoUnbuffered syncio.html#setStdIoUnbuffered proc setStdIoUnbuffered() 803 +nim readFile syncio.html#readFile,string proc readFile(filename: string): string 857 +nim writeFile syncio.html#writeFile,string,string proc writeFile(filename, content: string) 872 +nim writeFile syncio.html#writeFile,string,openArray[byte] proc writeFile(filename: string; content: openArray[byte]) 885 +nim readLines syncio.html#readLines,string,Natural proc readLines(filename: string; n: Natural): seq[string] 898 +nim readLines syncio.html#readLines.t,string template readLines(filename: string): seq[string] 915 +nim lines syncio.html#lines.i,string iterator lines(filename: string): string 919 +nim lines syncio.html#lines.i,File iterator lines(f: File): string 940 +nim `&=` syncio.html#&=.t,File,typed template `&=`(f: File; x: typed) 955 +nimgrp writefile syncio.html#writeFile-procs-all proc 872 +nimgrp write syncio.html#write-procs-all proc 210 +nimgrp readline syncio.html#readLine-procs-all proc 394 +nimgrp readchars syncio.html#readChars-procs-all proc 194 +nimgrp open syncio.html#open-procs-all proc 708 +nimgrp lines syncio.html#lines-iterators-all iterator 919 diff --git a/sysatomics.html b/sysatomics.html new file mode 100644 index 0000000000000..7d65b2e01ee44 --- /dev/null +++ b/sysatomics.html @@ -0,0 +1,795 @@ + + + + + + + +std/sysatomics + + + + + + + + + + + + + + + + +
+
+

std/sysatomics

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+
+ Deprecated: use `std/atomics` instead +
+ +

Perform the operation return the new value, all memory models are validPerform the operation return the old value, all memory models are valid

+
+

Types

+
+
+
AtomMemModel = distinct cint
+
+ + + Source   +Edit   + +
+
+
+
AtomType = SomeNumber | pointer | ptr | char | bool
+
+ + Type Class representing valid types for use with atomic procs + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
ATOMIC_ACQ_REL {.importc: "__ATOMIC_ACQ_REL", nodecl.}: AtomMemModel
+
+ + Full barrier in both directions and synchronizes with acquire loads and release stores in another thread. + Source   +Edit   + +
+
+
+
ATOMIC_ACQUIRE {.importc: "__ATOMIC_ACQUIRE", nodecl.}: AtomMemModel
+
+ + Barrier to hoisting of code and synchronizes with release (or stronger) semantic stores from another thread. + Source   +Edit   + +
+
+
+
ATOMIC_CONSUME {.importc: "__ATOMIC_CONSUME", nodecl.}: AtomMemModel
+
+ + Data dependency only for both barrier and synchronization with another thread. + Source   +Edit   + +
+
+
+
ATOMIC_RELAXED {.importc: "__ATOMIC_RELAXED", nodecl.}: AtomMemModel
+
+ + No barriers or synchronization. + Source   +Edit   + +
+
+
+
ATOMIC_RELEASE {.importc: "__ATOMIC_RELEASE", nodecl.}: AtomMemModel
+
+ + Barrier to sinking of code and synchronizes with acquire (or stronger) semantic loads from another thread. + Source   +Edit   + +
+
+
+
ATOMIC_SEQ_CST {.importc: "__ATOMIC_SEQ_CST", nodecl.}: AtomMemModel
+
+ + Full barrier in both directions and synchronizes with acquire loads and release stores in all threads. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc atomicAddFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {.
+    importc: "__atomic_add_fetch", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc atomicAlwaysLockFree(size: int; p: pointer): bool {.
+    importc: "__atomic_always_lock_free", nodecl, ...raises: [], tags: [],
+    forbids: [].}
+
+ + This built-in function returns true if objects of size bytes always generate lock free atomic instructions for the target architecture. size must resolve to a compile-time constant and the result also resolves to a compile-time constant. ptr is an optional pointer to the object that may be used to determine alignment. A value of 0 indicates typical alignment should be used. The compiler may also ignore this parameter. + Source   +Edit   + +
+
+ +
+
+
+
proc atomicAndFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {.
+    importc: "__atomic_and_fetch", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc atomicClear(p: pointer; mem: AtomMemModel) {.importc: "__atomic_clear",
+    nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + This built-in function performs an atomic clear operation at p. After the operation, at p contains 0. ATOMIC_RELAXED, ATOMIC_SEQ_CST, ATOMIC_RELEASE + Source   +Edit   + +
+
+ +
+
+
+
proc atomicCompareExchange[T: AtomType](p, expected, desired: ptr T; weak: bool;
+                                        success_memmodel: AtomMemModel;
+                                        failure_memmodel: AtomMemModel): bool {.
+    importc: "__atomic_compare_exchange", nodecl, ...raises: [], tags: [],
+    forbids: [].}
+
+ + This proc implements the generic version of atomic_compare_exchange. The proc is virtually identical to atomic_compare_exchange_n, except the desired value is also a pointer. + Source   +Edit   + +
+
+ +
+
+
+
proc atomicCompareExchangeN[T: AtomType](p, expected: ptr T; desired: T;
+    weak: bool; success_memmodel: AtomMemModel; failure_memmodel: AtomMemModel): bool {.
+    importc: "__atomic_compare_exchange_n", nodecl, ...raises: [], tags: [],
+    forbids: [].}
+
+ + This proc implements an atomic compare and exchange operation. This compares the contents at p with the contents at expected and if equal, writes desired at p. If they are not equal, the current contents at p is written into expected. Weak is true for weak compare_exchange, and false for the strong variation. Many targets only offer the strong variation and ignore the parameter. When in doubt, use the strong variation. True is returned if desired is written at p and the execution is considered to conform to the memory model specified by success_memmodel. There are no restrictions on what memory model can be used here. False is returned otherwise, and the execution is considered to conform to failure_memmodel. This memory model cannot be __ATOMIC_RELEASE nor __ATOMIC_ACQ_REL. It also cannot be a stronger model than that specified by success_memmodel. + Source   +Edit   + +
+
+ +
+
+
+
proc atomicDec(memLoc: var int; x: int = 1): int {.inline, discardable,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Atomically decrements the integer by some x. It returns the new value. + Source   +Edit   + +
+
+ +
+
+
+
proc atomicExchange[T: AtomType](p, val, ret: ptr T; mem: AtomMemModel) {.
+    importc: "__atomic_exchange", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + This is the generic version of an atomic exchange. It stores the contents at val at p. The original value at p is copied into ret. + Source   +Edit   + +
+
+ +
+
+
+
proc atomicExchangeN[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {.
+    importc: "__atomic_exchange_n", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + This proc implements an atomic exchange operation. It writes val at p, and returns the previous contents at p. ATOMIC_RELAXED, ATOMIC_SEQ_CST, ATOMIC_ACQUIRE, ATOMIC_RELEASE, ATOMIC_ACQ_REL + Source   +Edit   + +
+
+ +
+
+
+
proc atomicFetchAdd[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {.
+    importc: "__atomic_fetch_add", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc atomicFetchAnd[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {.
+    importc: "__atomic_fetch_and", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc atomicFetchNand[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {.
+    importc: "__atomic_fetch_nand", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc atomicFetchOr[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {.
+    importc: "__atomic_fetch_or", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc atomicFetchSub[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {.
+    importc: "__atomic_fetch_sub", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc atomicFetchXor[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {.
+    importc: "__atomic_fetch_xor", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc atomicInc(memLoc: var int; x: int = 1): int {.inline, discardable,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Atomically increments the integer by some x. It returns the new value. + Source   +Edit   + +
+
+ +
+
+
+
proc atomicIsLockFree(size: int; p: pointer): bool {.
+    importc: "__atomic_is_lock_free", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + This built-in function returns true if objects of size bytes always generate lock free atomic instructions for the target architecture. If it is not known to be lock free a call is made to a runtime routine named __atomic_is_lock_free. ptr is an optional pointer to the object that may be used to determine alignment. A value of 0 indicates typical alignment should be used. The compiler may also ignore this parameter. + Source   +Edit   + +
+
+ +
+
+
+
proc atomicLoad[T: AtomType](p, ret: ptr T; mem: AtomMemModel) {.
+    importc: "__atomic_load", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + This is the generic version of an atomic load. It returns the contents at p in ret. + Source   +Edit   + +
+
+ +
+
+
+
proc atomicLoadN[T: AtomType](p: ptr T; mem: AtomMemModel): T {.
+    importc: "__atomic_load_n", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + This proc implements an atomic load operation. It returns the contents at p. ATOMIC_RELAXED, ATOMIC_SEQ_CST, ATOMIC_ACQUIRE, ATOMIC_CONSUME. + Source   +Edit   + +
+
+ +
+
+
+
proc atomicNandFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {.
+    importc: "__atomic_nand_fetch", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc atomicOrFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {.
+    importc: "__atomic_or_fetch", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc atomicSignalFence(mem: AtomMemModel) {.importc: "__atomic_signal_fence",
+    nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + This built-in function acts as a synchronization fence between a thread and signal handlers based in the same thread. All memory orders are valid. + Source   +Edit   + +
+
+ +
+
+
+
proc atomicStore[T: AtomType](p, val: ptr T; mem: AtomMemModel) {.
+    importc: "__atomic_store", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + This is the generic version of an atomic store. It stores the value of val at p + Source   +Edit   + +
+
+ +
+
+
+
proc atomicStoreN[T: AtomType](p: ptr T; val: T; mem: AtomMemModel) {.
+    importc: "__atomic_store_n", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + This proc implements an atomic store operation. It writes val at p. ATOMIC_RELAXED, ATOMIC_SEQ_CST, and ATOMIC_RELEASE. + Source   +Edit   + +
+
+ +
+
+
+
proc atomicSubFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {.
+    importc: "__atomic_sub_fetch", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc atomicTestAndSet(p: pointer; mem: AtomMemModel): bool {.
+    importc: "__atomic_test_and_set", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + This built-in function performs an atomic test-and-set operation on the byte at p. The byte is set to some implementation defined nonzero "set" value and the return value is true if and only if the previous contents were "set". All memory models are valid. + Source   +Edit   + +
+
+ +
+
+
+
proc atomicThreadFence(mem: AtomMemModel) {.importc: "__atomic_thread_fence",
+    nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + This built-in function acts as a synchronization fence between threads based on the specified memory model. All memory orders are valid. + Source   +Edit   + +
+
+ +
+
+
+
proc atomicXorFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T {.
+    importc: "__atomic_xor_fetch", nodecl, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cas[T: bool | int | ptr](p: ptr T; oldValue, newValue: T): bool
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cpuRelax() {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template fence()
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/sysatomics.idx b/sysatomics.idx new file mode 100644 index 0000000000000..f44903dfc6073 --- /dev/null +++ b/sysatomics.idx @@ -0,0 +1,40 @@ +nimTitle sysatomics sysatomics.html module std/sysatomics 0 +nim AtomType sysatomics.html#AtomType type AtomType 22 +nim AtomMemModel sysatomics.html#AtomMemModel type AtomMemModel 26 +nim ATOMIC_RELAXED sysatomics.html#ATOMIC_RELAXED var ATOMIC_RELAXED 28 +nim ATOMIC_CONSUME sysatomics.html#ATOMIC_CONSUME var ATOMIC_CONSUME 30 +nim ATOMIC_ACQUIRE sysatomics.html#ATOMIC_ACQUIRE var ATOMIC_ACQUIRE 33 +nim ATOMIC_RELEASE sysatomics.html#ATOMIC_RELEASE var ATOMIC_RELEASE 37 +nim ATOMIC_ACQ_REL sysatomics.html#ATOMIC_ACQ_REL var ATOMIC_ACQ_REL 41 +nim ATOMIC_SEQ_CST sysatomics.html#ATOMIC_SEQ_CST var ATOMIC_SEQ_CST 45 +nim atomicLoadN sysatomics.html#atomicLoadN,ptr.T,AtomMemModel proc atomicLoadN[T: AtomType](p: ptr T; mem: AtomMemModel): T 50 +nim atomicLoad sysatomics.html#atomicLoad,ptr.T,ptr.T,AtomMemModel proc atomicLoad[T: AtomType](p, ret: ptr T; mem: AtomMemModel) 55 +nim atomicStoreN sysatomics.html#atomicStoreN,ptr.T,T,AtomMemModel proc atomicStoreN[T: AtomType](p: ptr T; val: T; mem: AtomMemModel) 59 +nim atomicStore sysatomics.html#atomicStore,ptr.T,ptr.T,AtomMemModel proc atomicStore[T: AtomType](p, val: ptr T; mem: AtomMemModel) 64 +nim atomicExchangeN sysatomics.html#atomicExchangeN,ptr.T,T,AtomMemModel proc atomicExchangeN[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T 68 +nim atomicExchange sysatomics.html#atomicExchange,ptr.T,ptr.T,ptr.T,AtomMemModel proc atomicExchange[T: AtomType](p, val, ret: ptr T; mem: AtomMemModel) 74 +nim atomicCompareExchangeN sysatomics.html#atomicCompareExchangeN,ptr.T,ptr.T,T,bool,AtomMemModel,AtomMemModel proc atomicCompareExchangeN[T: AtomType](p, expected: ptr T; desired: T; weak: bool;\n success_memmodel: AtomMemModel;\n failure_memmodel: AtomMemModel): bool 79 +nim atomicCompareExchange sysatomics.html#atomicCompareExchange,ptr.T,ptr.T,ptr.T,bool,AtomMemModel,AtomMemModel proc atomicCompareExchange[T: AtomType](p, expected, desired: ptr T; weak: bool;\n success_memmodel: AtomMemModel;\n failure_memmodel: AtomMemModel): bool 95 +nim atomicAddFetch sysatomics.html#atomicAddFetch,ptr.T,T,AtomMemModel proc atomicAddFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T 103 +nim atomicSubFetch sysatomics.html#atomicSubFetch,ptr.T,T,AtomMemModel proc atomicSubFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T 105 +nim atomicOrFetch sysatomics.html#atomicOrFetch,ptr.T,T,AtomMemModel proc atomicOrFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T 107 +nim atomicAndFetch sysatomics.html#atomicAndFetch,ptr.T,T,AtomMemModel proc atomicAndFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T 109 +nim atomicXorFetch sysatomics.html#atomicXorFetch,ptr.T,T,AtomMemModel proc atomicXorFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T 111 +nim atomicNandFetch sysatomics.html#atomicNandFetch,ptr.T,T,AtomMemModel proc atomicNandFetch[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T 113 +nim atomicFetchAdd sysatomics.html#atomicFetchAdd,ptr.T,T,AtomMemModel proc atomicFetchAdd[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T 117 +nim atomicFetchSub sysatomics.html#atomicFetchSub,ptr.T,T,AtomMemModel proc atomicFetchSub[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T 119 +nim atomicFetchOr sysatomics.html#atomicFetchOr,ptr.T,T,AtomMemModel proc atomicFetchOr[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T 121 +nim atomicFetchAnd sysatomics.html#atomicFetchAnd,ptr.T,T,AtomMemModel proc atomicFetchAnd[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T 123 +nim atomicFetchXor sysatomics.html#atomicFetchXor,ptr.T,T,AtomMemModel proc atomicFetchXor[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T 125 +nim atomicFetchNand sysatomics.html#atomicFetchNand,ptr.T,T,AtomMemModel proc atomicFetchNand[T: AtomType](p: ptr T; val: T; mem: AtomMemModel): T 127 +nim atomicTestAndSet sysatomics.html#atomicTestAndSet,pointer,AtomMemModel proc atomicTestAndSet(p: pointer; mem: AtomMemModel): bool 130 +nim atomicClear sysatomics.html#atomicClear,pointer,AtomMemModel proc atomicClear(p: pointer; mem: AtomMemModel) 137 +nim atomicThreadFence sysatomics.html#atomicThreadFence,AtomMemModel proc atomicThreadFence(mem: AtomMemModel) 143 +nim atomicSignalFence sysatomics.html#atomicSignalFence,AtomMemModel proc atomicSignalFence(mem: AtomMemModel) 148 +nim atomicAlwaysLockFree sysatomics.html#atomicAlwaysLockFree,int,pointer proc atomicAlwaysLockFree(size: int; p: pointer): bool 153 +nim atomicIsLockFree sysatomics.html#atomicIsLockFree,int,pointer proc atomicIsLockFree(size: int; p: pointer): bool 162 +nim fence sysatomics.html#fence.t template fence() 171 +nim atomicInc sysatomics.html#atomicInc,int,int proc atomicInc(memLoc: var int; x: int = 1): int 267 +nim atomicDec sysatomics.html#atomicDec,int,int proc atomicDec(memLoc: var int; x: int = 1): int 278 +nim cas sysatomics.html#cas,ptr.T,T,T proc cas[T: bool | int | ptr](p: ptr T; oldValue, newValue: T): bool 346 +nim cpuRelax sysatomics.html#cpuRelax proc cpuRelax() 358 diff --git a/syslocks.html b/syslocks.html new file mode 100644 index 0000000000000..c69666ca5146b --- /dev/null +++ b/syslocks.html @@ -0,0 +1,392 @@ + + + + + + + +std/private/syslocks + + + + + + + + + + + + + + + + +
+
+

std/private/syslocks

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
+

Types

+
+
+
SysCond = SysCondObj
+
+ + + Source   +Edit   + +
+
+
+
SysLock = SysLockObj
+
+ + + Source   +Edit   + +
+
+
+
SysLockAttr {.importc: "pthread_mutexattr_t", pure, final, header: """#include <sys/types.h>
+                          #include <pthread.h>""".} = object
+  when defined(linux) and defined(amd64):
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
SysLockType_Reentrant {.importc: "PTHREAD_MUTEX_RECURSIVE",
+                        header: "<pthread.h>".}: SysLockType
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc initSysLockAttr(a: var SysLockAttr) {.importc: "pthread_mutexattr_init",
+    header: "<pthread.h>", noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setSysLockType(a: var SysLockAttr; t: SysLockType) {.
+    importc: "pthread_mutexattr_settype", header: "<pthread.h>", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template acquireSys(L: var SysLock)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template broadcastSysCond(cond: var SysCond)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template deinitSys(L: SysLock)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template deinitSysCond(cond: SysCond)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template initSysCond(cond: var SysCond; cond_attr: ptr SysCondAttr = nil)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template initSysLock(L: var SysLock; attr: ptr SysLockAttr = nil)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template releaseSys(L: var SysLock)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template signalSysCond(cond: var SysCond)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template tryAcquireSys(L: var SysLock): bool
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template waitSysCond(cond: var SysCond; lock: var SysLock)
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/syslocks.idx b/syslocks.idx new file mode 100644 index 0000000000000..3b9758d21a565 --- /dev/null +++ b/syslocks.idx @@ -0,0 +1,17 @@ +nimTitle syslocks syslocks.html module std/private/syslocks 0 +nim SysLockAttr syslocks.html#SysLockAttr object SysLockAttr 110 +nim SysLock syslocks.html#SysLock type SysLock 171 +nim SysCond syslocks.html#SysCond type SysCond 172 +nim initSysLock syslocks.html#initSysLock.t,SysLockObj,ptr.SysLockAttr template initSysLock(L: var SysLock; attr: ptr SysLockAttr = nil) 174 +nim deinitSys syslocks.html#deinitSys.t,SysLockObj template deinitSys(L: SysLock) 176 +nim acquireSys syslocks.html#acquireSys.t,SysLockObj template acquireSys(L: var SysLock) 178 +nim tryAcquireSys syslocks.html#tryAcquireSys.t,SysLockObj template tryAcquireSys(L: var SysLock): bool 180 +nim releaseSys syslocks.html#releaseSys.t,SysLockObj template releaseSys(L: var SysLock) 182 +nim SysLockType_Reentrant syslocks.html#SysLockType_Reentrant var SysLockType_Reentrant 186 +nim initSysLockAttr syslocks.html#initSysLockAttr,SysLockAttr proc initSysLockAttr(a: var SysLockAttr) 188 +nim setSysLockType syslocks.html#setSysLockType,SysLockAttr,SysLockType proc setSysLockType(a: var SysLockAttr; t: SysLockType) 190 +nim initSysCond syslocks.html#initSysCond.t,SysCondObj,ptr.SysCondAttr template initSysCond(cond: var SysCond; cond_attr: ptr SysCondAttr = nil) 222 +nim deinitSysCond syslocks.html#deinitSysCond.t,SysCondObj template deinitSysCond(cond: SysCond) 224 +nim waitSysCond syslocks.html#waitSysCond.t,SysCondObj,SysLockObj template waitSysCond(cond: var SysCond; lock: var SysLock) 227 +nim signalSysCond syslocks.html#signalSysCond.t,SysCondObj template signalSysCond(cond: var SysCond) 229 +nim broadcastSysCond syslocks.html#broadcastSysCond.t,SysCondObj template broadcastSysCond(cond: var SysCond) 231 diff --git a/sysrand.html b/sysrand.html new file mode 100644 index 0000000000000..780882ef57622 --- /dev/null +++ b/sysrand.html @@ -0,0 +1,161 @@ + + + + + + + +std/sysrand + + + + + + + + + + + + + + + + +
+
+

std/sysrand

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Warning: +This module was added in Nim 1.6. If you are using it for cryptographic purposes, keep in mind that so far this has not been audited by any security professionals, therefore may not be secure.
+

std/sysrand generates random numbers from a secure source provided by the operating system. It is a cryptographically secure pseudorandom number generator and should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation.

+ + + + + + + + + + +
TargetsImplementation
WindowsBCryptGenRandom
Linuxgetrandom
MacOSXSecRandomCopyBytes
iOSSecRandomCopyBytes
OpenBSDgetentropy openbsd
FreeBSDgetrandom freebsd
JS (Web Browser)getRandomValues
Node.jsrandomFillSync
Other Unix platforms/dev/urandom

On a Linux target, a call to the getrandom syscall can be avoided (e.g. for targets running kernel version < 3.17) by passing a compile flag of -d:nimNoGetRandom. If this flag is passed, sysrand will use /dev/urandom as with any other POSIX compliant OS.

+ +

Example:

+
import std/sysrand
+doAssert urandom(0).len == 0
+doAssert urandom(113).len == 113
+doAssert urandom(1234) != urandom(1234) # unlikely to fail in practice
+

See also

+

+ +
+

Procs

+
+
+
+
proc urandom(dest: var openArray[byte]): bool {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Fills dest with random bytes suitable for cryptographic use. If the call succeeds, returns true.

+

If dest is empty, urandom immediately returns success, without calling the underlying operating system API.

+
Warning: +The code hasn't been audited by cryptography experts and is provided as-is without guarantees. Use at your own risks. For production systems we advise you to request an external audit.
+ + Source   +Edit   + +
+
+
+
proc urandom(size: Natural): seq[byte] {.inline, ...raises: [OSError], tags: [],
+    forbids: [].}
+
+ + Returns random bytes suitable for cryptographic use.
Warning: +The code hasn't been audited by cryptography experts and is provided as-is without guarantees. Use at your own risks. For production systems we advise you to request an external audit.
+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/sysrand.idx b/sysrand.idx new file mode 100644 index 0000000000000..a2d34478194ab --- /dev/null +++ b/sysrand.idx @@ -0,0 +1,5 @@ +nimTitle sysrand sysrand.html module std/sysrand 0 +nim urandom sysrand.html#urandom,openArray[byte] proc urandom(dest: var openArray[byte]): bool 295 +nim urandom sysrand.html#urandom,Natural proc urandom(size: Natural): seq[byte] 316 +heading See also sysrand.html#see-also See also 0 +nimgrp urandom sysrand.html#urandom-procs-all proc 295 diff --git a/system.html b/system.html new file mode 100644 index 0000000000000..83c409db4c8ad --- /dev/null +++ b/system.html @@ -0,0 +1,11068 @@ + + + + + + + +system + + + + + + + + + + + + + + + + +
+
+

system

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

The compiler depends on the System module to work properly and the System module depends on the compiler. Most of the routines listed here use special compiler magic.

+

Each module implicitly imports the System module; it must not be listed explicitly. Because of this there cannot be a user-defined module named system.

+ +

System module

The System module imports several separate modules, and their documentation is in separate files:

+ +

Here is a short overview of the most commonly used functions from the system module. Function names in the tables below are clickable and will take you to the full documentation of the function.

+

There are many more functions available than the ones listed in this overview. Use the table of contents on the left-hand side and/or Ctrl+F to navigate through this module.

+ +

Strings and characters

+ + + + + + +
ProcUsage
len(s)Return the length of a string
chr(i)Convert an int in the range 0..255 to a character
ord(c)Return int value of a character
a & bConcatenate two strings
s.add(c)Add character to the string
$Convert various types to string

See also:

+
  • strutils module for common string functions
  • +
  • strformat module for string interpolation and formatting
  • +
  • unicode module for Unicode UTF-8 handling
  • +
  • strscans for scanf and scanp macros, which offer easier substring extraction than regular expressions
  • +
  • strtabs module for efficient hash tables (dictionaries, in some programming languages) mapping from strings to strings
  • +
+ +

Seqs

+ + + + + + + + + + + + + + +
ProcUsage
newSeqCreate a new sequence of a given length
newSeqOfCapCreate a new sequence with zero length and a given capacity
setLenSet the length of a sequence
lenReturn the length of a sequence
@Turn an array into a sequence
addAdd an item to the sequence
insertInsert an item at a specific position
deleteDelete an item while preserving the order of elements (O(n) operation)
delO(1) removal, doesn't preserve the order
popRemove and return last item of a sequence
x & yConcatenate two sequences
x[a .. b]Slice of a sequence (both ends included)
x[a .. ^b]Slice of a sequence but b is a reversed index (both ends included)
x[a ..< b]Slice of a sequence (excluded upper bound)

See also:

+ + +

Sets

Built-in bit sets.

+ + + + + + + + + +
ProcUsage
inclInclude element y in the set x
exclExclude element y from the set x
cardReturn the cardinality of the set, i.e. the number of elements
a * bIntersection
a + bUnion
a - bDifference
containsCheck if an element is in the set
a < bCheck if a is a subset of b

See also:

+ + +

Numbers

+ + + + + + + + + + + +
ProcUsage Also known as (in other languages)
divInteger division//
modInteger modulo (remainder)%
shlShift left<<
shrShift right>>
ashrArithmetic shift right
andBitwise and&
orBitwise or|
xorBitwise xor^
notBitwise not (complement)~
toIntConvert floating-point number into an int
toFloatConvert an integer into a float

See also:

+ + +

Ordinals

Ordinal type includes integer, bool, character, and enumeration types, as well as their subtypes.

+ + + + + + + + +
ProcUsage
succSuccessor of the value
predPredecessor of the value
incIncrement the ordinal
decDecrement the ordinal
highReturn the highest possible value
lowReturn the lowest possible value
ordReturn int value of an ordinal value
+

Misc

+ + + + + + + + + + + + + +
ProcUsage
isCheck if two arguments are of the same type
isnotNegated version of is
!=Not equals
addrTake the address of a memory location
T and FBoolean and
T or FBoolean or
T xor FBoolean xor (exclusive or)
not TBoolean not
a[^x]Take the element at the reversed index x
a .. bBinary slice that constructs an interval [a, b]
a ..^ bInterval [a, b] but b as reversed index
a ..< bInterval [a, b) (excluded upper bound)
runnableExamplesCreate testable documentation
Default new string implementation used by Nim's core.Default seq implementation used by Nim's core.

+ +
+

Types

+
+
+
AllocStats = object
+
+ + + Source   +Edit   + +
+
+
+
any {....deprecated: "Deprecated since v1.5; Use auto instead.".} = distinct auto
+
+
+ Deprecated: Deprecated since v1.5; Use auto instead. +
+ + Deprecated; Use auto instead. See https://github.com/nim-lang/RFCs/issues/281 + Source   +Edit   + +
+
+
+
array[I; T] {.magic: "Array".}
+
+ + Generic type to construct fixed-length arrays. + Source   +Edit   + +
+
+
+
auto {.magic: Expr.}
+
+ + Meta type for automatic type determination. + Source   +Edit   + +
+
+
+
BackwardsIndex = distinct int
+
+ + Type that is constructed by ^ for reversed array accesses. (See ^ template) + Source   +Edit   + +
+
+
+
bool {.magic: "Bool".} = enum
+  false = 0, true = 1
+
+ + Built-in boolean type. + Source   +Edit   + +
+
+
+
byte = uint8
+
+ + This is an alias for uint8, that is an unsigned integer, 8 bits wide. + Source   +Edit   + +
+
+
+
CatchableError = object of Exception
+
+ + +Abstract class for all exceptions that are catchable. + Source   +Edit   + +
+
+
+
char {.magic: Char.}
+
+ + Built-in 8 bit character type (unsigned). + Source   +Edit   + +
+
+
+
cstring {.magic: Cstring.}
+
+ + Built-in cstring (compatible string) type. + Source   +Edit   + +
+
+
+
Defect = object of Exception
+
+ + +Abstract base class for all exceptions that Nim's runtime raises but that are strictly uncatchable as they can also be mapped to a quit / trap / exit operation. + Source   +Edit   + +
+
+
+
Endianness = enum
+  littleEndian, bigEndian
+
+ + Type describing the endianness of a processor. + Source   +Edit   + +
+
+
+
Exception {.compilerproc, magic: "Exception".} = object of RootObj
+  parent*: ref Exception     ## Parent exception (can be used as a stack).
+  name*: cstring             ## The exception's name is its Nim identifier.
+                             ## This field is filled automatically in the
+                             ## `raise` statement.
+  msg* {.exportc: "message".}: string ## The exception's message. Not
+                                      ## providing an exception message
+                                      ## is bad style.
+  when defined(js):
+    trace*: string
+  else:
+    trace*: seq[StackTraceEntry]
+
+ +

+Base exception class.

+

Each exception has to inherit from Exception. See the full exception hierarchy.

+ + Source   +Edit   + +
+
+
+
float {.magic: Float.}
+
+ + Default floating point type. + Source   +Edit   + +
+
+
+
float32 {.magic: Float32.}
+
+ + 32 bit floating point type. + Source   +Edit   + +
+
+
+
float64 {.magic: Float.}
+
+ + 64 bit floating point type. + Source   +Edit   + +
+
+
+
ForeignCell = object
+  data*: pointer
+
+ + + Source   +Edit   + +
+
+
+
ForLoopStmt {.compilerproc.} = object
+
+ + +A special type that marks a macro as a for-loop macro. See "For Loop Macro". + Source   +Edit   + +
+
+
+
GC_Strategy = enum
+  gcThroughput,             ## optimize for throughput
+  gcResponsiveness,         ## optimize for responsiveness (default)
+  gcOptimizeTime,           ## optimize for speed
+  gcOptimizeSpace            ## optimize for memory footprint
+
+ + The strategy the GC should use for the application. + Source   +Edit   + +
+
+
+
HSlice[T; U] = object
+  a*: T                      ## The lower bound (inclusive).
+  b*: U                      ## The upper bound (inclusive).
+
+ + "Heterogeneous" slice type. + Source   +Edit   + +
+
+
+
int {.magic: Int.}
+
+ + Default integer type; bitwidth depends on architecture, but is always the same as a pointer. + Source   +Edit   + +
+
+
+
int8 {.magic: Int8.}
+
+ + Signed 8 bit integer type. + Source   +Edit   + +
+
+
+
int16 {.magic: Int16.}
+
+ + Signed 16 bit integer type. + Source   +Edit   + +
+
+
+
int32 {.magic: Int32.}
+
+ + Signed 32 bit integer type. + Source   +Edit   + +
+
+
+
int64 {.magic: Int64.}
+
+ + Signed 64 bit integer type. + Source   +Edit   + +
+
+
+
iterable[T] {.magic: IterableType.}
+
+ + Represents an expression that yields T + Source   +Edit   + +
+
+
+
JsRoot = ref object of RootObj
+
+ + Root type of the JavaScript object hierarchy + Source   +Edit   + +
+
+
+
lent[T] {.magic: "BuiltinType".}
+
+ + + Source   +Edit   + +
+
+
+
Natural = range[0 .. high(int)]
+
+ + is an int type ranging from zero to the maximum value of an int. This type is often useful for documentation and debugging. + Source   +Edit   + +
+
+
+
NimNode {.magic: "PNimrodNode".} = ref NimNodeObj
+
+ + Represents a Nim AST node. Macros operate on this type. + Source   +Edit   + +
+
+
+
NimSeqV2[T] = object
+
+ + + Source   +Edit   + +
+
+
+
openArray[T] {.magic: "OpenArray".}
+
+ + Generic type to construct open arrays. Open arrays are implemented as a pointer to the array data and a length field. + Source   +Edit   + +
+
+
+
Ordinal[T] {.magic: Ordinal.}
+
+ + Generic ordinal type. Includes integer, bool, character, and enumeration types as well as their subtypes. See also SomeOrdinal. + Source   +Edit   + +
+
+
+
owned[T] {.magic: "BuiltinType".}
+
+ + type constructor to mark a ref/ptr or a closure as owned. + Source   +Edit   + +
+
+
+
PFrame = ptr TFrame
+
+ + Represents a runtime frame of the call stack; part of the debugger API. + Source   +Edit   + +
+
+
+
pointer {.magic: Pointer.}
+
+ + Built-in pointer type, use the addr operator to get a pointer to a variable. + Source   +Edit   + +
+
+
+
Positive = range[1 .. high(int)]
+
+ + is an int type ranging from one to the maximum value of an int. This type is often useful for documentation and debugging. + Source   +Edit   + +
+
+
+
ptr[T] {.magic: Pointer.}
+
+ + Built-in generic untraced pointer type. + Source   +Edit   + +
+
+
+
range[T] {.magic: "Range".}
+
+ + Generic type to construct range types. + Source   +Edit   + +
+
+
+
ref[T] {.magic: Pointer.}
+
+ + Built-in generic traced pointer type. + Source   +Edit   + +
+
+
+
RootEffect {.compilerproc.} = object of RootObj
+
+ +

+Base effect class.

+

Each effect should inherit from RootEffect unless you know what you're doing.

+ + Source   +Edit   + +
+
+
+
RootObj {.compilerproc, inheritable.} = object
+
+ +

The root of Nim's object hierarchy.

+

Objects should inherit from RootObj or one of its descendants. However, objects that have no ancestor are also allowed.

+ + Source   +Edit   + +
+
+
+
RootRef = ref RootObj
+
+ + Reference to RootObj. + Source   +Edit   + +
+
+
+
seq[T] {.magic: "Seq".}
+
+ + Generic type to construct sequences. + Source   +Edit   + +
+
+
+
set[T] {.magic: "Set".}
+
+ + Generic type to construct bit sets. + Source   +Edit   + +
+
+
+
sink[T] {.magic: "BuiltinType".}
+
+ + + Source   +Edit   + +
+
+
+
Slice[T] = HSlice[T, T]
+
+ + An alias for HSlice[T, T]. + Source   +Edit   + +
+
+
+
SomeFloat = float | float32 | float64
+
+ + Type class matching all floating point number types. + Source   +Edit   + +
+
+
+
SomeInteger = SomeSignedInt | SomeUnsignedInt
+
+ + Type class matching all integer types. + Source   +Edit   + +
+
+
+
SomeNumber = SomeInteger | SomeFloat
+
+ + Type class matching all number types. + Source   +Edit   + +
+
+
+
SomeOrdinal = int | int8 | int16 | int32 | int64 | bool | enum | uint | uint8 |
+    uint16 |
+    uint32 |
+    uint64
+
+ + Type class matching all ordinal types; however this includes enums with holes. See also Ordinal + Source   +Edit   + +
+
+
+
SomeSignedInt = int | int8 | int16 | int32 | int64
+
+ + Type class matching all signed integer types. + Source   +Edit   + +
+
+
+
SomeUnsignedInt = uint | uint8 | uint16 | uint32 | uint64
+
+ + Type class matching all unsigned integer types. + Source   +Edit   + +
+
+
+
StackTraceEntry = object
+  procname*: cstring         ## Name of the proc that is currently executing.
+  line*: int                 ## Line number of the proc that is currently executing.
+  filename*: cstring         ## Filename of the proc that is currently executing.
+  when NimStackTraceMsgs:
+    frameMsg*: string ## When a stacktrace is generated in a given frame and
+                      ## rendered at a later time, we should ensure the stacktrace
+                      ## data isn't invalidated; any pointer into PFrame is
+                      ## subject to being invalidated so shouldn't be stored.
+  when defined(nimStackTraceOverride):
+    programCounter*: uint ## Program counter - will be used to get the rest of the info,
+                          ## when `$` is called on this type. We can't use
+                          ## "cuintptr_t" in here.
+    procnameStr*, filenameStr*: string ## GC-ed alternatives to "procname" and "filename"
+
+ + In debug mode exceptions store the stack trace that led to them. A StackTraceEntry is a single entry of the stack trace. + Source   +Edit   + +
+
+
+
static[T] {.magic: "Static".}
+
+ +

Meta type representing all values that can be evaluated at compile-time.

+

The type coercion static(x) can be used to force the compile-time evaluation of the given expression x.

+ + Source   +Edit   + +
+
+
+
string {.magic: String.}
+
+ + Built-in string type. + Source   +Edit   + +
+
+
+
TFrame {.importc, nodecl, final.} = object
+  prev*: PFrame              ## Previous frame; used for chaining the call stack.
+  procname*: cstring         ## Name of the proc that is currently executing.
+  line*: int                 ## Line number of the proc that is currently executing.
+  filename*: cstring         ## Filename of the proc that is currently executing.
+  len*: int16                ## Length of the inspectable slots.
+  calldepth*: int16          ## Used for max call depth checking.
+  when NimStackTraceMsgs:
+    frameMsgLen*: int        ## end position in frameMsgBuf for this frame.
+
+ + The frame itself. + Source   +Edit   + +
+
+
+
type[T] {.magic: "Type".}
+
+ +

Meta type representing the type of all type values.

+

The coercion type(x) can be used to obtain the type of the given expression x.

+ + Source   +Edit   + +
+
+
+
typed {.magic: Stmt.}
+
+ + Meta type to denote an expression that is resolved (for templates). + Source   +Edit   + +
+
+
+
typedesc {.magic: TypeDesc.}
+
+ + Meta type to denote a type description. + Source   +Edit   + +
+
+
+
TypeOfMode = enum
+  typeOfProc,               ## Prefer the interpretation that means `x` is a proc call.
+  typeOfIter                 ## Prefer the interpretation that means `x` is an iterator call.
+
+ + Possible modes of typeof. + Source   +Edit   + +
+
+
+
uint {.magic: UInt.}
+
+ + Unsigned default integer type. + Source   +Edit   + +
+
+
+
uint8 {.magic: UInt8.}
+
+ + Unsigned 8 bit integer type. + Source   +Edit   + +
+
+
+
uint16 {.magic: UInt16.}
+
+ + Unsigned 16 bit integer type. + Source   +Edit   + +
+
+
+
uint32 {.magic: UInt32.}
+
+ + Unsigned 32 bit integer type. + Source   +Edit   + +
+
+
+
uint64 {.magic: UInt64.}
+
+ + Unsigned 64 bit integer type. + Source   +Edit   + +
+
+
+
UncheckedArray[T] {.magic: "UncheckedArray".}
+
+ + + Source   +Edit   + +
+
+
+
untyped {.magic: Expr.}
+
+ + Meta type to denote an expression that is not resolved (for templates). + Source   +Edit   + +
+
+
+
varargs[T] {.magic: "Varargs".}
+
+ + Generic type to construct a varargs type. + Source   +Edit   + +
+
+
+
void {.magic: "VoidType".}
+
+ + Meta type to denote the absence of any type. + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
errorMessageWriter: (proc (msg: string) {....tags: [WriteIOEffect], gcsafe, nimcall.})
+
+ + Function that will be called instead of stdmsg.write when printing stacktrace. Unstable API. + Source   +Edit   + +
+
+
+
globalRaiseHook: proc (e: ref Exception): bool {.nimcall, ...gcsafe.}
+
+ + With this hook you can influence exception handling on a global level. If not nil, every 'raise' statement ends up calling this hook.
Warning: +Ordinary application code should never set this hook! You better know what you do when setting this.
+

If globalRaiseHook returns false, the exception is caught and does not propagate further through the call stack.

+ + Source   +Edit   + +
+
+
+
localRaiseHook {.threadvar.}: proc (e: ref Exception): bool {.nimcall, ...gcsafe.}
+
+ + With this hook you can influence exception handling on a thread local level. If not nil, every 'raise' statement ends up calling this hook.
Warning: +Ordinary application code should never set this hook! You better know what you do when setting this.
+

If localRaiseHook returns false, the exception is caught and does not propagate further through the call stack.

+ + Source   +Edit   + +
+
+
+
nimThreadDestructionHandlers {.threadvar.}: seq[
+    proc () {.closure, ...gcsafe, raises: [].}]
+
+ + + Source   +Edit   + +
+
+
+
onUnhandledException: (proc (errorMsg: string) {.nimcall, ...gcsafe.})
+
+ +

Set this error +handler to override the existing behaviour on an unhandled exception.

+

The default is to write a stacktrace to stderr and then call quit(1). Unstable API.

+ + Source   +Edit   + +
+
+
+
outOfMemHook: proc () {.nimcall, ...tags: [], gcsafe, raises: [].}
+
+ +

Set this variable to provide a procedure that should be called in case of an out of memory event. The standard handler writes an error message and terminates the program.

+

outOfMemHook can be used to raise an exception in case of OOM like so:

+

var gOutOfMem: ref EOutOfMemory
+new(gOutOfMem) # need to be allocated *before* OOM really happened!
+gOutOfMem.msg = "out of memory"
+
+proc handleOOM() =
+  raise gOutOfMem
+
+system.outOfMemHook = handleOOM

+

If the handler does not raise an exception, ordinary control flow continues and the program is terminated.

+ + Source   +Edit   + +
+
+
+
programResult {.compilerproc, exportc: "nim_program_result".}: int
+
+ + deprecated, prefer quit or exitprocs.getProgramResult, exitprocs.setProgramResult. + Source   +Edit   + +
+
+
+
unhandledExceptionHook: proc (e: ref Exception) {.nimcall, ...tags: [], gcsafe,
+    raises: [].}
+
+ + Set this variable to provide a procedure that should be called in case of an unhandle exception event. The standard handler writes an error message and terminates the program, except when using --os:any + Source   +Edit   + +
+
+ +
+
+
+

Lets

+
+
+
nimvm {.magic: "Nimvm", compileTime.}: bool = false
+
+ + May be used only in when expression. It is true in Nim VM context and false otherwise. + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
appType {.magic: "AppType".}: string = ""
+
+ + A string that describes the application type. Possible values: "console", "gui", "lib". + Source   +Edit   + +
+
+
+
CompileDate {.magic: "CompileDate".}: string = "0000-00-00"
+
+ + The date (in UTC) of compilation as a string of the form YYYY-MM-DD. This works thanks to compiler magic. + Source   +Edit   + +
+
+
+
CompileTime {.magic: "CompileTime".}: string = "00:00:00"
+
+ + The time (in UTC) of compilation as a string of the form HH:MM:SS. This works thanks to compiler magic. + Source   +Edit   + +
+
+
+
cpuEndian {.magic: "CpuEndian".}: Endianness = littleEndian
+
+ + The endianness of the target CPU. This is a valuable piece of information for low-level code only. This works thanks to compiler magic. + Source   +Edit   + +
+
+
+
hostCPU {.magic: "HostCPU".}: string = ""
+
+ +

A string that describes the host CPU.

+

Possible values: "i386", "alpha", "powerpc", "powerpc64", "powerpc64el", "sparc", "amd64", "mips", "mipsel", "arm", "arm64", "mips64", "mips64el", "riscv32", "riscv64", "loongarch64".

+ + Source   +Edit   + +
+
+
+
hostOS {.magic: "HostOS".}: string = ""
+
+ +

A string that describes the host operating system.

+

Possible values: "windows", "macosx", "linux", "netbsd", "freebsd", "openbsd", "solaris", "aix", "haiku", "standalone".

+ + Source   +Edit   + +
+
+
+
Inf = 0x7FF0000000000000'f64
+
+ + Contains the IEEE floating point value of positive infinity. + Source   +Edit   + +
+
+
+
isMainModule {.magic: "IsMainModule".}: bool = false
+
+ + True only when accessed in the main module. This works thanks to compiler magic. It is useful to embed testing code in a module. + Source   +Edit   + +
+
+
+
NaN = 0x7FF7FFFFFFFFFFFF'f64
+
+ +

Contains an IEEE floating point value of Not A Number.

+

Note that you cannot compare a floating point value to this value and expect a reasonable result - use the isNaN or classify procedure in the math module for checking for NaN.

+ + Source   +Edit   + +
+
+
+
NegInf = 0xFFF0000000000000'f64
+
+ + Contains the IEEE floating point value of negative infinity. + Source   +Edit   + +
+
+
+
NimMajor {.intdefine.}: int = 2
+
+ +

is the major number of Nim's version. Example:

+

when (NimMajor, NimMinor, NimPatch) >= (1, 3, 1): discard

+ + Source   +Edit   + +
+
+
+
NimMinor {.intdefine.}: int = 2
+
+ + is the minor number of Nim's version. Odd for devel, even for releases. + Source   +Edit   + +
+
+
+
NimPatch {.intdefine.}: int = 1
+
+ + is the patch number of Nim's version. Odd for devel, even for releases. + Source   +Edit   + +
+
+
+
NimVersion: string = "2.2.1"
+
+ + is the version of Nim as a string. + Source   +Edit   + +
+
+
+
off = false
+
+ + Alias for false. + Source   +Edit   + +
+
+
+
on = true
+
+ + Alias for true. + Source   +Edit   + +
+
+
+
QuitFailure = 1
+
+ + is the value that should be passed to quit to indicate failure. + Source   +Edit   + +
+
+
+
QuitSuccess = 0
+
+ + is the value that should be passed to quit to indicate success. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `%%`(x, y: int): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Treats x and y as unsigned and compute the modulo of x and y.

+

The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible.

+ + Source   +Edit   + +
+
+
+
proc `%%`(x, y: int8): int8 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `%%`(x, y: int16): int16 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `%%`(x, y: int32): int32 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `%%`(x, y: int64): int64 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `&`(x, y: char): string {.magic: "ConStrStr", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ +

Concatenates characters x and y into a string.

+

assert('a' & 'b' == "ab")

+ + Source   +Edit   + +
+
+
+
proc `&`(x, y: string): string {.magic: "ConStrStr", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ +

Concatenates strings x and y.

+

assert("ab" & "cd" == "abcd")

+ + Source   +Edit   + +
+
+
+
proc `&`(x: char; y: string): string {.magic: "ConStrStr", noSideEffect,
+                                       ...raises: [], tags: [], forbids: [].}
+
+ +

Concatenates x with y.

+

assert('a' & "bc" == "abc")

+ + Source   +Edit   + +
+
+
+
proc `&`(x: string; y: char): string {.magic: "ConStrStr", noSideEffect,
+                                       ...raises: [], tags: [], forbids: [].}
+
+ +

Concatenates x with y.

+

assert("ab" & 'c' == "abc")

+ + Source   +Edit   + +
+
+
+
proc `&`[T](x, y: sink seq[T]): seq[T] {.noSideEffect.}
+
+ +

Concatenates two sequences.

+

Requires copying of the sequences.

+

assert(@[1, 2, 3, 4] & @[5, 6] == @[1, 2, 3, 4, 5, 6])

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc `&`[T](x: sink seq[T]; y: sink T): seq[T] {.noSideEffect.}
+
+ +

Appends element y to the end of the sequence.

+

Requires copying of the sequence.

+

assert(@[1, 2, 3] & 4 == @[1, 2, 3, 4])

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc `&`[T](x: sink T; y: sink seq[T]): seq[T] {.noSideEffect.}
+
+ +

Prepends the element x to the beginning of the sequence.

+

Requires copying of the sequence.

+

assert(1 & @[2, 3, 4] == @[1, 2, 3, 4])

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `&=`(x: var string; y: string) {.magic: "AppendStrStr", noSideEffect,
+                                      ...raises: [], tags: [], forbids: [].}
+
+ +

Appends in place to a string.

+

var a = "abc"
+a &= "de" # a <- "abcde"

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `*`(x, y: float): float {.magic: "MulF64", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `*`(x, y: float32): float32 {.magic: "MulF64", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `*`(x, y: int): int {.magic: "MulI", noSideEffect, ...raises: [], tags: [],
+                           forbids: [].}
+
+ + Binary * operator for an integer. + Source   +Edit   + +
+
+
+
proc `*`(x, y: int8): int8 {.magic: "MulI", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `*`(x, y: int16): int16 {.magic: "MulI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `*`(x, y: int32): int32 {.magic: "MulI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `*`(x, y: int64): int64 {.magic: "MulI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `*`(x, y: uint): uint {.magic: "MulU", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ + Binary * operator for unsigned integers. + Source   +Edit   + +
+
+
+
proc `*`(x, y: uint8): uint8 {.magic: "MulU", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `*`(x, y: uint16): uint16 {.magic: "MulU", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `*`(x, y: uint32): uint32 {.magic: "MulU", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `*`(x, y: uint64): uint64 {.magic: "MulU", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `*`[T](x, y: set[T]): set[T] {.magic: "MulSet", ...raises: [], tags: [],
+                                    forbids: [].}
+
+ + This operator computes the intersection of two sets. +

Example:

+
assert {1, 2, 3} * {2, 3, 4} == {2, 3}
+ Source   +Edit   + +
+
+ +
+
+
+
proc `*%`(x, y: int): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Treats x and y as unsigned and multiplies them.

+

The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible.

+ + Source   +Edit   + +
+
+
+
proc `*%`(x, y: int8): int8 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `*%`(x, y: int16): int16 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `*%`(x, y: int32): int32 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `*%`(x, y: int64): int64 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `*=`[T: float | float32 | float64](x: var T; y: T) {.inline, noSideEffect.}
+
+ + Multiplies in place a floating point number. + Source   +Edit   + +
+
+
+
proc `*=`[T: SomeInteger](x: var T; y: T) {.inline, noSideEffect.}
+
+ + Binary *= operator for integers. + Source   +Edit   + +
+
+ +
+
+
+
proc `+`(x, y: float): float {.magic: "AddF64", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(x, y: float32): float32 {.magic: "AddF64", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(x, y: int): int {.magic: "AddI", noSideEffect, ...raises: [], tags: [],
+                           forbids: [].}
+
+ + Binary + operator for an integer. + Source   +Edit   + +
+
+
+
proc `+`(x, y: int8): int8 {.magic: "AddI", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(x, y: int16): int16 {.magic: "AddI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(x, y: int32): int32 {.magic: "AddI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(x, y: int64): int64 {.magic: "AddI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(x, y: uint): uint {.magic: "AddU", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ + Binary + operator for unsigned integers. + Source   +Edit   + +
+
+
+
proc `+`(x, y: uint8): uint8 {.magic: "AddU", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(x, y: uint16): uint16 {.magic: "AddU", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(x, y: uint32): uint32 {.magic: "AddU", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(x, y: uint64): uint64 {.magic: "AddU", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(x: float): float {.magic: "UnaryPlusF64", noSideEffect, ...raises: [],
+                            tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(x: float32): float32 {.magic: "UnaryPlusF64", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(x: int): int {.magic: "UnaryPlusI", noSideEffect, ...raises: [], tags: [],
+                        forbids: [].}
+
+ + Unary + operator for an integer. Has no effect. + Source   +Edit   + +
+
+
+
proc `+`(x: int8): int8 {.magic: "UnaryPlusI", noSideEffect, ...raises: [],
+                          tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(x: int16): int16 {.magic: "UnaryPlusI", noSideEffect, ...raises: [],
+                            tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(x: int32): int32 {.magic: "UnaryPlusI", noSideEffect, ...raises: [],
+                            tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+`(x: int64): int64 {.magic: "UnaryPlusI", noSideEffect, ...raises: [],
+                            tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `+`[T](x, y: set[T]): set[T] {.magic: "PlusSet", ...raises: [], tags: [],
+                                    forbids: [].}
+
+ + This operator computes the union of two sets. +

Example:

+
assert {1, 2, 3} + {2, 3, 4} == {1, 2, 3, 4}
+ Source   +Edit   + +
+
+ +
+
+
+
proc `+%`(x, y: int): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Treats x and y as unsigned and adds them.

+

The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible.

+ + Source   +Edit   + +
+
+
+
proc `+%`(x, y: int8): int8 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+%`(x, y: int16): int16 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+%`(x, y: int32): int32 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+%`(x, y: int64): int64 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `+=`[T: float | float32 | float64](x: var T; y: T) {.inline, noSideEffect.}
+
+ + Increments in place a floating point number. + Source   +Edit   + +
+
+
+
proc `+=`[T: SomeInteger](x: var T; y: T) {.magic: "Inc", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Increments an integer. + Source   +Edit   + +
+
+ +
+
+
+
proc `-`(a, b: AllocStats): AllocStats {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x, y: float): float {.magic: "SubF64", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x, y: float32): float32 {.magic: "SubF64", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x, y: int): int {.magic: "SubI", noSideEffect, ...raises: [], tags: [],
+                           forbids: [].}
+
+ + Binary - operator for an integer. + Source   +Edit   + +
+
+
+
proc `-`(x, y: int8): int8 {.magic: "SubI", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x, y: int16): int16 {.magic: "SubI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x, y: int32): int32 {.magic: "SubI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x, y: int64): int64 {.magic: "SubI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x, y: uint): uint {.magic: "SubU", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ + Binary - operator for unsigned integers. + Source   +Edit   + +
+
+
+
proc `-`(x, y: uint8): uint8 {.magic: "SubU", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x, y: uint16): uint16 {.magic: "SubU", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x, y: uint32): uint32 {.magic: "SubU", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x, y: uint64): uint64 {.magic: "SubU", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x: float): float {.magic: "UnaryMinusF64", noSideEffect, ...raises: [],
+                            tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x: float32): float32 {.magic: "UnaryMinusF64", noSideEffect,
+                                ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x: int): int {.magic: "UnaryMinusI", noSideEffect, ...raises: [],
+                        tags: [], forbids: [].}
+
+ + Unary - operator for an integer. Negates x. + Source   +Edit   + +
+
+
+
proc `-`(x: int8): int8 {.magic: "UnaryMinusI", noSideEffect, ...raises: [],
+                          tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x: int16): int16 {.magic: "UnaryMinusI", noSideEffect, ...raises: [],
+                            tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x: int32): int32 {.magic: "UnaryMinusI", noSideEffect, ...raises: [],
+                            tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-`(x: int64): int64 {.magic: "UnaryMinusI64", noSideEffect, ...raises: [],
+                            tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func `-`[T](x, y: set[T]): set[T] {.magic: "MinusSet", ...raises: [], tags: [],
+                                    forbids: [].}
+
+ + This operator computes the difference of two sets. +

Example:

+
assert {1, 2, 3} - {2, 3, 4} == {1}
+ Source   +Edit   + +
+
+ +
+
+
+
proc `-%`(x, y: int): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Treats x and y as unsigned and subtracts them.

+

The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible.

+ + Source   +Edit   + +
+
+
+
proc `-%`(x, y: int8): int8 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-%`(x, y: int16): int16 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-%`(x, y: int32): int32 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-%`(x, y: int64): int64 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `-=`[T: float | float32 | float64](x: var T; y: T) {.inline, noSideEffect.}
+
+ + Decrements in place a floating point number. + Source   +Edit   + +
+
+
+
proc `-=`[T: SomeInteger](x: var T; y: T) {.magic: "Dec", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Decrements an integer. + Source   +Edit   + +
+
+ +
+
+
+
proc `..`[T, U](a: sink T; b: sink U): HSlice[T, U] {.noSideEffect, inline,
+    magic: "DotDot", ...raises: [], tags: [], forbids: [].}
+
+ +

Binary slice operator that constructs an interval [a, b], both a and b are inclusive.

+

Slices can also be used in the set constructor and in ordinal case statements, but then they are special-cased by the compiler.

+

let a = [10, 20, 30, 40, 50]
+echo a[2 .. 3] # @[30, 40]

+ + Source   +Edit   + +
+
+
+
proc `..`[T](b: sink T): HSlice[int, T] {.noSideEffect, inline, magic: "DotDot",
+    ...deprecated: "replace `..b` with `0..b`", raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: replace `..b` with `0..b` +
+ +

Unary slice operator that constructs an interval [default(int), b].

+

let a = [10, 20, 30, 40, 50]
+echo a[.. 2] # @[10, 20, 30]

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `/`(x, y: float): float {.magic: "DivF64", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `/`(x, y: float32): float32 {.magic: "DivF64", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `/`(x, y: int): float {.inline, noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ +

Division of integers that results in a float.

+

echo 7 / 5 # => 1.4

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `/%`(x, y: int): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Treats x and y as unsigned and divides them.

+

The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible.

+ + Source   +Edit   + +
+
+
+
proc `/%`(x, y: int8): int8 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `/%`(x, y: int16): int16 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `/%`(x, y: int32): int32 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `/%`(x, y: int64): int64 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `/=`(x: var float64; y: float64) {.inline, noSideEffect, ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + Divides in place a floating point number. + Source   +Edit   + +
+
+
+
proc `/=`[T: float | float32](x: var T; y: T) {.inline, noSideEffect.}
+
+ + Divides in place a floating point number. + Source   +Edit   + +
+
+ +
+
+
+
proc `<`(x, y: bool): bool {.magic: "LtB", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`(x, y: char): bool {.magic: "LtCh", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ + Compares two chars and returns true if x is lexicographically before y (uppercase letters come before lowercase letters). +

Example:

+
let
+  a = 'a'
+  b = 'b'
+  c = 'Z'
+assert a < b
+assert not (a < a)
+assert not (a < c)
+ Source   +Edit   + +
+
+
+
proc `<`(x, y: float): bool {.magic: "LtF64", noSideEffect, ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`(x, y: float32): bool {.magic: "LtF64", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`(x, y: int): bool {.magic: "LtI", noSideEffect, ...raises: [], tags: [],
+                            forbids: [].}
+
+ + Returns true if x is less than y. + Source   +Edit   + +
+
+
+
proc `<`(x, y: int8): bool {.magic: "LtI", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`(x, y: int16): bool {.magic: "LtI", noSideEffect, ...raises: [], tags: [],
+                              forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`(x, y: int32): bool {.magic: "LtI", noSideEffect, ...raises: [], tags: [],
+                              forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`(x, y: int64): bool {.magic: "LtI", noSideEffect, ...raises: [], tags: [],
+                              forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`(x, y: pointer): bool {.magic: "LtPtr", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`(x, y: string): bool {.magic: "LtStr", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + Compares two strings and returns true if x is lexicographically before y (uppercase letters come before lowercase letters). +

Example:

+
let
+  a = "abc"
+  b = "abd"
+  c = "ZZZ"
+assert a < b
+assert not (a < a)
+assert not (a < c)
+ Source   +Edit   + +
+
+
+
proc `<`(x, y: uint): bool {.magic: "LtU", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ + Returns true if x < y. + Source   +Edit   + +
+
+
+
proc `<`(x, y: uint8): bool {.magic: "LtU", noSideEffect, ...raises: [], tags: [],
+                              forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`(x, y: uint16): bool {.magic: "LtU", noSideEffect, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`(x, y: uint32): bool {.magic: "LtU", noSideEffect, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`(x, y: uint64): bool {.magic: "LtU", noSideEffect, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`[Enum: enum](x, y: Enum): bool {.magic: "LtEnum", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`[T: tuple](x, y: T): bool
+
+ + Generic lexicographic < operator for tuples that is lifted from the components of x and y. This implementation uses cmp. + Source   +Edit   + +
+
+
+
proc `<`[T](x, y: ptr T): bool {.magic: "LtPtr", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`[T](x, y: ref T): bool {.magic: "LtPtr", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<`[T](x, y: set[T]): bool {.magic: "LtSet", noSideEffect, ...raises: [],
+                                  tags: [], forbids: [].}
+
+ +

Returns true if x is a strict or proper subset of y.

+

A strict or proper subset x has all of its members in y but y has more elements than y.

+ +

Example:

+
let
+  a = {3, 5}
+  b = {1, 3, 5, 7}
+  c = {2}
+assert a < b
+assert not (a < a)
+assert not (a < c)
+ Source   +Edit   + +
+
+ +
+
+
+
proc `<%`(x, y: int): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Treats x and y as unsigned and compares them. Returns true if unsigned(x) < unsigned(y). + Source   +Edit   + +
+
+
+
proc `<%`(x, y: int8): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<%`(x, y: int16): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<%`(x, y: int32): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<%`(x, y: int64): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `<=`(x, y: bool): bool {.magic: "LeB", noSideEffect, ...raises: [], tags: [],
+                              forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`(x, y: char): bool {.magic: "LeCh", noSideEffect, ...raises: [], tags: [],
+                              forbids: [].}
+
+ + Compares two chars and returns true if x is lexicographically before y (uppercase letters come before lowercase letters). +

Example:

+
let
+  a = 'a'
+  b = 'b'
+  c = 'Z'
+assert a <= b
+assert a <= a
+assert not (a <= c)
+ Source   +Edit   + +
+
+
+
proc `<=`(x, y: float): bool {.magic: "LeF64", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`(x, y: float32): bool {.magic: "LeF64", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`(x, y: int): bool {.magic: "LeI", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ + Returns true if x is less than or equal to y. + Source   +Edit   + +
+
+
+
proc `<=`(x, y: int8): bool {.magic: "LeI", noSideEffect, ...raises: [], tags: [],
+                              forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`(x, y: int16): bool {.magic: "LeI", noSideEffect, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`(x, y: int32): bool {.magic: "LeI", noSideEffect, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`(x, y: int64): bool {.magic: "LeI", noSideEffect, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`(x, y: pointer): bool {.magic: "LePtr", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`(x, y: string): bool {.magic: "LeStr", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + Compares two strings and returns true if x is lexicographically before y (uppercase letters come before lowercase letters). +

Example:

+
let
+  a = "abc"
+  b = "abd"
+  c = "ZZZ"
+assert a <= b
+assert a <= a
+assert not (a <= c)
+ Source   +Edit   + +
+
+
+
proc `<=`(x, y: uint): bool {.magic: "LeU", noSideEffect, ...raises: [], tags: [],
+                              forbids: [].}
+
+ + Returns true if x <= y. + Source   +Edit   + +
+
+
+
proc `<=`(x, y: uint8): bool {.magic: "LeU", noSideEffect, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`(x, y: uint16): bool {.magic: "LeU", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`(x, y: uint32): bool {.magic: "LeU", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`(x, y: uint64): bool {.magic: "LeU", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`[Enum: enum](x, y: Enum): bool {.magic: "LeEnum", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`[T: tuple](x, y: T): bool
+
+ + Generic lexicographic <= operator for tuples that is lifted from the components of x and y. This implementation uses cmp. + Source   +Edit   + +
+
+
+
proc `<=`[T](x, y: ref T): bool {.magic: "LePtr", noSideEffect, ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`[T](x, y: set[T]): bool {.magic: "LeSet", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ +

Returns true if x is a subset of y.

+

A subset x has all of its members in y and y doesn't necessarily have more members than x. That is, x can be equal to y.

+ +

Example:

+
let
+  a = {3, 5}
+  b = {1, 3, 5, 7}
+  c = {2}
+assert a <= b
+assert a <= a
+assert not (a <= c)
+ Source   +Edit   + +
+
+ +
+
+
+
proc `<=%`(x, y: int): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Treats x and y as unsigned and compares them. Returns true if unsigned(x) <= unsigned(y). + Source   +Edit   + +
+
+
+
proc `<=%`(x, y: int8): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=%`(x, y: int16): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=%`(x, y: int32): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=%`(x, y: int64): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `=`[T](dest: var T; src: T) {.noSideEffect, magic: "Asgn", ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(x, y: bool): bool {.magic: "EqB", noSideEffect, ...raises: [], tags: [],
+                              forbids: [].}
+
+ + Checks for equality between two bool variables. + Source   +Edit   + +
+
+
+
proc `==`(x, y: char): bool {.magic: "EqCh", noSideEffect, ...raises: [], tags: [],
+                              forbids: [].}
+
+ + Checks for equality between two char variables. + Source   +Edit   + +
+
+
+
proc `==`(x, y: cstring): bool {.magic: "EqCString", noSideEffect, inline,
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + Checks for equality between two cstring variables. + Source   +Edit   + +
+
+
+
proc `==`(x, y: float): bool {.magic: "EqF64", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(x, y: float32): bool {.magic: "EqF64", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(x, y: int): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ + Compares two integers for equality. + Source   +Edit   + +
+
+
+
proc `==`(x, y: int8): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
+                              forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(x, y: int16): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(x, y: int32): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(x, y: int64): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(x, y: pointer): bool {.magic: "EqRef", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + Checks for equality between two pointer variables. +

Example:

+
var # this is a wildly dangerous example
+  a = cast[pointer](0)
+  b = cast[pointer](nil)
+assert a == b # true due to the special meaning of `nil`/0 as a pointer
+ Source   +Edit   + +
+
+
+
proc `==`(x, y: string): bool {.magic: "EqStr", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + Checks for equality between two string variables. + Source   +Edit   + +
+
+
+
proc `==`(x, y: uint): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
+                              forbids: [].}
+
+ + Compares two unsigned integers for equality. + Source   +Edit   + +
+
+
+
proc `==`(x, y: uint8): bool {.magic: "EqI", noSideEffect, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(x, y: uint16): bool {.magic: "EqI", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(x, y: uint32): bool {.magic: "EqI", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(x, y: uint64): bool {.magic: "EqI", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`[Enum: enum](x, y: Enum): bool {.magic: "EqEnum", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Checks whether values within the same enum have the same underlying value. +

Example:

+
type
+  Enum1 = enum
+    field1 = 3, field2
+  Enum2 = enum
+    place1, place2 = 3
+var
+  e1 = field1
+  e2 = place2.ord.Enum1
+assert e1 == e2
+assert not compiles(e1 == place2) # raises error
+ Source   +Edit   + +
+
+
+
proc `==`[I, T](x, y: array[I, T]): bool
+
+ + + Source   +Edit   + +
+
+
+
proc `==`[T: proc | iterator](x, y: T): bool {.magic: "EqProc", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Checks that two proc variables refer to the same procedure. + Source   +Edit   + +
+
+
+
proc `==`[T: tuple | object](x, y: T): bool
+
+ + Generic == operator for tuples that is lifted from the components. of x and y. + Source   +Edit   + +
+
+
+
proc `==`[T](x, y: openArray[T]): bool
+
+ + + Source   +Edit   + +
+
+
+
proc `==`[T](x, y: ptr T): bool {.magic: "EqRef", noSideEffect, ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + Checks that two ptr variables refer to the same item. + Source   +Edit   + +
+
+
+
proc `==`[T](x, y: ref T): bool {.magic: "EqRef", noSideEffect, ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + Checks that two ref variables refer to the same item. + Source   +Edit   + +
+
+
+
proc `==`[T](x, y: seq[T]): bool {.noSideEffect.}
+
+ + Generic equals operator for sequences: relies on a equals operator for the element type T. + Source   +Edit   + +
+
+
+
proc `==`[T](x, y: set[T]): bool {.magic: "EqSet", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + Checks for equality between two variables of type set. +

Example:

+
assert {1, 2, 2, 3} == {1, 2, 3} # duplication in sets is ignored
+ Source   +Edit   + +
+
+ +
+
+
+
proc `=copy`[T](dest: var T; src: T) {.noSideEffect, magic: "Asgn", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `=destroy`(x: string) {.inline, magic: "Destroy", enforceNoRaises,
+                             ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `=destroy`[T](x: ref T) {.inline, magic: "Destroy", ...raises: [], tags: [],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `=destroy`[T](x: seq[T]) {.inline, magic: "Destroy", ...raises: [], tags: [],
+                                forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `=destroy`[T](x: var T) {.inline, magic: "Destroy", ...raises: [], tags: [],
+                               forbids: [].}
+
+ + Generic destructor implementation that can be overridden. + Source   +Edit   + +
+
+ +
+
+
+
proc `=dup`[T](x: T): T {.inline, magic: "Dup", ...raises: [], tags: [],
+                          forbids: [].}
+
+ + Generic dup implementation that can be overridden. + Source   +Edit   + +
+
+ +
+
+
+
proc `=sink`[T](x: var T; y: T) {.inline, nodestroy, magic: "Asgn", ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + Generic sink implementation that can be overridden. + Source   +Edit   + +
+
+ +
+
+
+
proc `=trace`[T](x: var T; env: pointer) {.inline, magic: "Trace", ...raises: [],
+    tags: [], forbids: [].}
+
+ + Generic trace implementation that can be overridden. + Source   +Edit   + +
+
+ +
+
+
+
proc `=wasMoved`[T](obj: var T) {.magic: "WasMoved", noSideEffect, ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + Generic wasMoved implementation that can be overridden. + Source   +Edit   + +
+
+ +
+
+
+
proc `@`[IDX, T](a: sink array[IDX, T]): seq[T] {.magic: "ArrToSeq",
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Turns an array into a sequence.

+

This most often useful for constructing sequences with the array constructor: @[1, 2, 3] has the type seq[int], while [1, 2, 3] has the type array[0..2, int].

+

let
+  a = [1, 3, 5]
+  b = "foo"
+
+echo @a # => @[1, 3, 5]
+echo @b # => @['f', 'o', 'o']

+ + Source   +Edit   + +
+
+
+
proc `@`[T](a: openArray[T]): seq[T] {.magic: "OpenArrayToSeq", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ +

Turns an openArray into a sequence.

+

This is not as efficient as turning a fixed length array into a sequence as it always copies every element of a.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `[]`(s: string; i: BackwardsIndex): char {.inline, systemRaisesDefect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `[]`(s: var string; i: BackwardsIndex): var char {.inline,
+    systemRaisesDefect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `[]`[I: Ordinal; T](a: T; i: I): T {.noSideEffect, magic: "ArrGet",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `[]`[Idx, T; U, V: Ordinal](a: array[Idx, T]; x: HSlice[U, V]): seq[T] {.
+    systemRaisesDefect.}
+
+ +

Slice operation for arrays. Returns the inclusive range [a[x.a], a[x.b]]:

+

var a = [1, 2, 3, 4]
+assert a[0..2] == @[1, 2, 3]

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc `[]`[Idx, T](a: array[Idx, T]; i: BackwardsIndex): T {.inline,
+    systemRaisesDefect.}
+
+ + + Source   +Edit   + +
+
+
+
proc `[]`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex): var T {.inline,
+    systemRaisesDefect.}
+
+ + + Source   +Edit   + +
+
+
+
proc `[]`[T, U: Ordinal](s: string; x: HSlice[T, U]): string {.inline,
+    systemRaisesDefect.}
+
+ +

Slice operation for strings. Returns the inclusive range [s[x.a], s[x.b]]:

+

var s = "abcdef"
+assert s[1..3] == "bcd"

+ + Source   +Edit   + +
+
+
+
proc `[]`[T; U, V: Ordinal](s: openArray[T]; x: HSlice[U, V]): seq[T] {.
+    systemRaisesDefect.}
+
+ +

Slice operation for sequences. Returns the inclusive range [s[x.a], s[x.b]]:

+

var s = @[1, 2, 3, 4]
+assert s[0..2] == @[1, 2, 3]

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc `[]`[T](s: openArray[T]; i: BackwardsIndex): T {.inline, systemRaisesDefect.}
+
+ + + Source   +Edit   + +
+
+
+
proc `[]`[T](s: var openArray[T]; i: BackwardsIndex): var T {.inline,
+    systemRaisesDefect.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `[]=`(s: var string; i: BackwardsIndex; x: char) {.inline,
+    systemRaisesDefect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `[]=`[I: Ordinal; T, S](a: T; i: I; x: sink S) {.noSideEffect,
+    magic: "ArrPut", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `[]=`[Idx, T; U, V: Ordinal](a: var array[Idx, T]; x: HSlice[U, V];
+                                  b: openArray[T]) {.systemRaisesDefect.}
+
+ +

Slice assignment for arrays.

+

var a = [10, 20, 30, 40, 50]
+a[1..2] = @[99, 88]
+assert a == [10, 99, 88, 40, 50]

+ + Source   +Edit   + +
+
+
+
proc `[]=`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex; x: T) {.inline,
+    systemRaisesDefect.}
+
+ + + Source   +Edit   + +
+
+
+
proc `[]=`[T, U: Ordinal](s: var string; x: HSlice[T, U]; b: string) {.
+    systemRaisesDefect.}
+
+ +

Slice assignment for strings.

+

If b.len is not exactly the number of elements that are referred to by x, a splice is performed:

+ +

Example:

+
var s = "abcdefgh"
+s[1 .. ^2] = "xyz"
+assert s == "axyzh"
+ Source   +Edit   + +
+
+
+
proc `[]=`[T; U, V: Ordinal](s: var seq[T]; x: HSlice[U, V]; b: openArray[T]) {.
+    systemRaisesDefect.}
+
+ +

Slice assignment for sequences.

+

If b.len is not exactly the number of elements that are referred to by x, a splice is performed.

+ +

Example:

+
var s = @"abcdefgh"
+s[1 .. ^2] = @"xyz"
+assert s == @"axyzh"
+ Source   +Edit   + +
+
+
+
proc `[]=`[T](s: var openArray[T]; i: BackwardsIndex; x: T) {.inline,
+    systemRaisesDefect.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func abs(x: int): int {.magic: "AbsI", inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func abs(x: int8): int8 {.magic: "AbsI", inline, ...raises: [], tags: [],
+                          forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func abs(x: int16): int16 {.magic: "AbsI", inline, ...raises: [], tags: [],
+                            forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func abs(x: int32): int32 {.magic: "AbsI", inline, ...raises: [], tags: [],
+                            forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
func abs(x: int64): int64 {.magic: "AbsI", inline, ...raises: [], tags: [],
+                            forbids: [].}
+
+ +

Returns the absolute value of x.

+

If x is low(x) (that is -MININT for its type), an overflow exception is thrown (if overflow checking is turned on).

+ + Source   +Edit   + +
+
+
+
proc abs[T: float64 | float32](x: T): T {.noSideEffect, inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc add(x: var cstring; y: cstring) {.magic: "AppendStrStr", ...raises: [],
+                                       tags: [], forbids: [].}
+
+ + Appends y to x in place. Only implemented for JS backend. +

Example:

+
when defined(js):
+  var tmp: cstring = ""
+  tmp.add(cstring("ab"))
+  tmp.add(cstring("cd"))
+  doAssert tmp == cstring("abcd")
+ Source   +Edit   + +
+
+
+
proc add(x: var string; y: char) {.magic: "AppendStrCh", noSideEffect,
+                                   ...raises: [], tags: [], forbids: [].}
+
+ +

Appends y to x in place.

+

var tmp = ""
+tmp.add('a')
+tmp.add('b')
+assert(tmp == "ab")

+ + Source   +Edit   + +
+
+
+
proc add(x: var string; y: cstring) {.asmNoStackFrame, ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + Appends y to x in place. +

Example:

+
var tmp = ""
+tmp.add(cstring("ab"))
+tmp.add(cstring("cd"))
+doAssert tmp == "abcd"
+ Source   +Edit   + +
+
+
+
proc add(x: var string; y: string) {.magic: "AppendStrStr", noSideEffect,
+                                     ...raises: [], tags: [], forbids: [].}
+
+ +

Concatenates x and y in place.

+

See also strbasics.add.

+ +

Example:

+
var tmp = ""
+tmp.add("ab")
+tmp.add("cd")
+assert tmp == "abcd"
+ Source   +Edit   + +
+
+
+
proc add[T](x: var seq[T]; y: openArray[T]) {.noSideEffect.}
+
+ +

Generic proc for adding a container y to a container x.

+

For containers that have an order, add means append. New generic containers should also call their adding proc add for consistency. Generic code becomes much easier to write if the Nim naming scheme is respected.

+

See also:

+ + +

Example:

+
var a = @["a1", "a2"]
+a.add(["b1", "b2"])
+assert a == @["a1", "a2", "b1", "b2"]
+var c = @["c0", "c1", "c2", "c3"]
+a.add(c.toOpenArray(1, 2))
+assert a == @["a1", "a2", "b1", "b2", "c1", "c2"]
+ Source   +Edit   + +
+
+
+
proc add[T](x: var seq[T]; y: sink T) {.magic: "AppendSeqElem", noSideEffect,
+                                        nodestroy, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ +

Generic proc for adding a data item y to a container x.

+

For containers that have an order, add means append. New generic containers should also call their adding proc add for consistency. Generic code becomes much easier to write if the Nim naming scheme is respected.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc addEscapedChar(s: var string; c: char) {.noSideEffect, inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Adds a char to string s and applies the following escaping:
  • replaces any \ by \\
  • +
  • replaces any ' by \'
  • +
  • replaces any " by \"
  • +
  • replaces any \a by \\a
  • +
  • replaces any \b by \\b
  • +
  • replaces any \t by \\t
  • +
  • replaces any \n by \\n
  • +
  • replaces any \v by \\v
  • +
  • replaces any \f by \\f
  • +
  • replaces any \r by \\r
  • +
  • replaces any \e by \\e
  • +
  • replaces any other character not in the set {\21..\126} by \xHH where HH is its hexadecimal value
  • +
+

The procedure has been designed so that its output is usable for many different common syntaxes.

+
Warning: +This is not correct for producing ANSI C code!
+ + Source   +Edit   + +
+
+ +
+
+
+
proc addQuoted[T](s: var string; x: T)
+
+ +

Appends x to string s in place, applying quoting and escaping if x is a string or char.

+

See addEscapedChar for the escaping scheme. When x is a string, characters in the range {\128..\255} are never escaped so that multibyte UTF-8 characters are untouched (note that this behavior is different from addEscapedChar).

+

The Nim standard library uses this function on the elements of collections when producing a string representation of a collection. It is recommended to use this function as well for user-side collections. Users may overload addQuoted for custom (string-like) types if they want to implement a customized element representation.

+

var tmp = ""
+tmp.addQuoted(1)
+tmp.add(", ")
+tmp.addQuoted("string")
+tmp.add(", ")
+tmp.addQuoted('c')
+assert(tmp == """1, "string", 'c'""")

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `addr`[T](x: T): ptr T {.magic: "Addr", noSideEffect, ...raises: [], tags: [],
+                              forbids: [].}
+
+ + Builtin addr operator for taking the address of a memory location.
Note: +This works for let variables or parameters for better interop with C. When you use it to write a wrapper for a C library and take the address of let variables or parameters, you should always check that the original library does never write to data behind the pointer that is returned from this procedure.
+

Cannot be overloaded.

+

var
+  buf: seq[char] = @['a','b','c']
+  p = buf[1].addr
+echo p.repr # ref 0x7faa35c40059 --> 'b'
+echo p[]    # b

+ + Source   +Edit   + +
+
+ +
+
+
+
proc alignof(x: typedesc): int {.magic: "AlignOf", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc alignof[T](x: T): int {.magic: "AlignOf", noSideEffect, ...raises: [],
+                             tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc alloc0Impl(size: Natural): pointer {.noconv, ...gcsafe, tags: [], gcsafe,
+    raises: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc allocCStringArray(a: openArray[string]): cstringArray {....raises: [],
+    tags: [], forbids: [].}
+
+ + Creates a NULL terminated cstringArray from a. The result has to be freed with deallocCStringArray after it's not needed anymore. + Source   +Edit   + +
+
+ +
+
+
+
proc allocImpl(size: Natural): pointer {.noconv, ...gcsafe, tags: [], gcsafe,
+    raises: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc allocShared0Impl(size: Natural): pointer {.noconv, ...gcsafe, gcsafe,
+    raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc allocSharedImpl(size: Natural): pointer {.noconv, compilerproc, ...gcsafe,
+    gcsafe, raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `and`(a, b: typedesc): typedesc {.magic: "TypeTrait", noSideEffect,
+                                       ...raises: [], tags: [], forbids: [].}
+
+ + Constructs an and meta class. + Source   +Edit   + +
+
+
+
proc `and`(x, y: bool): bool {.magic: "And", noSideEffect, ...raises: [], tags: [],
+                               forbids: [].}
+
+ +

Boolean and; returns true if x == y == true (if both arguments are true).

+

Evaluation is lazy: if x is false, y will not even be evaluated.

+ + Source   +Edit   + +
+
+
+
proc `and`(x, y: int): int {.magic: "BitandI", noSideEffect, ...raises: [],
+                             tags: [], forbids: [].}
+
+ + Computes the bitwise and of numbers x and y. +

Example:

+
assert (0b0011 and 0b0101) == 0b0001
+assert (0b0111 and 0b1100) == 0b0100
+ Source   +Edit   + +
+
+
+
proc `and`(x, y: int8): int8 {.magic: "BitandI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `and`(x, y: int16): int16 {.magic: "BitandI", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `and`(x, y: int32): int32 {.magic: "BitandI", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `and`(x, y: int64): int64 {.magic: "BitandI", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `and`(x, y: uint): uint {.magic: "BitandI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + Computes the bitwise and of numbers x and y. + Source   +Edit   + +
+
+
+
proc `and`(x, y: uint8): uint8 {.magic: "BitandI", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `and`(x, y: uint16): uint16 {.magic: "BitandI", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `and`(x, y: uint32): uint32 {.magic: "BitandI", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `and`(x, y: uint64): uint64 {.magic: "BitandI", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc arrayWith[T](y: T; size: static int): array[size, T] {....raises: [].}
+
+ + Creates a new array filled with y. + Source   +Edit   + +
+
+ +
+
+
+
proc arrayWithDefault[T](size: static int): array[size, T] {....raises: [].}
+
+ + Creates a new array filled with default(T). + Source   +Edit   + +
+
+ +
+
+
+
proc ashr(x: int8; y: SomeInteger): int8 {.magic: "AshrI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc ashr(x: int16; y: SomeInteger): int16 {.magic: "AshrI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc ashr(x: int32; y: SomeInteger): int32 {.magic: "AshrI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc ashr(x: int64; y: SomeInteger): int64 {.magic: "AshrI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc ashr(x: int; y: SomeInteger): int {.magic: "AshrI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off.

+

Note that ashr is not an operator so use the normal function call syntax for it.

+

See also:

+ + +

Example:

+
assert ashr(0b0001_0000'i8, 2) == 0b0000_0100'i8
+assert ashr(0b1000_0000'i8, 8) == 0b1111_1111'i8
+assert ashr(0b1000_0000'i8, 1) == 0b1100_0000'i8
+ Source   +Edit   + +
+
+ +
+
+
+
proc astToStr[T](x: T): string {.magic: "AstToStr", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + Converts the AST of x into a string representation. This is very useful for debugging. + Source   +Edit   + +
+
+ +
+
+
+
func capacity(self: string): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Returns the current capacity of the string. +

Example:

+
var str = newStringOfCap(cap = 42)
+str.add "Nim"
+assert str.capacity == 42
+ Source   +Edit   + +
+
+
+
func capacity[T](self: seq[T]): int {.inline.}
+
+ + Returns the current capacity of the seq. +

Example:

+
var lst = newSeqOfCap[string](cap = 42)
+lst.add "Nim"
+assert lst.capacity == 42
+ Source   +Edit   + +
+
+ +
+
+
+
func card[T](x: set[T]): int {.magic: "Card", ...raises: [], tags: [], forbids: [].}
+
+ + Returns the cardinality of the set x, i.e. the number of elements in the set. +

Example:

+
var a = {1, 3, 5, 7}
+assert card(a) == 4
+var b = {1, 3, 5, 7, 5}
+assert card(b) == 4 # repeated 5 doesn't count
+ Source   +Edit   + +
+
+ +
+
+
+
func chr(u: range[0 .. 255]): char {.magic: "Chr", ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + Converts u to a char, same as char(u). +

Example:

+
doAssert chr(65) == 'A'
+doAssert chr(255) == '\255'
+doAssert chr(255) == char(255)
+doAssert not compiles chr(256)
+doAssert not compiles char(256)
+var x = 256
+doAssertRaises(RangeDefect): discard chr(x)
+doAssertRaises(RangeDefect): discard char(x)
+ Source   +Edit   + +
+
+ +
+
+
+
proc clamp[T](x, a, b: T): T
+
+ + Limits the value x within the interval [a, b]. This proc is equivalent to but faster than max(a, min(b, x)).
Warning: +a <= b is assumed and will not be checked (currently).
+

See also: math.clamp for a version that takes a Slice[T] instead.

+ +

Example:

+
assert (1.4).clamp(0.0, 1.0) == 1.0
+assert (0.5).clamp(0.0, 1.0) == 0.5
+assert 4.clamp(1, 3) == max(1, min(3, 4))
+ Source   +Edit   + +
+
+ +
+
+
+
proc cmp(x, y: string): int {.noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Compare proc for strings. More efficient than the generic version.

+

Note: The precise result values depend on the used C runtime library and can differ between operating systems!

+ + Source   +Edit   + +
+
+
+
proc cmp[T](x, y: T): int
+
+ +

Generic compare proc.

+

Returns:

+
  • a value less than zero, if x < y
  • +
  • a value greater than zero, if x > y
  • +
  • zero, if x == y
  • +
+

This is useful for writing generic algorithms without performance loss. This generic implementation uses the == and < operators.

+

import std/algorithm
+echo sorted(@[4, 2, 6, 5, 8, 7], cmp[int])

+ + Source   +Edit   + +
+
+ +
+
+
+
proc cmpMem(a, b: pointer; size: Natural): int {.inline, noSideEffect, ...tags: [],
+    raises: [], forbids: [].}
+
+ +

Compares the memory blocks a and b. size bytes will be compared.

+

Returns:

+
  • a value less than zero, if a < b
  • +
  • a value greater than zero, if a > b
  • +
  • zero, if a == b
  • +
+

Like any procedure dealing with raw memory this is unsafe.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc compileOption(option, arg: string): bool {.magic: "CompileOptionArg",
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Can be used to determine an enum compile-time option.

+

See also:

+ + +

Example:

+
when compileOption("opt", "size") and compileOption("gc", "boehm"):
+  discard "compiled with optimization for size and uses Boehm's GC"
+ Source   +Edit   + +
+
+
+
proc compileOption(option: string): bool {.magic: "CompileOption", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Can be used to determine an on|off compile-time option.

+

See also:

+ + +

Example: cmd: --floatChecks:off

+
static: doAssert not compileOption("floatchecks")
+{.push floatChecks: on.}
+static: doAssert compileOption("floatchecks")
+# floating point NaN and Inf checks enabled in this scope
+{.pop.}
+ Source   +Edit   + +
+
+ +
+
+
+
proc compiles(x: untyped): bool {.magic: "Compiles", noSideEffect, compileTime,
+                                  ...raises: [], tags: [], forbids: [].}
+
+ +

Special compile-time procedure that checks whether x can be compiled without any semantic error. This can be used to check whether a type supports some operation:

+

when compiles(3 + 4):
+  echo "'+' for integers is available"

+ + Source   +Edit   + +
+
+ +
+
+
+
proc contains[T](a: openArray[T]; item: T): bool {.inline.}
+
+ +

Returns true if item is in a or false if not found. This is a shortcut for find(a, item) >= 0.

+

This allows the in operator: a.contains(item) is the same as item in a.

+

var a = @[1, 3, 5]
+assert a.contains(5)
+assert 3 in a
+assert 99 notin a

+ + Source   +Edit   + +
+
+
+
func contains[T](x: set[T]; y: T): bool {.magic: "InSet", ...raises: [], tags: [],
+    forbids: [].}
+
+ +

One should overload this proc if one wants to overload the in operator.

+

The parameters are in reverse order! a in b is a template for contains(b, a). This is because the unification algorithm that Nim uses for overload resolution works from left to right. But for the in operator that would be the wrong direction for this piece of code:

+ +

Example:

+
var s: set[range['a'..'z']] = {'a'..'c'}
+assert s.contains('c')
+assert 'b' in s
+assert 'd' notin s
+assert set['a'..'z'] is set[range['a'..'z']]
If in had been declared as [T](elem: T, s: set[T]) then T would have been bound to char. But s is not compatible to type set[char]! The solution is to bind T to range['a'..'z']. This is achieved by reversing the parameters for contains; in then passes its arguments in reverse order. + Source   +Edit   + +
+
+
+
proc contains[U, V, W](s: HSlice[U, V]; value: W): bool {.noSideEffect, inline.}
+
+ +

Checks if value is within the range of s; returns true if value >= s.a and value <= s.b.

+

assert((1..3).contains(1) == true)
+assert((1..3).contains(2) == true)
+assert((1..3).contains(4) == false)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc copyMem(dest, source: pointer; size: Natural) {.inline, ...gcsafe, tags: [],
+    raises: [], forbids: [].}
+
+ + Copies the contents from the memory at source to the memory at dest. Exactly size bytes will be copied. The memory regions may not overlap. Like any procedure dealing with raw memory this is unsafe. + Source   +Edit   + +
+
+ +
+
+
+
proc create(T: typedesc; size = 1.Positive): ptr T:type {.inline, ...gcsafe,
+    raises: [].}
+
+ +

Allocates a new memory block with at least T.sizeof * size bytes.

+

The block has to be freed with resize(block, 0) or dealloc(block). The block is initialized with all bytes containing zero, so it is somewhat safer than createU.

+

The allocated memory belongs to its allocating thread! Use createShared to allocate from a shared heap.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc createShared(T: typedesc; size = 1.Positive): ptr T:type {.inline.}
+
+ +

Allocates a new memory block on the shared heap with at least T.sizeof * size bytes.

+

The block has to be freed with resizeShared(block, 0) or freeShared(block).

+

The block is initialized with all bytes containing zero, so it is somewhat safer than createSharedU.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc createSharedU(T: typedesc; size = 1.Positive): ptr T:type {.inline,
+    ...tags: [], gcsafe, raises: [].}
+
+ +

Allocates a new memory block on the shared heap with at least T.sizeof * size bytes.

+

The block has to be freed with resizeShared(block, 0) or freeShared(block).

+

The block is not initialized, so reading from it before writing to it is undefined behaviour!

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createU(T: typedesc; size = 1.Positive): ptr T:type {.inline, ...gcsafe,
+    raises: [].}
+
+ +

Allocates a new memory block with at least T.sizeof * size bytes.

+

The block has to be freed with resize(block, 0) or dealloc(block). The block is not initialized, so reading from it before writing to it is undefined behaviour!

+

The allocated memory belongs to its allocating thread! Use createSharedU to allocate from a shared heap.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cstringArrayToSeq(a: cstringArray): seq[string] {....raises: [], tags: [],
+    forbids: [].}
+
+ + Converts a cstringArray to a seq[string]. a is supposed to be terminated by nil. + Source   +Edit   + +
+
+
+
proc cstringArrayToSeq(a: cstringArray; len: Natural): seq[string] {....raises: [],
+    tags: [], forbids: [].}
+
+ + Converts a cstringArray to a seq[string]. a is supposed to be of length len. + Source   +Edit   + +
+
+ +
+
+
+
proc dealloc(p: pointer) {.noconv, compilerproc, ...gcsafe, gcsafe, raises: [],
+                           tags: [], forbids: [].}
+
+ +

Frees the memory allocated with alloc, alloc0, realloc, create or createU.

+

This procedure is dangerous! If one forgets to free the memory a leak occurs; if one tries to access freed memory (or just freeing it twice!) a core dump may happen or other memory may be corrupted.

+

The freed memory must belong to its allocating thread! Use deallocShared to deallocate from a shared heap.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc deallocCStringArray(a: cstringArray) {....raises: [], tags: [], forbids: [].}
+
+ + Frees a NULL terminated cstringArray. + Source   +Edit   + +
+
+ +
+
+
+
proc deallocImpl(p: pointer) {.noconv, ...gcsafe, tags: [], gcsafe, raises: [],
+                               forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc deallocShared(p: pointer) {.noconv, compilerproc, ...gcsafe, gcsafe,
+                                 raises: [], tags: [], forbids: [].}
+
+ +

Frees the memory allocated with allocShared, allocShared0 or reallocShared.

+

This procedure is dangerous! If one forgets to free the memory a leak occurs; if one tries to access freed memory (or just freeing it twice!) a core dump may happen or other memory may be corrupted.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc deallocSharedImpl(p: pointer) {.noconv, ...gcsafe, gcsafe, raises: [],
+                                     tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc debugEcho(x: varargs[typed, `$`]) {.magic: "Echo", noSideEffect, ...tags: [],
+    raises: [], forbids: [].}
+
+ + Same as echo, but as a special semantic rule, debugEcho pretends to be free of side effects, so that it can be used for debugging routines marked as noSideEffect. + Source   +Edit   + +
+
+ +
+
+
+
proc dec[T, V: Ordinal](x: var T; y: V = 1) {.magic: "Dec", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Decrements the ordinal x by y.

+

If such a value does not exist, OverflowDefect is raised or a compile time error occurs. This is a short notation for: x = pred(x, y).

+ +

Example:

+
var i = 2
+dec(i)
+assert i == 1
+dec(i, 3)
+assert i == -2
+ Source   +Edit   + +
+
+ +
+
+
+
proc declared(x: untyped): bool {.magic: "Declared", noSideEffect, compileTime,
+                                  ...raises: [], tags: [], forbids: [].}
+
+ +

Special compile-time procedure that checks whether x is declared. x has to be an identifier or a qualified identifier.

+

This can be used to check whether a library provides a certain feature or not:

+

when not declared(strutils.toUpper):
+  # provide our own toUpper proc here, because strutils is
+  # missing it.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc declaredInScope(x: untyped): bool {.magic: "DeclaredInScope", noSideEffect,
+    compileTime, ...raises: [], tags: [], forbids: [].}
+
+ + Special compile-time procedure that checks whether x is declared in the current scope. x has to be an identifier. + Source   +Edit   + +
+
+ +
+
+
+
proc deepCopy[T](x: var T; y: T) {.noSideEffect, magic: "DeepCopy", ...raises: [],
+                                   tags: [], forbids: [].}
+
+ +

Performs a deep copy of y and copies it into x.

+

This is also used by the code generator for the implementation of spawn.

+

For --mm:arc or --mm:orc deepcopy support has to be enabled via --deepcopy:on.

+ + Source   +Edit   + +
+
+
+
proc deepCopy[T](y: T): T
+
+ + Convenience wrapper around deepCopy overload. + Source   +Edit   + +
+
+ +
+
+
+
proc default[T](_: typedesc[T]): T {.magic: "Default", noSideEffect, ...raises: [],
+                                     tags: [], forbids: [].}
+
+ +

Returns the default value of the type T. Contrary to zeroDefault, it takes default fields of an object into consideration.

+

See also:

+ + +

Example: cmd: -d:nimPreviewRangeDefault

+
assert (int, float).default == (0, 0.0)
+type Foo = object
+  a: range[2..6]
+var x = Foo.default
+assert x.a == 2
+ Source   +Edit   + +
+
+ +
+
+
+
proc defined(x: untyped): bool {.magic: "Defined", noSideEffect, compileTime,
+                                 ...raises: [], tags: [], forbids: [].}
+
+ +

Special compile-time procedure that checks whether x is defined.

+

x is an external symbol introduced through the compiler's -d:x switch to enable build time conditionals:

+

when not defined(release):
+  # Do here programmer friendly expensive sanity checks.
+# Put here the normal code

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc del[T](x: var seq[T]; i: Natural) {.noSideEffect.}
+
+ +

Deletes the item at index i by putting x[high(x)] into position i.

+

This is an O(1) operation.

+

See also:

+
  • delete for preserving the order
  • +
+ +

Example:

+
var a = @[10, 11, 12, 13, 14]
+a.del(2)
+assert a == @[10, 11, 14, 13]
+ Source   +Edit   + +
+
+ +
+
+
+
proc delete[T](x: var seq[T]; i: Natural) {.noSideEffect, systemRaisesDefect.}
+
+ +

Deletes the item at index i by moving all x[i+1..^1] items by one position.

+

This is an O(n) operation.

+

See also:

+
  • del for O(1) operation
  • +
+ +

Example:

+
var s = @[1, 2, 3, 4, 5]
+s.delete(2)
+doAssert s == @[1, 2, 4, 5]
+ Source   +Edit   + +
+
+ +
+
+
+
proc dispose(x: ForeignCell) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `div`(x, y: int): int {.magic: "DivI", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ +

Computes the integer division.

+

This is roughly the same as math.trunc(x/y).int.

+ +

Example:

+
assert (1 div 2) == 0
+assert (2 div 2) == 1
+assert (3 div 2) == 1
+assert (7 div 3) == 2
+assert (-7 div 3) == -2
+assert (7 div -3) == -2
+assert (-7 div -3) == 2
+ Source   +Edit   + +
+
+
+
proc `div`(x, y: int8): int8 {.magic: "DivI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `div`(x, y: int16): int16 {.magic: "DivI", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `div`(x, y: int32): int32 {.magic: "DivI", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `div`(x, y: int64): int64 {.magic: "DivI", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `div`(x, y: uint): uint {.magic: "DivU", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + Computes the integer division for unsigned integers. This is roughly the same as trunc(x/y). + Source   +Edit   + +
+
+
+
proc `div`(x, y: uint8): uint8 {.magic: "DivU", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `div`(x, y: uint16): uint16 {.magic: "DivU", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `div`(x, y: uint32): uint32 {.magic: "DivU", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `div`(x, y: uint64): uint64 {.magic: "DivU", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc echo(x: varargs[typed, `$`]) {.magic: "Echo", ...gcsafe, sideEffect,
+                                    ...raises: [], tags: [], forbids: [].}
+
+ +

Writes and flushes the parameters to the standard output.

+

Special built-in that takes a variable number of arguments. Each argument is converted to a string via $, so it works for user-defined types that have an overloaded $ operator. It is roughly equivalent to writeLine(stdout, x); flushFile(stdout), but available for the JavaScript target too.

+

Unlike other IO operations this is guaranteed to be thread-safe as echo is very often used for debugging convenience. If you want to use echo inside a proc without side effects you can use debugEcho instead.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc ensureMove[T](x: T): T {.magic: "EnsureMove", noSideEffect, ...raises: [],
+                              tags: [], forbids: [].}
+
+ + Ensures that x is moved to the new location, otherwise it gives an error at the compile time. +

Example:

+
proc foo =
+  var x = "Hello"
+  let y = ensureMove(x)
+  doAssert y == "Hello"
+foo()
+ Source   +Edit   + +
+
+ +
+
+
+
proc equalMem(a, b: pointer; size: Natural): bool {.inline, noSideEffect,
+    ...tags: [], raises: [], forbids: [].}
+
+ +

Compares the memory blocks a and b. size bytes will be compared.

+

If the blocks are equal, true is returned, false otherwise. Like any procedure dealing with raw memory this is unsafe.

+ + Source   +Edit   + +
+
+ +
+
+
+
func excl[T](x: var set[T]; y: T) {.magic: "Excl", ...raises: [], tags: [],
+                                    forbids: [].}
+
+ +

Excludes element y from the set x.

+

This is the same as x = x - {y}, but it might be more efficient.

+ +

Example:

+
var b = {2, 3, 5, 6, 12, 54}
+b.excl(5)
+assert b == {2, 3, 6, 12, 54}
+ Source   +Edit   + +
+
+ +
+
+
+
proc find[T, S](a: T; item: S): int {.inline.}
+
+ + Returns the first index of item in a or -1 if not found. This requires appropriate items and == operations to work. + Source   +Edit   + +
+
+ +
+
+
+
proc finished[T: iterator {.closure.}](x: T): bool {.noSideEffect, inline,
+    magic: "Finished", ...raises: [], tags: [], forbids: [].}
+
+ + It can be used to determine if a first class iterator has finished. + Source   +Edit   + +
+
+ +
+
+
+
proc freeShared[T](p: ptr T) {.inline, ...gcsafe, raises: [].}
+
+ +

Frees the memory allocated with createShared, createSharedU or resizeShared.

+

This procedure is dangerous! If one forgets to free the memory a leak occurs; if one tries to access freed memory (or just freeing it twice!) a core dump may happen or other memory may be corrupted.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc GC_disableMarkAndSweep() {....raises: [], tags: [], forbids: [].}
+
+ + For --mm:orc an alias for GC_disableOrc. + Source   +Edit   + +
+
+ +
+
+
+
proc GC_disableOrc() {....raises: [], tags: [], forbids: [].}
+
+ + Disables the cycle collector subsystem of --mm:orc. This is a --mm:orc specific API. Check with when defined(gcOrc) for its existence. + Source   +Edit   + +
+
+ +
+
+
+
proc GC_enableMarkAndSweep() {....raises: [], tags: [], forbids: [].}
+
+ + For --mm:orc an alias for GC_enableOrc. + Source   +Edit   + +
+
+ +
+
+
+
proc GC_enableOrc() {....raises: [], tags: [], forbids: [].}
+
+ + Enables the cycle collector subsystem of --mm:orc. This is a --mm:orc specific API. Check with when defined(gcOrc) for its existence. + Source   +Edit   + +
+
+ +
+
+
+
proc GC_fullCollect() {....raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + Forces a full garbage collection pass. With --mm:orc triggers the cycle collector. This is an alias for GC_runOrc. + Source   +Edit   + +
+
+ +
+
+
+
proc GC_getStatistics(): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc GC_partialCollect(limit: int) {....raises: [Exception], tags: [RootEffect],
+                                     forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc GC_prepareOrc(): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc GC_ref[T](x: ref T)
+
+ + New runtime only supports this operation for 'ref T'. + Source   +Edit   + +
+
+ +
+
+
+
proc GC_runOrc() {....raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + Forces a cycle collection pass. + Source   +Edit   + +
+
+ +
+
+
+
proc GC_unref[T](x: ref T)
+
+ + New runtime only supports this operation for 'ref T'. + Source   +Edit   + +
+
+ +
+
+
+
proc getAllocStats(): AllocStats {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getCurrentException(): ref Exception {.compilerproc, inline, ...gcsafe,
+    raises: [], tags: [], forbids: [].}
+
+ + Retrieves the current exception; if there is none, nil is returned. + Source   +Edit   + +
+
+ +
+
+
+
proc getCurrentExceptionMsg(): string {.inline, ...gcsafe, raises: [], tags: [],
+                                        forbids: [].}
+
+ + Retrieves the error message that was attached to the current exception; if there is none, "" is returned. + Source   +Edit   + +
+
+ +
+
+
+
proc getFrame(): PFrame {.compilerproc, inline, ...raises: [], tags: [],
+                          forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getFrameState(): FrameState {.compilerproc, inline, ...raises: [], tags: [],
+                                   forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getFreeMem(): int {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ + Returns the number of bytes that are owned by the process, but do not hold any meaningful data. + Source   +Edit   + +
+
+ +
+
+
+
proc getFreeSharedMem(): int {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ + Returns the number of bytes that are owned by the process on the shared heap, but do not hold any meaningful data. This is only available when threads are enabled. + Source   +Edit   + +
+
+ +
+
+
+
proc getMaxMem(): int {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getOccupiedMem(): int {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ + Returns the number of bytes that are owned by the process and hold data. + Source   +Edit   + +
+
+ +
+
+
+
proc getOccupiedSharedMem(): int {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ + Returns the number of bytes that are owned by the process on the shared heap and hold data. This is only available when threads are enabled. + Source   +Edit   + +
+
+ +
+
+
+
proc getStackTrace(): string {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ + Gets the current stack trace. This only works for debug builds. + Source   +Edit   + +
+
+
+
proc getStackTrace(e: ref Exception): string {....gcsafe, raises: [], tags: [],
+    forbids: [].}
+
+ + Gets the stack trace associated with e, which is the stack that lead to the raise statement. This only works for debug builds. + Source   +Edit   + +
+
+ +
+
+
+
proc getStackTraceEntries(): seq[StackTraceEntry] {....raises: [], tags: [],
+    forbids: [].}
+
+ + Returns the stack trace entries for the current stack trace. This is not yet available for the JS backend. + Source   +Edit   + +
+
+
+
proc getStackTraceEntries(e: ref Exception): lent seq[StackTraceEntry] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getThreadId(): int {....raises: [], tags: [], forbids: [].}
+
+ + Gets the ID of the currently running thread. + Source   +Edit   + +
+
+ +
+
+
+
proc getTotalMem(): int {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ + Returns the number of bytes that are owned by the process. + Source   +Edit   + +
+
+ +
+
+
+
proc getTotalSharedMem(): int {....gcsafe, raises: [], tags: [], forbids: [].}
+
+ + Returns the number of bytes on the shared heap that are owned by the process. This is only available when threads are enabled. + Source   +Edit   + +
+
+ +
+
+
+
proc getTypeInfo[T](x: T): pointer {.magic: "GetTypeInfo", ...gcsafe, raises: [],
+                                     tags: [], forbids: [].}
+
+ +

Get type information for x.

+

Ordinary code should not use this, but the typeinfo module instead.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc gorge(command: string; input = ""; cache = ""): string {.
+    magic: "StaticExec", ...raises: [], tags: [], forbids: [].}
+
+ + This is an alias for staticExec. + Source   +Edit   + +
+
+ +
+
+
+
proc gorgeEx(command: string; input = ""; cache = ""): tuple[output: string,
+    exitCode: int] {....raises: [], tags: [], forbids: [].}
+
+ + Similar to gorge but also returns the precious exit code. + Source   +Edit   + +
+
+ +
+
+
+
proc grow[T](x: var seq[T]; newLen: Natural; value: T) {.nodestroy.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc high(T: typedesc[SomeFloat]): T:type
+
+ + + Source   +Edit   + +
+
+
+
proc high(x: cstring): int {.magic: "High", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ +

Returns the highest possible index of a compatible string x. This is sometimes an O(n) operation.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc high(x: string): int {.magic: "High", noSideEffect, ...raises: [], tags: [],
+                            forbids: [].}
+
+ +

Returns the highest possible index of a string x.

+

var str = "Hello world!"
+high(str) # => 11

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc high[I, T](x: array[I, T]): I {.magic: "High", noSideEffect, ...raises: [],
+                                     tags: [], forbids: [].}
+
+ +

Returns the highest possible index of an array x.

+

For empty arrays, the return type is int.

+

var arr = [1, 2, 3, 4, 5, 6, 7]
+high(arr) # => 6
+for i in low(arr)..high(arr):
+  echo arr[i]

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc high[I, T](x: typedesc[array[I, T]]): I {.magic: "High", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the highest possible index of an array type.

+

For empty arrays, the return type is int.

+

high(array[7, int]) # => 6

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc high[T: Ordinal | enum | range](x: T): T {.magic: "High", noSideEffect, ...deprecated: "Deprecated since v1.4; there should not be `high(value)`. Use `high(type)`.",
+    raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v1.4; there should not be `high(value)`. Use `high(type)`. +
+ +

Returns the highest possible value of an ordinal value x.

+

As a special semantic rule, x may also be a type identifier.

+

This proc is deprecated, use this one instead:

+ +

high(2) # => 9223372036854775807

+ + Source   +Edit   + +
+
+
+
proc high[T: Ordinal | enum | range](x: typedesc[T]): T {.magic: "High",
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the highest possible value of an ordinal or enum type.

+

high(int) is Nim's way of writing INT_MAX or MAX_INT.

+

high(int) # => 9223372036854775807

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc high[T](x: openArray[T]): int {.magic: "High", noSideEffect, ...raises: [],
+                                     tags: [], forbids: [].}
+
+ +

Returns the highest possible index of a sequence x.

+

var s = @[1, 2, 3, 4, 5, 6, 7]
+high(s) # => 6
+for i in low(s)..high(s):
+  echo s[i]

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inc[T, V: Ordinal](x: var T; y: V = 1) {.magic: "Inc", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Increments the ordinal x by y.

+

If such a value does not exist, OverflowDefect is raised or a compile time error occurs. This is a short notation for: x = succ(x, y).

+ +

Example:

+
var i = 2
+inc(i)
+assert i == 3
+inc(i, 3)
+assert i == 6
+ Source   +Edit   + +
+
+ +
+
+
+
func incl[T](x: var set[T]; y: T) {.magic: "Incl", ...raises: [], tags: [],
+                                    forbids: [].}
+
+ +

Includes element y in the set x.

+

This is the same as x = x + {y}, but it might be more efficient.

+ +

Example:

+
var a = {1, 3, 5}
+a.incl(2)
+assert a == {1, 2, 3, 5}
+a.incl(4)
+assert a == {1, 2, 3, 4, 5}
+ Source   +Edit   + +
+
+ +
+
+
+
proc insert(x: var string; item: string; i = 0.Natural) {.noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Inserts item into x at position i.

+

var a = "abc"
+a.insert("zz", 0) # a <- "zzabc"

+ + Source   +Edit   + +
+
+
+
proc insert[T](x: var seq[T]; item: sink T; i = 0.Natural) {.noSideEffect.}
+
+ +

Inserts item into x at position i.

+

var i = @[1, 3, 5]
+i.insert(99, 0) # i <- @[99, 1, 3, 5]

+ + Source   +Edit   + +
+
+ +
+
+
+
proc instantiationInfo(index = -1; fullPaths = false): tuple[filename: string,
+    line: int, column: int] {.magic: "InstantiationInfo", noSideEffect,
+                              ...raises: [], tags: [], forbids: [].}
+
+ +

Provides access to the compiler's instantiation stack line information of a template.

+

While similar to the caller info of other languages, it is determined at compile time.

+

This proc is mostly useful for meta programming (eg. assert template) to retrieve information about the current filename and line number. Example:

+

import std/strutils
+
+template testException(exception, code: untyped): typed =
+  try:
+    let pos = instantiationInfo()
+    discard(code)
+    echo "Test failure at $1:$2 with '$3'" % [pos.filename,
+      $pos.line, astToStr(code)]
+    assert false, "A test expecting failure succeeded?"
+  except exception:
+    discard
+
+proc tester(pos: int): int =
+  let
+    a = @[1, 2, 3]
+  result = a[pos]
+
+when isMainModule:
+  testException(IndexDefect, tester(30))
+  testException(IndexDefect, tester(1))
+  # --> Test failure at example.nim:20 with 'tester(1)'

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `is`[T, S](x: T; y: S): bool {.magic: "Is", noSideEffect, ...raises: [],
+                                    tags: [], forbids: [].}
+
+ +

Checks if T is of the same type as S.

+

For a negated version, use isnot.

+

assert 42 is int
+assert @[1, 2] is seq
+
+proc test[T](a: T): int =
+  when (T is int):
+    return a
+  else:
+    return 0
+
+assert(test[int](3) == 3)
+assert(test[string]("xyz") == 0)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc isNil(x: cstring): bool {.noSideEffect, magic: "IsNil", ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc isNil(x: pointer): bool {.noSideEffect, magic: "IsNil", ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc isNil[T: proc | iterator {.closure.}](x: T): bool {.noSideEffect,
+    magic: "IsNil", ...raises: [], tags: [], forbids: [].}
+
+ + Fast check whether x is nil. This is sometimes more efficient than == nil. + Source   +Edit   + +
+
+
+
proc isNil[T](x: ptr T): bool {.noSideEffect, magic: "IsNil", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc isNil[T](x: ref T): bool {.noSideEffect, magic: "IsNil", ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isNotForeign(x: ForeignCell): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isUniqueRef[T](x: ref T): bool {.inline.}
+
+ + Returns true if the object x points to is uniquely referenced. Such an object can potentially be passed over to a different thread safely, if great care is taken. This queries the internal reference count of the object which is subject to lots of optimizations! In other words the value of isUniqueRef can depend on the used compiler version and optimizer setting. Nevertheless it can be used as a very valuable debugging tool and can be used to specify the constraints of a threading related API via assert isUniqueRef(x). + Source   +Edit   + +
+
+ +
+
+
+
proc iterToProc(iter: typed; envType: typedesc; procName: untyped) {.
+    magic: "Plugin", compileTime, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func len(x: (type array) | array): int {.magic: "LengthArray", ...raises: [],
+    tags: [], forbids: [].}
+
+ + Returns the length of an array or an array type. This is roughly the same as high(T)-low(T)+1. +

Example:

+
var a = [1, 1, 1]
+assert a.len == 3
+assert array[0, float].len == 0
+static: assert array[-2..2, float].len == 5
+ Source   +Edit   + +
+
+
+
proc len(x: cstring): int {.magic: "LengthStr", noSideEffect, ...raises: [],
+                            tags: [], forbids: [].}
+
+ +

Returns the length of a compatible string. This is an O(n) operation except in js at runtime.

+

Note: On the JS backend this currently counts UTF-16 code points instead of bytes at runtime (not at compile time). For now, if you need the byte length of the UTF-8 encoding, convert to string with $ first then call len.

+ +

Example:

+
doAssert len(cstring"abc") == 3
+doAssert len(cstring r"ab\0c") == 5 # \0 is escaped
+doAssert len(cstring"ab\0c") == 5 # ditto
+var a: cstring = "ab\0c"
+when defined(js): doAssert a.len == 4 # len ignores \0 for js
+else: doAssert a.len == 2 # \0 is a null terminator
+static:
+  var a2: cstring = "ab\0c"
+  doAssert a2.len == 2 # \0 is a null terminator, even in js vm
+ Source   +Edit   + +
+
+
+
func len(x: string): int {.magic: "LengthStr", ...raises: [], tags: [], forbids: [].}
+
+ + Returns the length of a string. +

Example:

+
assert "abc".len == 3
+assert "".len == 0
+assert string.default.len == 0
+ Source   +Edit   + +
+
+
+
func len[T](x: seq[T]): int {.magic: "LengthSeq", ...raises: [], tags: [],
+                              forbids: [].}
+
+ + Returns the length of x. +

Example:

+
assert @[0, 1].len == 2
+assert seq[int].default.len == 0
+assert newSeq[int](3).len == 3
+let s = newSeqOfCap[int](3)
+assert s.len == 0
+ Source   +Edit   + +
+
+
+
func len[T](x: set[T]): int {.magic: "Card", ...raises: [], tags: [], forbids: [].}
+
+ + An alias for card(x). + Source   +Edit   + +
+
+
+
func len[TOpenArray: openArray | varargs](x: TOpenArray): int {.
+    magic: "LengthOpenArray", ...raises: [], tags: [], forbids: [].}
+
+ + Returns the length of an openArray. +

Example:

+
proc bar[T](a: openArray[T]): int = len(a)
+assert bar([1,2]) == 2
+assert [1,2].len == 2
+ Source   +Edit   + +
+
+
+
proc len[U: Ordinal; V: Ordinal](x: HSlice[U, V]): int {.noSideEffect, inline.}
+
+ +

Length of ordinal slice. When x.b < x.a returns zero length.

+

assert((0..5).len == 6)
+assert((5..2).len == 0)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc locals(): RootObj {.magic: "Plugin", noSideEffect, ...raises: [], tags: [],
+                         forbids: [].}
+
+ +

Generates a tuple constructor expression listing all the local variables in the current scope.

+

This is quite fast as it does not rely on any debug or runtime information. Note that in contrast to what the official signature says, the return type is not RootObj but a tuple of a structure that depends on the current scope. Example:

+

proc testLocals() =
+  var
+    a = "something"
+    b = 4
+    c = locals()
+    d = "super!"
+  
+  b = 1
+  for name, value in fieldPairs(c):
+    echo "name ", name, " with value ", value
+  echo "B is ", b
+# -> name a with value something
+# -> name b with value 4
+# -> B is 1

+ + Source   +Edit   + +
+
+ +
+
+
+
proc low(T: typedesc[SomeFloat]): T:type
+
+ + + Source   +Edit   + +
+
+
+
proc low(x: cstring): int {.magic: "Low", noSideEffect, ...raises: [], tags: [],
+                            forbids: [].}
+
+ +

Returns the lowest possible index of a compatible string x.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc low(x: string): int {.magic: "Low", noSideEffect, ...raises: [], tags: [],
+                           forbids: [].}
+
+ +

Returns the lowest possible index of a string x.

+

var str = "Hello world!"
+low(str) # => 0

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc low[I, T](x: array[I, T]): I {.magic: "Low", noSideEffect, ...raises: [],
+                                    tags: [], forbids: [].}
+
+ +

Returns the lowest possible index of an array x.

+

For empty arrays, the return type is int.

+

var arr = [1, 2, 3, 4, 5, 6, 7]
+low(arr) # => 0
+for i in low(arr)..high(arr):
+  echo arr[i]

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc low[I, T](x: typedesc[array[I, T]]): I {.magic: "Low", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the lowest possible index of an array type.

+

For empty arrays, the return type is int.

+

low(array[7, int]) # => 0

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc low[T: Ordinal | enum | range](x: T): T {.magic: "Low", noSideEffect, ...deprecated: "Deprecated since v1.4; there should not be `low(value)`. Use `low(type)`.",
+    raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v1.4; there should not be `low(value)`. Use `low(type)`. +
+ +

Returns the lowest possible value of an ordinal value x. As a special semantic rule, x may also be a type identifier.

+

This proc is deprecated, use this one instead:

+ +

low(2) # => -9223372036854775808

+ + Source   +Edit   + +
+
+
+
proc low[T: Ordinal | enum | range](x: typedesc[T]): T {.magic: "Low",
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the lowest possible value of an ordinal or enum type.

+

low(int) is Nim's way of writing INT_MIN or MIN_INT.

+

low(int) # => -9223372036854775808

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc low[T](x: openArray[T]): int {.magic: "Low", noSideEffect, ...raises: [],
+                                    tags: [], forbids: [].}
+
+ +

Returns the lowest possible index of a sequence x.

+

var s = @[1, 2, 3, 4, 5, 6, 7]
+low(s) # => 0
+for i in low(s)..high(s):
+  echo s[i]

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc max(x, y: float32): float32 {.noSideEffect, inline, ...raises: [], tags: [],
+                                   forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc max(x, y: float64): float64 {.noSideEffect, inline, ...raises: [], tags: [],
+                                   forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc max(x, y: int): int {.magic: "MaxI", noSideEffect, ...raises: [], tags: [],
+                           forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc max(x, y: int8): int8 {.magic: "MaxI", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc max(x, y: int16): int16 {.magic: "MaxI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc max(x, y: int32): int32 {.magic: "MaxI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc max(x, y: int64): int64 {.magic: "MaxI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + The maximum value of two integers. + Source   +Edit   + +
+
+
+
proc max[T: not SomeFloat](x, y: T): T {.inline.}
+
+ + Generic maximum operator of 2 values based on <=. + Source   +Edit   + +
+
+
+
proc max[T](x: openArray[T]): T
+
+ + The maximum value of x. T needs to have a < operator. + Source   +Edit   + +
+
+ +
+
+
+
proc min(x, y: float32): float32 {.noSideEffect, inline, ...raises: [], tags: [],
+                                   forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc min(x, y: float64): float64 {.noSideEffect, inline, ...raises: [], tags: [],
+                                   forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc min(x, y: int): int {.magic: "MinI", noSideEffect, ...raises: [], tags: [],
+                           forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc min(x, y: int8): int8 {.magic: "MinI", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc min(x, y: int16): int16 {.magic: "MinI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc min(x, y: int32): int32 {.magic: "MinI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc min(x, y: int64): int64 {.magic: "MinI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + The minimum value of two integers. + Source   +Edit   + +
+
+
+
proc min[T: not SomeFloat](x, y: T): T {.inline.}
+
+ + Generic minimum operator of 2 values based on <=. + Source   +Edit   + +
+
+
+
proc min[T](x: openArray[T]): T
+
+ + The minimum value of x. T needs to have a < operator. + Source   +Edit   + +
+
+ +
+
+
+
proc `mod`(x, y: int): int {.magic: "ModI", noSideEffect, ...raises: [], tags: [],
+                             forbids: [].}
+
+ +

Computes the integer modulo operation (remainder).

+

This is the same as x - (x div y) * y.

+ +

Example:

+
assert (7 mod 5) == 2
+assert (-7 mod 5) == -2
+assert (7 mod -5) == 2
+assert (-7 mod -5) == -2
+ Source   +Edit   + +
+
+
+
proc `mod`(x, y: int8): int8 {.magic: "ModI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `mod`(x, y: int16): int16 {.magic: "ModI", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `mod`(x, y: int32): int32 {.magic: "ModI", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `mod`(x, y: int64): int64 {.magic: "ModI", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `mod`(x, y: uint): uint {.magic: "ModU", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + Computes the integer modulo operation (remainder) for unsigned integers. This is the same as x - (x div y) * y. + Source   +Edit   + +
+
+
+
proc `mod`(x, y: uint8): uint8 {.magic: "ModU", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `mod`(x, y: uint16): uint16 {.magic: "ModU", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `mod`(x, y: uint32): uint32 {.magic: "ModU", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `mod`(x, y: uint64): uint64 {.magic: "ModU", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc move[T](x: var T): T {.magic: "Move", noSideEffect, ...raises: [], tags: [],
+                            forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc moveMem(dest, source: pointer; size: Natural) {.inline, ...gcsafe, tags: [],
+    raises: [], forbids: [].}
+
+ +

Copies the contents from the memory at source to the memory at dest.

+

Exactly size bytes will be copied. The memory regions may overlap, moveMem handles this case appropriately and is thus somewhat more safe than copyMem. Like any procedure dealing with raw memory this is still unsafe, though.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc new(t: typedesc): auto
+
+ +

Creates a new object of type T and returns a safe (traced) reference to it as result value.

+

When T is a ref type then the resulting type will be T, otherwise it will be ref T.

+ + Source   +Edit   + +
+
+
+
proc new[T](a: var ref T) {.magic: "New", noSideEffect, ...raises: [], tags: [],
+                            forbids: [].}
+
+ + Creates a new object of type T and returns a safe (traced) reference to it in a. + Source   +Edit   + +
+
+
+
proc new[T](a: var ref T; finalizer: proc (x: ref T) {.nimcall.}) {.
+    magic: "NewFinalize", noSideEffect,
+    ...deprecated: "pass a finalizer of the \'proc (x: T) {.nimcall.}\' type",
+    raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: pass a finalizer of the 'proc (x: T) {.nimcall.}' type +
+ + + Source   +Edit   + +
+
+
+
proc new[T](a: var ref T; finalizer: proc (x: T) {.nimcall.}) {.
+    magic: "NewFinalize", noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new object of type T and returns a safe (traced) reference to it in a.

+

When the garbage collector frees the object, finalizer is called. The finalizer may not keep a reference to the object pointed to by x. The finalizer cannot prevent the GC from freeing the object.

+

Note: The finalizer refers to the type T, not to the object! This means that for each object of type T the finalizer will be called!

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newSeq[T](len = 0.Natural): seq[T]
+
+ +

Creates a new sequence of type seq[T] with length len.

+

Note that the sequence will be filled with zeroed entries. After the creation of the sequence you should assign entries to the sequence instead of adding them.

+

var inputStrings = newSeq[string](3)
+assert len(inputStrings) == 3
+inputStrings[0] = "The fourth"
+inputStrings[1] = "assignment"
+inputStrings[2] = "would crash"
+#inputStrings[3] = "out of bounds"

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc newSeq[T](s: var seq[T]; len: Natural) {.magic: "NewSeq", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new sequence of type seq[T] with length len.

+

This is equivalent to s = @[]; setlen(s, len), but more efficient since no reallocation is needed.

+

Note that the sequence will be filled with zeroed entries. After the creation of the sequence you should assign entries to the sequence instead of adding them. Example:

+

var inputStrings: seq[string]
+newSeq(inputStrings, 3)
+assert len(inputStrings) == 3
+inputStrings[0] = "The fourth"
+inputStrings[1] = "assignment"
+inputStrings[2] = "would crash"
+#inputStrings[3] = "out of bounds"

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newSeqOfCap[T](cap: Natural): seq[T] {.magic: "NewSeqOfCap", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new sequence of type seq[T] with length zero and capacity cap. Example:

+

var x = newSeqOfCap[int](5)
+assert len(x) == 0
+x.add(10)
+assert len(x) == 1

+ + Source   +Edit   + +
+
+ +
+
+
+
func newSeqUninit[T](len: Natural): seq[T]
+
+ +

Creates a new sequence of type seq[T] with length len.

+

Only available for types, which don't contain managed memory or have destructors. Note that the sequence will be uninitialized. After the creation of the sequence you should assign entries to the sequence instead of adding them.

+ +

Example:

+
var x = newSeqUninit[int](3)
+assert len(x) == 3
+x[0] = 10
+ Source   +Edit   + +
+
+ +
+
+
+
proc newSeqUninitialized[T: SomeNumber](len: Natural): seq[T] {.
+    ...deprecated: "Use `newSeqUninit` instead".}
+
+
+ Deprecated: Use `newSeqUninit` instead +
+ +

Creates a new sequence of type seq[T] with length len.

+

Only available for numbers types. Note that the sequence will be uninitialized. After the creation of the sequence you should assign entries to the sequence instead of adding them. Example:

+

var x = newSeqUninitialized[int](3)
+assert len(x) == 3
+x[0] = 10

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newString(len: Natural): string {.magic: "NewString",
+                                       importc: "mnewString", noSideEffect,
+                                       ...raises: [], tags: [], forbids: [].}
+
+ +

Returns a new string of length len. One needs to fill the string character after character with the index operator s[i].

+

This procedure exists only for optimization purposes; the same effect can be achieved with the & operator or with add.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newStringOfCap(cap: Natural): string {.magic: "NewStringOfCap",
+    importc: "rawNewString", noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Returns a new string of length 0 but with capacity cap.

+

This procedure exists only for optimization purposes; the same effect can be achieved with the & operator or with add.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc newStringUninit(len: Natural): string {....raises: [], tags: [], forbids: [].}
+
+ +

Returns a new string of length len but with uninitialized content. One needs to fill the string character after character with the index operator s[i].

+

This procedure exists only for optimization purposes; the same effect can be achieved with the & operator or with add.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `not`(a: typedesc): typedesc {.magic: "TypeTrait", noSideEffect,
+                                    ...raises: [], tags: [], forbids: [].}
+
+ + Constructs an not meta class. + Source   +Edit   + +
+
+
+
proc `not`(x: bool): bool {.magic: "Not", noSideEffect, ...raises: [], tags: [],
+                            forbids: [].}
+
+ + Boolean not; returns true if x == false. + Source   +Edit   + +
+
+
+
proc `not`(x: int): int {.magic: "BitnotI", noSideEffect, ...raises: [], tags: [],
+                          forbids: [].}
+
+ + Computes the bitwise complement of the integer x. +

Example:

+
assert not 0'u8 == 255
+assert not 0'i8 == -1
+assert not 1000'u16 == 64535
+assert not 1000'i16 == -1001
+ Source   +Edit   + +
+
+
+
proc `not`(x: int8): int8 {.magic: "BitnotI", noSideEffect, ...raises: [],
+                            tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `not`(x: int16): int16 {.magic: "BitnotI", noSideEffect, ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `not`(x: int32): int32 {.magic: "BitnotI", noSideEffect, ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `not`(x: int64): int64 {.magic: "BitnotI", noSideEffect, ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `not`(x: uint): uint {.magic: "BitnotI", noSideEffect, ...raises: [],
+                            tags: [], forbids: [].}
+
+ + Computes the bitwise complement of the integer x. + Source   +Edit   + +
+
+
+
proc `not`(x: uint8): uint8 {.magic: "BitnotI", noSideEffect, ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `not`(x: uint16): uint16 {.magic: "BitnotI", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `not`(x: uint32): uint32 {.magic: "BitnotI", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `not`(x: uint64): uint64 {.magic: "BitnotI", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `of`[T, S](x: T; y: typedesc[S]): bool {.magic: "Of", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Checks if x is an instance of y. +

Example:

+
type
+  Base = ref object of RootObj
+  Sub1 = ref object of Base
+  Sub2 = ref object of Base
+  Unrelated = ref object
+
+var base: Base = Sub1() # downcast
+doAssert base of Base # generates `CondTrue` (statically true)
+doAssert base of Sub1
+doAssert base isnot Sub1
+doAssert not (base of Sub2)
+
+base = Sub2() # re-assign
+doAssert base of Sub2
+doAssert Sub2(base) != nil # upcast
+doAssertRaises(ObjectConversionDefect): discard Sub1(base)
+
+var sub1 = Sub1()
+doAssert sub1 of Base
+doAssert sub1.Base of Sub1
+
+doAssert not compiles(base of Unrelated)
+ Source   +Edit   + +
+
+ +
+
+
+
proc onThreadDestruction(handler: proc () {.closure, ...gcsafe, raises: [].}) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Registers a thread local handler that is called at the thread's destruction.

+

A thread is destructed when the .thread proc returns normally or when it raises an exception. Note that unhandled exceptions in a thread nevertheless cause the whole process to die.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `or`(a, b: typedesc): typedesc {.magic: "TypeTrait", noSideEffect,
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + Constructs an or meta class. + Source   +Edit   + +
+
+
+
proc `or`(x, y: bool): bool {.magic: "Or", noSideEffect, ...raises: [], tags: [],
+                              forbids: [].}
+
+ +

Boolean or; returns true if not (not x and not y) (if any of the arguments is true).

+

Evaluation is lazy: if x is true, y will not even be evaluated.

+ + Source   +Edit   + +
+
+
+
proc `or`(x, y: int): int {.magic: "BitorI", noSideEffect, ...raises: [], tags: [],
+                            forbids: [].}
+
+ + Computes the bitwise or of numbers x and y. +

Example:

+
assert (0b0011 or 0b0101) == 0b0111
+assert (0b0111 or 0b1100) == 0b1111
+ Source   +Edit   + +
+
+
+
proc `or`(x, y: int8): int8 {.magic: "BitorI", noSideEffect, ...raises: [],
+                              tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `or`(x, y: int16): int16 {.magic: "BitorI", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `or`(x, y: int32): int32 {.magic: "BitorI", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `or`(x, y: int64): int64 {.magic: "BitorI", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `or`(x, y: uint): uint {.magic: "BitorI", noSideEffect, ...raises: [],
+                              tags: [], forbids: [].}
+
+ + Computes the bitwise or of numbers x and y. + Source   +Edit   + +
+
+
+
proc `or`(x, y: uint8): uint8 {.magic: "BitorI", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `or`(x, y: uint16): uint16 {.magic: "BitorI", noSideEffect, ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `or`(x, y: uint32): uint32 {.magic: "BitorI", noSideEffect, ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `or`(x, y: uint64): uint64 {.magic: "BitorI", noSideEffect, ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func ord[T: Ordinal | enum](x: T): int {.magic: "Ord", ...raises: [], tags: [],
+    forbids: [].}
+
+ + Returns the internal int value of x, including for enum with holes and distinct ordinal types. +

Example:

+
assert ord('A') == 65
+type Foo = enum
+  f0 = 0, f1 = 3
+assert f1.ord == 3
+type Bar = distinct int
+assert 3.Bar.ord == 3
+ Source   +Edit   + +
+
+ +
+
+
+
proc pop[T](s: var seq[T]): T {.inline, noSideEffect.}
+
+ +

Returns the last item of s and decreases s.len by one. This treats s as a stack and implements the common pop operation.

+

Raises IndexDefect if s is empty.

+ +

Example:

+
var a = @[1, 3, 5, 7]
+let b = pop(a)
+assert b == 7
+assert a == @[1, 3, 5]
+ Source   +Edit   + +
+
+ +
+
+
+
proc pred[T, V: Ordinal](x: T; y: V = 1): T {.magic: "Pred", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the y-th predecessor (default: 1) of the value x.

+

If such a value does not exist, OverflowDefect is raised or a compile time error occurs.

+ +

Example:

+
assert pred(5) == 4
+assert pred(5, 3) == 2
+ Source   +Edit   + +
+
+ +
+
+
+
proc prepareMutation(s: var string) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc procCall(x: untyped) {.magic: "ProcCall", compileTime, ...raises: [],
+                            tags: [], forbids: [].}
+
+ +

Special magic to prohibit dynamic binding for method calls. This is similar to super in ordinary OO languages.

+

# 'someMethod' will be resolved fully statically:
+procCall someMethod(a, b)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc protect(x: pointer): ForeignCell {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc quit(errorcode: int = QuitSuccess) {.magic: "Exit", noreturn, ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Stops the program immediately with an exit code.

+

Before stopping the program the "exit procedures" are called in the opposite order they were added with addExitProc.

+

The proc quit(QuitSuccess) is called implicitly when your nim program finishes without incident for platforms where this is the expected behavior. A raised unhandled exception is equivalent to calling quit(QuitFailure).

+

Note that this is a runtime call and using quit inside a macro won't have any compile time effect. If you need to stop the compiler inside a macro, use the error or fatal pragmas.

+
Warning: +errorcode gets saturated when it exceeds the valid range on the specific platform. On Posix, the valid range is low(int8)..high(int8). On Windows, the valid range is low(int32)..high(int32). For instance, quit(int(0x100000000)) is equal to quit(127) on Linux.
+
Danger: +In almost all cases, in particular in library code, prefer alternatives, e.g. raiseAssert or raise a Defect. quit bypasses regular control flow in particular defer, try, catch, finally and destructors, and exceptions that may have been raised by an addExitProc proc, as well as cleanup code in other threads. It does not call the garbage collector to free all the memory, unless an addExitProc proc calls GC_fullCollect.
+ + Source   +Edit   + +
+
+
+
proc quit(errormsg: string; errorcode = QuitFailure) {.noreturn, ...raises: [],
+    tags: [], forbids: [].}
+
+ + A shorthand for echo(errormsg); quit(errorcode). + Source   +Edit   + +
+
+ +
+
+
+
proc rawEnv[T: proc {.closure.} | iterator {.closure.}](x: T): pointer {.
+    noSideEffect, inline.}
+
+ + Retrieves the raw environment pointer of the closure x. See also rawProc. This is not available for the JS target. + Source   +Edit   + +
+
+ +
+
+
+
proc rawProc[T: proc {.closure.} | iterator {.closure.}](x: T): pointer {.
+    noSideEffect, inline.}
+
+ + Retrieves the raw proc pointer of the closure x. This is useful for interfacing closures with C/C++, hash computations, etc. If rawEnv(x) returns nil, the proc which the result points to takes as many parameters as x, but with {.nimcall.} as its calling convention instead of {.closure.}, otherwise it takes one more parameter which is a pointer, and it still has {.nimcall.} as its calling convention. To invoke the resulted proc, what this returns has to be casted into a proc, not a ptr proc, and, in a case where rawEnv(x) returns non-nil, the last and additional argument has to be the result of rawEnv(x). This is not available for the JS target. +

Example:

+
proc makeClosure(x: int): (proc(y: int): int) =
+  var n = x
+  result = (
+    proc(y: int): int =
+      n += y
+      return n
+  )
+
+var
+  c1 = makeClosure(10)
+  e = c1.rawEnv()
+  p = c1.rawProc()
+
+if e.isNil():
+  let c2 = cast[proc(y: int): int {.nimcall.}](p)
+  echo c2(2)
+else:
+  let c3 = cast[proc(y: int; env: pointer): int {.nimcall.}](p)
+  echo c3(3, e)
+ Source   +Edit   + +
+
+ +
+
+
+
proc realloc0Impl(p: pointer; oldSize, newSize: Natural): pointer {.noconv,
+    ...gcsafe, tags: [], gcsafe, raises: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc reallocImpl(p: pointer; newSize: Natural): pointer {.noconv, ...gcsafe,
+    tags: [], gcsafe, raises: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc reallocShared0Impl(p: pointer; oldSize, newSize: Natural): pointer {.
+    noconv, ...gcsafe, tags: [], gcsafe, raises: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc reallocSharedImpl(p: pointer; newSize: Natural): pointer {.noconv, ...gcsafe,
+    tags: [], gcsafe, raises: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc repr[T, U](x: HSlice[T, U]): string
+
+ +

Generic repr operator for slices that is lifted from the components of x. Example:

+

$(1 .. 5) == "1 .. 5"

+ + Source   +Edit   + +
+
+ +
+
+
+
proc reset[T](obj: var T) {.noSideEffect.}
+
+ + Resets an object obj to its default value. + Source   +Edit   + +
+
+ +
+
+
+
proc resize[T](p: ptr T; newSize: Natural): ptr T {.inline, ...gcsafe, raises: [].}
+
+ +

Grows or shrinks a given memory block.

+

If p is nil then a new memory block is returned. In either way the block has at least T.sizeof * newSize bytes. If newSize == 0 and p is not nil resize calls dealloc(p). In other cases the block has to be freed with free.

+

The allocated memory belongs to its allocating thread! Use resizeShared to reallocate from a shared heap.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc resizeShared[T](p: ptr T; newSize: Natural): ptr T {.inline, ...raises: [].}
+
+ +

Grows or shrinks a given memory block on the heap.

+

If p is nil then a new memory block is returned. In either way the block has at least T.sizeof * newSize bytes. If newSize == 0 and p is not nil resizeShared calls freeShared(p). In other cases the block has to be freed with freeShared.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc runnableExamples(rdoccmd = ""; body: untyped) {.magic: "RunnableExamples",
+    ...raises: [], tags: [], forbids: [].}
+
+ + A section you should use to mark runnable example code with.
  • In normal debug and release builds code within a runnableExamples section is ignored.
  • +
  • The documentation generator is aware of these examples and considers them part of the ## doc comment. As the last step of documentation generation each runnableExample is put in its own file $file_examples$i.nim, compiled and tested. The collected examples are put into their own module to ensure the examples do not refer to non-exported symbols.
  • +
+ +

Example:

+
proc timesTwo*(x: int): int =
+  ## This proc doubles a number.
+  runnableExamples:
+    # at module scope
+    const exported* = 123
+    assert timesTwo(5) == 10
+    block: # at block scope
+      defer: echo "done"
+  runnableExamples "-d:foo -b:cpp":
+    import std/compilesettings
+    assert querySetting(backend) == "cpp"
+    assert defined(foo)
+  runnableExamples "-r:off": ## this one is only compiled
+     import std/browsers
+     openDefaultBrowser "https://forum.nim-lang.org/"
+  2 * x
+ Source   +Edit   + +
+
+ +
+
+
+
proc setControlCHook(hook: proc () {.noconv.}) {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Allows you to override the behaviour of your application when CTRL+C is pressed. Only one such hook is supported. Example:

+

proc ctrlc() {.noconv.} =
+  echo "Ctrl+C fired!"
+  # do clean up stuff
+  quit()
+
+setControlCHook(ctrlc)

+ + Source   +Edit   + +
+
+ +
+
+
+
proc setCurrentException(exc: ref Exception) {.inline, ...gcsafe, raises: [],
+    tags: [], forbids: [].}
+
+ + Sets the current exception.
Warning: +Only use this if you know what you are doing.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc setFrame(s: PFrame) {.compilerproc, inline, ...raises: [], tags: [],
+                           forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setFrameState(state: FrameState) {.compilerproc, inline, ...raises: [],
+                                        tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setLen(s: var string; newlen: Natural) {.magic: "SetLengthStr",
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Sets the length of string s to newlen.

+

If the current length is greater than the new length, s will be truncated.

+

var myS = "Nim is great!!"
+myS.setLen(3) # myS <- "Nim"
+echo myS, " is fantastic!!"

+ + Source   +Edit   + +
+
+
+
proc setLen[T](s: var seq[T]; newlen: Natural) {.magic: "SetLengthSeq",
+    noSideEffect, nodestroy, ...raises: [], tags: [], forbids: [].}
+
+ +

Sets the length of seq s to newlen. T may be any sequence type.

+

If the current length is greater than the new length, s will be truncated.

+

var x = @[10, 20]
+x.setLen(5)
+x[4] = 50
+assert x == @[10, 20, 0, 0, 50]
+x.setLen(1)
+assert x == @[10]

+ + Source   +Edit   + +
+
+ +
+
+
+
func setLenUninit[T](s: var seq[T]; newlen: Natural) {.nodestroy.}
+
+ +

Sets the length of seq s to newlen. T may be any sequence type. New slots will not be initialized.

+

If the current length is greater than the new length, s will be truncated.

+

var x = @[10, 20]
+x.setLenUninit(5)
+x[4] = 50
+assert x[4] == 50
+x.setLenUninit(1)
+assert x == @[10]

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `shl`(x: int8; y: SomeInteger): int8 {.magic: "ShlI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shl`(x: int16; y: SomeInteger): int16 {.magic: "ShlI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shl`(x: int32; y: SomeInteger): int32 {.magic: "ShlI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shl`(x: int64; y: SomeInteger): int64 {.magic: "ShlI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shl`(x: int; y: SomeInteger): int {.magic: "ShlI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the shift left operation of x and y.

+

Note: Operator precedence is different than in C.

+ +

Example:

+
assert 1'i32 shl 4 == 0x0000_0010
+assert 1'i64 shl 4 == 0x0000_0000_0000_0010
+ Source   +Edit   + +
+
+
+
proc `shl`(x: uint8; y: SomeInteger): uint8 {.magic: "ShlI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shl`(x: uint16; y: SomeInteger): uint16 {.magic: "ShlI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shl`(x: uint32; y: SomeInteger): uint32 {.magic: "ShlI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shl`(x: uint64; y: SomeInteger): uint64 {.magic: "ShlI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shl`(x: uint; y: SomeInteger): uint {.magic: "ShlI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Computes the shift left operation of x and y. + Source   +Edit   + +
+
+ +
+
+
+
proc `shr`(x: int8; y: SomeInteger): int8 {.magic: "AshrI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shr`(x: int16; y: SomeInteger): int16 {.magic: "AshrI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shr`(x: int32; y: SomeInteger): int32 {.magic: "AshrI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shr`(x: int64; y: SomeInteger): int64 {.magic: "AshrI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shr`(x: int; y: SomeInteger): int {.magic: "AshrI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Computes the shift right operation of x and y, filling vacant bit positions with the sign bit.

+

Note: Operator precedence is different than in C.

+

See also:

+ + +

Example:

+
assert 0b0001_0000'i8 shr 2 == 0b0000_0100'i8
+assert 0b0000_0001'i8 shr 1 == 0b0000_0000'i8
+assert 0b1000_0000'i8 shr 4 == 0b1111_1000'i8
+assert -1 shr 5 == -1
+assert 1 shr 5 == 0
+assert 16 shr 2 == 4
+assert -16 shr 2 == -4
+ Source   +Edit   + +
+
+
+
proc `shr`(x: uint8; y: SomeInteger): uint8 {.magic: "ShrI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shr`(x: uint16; y: SomeInteger): uint16 {.magic: "ShrI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shr`(x: uint32; y: SomeInteger): uint32 {.magic: "ShrI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shr`(x: uint64; y: SomeInteger): uint64 {.magic: "ShrI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `shr`(x: uint; y: SomeInteger): uint {.magic: "ShrI", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Computes the shift right operation of x and y. + Source   +Edit   + +
+
+ +
+
+
+
proc shrink[T](x: var seq[T]; newLen: Natural) {....tags: [], raises: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sizeof(x: typedesc): int {.magic: "SizeOf", noSideEffect, ...raises: [],
+                                tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc sizeof[T](x: T): int {.magic: "SizeOf", noSideEffect, ...raises: [], tags: [],
+                            forbids: [].}
+
+ +

Returns the size of x in bytes.

+

Since this is a low-level proc, its usage is discouraged - using new for the most cases suffices that one never needs to know x's size.

+

As a special semantic rule, x may also be a type identifier (sizeof(int) is valid).

+

Limitations: If used for types that are imported from C or C++, sizeof should fallback to the sizeof in the C compiler. The result isn't available for the Nim compiler and therefore can't be used inside of macros.

+

sizeof('A') # => 1
+sizeof(2) # => 8

+ + Source   +Edit   + +
+
+ +
+
+
+
proc slurp(filename: string): string {.magic: "Slurp", ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + This is an alias for staticRead. + Source   +Edit   + +
+
+ +
+
+
+
proc stackTraceAvailable(): bool {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc staticExec(command: string; input = ""; cache = ""): string {.
+    magic: "StaticExec", ...raises: [], tags: [], forbids: [].}
+
+ +

Executes an external process at compile-time and returns its text output (stdout + stderr).

+

If input is not an empty string, it will be passed as a standard input to the executed program.

+

const buildInfo = "Revision " & staticExec("git rev-parse HEAD") &
+                  "\nCompiled on " & staticExec("uname -v")

+

gorge is an alias for staticExec.

+

Note that you can use this proc inside a pragma like passc or passl.

+

If cache is not empty, the results of staticExec are cached within the nimcache directory. Use --forceBuild to get rid of this caching behaviour then. command & input & cache (the concatenated string) is used to determine whether the entry in the cache is still valid. You can use versioning information for cache:

+

const stateMachine = staticExec("dfaoptimizer", "input", "0.8.0")

+ + Source   +Edit   + +
+
+ +
+
+
+
proc staticRead(filename: string): string {.magic: "Slurp", ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Compile-time readFile proc for easy resource embedding:

+

The maximum file size limit that staticRead and slurp can read is near or equal to the free memory of the device you are using to compile.

+

const myResource = staticRead"mydatafile.bin"

+

slurp is an alias for staticRead.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc substr(s: openArray[char]): string {....raises: [], tags: [], forbids: [].}
+
+ + Copies a slice of s into a new string and returns this new string. +

Example:

+
let a = "abcdefgh"
+assert a.substr(2, 5) == "cdef"
+assert a.substr(2) == "cdefgh"
+assert a.substr(5, 99) == "fgh"
+ Source   +Edit   + +
+
+
+
proc substr(s: string; first = 0): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc substr(s: string; first, last: int): string {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Copies a slice of s into a new string and returns this new string.

+

The bounds first and last denote the indices of the first and last characters that shall be copied. If last is omitted, it is treated as high(s). If last >= s.len, s.len is used instead: This means substr can also be used to cut or limit a string's length.

+ +

Example:

+
let a = "abcdefgh"
+assert a.substr(2, 5) == "cdef"
+assert a.substr(2) == "cdefgh"
+assert a.substr(5, 99) == "fgh"
+ Source   +Edit   + +
+
+ +
+
+
+
proc succ[T, V: Ordinal](x: T; y: V = 1): T {.magic: "Succ", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the y-th successor (default: 1) of the value x.

+

If such a value does not exist, OverflowDefect is raised or a compile time error occurs.

+ +

Example:

+
assert succ(5) == 6
+assert succ(5, 3) == 8
+ Source   +Edit   + +
+
+ +
+
+
+
proc swap[T](a, b: var T) {.magic: "Swap", noSideEffect, ...raises: [], tags: [],
+                            forbids: [].}
+
+ +

Swaps the values a and b.

+

This is often more efficient than tmp = a; a = b; b = tmp. Particularly useful for sorting algorithms.

+

var
+  a = 5
+  b = 9
+
+swap(a, b)
+
+assert a == 9
+assert b == 5

+ + Source   +Edit   + +
+
+ +
+
+
+
proc toBiggestFloat(i: BiggestInt): BiggestFloat {.noSideEffect, inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ + Same as toFloat but for BiggestInt to BiggestFloat. + Source   +Edit   + +
+
+ +
+
+
+
proc toBiggestInt(f: BiggestFloat): BiggestInt {.noSideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + Same as toInt but for BiggestFloat to BiggestInt. + Source   +Edit   + +
+
+ +
+
+
+
proc toFloat(i: int): float {.noSideEffect, inline, ...raises: [], tags: [],
+                              forbids: [].}
+
+ +

Converts an integer i into a float. Same as float(i).

+

If the conversion fails, ValueError is raised. However, on most platforms the conversion cannot fail.

+

let
+  a = 2
+  b = 3.7
+
+echo a.toFloat + b # => 5.7

+ + Source   +Edit   + +
+
+ +
+
+
+
proc toInt(f: float): int {.noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Converts a floating point number f into an int.

+

Conversion rounds f half away from 0, see Round half away from zero, as opposed to a type conversion which rounds towards zero.

+

Note that some floating point numbers (e.g. infinity or even 1e19) cannot be accurately converted.

+

doAssert toInt(0.49) == 0
+doAssert toInt(0.5) == 1
+doAssert toInt(-0.5) == -1 # rounding is symmetrical

+ + Source   +Edit   + +
+
+ +
+
+
+
proc toOpenArray(x: cstring; first, last: int): openArray[char] {.
+    magic: "Slice", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc toOpenArray(x: string; first, last: int): openArray[char] {.magic: "Slice",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc toOpenArray[I, T](x: array[I, T]; first, last: I): openArray[T] {.
+    magic: "Slice", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc toOpenArray[T](x: openArray[T]; first, last: int): openArray[T] {.
+    magic: "Slice", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc toOpenArray[T](x: ptr UncheckedArray[T]; first, last: int): openArray[T] {.
+    magic: "Slice", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc toOpenArray[T](x: seq[T]; first, last: int): openArray[T] {.magic: "Slice",
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Allows passing the slice of x from the element at first to the element at last to openArray[T] parameters without copying it.

+

Example:

+

proc test(x: openArray[int]) =
+  doAssert x == [1, 2, 3]
+
+let s = @[0, 1, 2, 3, 4]
+s.toOpenArray(1, 3).test

+ + Source   +Edit   + +
+
+ +
+
+
+
proc toOpenArrayByte(x: cstring; first, last: int): openArray[byte] {.
+    magic: "Slice", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc toOpenArrayByte(x: openArray[char]; first, last: int): openArray[byte] {.
+    magic: "Slice", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc toOpenArrayByte(x: seq[char]; first, last: int): openArray[byte] {.
+    magic: "Slice", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc toOpenArrayByte(x: string; first, last: int): openArray[byte] {.
+    magic: "Slice", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toOpenArrayChar(x: openArray[byte]; first, last: int): openArray[char] {.
+    magic: "Slice", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc typeof(x: untyped; mode = typeOfIter): typedesc {.magic: "TypeOf",
+    noSideEffect, compileTime, ...raises: [], tags: [], forbids: [].}
+
+ + Builtin typeof operation for accessing the type of an expression. Since version 0.20.0. +

Example:

+
proc myFoo(): float = 0.0
+iterator myFoo(): string = yield "abc"
+iterator myFoo2(): string = yield "abc"
+iterator myFoo3(): string {.closure.} = yield "abc"
+doAssert type(myFoo()) is string
+doAssert typeof(myFoo()) is string
+doAssert typeof(myFoo(), typeOfIter) is string
+doAssert typeof(myFoo3) is iterator
+
+doAssert typeof(myFoo(), typeOfProc) is float
+doAssert typeof(0.0, typeOfProc) is float
+doAssert typeof(myFoo3, typeOfProc) is iterator
+doAssert not compiles(typeof(myFoo2(), typeOfProc))
+  # this would give: Error: attempting to call routine: 'myFoo2'
+  # since `typeOfProc` expects a typed expression and `myFoo2()` can
+  # only be used in a `for` context.
+ Source   +Edit   + +
+
+ +
+
+
+
proc unsafeAddr[T](x: T): ptr T {.magic: "Addr", noSideEffect, ...raises: [],
+                                  tags: [], forbids: [].}
+
+ +
Warning: +unsafeAddr is a deprecated alias for addr, use addr instead.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc unsafeNew[T](a: var ref T; size: Natural) {.magic: "New", noSideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new object of type T and returns a safe (traced) reference to it in a.

+

This is unsafe as it allocates an object of the passed size. This should only be used for optimization purposes when you know what you're doing!

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc unsetControlCHook() {....raises: [], tags: [], forbids: [].}
+
+ + Reverts a call to setControlCHook. + Source   +Edit   + +
+
+ +
+
+
+
proc wasMoved[T](obj: var T) {.inline, noSideEffect.}
+
+ + Resets an object obj to its initial (binary zero) value to signify it was "moved" and to signify its destructor should do nothing and ideally be optimized away. + Source   +Edit   + +
+
+ +
+
+
+
proc writeStackTrace() {....tags: [], gcsafe, raises: [], forbids: [].}
+
+ + Writes the current stack trace to stderr. This is only works for debug builds. Since it's usually used for debugging, this is proclaimed to have no IO effect! + Source   +Edit   + +
+
+ +
+
+
+
proc `xor`(x, y: bool): bool {.magic: "Xor", noSideEffect, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + Boolean exclusive or; returns true if x != y (if either argument is true while the other is false). + Source   +Edit   + +
+
+
+
proc `xor`(x, y: int): int {.magic: "BitxorI", noSideEffect, ...raises: [],
+                             tags: [], forbids: [].}
+
+ + Computes the bitwise xor of numbers x and y. +

Example:

+
assert (0b0011 xor 0b0101) == 0b0110
+assert (0b0111 xor 0b1100) == 0b1011
+ Source   +Edit   + +
+
+
+
proc `xor`(x, y: int8): int8 {.magic: "BitxorI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `xor`(x, y: int16): int16 {.magic: "BitxorI", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `xor`(x, y: int32): int32 {.magic: "BitxorI", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `xor`(x, y: int64): int64 {.magic: "BitxorI", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `xor`(x, y: uint): uint {.magic: "BitxorI", noSideEffect, ...raises: [],
+                               tags: [], forbids: [].}
+
+ + Computes the bitwise xor of numbers x and y. + Source   +Edit   + +
+
+
+
proc `xor`(x, y: uint8): uint8 {.magic: "BitxorI", noSideEffect, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `xor`(x, y: uint16): uint16 {.magic: "BitxorI", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `xor`(x, y: uint32): uint32 {.magic: "BitxorI", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `xor`(x, y: uint64): uint64 {.magic: "BitxorI", noSideEffect, ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
func zeroDefault[T](_: typedesc[T]): T {.magic: "ZeroDefault", ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Returns the binary zeros representation of the type T. It ignores default fields of an object.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc zeroMem(p: pointer; size: Natural) {.inline, noSideEffect, ...tags: [],
+    raises: [], forbids: [].}
+
+ +

Overwrites the contents of the memory at p with the value 0.

+

Exactly size bytes will be overwritten. Like any procedure dealing with raw memory this is unsafe.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `|`(a, b: typedesc): typedesc
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator `..`(a, b: int32): int32 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

A type specialized version of .. for convenience so that mixing integer types works better.

+

See also:

+ + + Source   +Edit   + +
+
+
+
iterator `..`(a, b: int64): int64 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

A type specialized version of .. for convenience so that mixing integer types works better.

+

See also:

+ + + Source   +Edit   + +
+
+
+
iterator `..`(a, b: uint32): uint32 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

A type specialized version of .. for convenience so that mixing integer types works better.

+

See also:

+ + + Source   +Edit   + +
+
+
+
iterator `..`(a, b: uint64): uint64 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

A type specialized version of .. for convenience so that mixing integer types works better.

+

See also:

+ + + Source   +Edit   + +
+
+
+
iterator `..`[T](a, b: T): T {.inline.}
+
+ +

An alias for countup(a, b, 1).

+

See also:

+ + +

Example:

+
import std/sugar
+
+let x = collect(newSeq):
+  for i in 3 .. 7:
+    i
+
+assert x == @[3, 4, 5, 6, 7]
+ Source   +Edit   + +
+
+ +
+
+
+
iterator `..<`(a, b: int32): int32 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + A type specialized version of ..< for convenience so that mixing integer types works better. + Source   +Edit   + +
+
+
+
iterator `..<`(a, b: int64): int64 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + A type specialized version of ..< for convenience so that mixing integer types works better. + Source   +Edit   + +
+
+
+
iterator `..<`(a, b: uint32): uint32 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + A type specialized version of ..< for convenience so that mixing integer types works better. + Source   +Edit   + +
+
+
+
iterator `..<`(a, b: uint64): uint64 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + A type specialized version of ..< for convenience so that mixing integer types works better. + Source   +Edit   + +
+
+
+
iterator `..<`[T](a, b: T): T {.inline.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
iterator countdown[T](a, b: T; step: Positive = 1): T {.inline.}
+
+ +

Counts from ordinal value a down to b (inclusive) with the given step count.

+

T may be any ordinal type, step may only be positive.

+

Note: This fails to count to low(int) if T = int for efficiency reasons.

+ +

Example:

+
import std/sugar
+let x = collect(newSeq):
+  for i in countdown(7, 3):
+    i
+
+assert x == @[7, 6, 5, 4, 3]
+
+let y = collect(newseq):
+  for i in countdown(9, 2, 3):
+    i
+assert y == @[9, 6, 3]
+ Source   +Edit   + +
+
+ +
+
+
+
iterator countup[T](a, b: T; step: Positive = 1): T {.inline.}
+
+ +

Counts from ordinal value a to b (inclusive) with the given step count.

+

T may be any ordinal type, step may only be positive.

+

Note: This fails to count to high(int) if T = int for efficiency reasons.

+ +

Example:

+
import std/sugar
+let x = collect(newSeq):
+  for i in countup(3, 7):
+    i
+
+assert x == @[3, 4, 5, 6, 7]
+
+let y = collect(newseq):
+  for i in countup(2, 9, 3):
+    i
+assert y == @[2, 5, 8]
+ Source   +Edit   + +
+
+ +
+
+
+
iterator `||`[S, T](a: S; b: T; annotation: static string = "parallel for"): T {.
+    inline, magic: "OmpParFor", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

OpenMP parallel loop iterator. Same as .. but the loop may run in parallel.

+

annotation is an additional annotation for the code generator to use. The default annotation is parallel for. Please refer to the OpenMP Syntax Reference for further information.

+

Note that the compiler maps that to the #pragma omp parallel for construct of OpenMP and as such isn't aware of the parallelism in your code! Be careful! Later versions of || will get proper support by Nim's code generator and GC.

+ + Source   +Edit   + +
+
+
+
iterator `||`[S, T](a: S; b: T; step: Positive;
+                    annotation: static string = "parallel for"): T {.inline,
+    magic: "OmpParFor", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

OpenMP parallel loop iterator with stepping.  Same as countup but the loop may run in parallel.

+

annotation is an additional annotation for the code generator to use. The default annotation is parallel for. Please refer to the OpenMP Syntax Reference for further information.

+

Note that the compiler maps that to the #pragma omp parallel for construct of OpenMP and as such isn't aware of the parallelism in your code! Be careful! Later versions of || will get proper support by Nim's code generator and GC.

+ + Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro varargsLen(x: varargs[untyped]): int
+
+ + returns number of variadic arguments in x + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template `!=`(x, y: untyped): untyped {.callsite.}
+
+ + Unequals operator. This is a shorthand for not (x == y). + Source   +Edit   + +
+
+ +
+
+
+
template `&=`(x, y: typed)
+
+ +

Generic 'sink' operator for Nim.

+

If not specialized further, an alias for add.

+ + Source   +Edit   + +
+
+ +
+
+
+
template `..<`(a, b: untyped): untyped
+
+ +

A shortcut for a .. pred(b).

+

for i in 5 ..< 9:
+  echo i # => 5; 6; 7; 8

+ + Source   +Edit   + +
+
+ +
+
+
+
template `..^`(a, b: untyped): untyped
+
+ + A shortcut for .. ^ to avoid the common gotcha that a space between '..' and '^' is required. + Source   +Edit   + +
+
+ +
+
+
+
template `=dispose`[T](x: owned(ref T))
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template `>`(x, y: untyped): untyped {.callsite.}
+
+ + "is greater" operator. This is the same as y < x. + Source   +Edit   + +
+
+ +
+
+
+
template `>%`(x, y: untyped): untyped
+
+ + Treats x and y as unsigned and compares them. Returns true if unsigned(x) > unsigned(y). + Source   +Edit   + +
+
+ +
+
+
+
template `>=`(x, y: untyped): untyped {.callsite.}
+
+ + "is greater or equals" operator. This is the same as y <= x. + Source   +Edit   + +
+
+ +
+
+
+
template `>=%`(x, y: untyped): untyped
+
+ + Treats x and y as unsigned and compares them. Returns true if unsigned(x) >= unsigned(y). + Source   +Edit   + +
+
+ +
+
+
+
template `[]`(s: string; i: int): char
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template `[]=`(s: string; i: int; val: char)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template `^`(x: int): BackwardsIndex
+
+ +

Builtin roof operator that can be used for convenient array access. a[^x] is a shortcut for a[a.len-x].

+

let
+  a = [1, 3, 5, 7, 9]
+  b = "abcdefgh"
+
+echo a[^1] # => 9
+echo b[^2] # => g

+ + Source   +Edit   + +
+
+ +
+
+
+
template alloc(size: Natural): pointer
+
+ +

Allocates a new memory block with at least size bytes.

+

The block has to be freed with realloc(block, 0) or dealloc(block). The block is not initialized, so reading from it before writing to it is undefined behaviour!

+

The allocated memory belongs to its allocating thread! Use allocShared to allocate from a shared heap.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
template alloc0(size: Natural): pointer
+
+ +

Allocates a new memory block with at least size bytes.

+

The block has to be freed with realloc(block, 0) or dealloc(block). The block is initialized with all bytes containing zero, so it is somewhat safer than alloc.

+

The allocated memory belongs to its allocating thread! Use allocShared0 to allocate from a shared heap.

+ + Source   +Edit   + +
+
+ +
+
+
+
template allocShared(size: Natural): pointer
+
+ +

Allocates a new memory block on the shared heap with at least size bytes.

+

The block has to be freed with reallocShared(block, 0) or deallocShared(block).

+

The block is not initialized, so reading from it before writing to it is undefined behaviour!

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
template allocShared0(size: Natural): pointer
+
+ +

Allocates a new memory block on the shared heap with at least size bytes.

+

The block has to be freed with reallocShared(block, 0) or deallocShared(block).

+

The block is initialized with all bytes containing zero, so it is somewhat safer than allocShared.

+ + Source   +Edit   + +
+
+ +
+
+
+
template closureScope(body: untyped): untyped
+
+ +

Useful when creating a closure in a loop to capture local loop variables by their current iteration values.

+

Note: This template may not work in some cases, use capture instead.

+

Example:

+

var myClosure : proc()
+# without closureScope:
+for i in 0 .. 5:
+  let j = i
+  if j == 3:
+    myClosure = proc() = echo j
+myClosure() # outputs 5. `j` is changed after closure creation
+# with closureScope:
+for i in 0 .. 5:
+  closureScope: # Everything in this scope is locked after closure creation
+    let j = i
+    if j == 3:
+      myClosure = proc() = echo j
+myClosure() # outputs 3

+ + Source   +Edit   + +
+
+ +
+
+
+
template currentSourcePath(): string
+
+ +

Returns the full file-system path of the current source.

+

To get the directory containing the current source, use it with ospaths2.parentDir() as currentSourcePath.parentDir().

+

The path returned by this template is set at compile time.

+

See the docstring of macros.getProjectPath() for an example to see the distinction between the currentSourcePath() and getProjectPath().

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
template disarm(x: typed)
+
+ + Useful for disarming dangling pointers explicitly for --newruntime. Regardless of whether --newruntime is used or not this sets the pointer or callback x to nil. This is an experimental API! + Source   +Edit   + +
+
+ +
+
+
+
template dumpAllocstats(code: untyped)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template excl[T](x: var set[T]; y: set[T]) {.callsite.}
+
+ + Excludes the set y from the set x. +

Example:

+
var a = {1, 3, 5, 7}
+var b = {3, 4, 5}
+a.excl(b) 
+assert a == {1, 7}
+ Source   +Edit   + +
+
+ +
+
+
+
template formatErrorIndexBound[T](i, a, b: T): string
+
+ + + Source   +Edit   + +
+
+
+
template formatErrorIndexBound[T](i, n: T): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template formatFieldDefect(f, discVal): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template `in`(x, y: untyped): untyped {.dirty, callsite.}
+
+ +

Sugar for contains.

+

assert(1 in (1..3) == true)
+assert(5 in (1..3) == false)

+ + Source   +Edit   + +
+
+ +
+
+
+
template incl[T](x: var set[T]; y: set[T]) {.callsite.}
+
+ + Includes the set y in the set x. +

Example:

+
var a = {1, 3, 5, 7}
+var b = {4, 5, 6}
+a.incl(b)
+assert a == {1, 3, 4, 5, 6, 7}
+ Source   +Edit   + +
+
+ +
+
+
+
template `isnot`(x, y: untyped): untyped {.callsite.}
+
+ +

Negated version of is. Equivalent to not(x is y).

+

assert 42 isnot float
+assert @[1, 2] isnot enum

+ + Source   +Edit   + +
+
+ +
+
+
+
template likely(val: bool): bool
+
+ +

Hints the optimizer that val is likely going to be true.

+

You can use this template to decorate a branch condition. On certain platforms this can help the processor predict better which branch is going to be run. Example:

+

for value in inputValues:
+  if likely(value <= 100):
+    process(value)
+  else:
+    echo "Value too big!"

+

On backends without branch prediction (JS and the nimscript VM), this template will not affect code execution.

+ + Source   +Edit   + +
+
+ +
+
+
+
template newException(exceptn: typedesc; message: string;
+                      parentException: ref Exception = nil): untyped
+
+ + Creates an exception object of type exceptn and sets its msg field to message. Returns the new exception object. + Source   +Edit   + +
+
+ +
+
+
+
template nimThreadProcWrapperBody(closure: untyped): untyped
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template `notin`(x, y: untyped): untyped {.dirty, callsite.}
+
+ +

Sugar for not contains.

+

assert(1 notin (1..3) == false)
+assert(5 notin (1..3) == true)

+ + Source   +Edit   + +
+
+ +
+
+
+
template offsetOf[T](t: typedesc[T]; member: untyped): int
+
+ + + Source   +Edit   + +
+
+
+
template offsetOf[T](value: T; member: untyped): int
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template once(body: untyped): untyped
+
+ +

Executes a block of code only once (the first time the block is reached).

+

proc draw(t: Triangle) =
+  once:
+    graphicsInit()
+  line(t.p1, t.p2)
+  line(t.p2, t.p3)
+  line(t.p3, t.p1)

+ + Source   +Edit   + +
+
+ +
+
+
+
template rangeCheck(cond)
+
+ + Helper for performing user-defined range checks. Such checks will be performed only when the rangechecks compile-time option is enabled. + Source   +Edit   + +
+
+ +
+
+
+
template realloc(p: pointer; newSize: Natural): pointer
+
+ +

Grows or shrinks a given memory block.

+

If p is nil then a new memory block is returned. In either way the block has at least newSize bytes. If newSize == 0 and p is not nil realloc calls dealloc(p). In other cases the block has to be freed with dealloc(block).

+

The allocated memory belongs to its allocating thread! Use reallocShared to reallocate from a shared heap.

+ + Source   +Edit   + +
+
+ +
+
+
+
template realloc0(p: pointer; oldSize, newSize: Natural): pointer
+
+ +

Grows or shrinks a given memory block.

+

If p is nil then a new memory block is returned. In either way the block has at least newSize bytes. If newSize == 0 and p is not nil realloc calls dealloc(p). In other cases the block has to be freed with dealloc(block).

+

The block is initialized with all bytes containing zero, so it is somewhat safer then realloc

+

The allocated memory belongs to its allocating thread! Use reallocShared to reallocate from a shared heap.

+ + Source   +Edit   + +
+
+ +
+
+
+
template reallocShared(p: pointer; newSize: Natural): pointer
+
+ +

Grows or shrinks a given memory block on the heap.

+

If p is nil then a new memory block is returned. In either way the block has at least newSize bytes. If newSize == 0 and p is not nil reallocShared calls deallocShared(p). In other cases the block has to be freed with deallocShared.

+ + Source   +Edit   + +
+
+ +
+
+
+
template reallocShared0(p: pointer; oldSize, newSize: Natural): pointer
+
+ +

Grows or shrinks a given memory block on the heap.

+

When growing, the new bytes of the block is initialized with all bytes containing zero, so it is somewhat safer then reallocShared

+

If p is nil then a new memory block is returned. In either way the block has at least newSize bytes. If newSize == 0 and p is not nil reallocShared calls deallocShared(p). In other cases the block has to be freed with deallocShared.

+ + Source   +Edit   + +
+
+ +
+
+
+
template setupForeignThreadGc()
+
+ + With --mm:arc a nop. + Source   +Edit   + +
+
+ +
+
+
+
template tearDownForeignThreadGc()
+
+ + With --mm:arc a nop. + Source   +Edit   + +
+
+ +
+
+
+
template unlikely(val: bool): bool
+
+ +

Hints the optimizer that val is likely going to be false.

+

You can use this proc to decorate a branch condition. On certain platforms this can help the processor predict better which branch is going to be run. Example:

+

for value in inputValues:
+  if unlikely(value > 100):
+    echo "Value too big!"
+  else:
+    process(value)

+

On backends without branch prediction (JS and the nimscript VM), this template will not affect code execution.

+ + Source   +Edit   + +
+
+ +
+
+
+
template unown(x: typed): untyped
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/system.idx b/system.idx new file mode 100644 index 0000000000000..63d7b3043ea47 --- /dev/null +++ b/system.idx @@ -0,0 +1,793 @@ +nimTitle system system.html module system 0 +nim int system.html#int type int 2 +nim int8 system.html#int8 type int8 4 +nim int16 system.html#int16 type int16 5 +nim int32 system.html#int32 type int32 6 +nim int64 system.html#int64 type int64 7 +nim uint system.html#uint type uint 8 +nim uint8 system.html#uint8 type uint8 9 +nim uint16 system.html#uint16 type uint16 10 +nim uint32 system.html#uint32 type uint32 11 +nim uint64 system.html#uint64 type uint64 12 +nim float system.html#float type float 15 +nim float32 system.html#float32 type float32 16 +nim float64 system.html#float64 type float64 17 +nim char system.html#char type char 22 +nim string system.html#string type string 23 +nim cstring system.html#cstring type cstring 24 +nim pointer system.html#pointer type pointer 25 +nim typedesc system.html#typedesc type typedesc 28 +nim `ptr` system.html#ptr type `ptr` 31 +nim `ref` system.html#ref type `ref` 32 +nim void system.html#void type void 36 +nim auto system.html#auto type auto 37 +nim any system.html#any type any 38 +nim untyped system.html#untyped type untyped 39 +nim typed system.html#typed type typed 41 +nim bool system.html#bool enum bool 45 +nim on system.html#on const on 49 +nim off system.html#off const off 50 +nim SomeSignedInt system.html#SomeSignedInt type SomeSignedInt 53 +nim SomeUnsignedInt system.html#SomeUnsignedInt type SomeUnsignedInt 56 +nim SomeInteger system.html#SomeInteger type SomeInteger 59 +nim SomeFloat system.html#SomeFloat type SomeFloat 62 +nim SomeNumber system.html#SomeNumber type SomeNumber 65 +nim SomeOrdinal system.html#SomeOrdinal type SomeOrdinal 68 +nim `not` system.html#not,bool proc `not`(x: bool): bool 76 +nim `and` system.html#and,bool,bool proc `and`(x, y: bool): bool 79 +nim `or` system.html#or,bool,bool proc `or`(x, y: bool): bool 84 +nim `xor` system.html#xor,bool,bool proc `xor`(x, y: bool): bool 89 +nim zeroDefault system.html#zeroDefault,typedesc[T] proc zeroDefault[T](_: typedesc[T]): T 27 +nim NimMajor system.html#NimMajor const NimMajor 2 +nim NimMinor system.html#NimMinor const NimMinor 9 +nim NimPatch system.html#NimPatch const NimPatch 13 +nim nimvm system.html#nimvm let nimvm 18 +nim isMainModule system.html#isMainModule const isMainModule 24 +nim CompileDate system.html#CompileDate const CompileDate 28 +nim CompileTime system.html#CompileTime const CompileTime 32 +nim defined system.html#defined,untyped proc defined(x: untyped): bool 36 +nim declared system.html#declared,untyped proc declared(x: untyped): bool 54 +nim declaredInScope system.html#declaredInScope,untyped proc declaredInScope(x: untyped): bool 69 +nim compiles system.html#compiles,untyped proc compiles(x: untyped): bool 73 +nim astToStr system.html#astToStr,T proc astToStr[T](x: T): string 83 +nim runnableExamples system.html#runnableExamples,string,untyped proc runnableExamples(rdoccmd = ""; body: untyped) 87 +nim compileOption system.html#compileOption,string proc compileOption(option: string): bool 116 +nim compileOption system.html#compileOption,string,string proc compileOption(option, arg: string): bool 131 +nim currentSourcePath system.html#currentSourcePath.t template currentSourcePath(): string 143 +nim slurp system.html#slurp,string proc slurp(filename: string): string 159 +nim staticRead system.html#staticRead,string proc staticRead(filename: string): string 162 +nim gorge system.html#gorge,string,string,string proc gorge(command: string; input = ""; cache = ""): string 174 +nim staticExec system.html#staticExec,string,string,string proc staticExec(command: string; input = ""; cache = ""): string 178 +nim gorgeEx system.html#gorgeEx,string,string,string proc gorgeEx(command: string; input = ""; cache = ""): tuple[output: string,\n exitCode: int] 205 +nim `static` system.html#static type `static` 40 +nim `type` system.html#type type `type` 46 +nim typeOfProc system.html#typeOfProc TypeOfMode.typeOfProc 53 +nim typeOfIter system.html#typeOfIter TypeOfMode.typeOfIter 53 +nim TypeOfMode system.html#TypeOfMode enum TypeOfMode 53 +nim typeof system.html#typeof,untyped proc typeof(x: untyped; mode = typeOfIter): typedesc 57 +nim `or` system.html#or,typedesc,typedesc proc `or`(a, b: typedesc): typedesc 79 +nim `and` system.html#and,typedesc,typedesc proc `and`(a, b: typedesc): typedesc 82 +nim `not` system.html#not,typedesc proc `not`(a: typedesc): typedesc 85 +nim iterable system.html#iterable type iterable 90 +nim Ordinal system.html#Ordinal type Ordinal 93 +nim `addr` system.html#addr,T proc `addr`[T](x: T): ptr T 99 +nim unsafeAddr system.html#unsafeAddr,T proc unsafeAddr[T](x: T): ptr T 120 +nim new system.html#new,ref.T,proc(T) proc new[T](a: var ref T; finalizer: proc (x: T) {.nimcall.}) 131 +nim new system.html#new,ref.T,proc(ref.T) proc new[T](a: var ref T; finalizer: proc (x: ref T) {.nimcall.}) 144 +nim `=wasMoved` system.html#=wasMoved,T proc `=wasMoved`[T](obj: var T) 161 +nim wasMoved system.html#wasMoved,T proc wasMoved[T](obj: var T) 164 +nim move system.html#move,T proc move[T](x: var T): T 171 +nim ensureMove system.html#ensureMove,T proc ensureMove[T](x: T): T 177 +nim range system.html#range type range 189 +nim array system.html#array type array 190 +nim openArray system.html#openArray type openArray 192 +nim varargs system.html#varargs type varargs 196 +nim seq system.html#seq type seq 197 +nim set system.html#set type set 198 +nim UncheckedArray system.html#UncheckedArray type UncheckedArray 201 +nim sink system.html#sink type sink 204 +nim lent system.html#lent type lent 205 +nim high system.html#high,T proc high[T: Ordinal | enum | range](x: T): T 207 +nim high system.html#high,typedesc[T] proc high[T: Ordinal | enum | range](x: typedesc[T]): T 220 +nim high system.html#high,openArray[T] proc high[T](x: openArray[T]): int 231 +nim high system.html#high,array[I,T] proc high[I, T](x: array[I, T]): I 243 +nim high system.html#high,typedesc[array[I,T]] proc high[I, T](x: typedesc[array[I, T]]): I 257 +nim high system.html#high,cstring proc high(x: cstring): int 268 +nim high system.html#high,string proc high(x: string): int 275 +nim low system.html#low,T proc low[T: Ordinal | enum | range](x: T): T 285 +nim low system.html#low,typedesc[T] proc low[T: Ordinal | enum | range](x: typedesc[T]): T 297 +nim low system.html#low,openArray[T] proc low[T](x: openArray[T]): int 308 +nim low system.html#low,array[I,T] proc low[I, T](x: array[I, T]): I 320 +nim low system.html#low,typedesc[array[I,T]] proc low[I, T](x: typedesc[array[I, T]]): I 334 +nim low system.html#low,cstring proc low(x: cstring): int 345 +nim low system.html#low,string proc low(x: string): int 351 +nim `[]` system.html#[],T,I proc `[]`[I: Ordinal; T](a: T; i: I): T 373 +nim `[]=` system.html#[]=,T,I,sinkS proc `[]=`[I: Ordinal; T, S](a: T; i: I; x: sink S) 375 +nim `=` system.html#=,T,T proc `=`[T](dest: var T; src: T) 377 +nim `=copy` system.html#=copy,T,T proc `=copy`[T](dest: var T; src: T) 378 +nim `=destroy` system.html#=destroy,T proc `=destroy`[T](x: var T) 391 +nim `=destroy` system.html#=destroy,string proc `=destroy`(x: string) 396 +nim `=destroy` system.html#=destroy,seq[T] proc `=destroy`[T](x: seq[T]) 399 +nim `=destroy` system.html#=destroy,ref.T proc `=destroy`[T](x: ref T) 402 +nim `=dup` system.html#=dup,T proc `=dup`[T](x: T): T 406 +nim `=sink` system.html#=sink,T,T proc `=sink`[T](x: var T; y: T) 410 +nim `=trace` system.html#=trace,T,pointer proc `=trace`[T](x: var T; env: pointer) 418 +nim HSlice system.html#HSlice object HSlice 423 +nim Slice system.html#Slice type Slice 426 +nim `..` system.html#..,sinkT,sinkU proc `..`[T, U](a: sink T; b: sink U): HSlice[T, U] 428 +nim `..` system.html#..,sinkT proc `..`[T](b: sink T): HSlice[int, T] 440 +nim succ system.html#succ,T,V proc succ[T, V: Ordinal](x: T; y: V = 1): T 1 +nim pred system.html#pred,T,V proc pred[T, V: Ordinal](x: T; y: V = 1): T 10 +nim inc system.html#inc,T,V proc inc[T, V: Ordinal](x: var T; y: V = 1) 19 +nim dec system.html#dec,T,V proc dec[T, V: Ordinal](x: var T; y: V = 1) 31 +nim `+` system.html#+,int proc `+`(x: int): int 49 +nim `+` system.html#+,int8 proc `+`(x: int8): int8 51 +nim `+` system.html#+,int16 proc `+`(x: int16): int16 52 +nim `+` system.html#+,int32 proc `+`(x: int32): int32 53 +nim `+` system.html#+,int64 proc `+`(x: int64): int64 54 +nim `-` system.html#-,int proc `-`(x: int): int 56 +nim `-` system.html#-,int8 proc `-`(x: int8): int8 58 +nim `-` system.html#-,int16 proc `-`(x: int16): int16 59 +nim `-` system.html#-,int32 proc `-`(x: int32): int32 60 +nim `-` system.html#-,int64 proc `-`(x: int64): int64 61 +nim `not` system.html#not,int proc `not`(x: int): int 63 +nim `not` system.html#not,int8 proc `not`(x: int8): int8 70 +nim `not` system.html#not,int16 proc `not`(x: int16): int16 71 +nim `not` system.html#not,int32 proc `not`(x: int32): int32 72 +nim `not` system.html#not,int64 proc `not`(x: int64): int64 73 +nim `+` system.html#+,int,int proc `+`(x, y: int): int 75 +nim `+` system.html#+,int8,int8 proc `+`(x, y: int8): int8 77 +nim `+` system.html#+,int16,int16 proc `+`(x, y: int16): int16 78 +nim `+` system.html#+,int32,int32 proc `+`(x, y: int32): int32 79 +nim `+` system.html#+,int64,int64 proc `+`(x, y: int64): int64 80 +nim `-` system.html#-,int,int proc `-`(x, y: int): int 82 +nim `-` system.html#-,int8,int8 proc `-`(x, y: int8): int8 84 +nim `-` system.html#-,int16,int16 proc `-`(x, y: int16): int16 85 +nim `-` system.html#-,int32,int32 proc `-`(x, y: int32): int32 86 +nim `-` system.html#-,int64,int64 proc `-`(x, y: int64): int64 87 +nim `*` system.html#*,int,int proc `*`(x, y: int): int 89 +nim `*` system.html#*,int8,int8 proc `*`(x, y: int8): int8 91 +nim `*` system.html#*,int16,int16 proc `*`(x, y: int16): int16 92 +nim `*` system.html#*,int32,int32 proc `*`(x, y: int32): int32 93 +nim `*` system.html#*,int64,int64 proc `*`(x, y: int64): int64 94 +nim `div` system.html#div,int,int proc `div`(x, y: int): int 96 +nim `div` system.html#div,int8,int8 proc `div`(x, y: int8): int8 108 +nim `div` system.html#div,int16,int16 proc `div`(x, y: int16): int16 109 +nim `div` system.html#div,int32,int32 proc `div`(x, y: int32): int32 110 +nim `div` system.html#div,int64,int64 proc `div`(x, y: int64): int64 111 +nim `mod` system.html#mod,int,int proc `mod`(x, y: int): int 113 +nim `mod` system.html#mod,int8,int8 proc `mod`(x, y: int8): int8 122 +nim `mod` system.html#mod,int16,int16 proc `mod`(x, y: int16): int16 123 +nim `mod` system.html#mod,int32,int32 proc `mod`(x, y: int32): int32 124 +nim `mod` system.html#mod,int64,int64 proc `mod`(x, y: int64): int64 125 +nim `shr` system.html#shr,int,SomeInteger proc `shr`(x: int; y: SomeInteger): int 135 +nim `shr` system.html#shr,int8,SomeInteger proc `shr`(x: int8; y: SomeInteger): int8 152 +nim `shr` system.html#shr,int16,SomeInteger proc `shr`(x: int16; y: SomeInteger): int16 153 +nim `shr` system.html#shr,int32,SomeInteger proc `shr`(x: int32; y: SomeInteger): int32 154 +nim `shr` system.html#shr,int64,SomeInteger proc `shr`(x: int64; y: SomeInteger): int64 155 +nim `shl` system.html#shl,int,SomeInteger proc `shl`(x: int; y: SomeInteger): int 158 +nim `shl` system.html#shl,int8,SomeInteger proc `shl`(x: int8; y: SomeInteger): int8 166 +nim `shl` system.html#shl,int16,SomeInteger proc `shl`(x: int16; y: SomeInteger): int16 167 +nim `shl` system.html#shl,int32,SomeInteger proc `shl`(x: int32; y: SomeInteger): int32 168 +nim `shl` system.html#shl,int64,SomeInteger proc `shl`(x: int64; y: SomeInteger): int64 169 +nim ashr system.html#ashr,int,SomeInteger proc ashr(x: int; y: SomeInteger): int 171 +nim ashr system.html#ashr,int8,SomeInteger proc ashr(x: int8; y: SomeInteger): int8 184 +nim ashr system.html#ashr,int16,SomeInteger proc ashr(x: int16; y: SomeInteger): int16 185 +nim ashr system.html#ashr,int32,SomeInteger proc ashr(x: int32; y: SomeInteger): int32 186 +nim ashr system.html#ashr,int64,SomeInteger proc ashr(x: int64; y: SomeInteger): int64 187 +nim `and` system.html#and,int,int proc `and`(x, y: int): int 189 +nim `and` system.html#and,int8,int8 proc `and`(x, y: int8): int8 194 +nim `and` system.html#and,int16,int16 proc `and`(x, y: int16): int16 195 +nim `and` system.html#and,int32,int32 proc `and`(x, y: int32): int32 196 +nim `and` system.html#and,int64,int64 proc `and`(x, y: int64): int64 197 +nim `or` system.html#or,int,int proc `or`(x, y: int): int 199 +nim `or` system.html#or,int8,int8 proc `or`(x, y: int8): int8 204 +nim `or` system.html#or,int16,int16 proc `or`(x, y: int16): int16 205 +nim `or` system.html#or,int32,int32 proc `or`(x, y: int32): int32 206 +nim `or` system.html#or,int64,int64 proc `or`(x, y: int64): int64 207 +nim `xor` system.html#xor,int,int proc `xor`(x, y: int): int 209 +nim `xor` system.html#xor,int8,int8 proc `xor`(x, y: int8): int8 214 +nim `xor` system.html#xor,int16,int16 proc `xor`(x, y: int16): int16 215 +nim `xor` system.html#xor,int32,int32 proc `xor`(x, y: int32): int32 216 +nim `xor` system.html#xor,int64,int64 proc `xor`(x, y: int64): int64 217 +nim `not` system.html#not,uint proc `not`(x: uint): uint 220 +nim `not` system.html#not,uint8 proc `not`(x: uint8): uint8 222 +nim `not` system.html#not,uint16 proc `not`(x: uint16): uint16 223 +nim `not` system.html#not,uint32 proc `not`(x: uint32): uint32 224 +nim `not` system.html#not,uint64 proc `not`(x: uint64): uint64 225 +nim `shr` system.html#shr,uint,SomeInteger proc `shr`(x: uint; y: SomeInteger): uint 227 +nim `shr` system.html#shr,uint8,SomeInteger proc `shr`(x: uint8; y: SomeInteger): uint8 229 +nim `shr` system.html#shr,uint16,SomeInteger proc `shr`(x: uint16; y: SomeInteger): uint16 230 +nim `shr` system.html#shr,uint32,SomeInteger proc `shr`(x: uint32; y: SomeInteger): uint32 231 +nim `shr` system.html#shr,uint64,SomeInteger proc `shr`(x: uint64; y: SomeInteger): uint64 232 +nim `shl` system.html#shl,uint,SomeInteger proc `shl`(x: uint; y: SomeInteger): uint 234 +nim `shl` system.html#shl,uint8,SomeInteger proc `shl`(x: uint8; y: SomeInteger): uint8 236 +nim `shl` system.html#shl,uint16,SomeInteger proc `shl`(x: uint16; y: SomeInteger): uint16 237 +nim `shl` system.html#shl,uint32,SomeInteger proc `shl`(x: uint32; y: SomeInteger): uint32 238 +nim `shl` system.html#shl,uint64,SomeInteger proc `shl`(x: uint64; y: SomeInteger): uint64 239 +nim `and` system.html#and,uint,uint proc `and`(x, y: uint): uint 241 +nim `and` system.html#and,uint8,uint8 proc `and`(x, y: uint8): uint8 243 +nim `and` system.html#and,uint16,uint16 proc `and`(x, y: uint16): uint16 244 +nim `and` system.html#and,uint32,uint32 proc `and`(x, y: uint32): uint32 245 +nim `and` system.html#and,uint64,uint64 proc `and`(x, y: uint64): uint64 246 +nim `or` system.html#or,uint,uint proc `or`(x, y: uint): uint 248 +nim `or` system.html#or,uint8,uint8 proc `or`(x, y: uint8): uint8 250 +nim `or` system.html#or,uint16,uint16 proc `or`(x, y: uint16): uint16 251 +nim `or` system.html#or,uint32,uint32 proc `or`(x, y: uint32): uint32 252 +nim `or` system.html#or,uint64,uint64 proc `or`(x, y: uint64): uint64 253 +nim `xor` system.html#xor,uint,uint proc `xor`(x, y: uint): uint 255 +nim `xor` system.html#xor,uint8,uint8 proc `xor`(x, y: uint8): uint8 257 +nim `xor` system.html#xor,uint16,uint16 proc `xor`(x, y: uint16): uint16 258 +nim `xor` system.html#xor,uint32,uint32 proc `xor`(x, y: uint32): uint32 259 +nim `xor` system.html#xor,uint64,uint64 proc `xor`(x, y: uint64): uint64 260 +nim `+` system.html#+,uint,uint proc `+`(x, y: uint): uint 262 +nim `+` system.html#+,uint8,uint8 proc `+`(x, y: uint8): uint8 264 +nim `+` system.html#+,uint16,uint16 proc `+`(x, y: uint16): uint16 265 +nim `+` system.html#+,uint32,uint32 proc `+`(x, y: uint32): uint32 266 +nim `+` system.html#+,uint64,uint64 proc `+`(x, y: uint64): uint64 267 +nim `-` system.html#-,uint,uint proc `-`(x, y: uint): uint 269 +nim `-` system.html#-,uint8,uint8 proc `-`(x, y: uint8): uint8 271 +nim `-` system.html#-,uint16,uint16 proc `-`(x, y: uint16): uint16 272 +nim `-` system.html#-,uint32,uint32 proc `-`(x, y: uint32): uint32 273 +nim `-` system.html#-,uint64,uint64 proc `-`(x, y: uint64): uint64 274 +nim `*` system.html#*,uint,uint proc `*`(x, y: uint): uint 276 +nim `*` system.html#*,uint8,uint8 proc `*`(x, y: uint8): uint8 278 +nim `*` system.html#*,uint16,uint16 proc `*`(x, y: uint16): uint16 279 +nim `*` system.html#*,uint32,uint32 proc `*`(x, y: uint32): uint32 280 +nim `*` system.html#*,uint64,uint64 proc `*`(x, y: uint64): uint64 281 +nim `div` system.html#div,uint,uint proc `div`(x, y: uint): uint 283 +nim `div` system.html#div,uint8,uint8 proc `div`(x, y: uint8): uint8 286 +nim `div` system.html#div,uint16,uint16 proc `div`(x, y: uint16): uint16 287 +nim `div` system.html#div,uint32,uint32 proc `div`(x, y: uint32): uint32 288 +nim `div` system.html#div,uint64,uint64 proc `div`(x, y: uint64): uint64 289 +nim `mod` system.html#mod,uint,uint proc `mod`(x, y: uint): uint 291 +nim `mod` system.html#mod,uint8,uint8 proc `mod`(x, y: uint8): uint8 294 +nim `mod` system.html#mod,uint16,uint16 proc `mod`(x, y: uint16): uint16 295 +nim `mod` system.html#mod,uint32,uint32 proc `mod`(x, y: uint32): uint32 296 +nim `mod` system.html#mod,uint64,uint64 proc `mod`(x, y: uint64): uint64 297 +nim `+=` system.html#+=,T,T proc `+=`[T: SomeInteger](x: var T; y: T) 299 +nim `-=` system.html#-=,T,T proc `-=`[T: SomeInteger](x: var T; y: T) 303 +nim `*=` system.html#*=,T,T proc `*=`[T: SomeInteger](x: var T; y: T) 307 +nim `+` system.html#+,float32 proc `+`(x: float32): float32 313 +nim `-` system.html#-,float32 proc `-`(x: float32): float32 314 +nim `+` system.html#+,float32,float32 proc `+`(x, y: float32): float32 315 +nim `-` system.html#-,float32,float32 proc `-`(x, y: float32): float32 316 +nim `*` system.html#*,float32,float32 proc `*`(x, y: float32): float32 317 +nim `/` system.html#/,float32,float32 proc `/`(x, y: float32): float32 318 +nim `+` system.html#+,float proc `+`(x: float): float 320 +nim `-` system.html#-,float proc `-`(x: float): float 321 +nim `+` system.html#+,float,float proc `+`(x, y: float): float 322 +nim `-` system.html#-,float,float proc `-`(x, y: float): float 323 +nim `*` system.html#*,float,float proc `*`(x, y: float): float 324 +nim `/` system.html#/,float,float proc `/`(x, y: float): float 325 +nim `+=` system.html#+=,T,T_2 proc `+=`[T: float | float32 | float64](x: var T; y: T) 327 +nim `-=` system.html#-=,T,T_2 proc `-=`[T: float | float32 | float64](x: var T; y: T) 332 +nim `*=` system.html#*=,T,T_2 proc `*=`[T: float | float32 | float64](x: var T; y: T) 337 +nim `/=` system.html#/=,float64,float64 proc `/=`(x: var float64; y: float64) 342 +nim `/=` system.html#/=,T,T proc `/=`[T: float | float32](x: var T; y: T) 346 +nim `+%` system.html#+%,int,int proc `+%`(x, y: int): int 352 +nim `+%` system.html#+%,int8,int8 proc `+%`(x, y: int8): int8 358 +nim `+%` system.html#+%,int16,int16 proc `+%`(x, y: int16): int16 359 +nim `+%` system.html#+%,int32,int32 proc `+%`(x, y: int32): int32 360 +nim `+%` system.html#+%,int64,int64 proc `+%`(x, y: int64): int64 361 +nim `-%` system.html#-%,int,int proc `-%`(x, y: int): int 363 +nim `-%` system.html#-%,int8,int8 proc `-%`(x, y: int8): int8 369 +nim `-%` system.html#-%,int16,int16 proc `-%`(x, y: int16): int16 370 +nim `-%` system.html#-%,int32,int32 proc `-%`(x, y: int32): int32 371 +nim `-%` system.html#-%,int64,int64 proc `-%`(x, y: int64): int64 372 +nim `*%` system.html#*%,int,int proc `*%`(x, y: int): int 374 +nim `*%` system.html#*%,int8,int8 proc `*%`(x, y: int8): int8 380 +nim `*%` system.html#*%,int16,int16 proc `*%`(x, y: int16): int16 381 +nim `*%` system.html#*%,int32,int32 proc `*%`(x, y: int32): int32 382 +nim `*%` system.html#*%,int64,int64 proc `*%`(x, y: int64): int64 383 +nim `/%` system.html#/%,int,int proc `/%`(x, y: int): int 385 +nim `/%` system.html#/%,int8,int8 proc `/%`(x, y: int8): int8 391 +nim `/%` system.html#/%,int16,int16 proc `/%`(x, y: int16): int16 392 +nim `/%` system.html#/%,int32,int32 proc `/%`(x, y: int32): int32 393 +nim `/%` system.html#/%,int64,int64 proc `/%`(x, y: int64): int64 394 +nim `%%` system.html#%%,int,int proc `%%`(x, y: int): int 396 +nim `%%` system.html#%%,int8,int8 proc `%%`(x, y: int8): int8 402 +nim `%%` system.html#%%,int16,int16 proc `%%`(x, y: int16): int16 403 +nim `%%` system.html#%%,int32,int32 proc `%%`(x, y: int32): int32 404 +nim `%%` system.html#%%,int64,int64 proc `%%`(x, y: int64): int64 405 +nim `==` system.html#==,Enum,Enum proc `==`[Enum: enum](x, y: Enum): bool 2 +nim `==` system.html#==,pointer,pointer proc `==`(x, y: pointer): bool 15 +nim `==` system.html#==,string,string proc `==`(x, y: string): bool 22 +nim `==` system.html#==,char,char proc `==`(x, y: char): bool 25 +nim `==` system.html#==,bool,bool proc `==`(x, y: bool): bool 27 +nim `==` system.html#==,set[T],set[T] proc `==`[T](x, y: set[T]): bool 29 +nim `==` system.html#==,ref.T,ref.T proc `==`[T](x, y: ref T): bool 34 +nim `==` system.html#==,ptr.T,ptr.T proc `==`[T](x, y: ptr T): bool 36 +nim `==` system.html#==,T,T proc `==`[T: proc | iterator](x, y: T): bool 38 +nim `<=` system.html#<=,Enum,Enum proc `<=`[Enum: enum](x, y: Enum): bool 41 +nim `<=` system.html#<=,string,string proc `<=`(x, y: string): bool 42 +nim `<=` system.html#<=,char,char proc `<=`(x, y: char): bool 54 +nim `<=` system.html#<=,set[T],set[T] proc `<=`[T](x, y: set[T]): bool 66 +nim `<=` system.html#<=,bool,bool proc `<=`(x, y: bool): bool 80 +nim `<=` system.html#<=,ref.T,ref.T proc `<=`[T](x, y: ref T): bool 81 +nim `<=` system.html#<=,pointer,pointer proc `<=`(x, y: pointer): bool 82 +nim `<` system.html#<,Enum,Enum proc `<`[Enum: enum](x, y: Enum): bool 84 +nim `<` system.html#<,string,string proc `<`(x, y: string): bool 85 +nim `<` system.html#<,char,char proc `<`(x, y: char): bool 97 +nim `<` system.html#<,set[T],set[T] proc `<`[T](x, y: set[T]): bool 109 +nim `<` system.html#<,bool,bool proc `<`(x, y: bool): bool 123 +nim `<` system.html#<,ref.T,ref.T proc `<`[T](x, y: ref T): bool 124 +nim `<` system.html#<,ptr.T,ptr.T proc `<`[T](x, y: ptr T): bool 125 +nim `<` system.html#<,pointer,pointer proc `<`(x, y: pointer): bool 126 +nim `!=` system.html#!=.t,untyped,untyped template `!=`(x, y: untyped): untyped 131 +nim `>=` system.html#>=.t,untyped,untyped template `>=`(x, y: untyped): untyped 135 +nim `>` system.html#>.t,untyped,untyped template `>`(x, y: untyped): untyped 139 +nim `==` system.html#==,int,int proc `==`(x, y: int): bool 144 +nim `==` system.html#==,int8,int8 proc `==`(x, y: int8): bool 146 +nim `==` system.html#==,int16,int16 proc `==`(x, y: int16): bool 147 +nim `==` system.html#==,int32,int32 proc `==`(x, y: int32): bool 148 +nim `==` system.html#==,int64,int64 proc `==`(x, y: int64): bool 149 +nim `<=` system.html#<=,int,int proc `<=`(x, y: int): bool 151 +nim `<=` system.html#<=,int8,int8 proc `<=`(x, y: int8): bool 153 +nim `<=` system.html#<=,int16,int16 proc `<=`(x, y: int16): bool 154 +nim `<=` system.html#<=,int32,int32 proc `<=`(x, y: int32): bool 155 +nim `<=` system.html#<=,int64,int64 proc `<=`(x, y: int64): bool 156 +nim `<` system.html#<,int,int proc `<`(x, y: int): bool 158 +nim `<` system.html#<,int8,int8 proc `<`(x, y: int8): bool 160 +nim `<` system.html#<,int16,int16 proc `<`(x, y: int16): bool 161 +nim `<` system.html#<,int32,int32 proc `<`(x, y: int32): bool 162 +nim `<` system.html#<,int64,int64 proc `<`(x, y: int64): bool 163 +nim `<=` system.html#<=,uint,uint proc `<=`(x, y: uint): bool 165 +nim `<=` system.html#<=,uint8,uint8 proc `<=`(x, y: uint8): bool 167 +nim `<=` system.html#<=,uint16,uint16 proc `<=`(x, y: uint16): bool 168 +nim `<=` system.html#<=,uint32,uint32 proc `<=`(x, y: uint32): bool 169 +nim `<=` system.html#<=,uint64,uint64 proc `<=`(x, y: uint64): bool 170 +nim `<` system.html#<,uint,uint proc `<`(x, y: uint): bool 172 +nim `<` system.html#<,uint8,uint8 proc `<`(x, y: uint8): bool 174 +nim `<` system.html#<,uint16,uint16 proc `<`(x, y: uint16): bool 175 +nim `<` system.html#<,uint32,uint32 proc `<`(x, y: uint32): bool 176 +nim `<` system.html#<,uint64,uint64 proc `<`(x, y: uint64): bool 177 +nim `<=%` system.html#<=%,int,int proc `<=%`(x, y: int): bool 179 +nim `<=%` system.html#<=%,int8,int8 proc `<=%`(x, y: int8): bool 183 +nim `<=%` system.html#<=%,int16,int16 proc `<=%`(x, y: int16): bool 184 +nim `<=%` system.html#<=%,int32,int32 proc `<=%`(x, y: int32): bool 185 +nim `<=%` system.html#<=%,int64,int64 proc `<=%`(x, y: int64): bool 186 +nim `<%` system.html#<%,int,int proc `<%`(x, y: int): bool 188 +nim `<%` system.html#<%,int8,int8 proc `<%`(x, y: int8): bool 192 +nim `<%` system.html#<%,int16,int16 proc `<%`(x, y: int16): bool 193 +nim `<%` system.html#<%,int32,int32 proc `<%`(x, y: int32): bool 194 +nim `<%` system.html#<%,int64,int64 proc `<%`(x, y: int64): bool 195 +nim `>=%` system.html#>=%.t,untyped,untyped template `>=%`(x, y: untyped): untyped 197 +nim `>%` system.html#>%.t,untyped,untyped template `>%`(x, y: untyped): untyped 201 +nim `==` system.html#==,uint,uint proc `==`(x, y: uint): bool 205 +nim `==` system.html#==,uint8,uint8 proc `==`(x, y: uint8): bool 207 +nim `==` system.html#==,uint16,uint16 proc `==`(x, y: uint16): bool 208 +nim `==` system.html#==,uint32,uint32 proc `==`(x, y: uint32): bool 209 +nim `==` system.html#==,uint64,uint64 proc `==`(x, y: uint64): bool 210 +nim `<=` system.html#<=,float32,float32 proc `<=`(x, y: float32): bool 212 +nim `<=` system.html#<=,float,float proc `<=`(x, y: float): bool 213 +nim `<` system.html#<,float32,float32 proc `<`(x, y: float32): bool 215 +nim `<` system.html#<,float,float proc `<`(x, y: float): bool 216 +nim `==` system.html#==,float32,float32 proc `==`(x, y: float32): bool 218 +nim `==` system.html#==,float,float proc `==`(x, y: float): bool 219 +nim min system.html#min,int,int proc min(x, y: int): int 223 +nim min system.html#min,int8,int8 proc min(x, y: int8): int8 225 +nim min system.html#min,int16,int16 proc min(x, y: int16): int16 227 +nim min system.html#min,int32,int32 proc min(x, y: int32): int32 229 +nim min system.html#min,int64,int64 proc min(x, y: int64): int64 231 +nim min system.html#min,float32,float32 proc min(x, y: float32): float32 234 +nim min system.html#min,float64,float64 proc min(x, y: float64): float64 236 +nim min system.html#min,T,T proc min[T: not SomeFloat](x, y: T): T 238 +nim max system.html#max,int,int proc max(x, y: int): int 242 +nim max system.html#max,int8,int8 proc max(x, y: int8): int8 244 +nim max system.html#max,int16,int16 proc max(x, y: int16): int16 246 +nim max system.html#max,int32,int32 proc max(x, y: int32): int32 248 +nim max system.html#max,int64,int64 proc max(x, y: int64): int64 250 +nim max system.html#max,float32,float32 proc max(x, y: float32): float32 253 +nim max system.html#max,float64,float64 proc max(x, y: float64): float64 255 +nim max system.html#max,T,T proc max[T: not SomeFloat](x, y: T): T 257 +nim min system.html#min,openArray[T] proc min[T](x: openArray[T]): T 262 +nim max system.html#max,openArray[T] proc max[T](x: openArray[T]): T 268 +nim clamp system.html#clamp,T,T,T proc clamp[T](x, a, b: T): T 277 +nim `==` system.html#==,array[I,T],array[I,T] proc `==`[I, T](x, y: array[I, T]): bool 294 +nim `==` system.html#==,openArray[T],openArray[T] proc `==`[T](x, y: openArray[T]): bool 300 +nim `==` system.html#==,seq[T],seq[T] proc `==`[T](x, y: seq[T]): bool 309 +nim appType system.html#appType const appType 458 +nim byte system.html#byte type byte 486 +nim Natural system.html#Natural type Natural 489 +nim Positive system.html#Positive type Positive 493 +nim RootObj system.html#RootObj object RootObj 498 +nim RootRef system.html#RootRef type RootRef 503 +nim RootEffect system.html#RootEffect object RootEffect 508 +nim StackTraceEntry system.html#StackTraceEntry object StackTraceEntry 515 +nim Exception system.html#Exception object Exception 532 +nim Defect system.html#Defect object Defect 550 +nim CatchableError system.html#CatchableError object CatchableError 555 +nim JsRoot system.html#JsRoot type JsRoot 566 +nim unsafeNew system.html#unsafeNew,ref.T,Natural proc unsafeNew[T](a: var ref T; size: Natural) 569 +nim sizeof system.html#sizeof,T proc sizeof[T](x: T): int 580 +nim alignof system.html#alignof,T proc alignof[T](x: T): int 599 +nim alignof system.html#alignof,typedesc proc alignof(x: typedesc): int 600 +nim offsetOf system.html#offsetOf.t,typedesc[T],untyped template offsetOf[T](t: typedesc[T]; member: untyped): int 604 +nim offsetOf system.html#offsetOf.t,T,untyped template offsetOf[T](value: T; member: untyped): int 608 +nim sizeof system.html#sizeof,typedesc proc sizeof(x: typedesc): int 613 +nim newSeq system.html#newSeq,seq[T],Natural proc newSeq[T](s: var seq[T]; len: Natural) 616 +nim newSeq system.html#newSeq proc newSeq[T](len = 0.Natural): seq[T] 635 +nim newSeqOfCap system.html#newSeqOfCap,Natural proc newSeqOfCap[T](cap: Natural): seq[T] 655 +nim len system.html#len,TOpenArray proc len[TOpenArray: openArray | varargs](x: TOpenArray): int 667 +nim len system.html#len,string proc len(x: string): int 674 +nim len system.html#len,cstring proc len(x: cstring): int 681 +nim len system.html#len proc len(x: (type array) | array): int 700 +nim len system.html#len,seq[T] proc len[T](x: seq[T]): int 709 +nim ord system.html#ord,T proc ord[T: Ordinal | enum](x: T): int 719 +nim chr system.html#chr,range[] proc chr(u: range[0 .. 255]): char 730 +nim incl system.html#incl,set[T],T proc incl[T](x: var set[T]; y: T) 1 +nim incl system.html#incl.t,set[T],set[T] template incl[T](x: var set[T]; y: set[T]) 15 +nim excl system.html#excl,set[T],T proc excl[T](x: var set[T]; y: T) 24 +nim excl system.html#excl.t,set[T],set[T] template excl[T](x: var set[T]; y: set[T]) 33 +nim card system.html#card,set[T] proc card[T](x: set[T]): int 42 +nim len system.html#len,set[T] proc len[T](x: set[T]): int 51 +nim `*` system.html#*,set[T],set[T] proc `*`[T](x, y: set[T]): set[T] 55 +nim `+` system.html#+,set[T],set[T] proc `+`[T](x, y: set[T]): set[T] 60 +nim `-` system.html#-,set[T],set[T] proc `-`[T](x, y: set[T]): set[T] 65 +nim contains system.html#contains,set[T],T proc contains[T](x: set[T]; y: T): bool 70 +nim contains system.html#contains,HSlice[U,V],W proc contains[U, V, W](s: HSlice[U, V]; value: W): bool 746 +nim `in` system.html#in.t,untyped,untyped template `in`(x, y: untyped): untyped 759 +nim `notin` system.html#notin.t,untyped,untyped template `notin`(x, y: untyped): untyped 765 +nim `is` system.html#is,T,S proc `is`[T, S](x: T; y: S): bool 772 +nim `isnot` system.html#isnot.t,untyped,untyped template `isnot`(x, y: untyped): untyped 790 +nim owned system.html#owned type owned 798 +nim unown system.html#unown.t,typed template unown(x: typed): untyped 825 +nim new system.html#new,ref.T proc new[T](a: var ref T) 827 +nim new system.html#new,typedesc proc new(t: typedesc): auto 831 +nim disarm system.html#disarm.t,typed template disarm(x: typed) 845 +nim `of` system.html#of,T,typedesc[S] proc `of`[T, S](x: T; y: typedesc[S]): bool 852 +nim cmp system.html#cmp,T,T proc cmp[T](x, y: T): int 878 +nim cmp system.html#cmp,string,string proc cmp(x, y: string): int 896 +nim `@` system.html#@,sinkarray[IDX,T] proc `@`[IDX, T](a: sink array[IDX, T]): seq[T] 902 +nim default system.html#default,typedesc[T] proc default[T](_: typedesc[T]): T 918 +nim reset system.html#reset,T proc reset[T](obj: var T) 933 +nim setLen system.html#setLen,seq[T],Natural proc setLen[T](s: var seq[T]; newlen: Natural) 945 +nim setLen system.html#setLen,string,Natural proc setLen(s: var string; newlen: Natural) 960 +nim newString system.html#newString,Natural proc newString(len: Natural): string 972 +nim newStringOfCap system.html#newStringOfCap,Natural proc newStringOfCap(cap: Natural): string 981 +nim `&` system.html#&,string,char proc `&`(x: string; y: char): string 988 +nim `&` system.html#&,char,char proc `&`(x, y: char): string 994 +nim `&` system.html#&,string,string proc `&`(x, y: string): string 1000 +nim `&` system.html#&,char,string proc `&`(x: char; y: string): string 1006 +nim add system.html#add,string,char proc add(x: var string; y: char) 1016 +nim add system.html#add,string,string proc add(x: var string; y: string) 1025 +nim littleEndian system.html#littleEndian Endianness.littleEndian 1036 +nim bigEndian system.html#bigEndian Endianness.bigEndian 1036 +nim Endianness system.html#Endianness enum Endianness 1036 +nim cpuEndian system.html#cpuEndian const cpuEndian 1040 +nim hostOS system.html#hostOS const hostOS 1045 +nim hostCPU system.html#hostCPU const hostCPU 1052 +nim QuitSuccess system.html#QuitSuccess const QuitSuccess 1105 +nim QuitFailure system.html#QuitFailure const QuitFailure 1109 +nim programResult system.html#programResult var programResult 1114 +nim add system.html#add,seq[T],openArray[T] proc add[T](x: var seq[T]; y: openArray[T]) 1185 +nim del system.html#del,seq[T],Natural proc del[T](x: var seq[T]; i: Natural) 1216 +nim insert system.html#insert,seq[T],sinkT proc insert[T](x: var seq[T]; item: sink T; i = 0.Natural) 1231 +nim Inf system.html#Inf const Inf 1277 +nim NegInf system.html#NegInf const NegInf 1279 +nim NaN system.html#NaN const NaN 1281 +nim high system.html#high,typedesc[SomeFloat] proc high(T: typedesc[SomeFloat]): T:type 1288 +nim low system.html#low,typedesc[SomeFloat] proc low(T: typedesc[SomeFloat]): T:type 1289 +nim toFloat system.html#toFloat,int proc toFloat(i: int): float 1291 +nim toBiggestFloat system.html#toBiggestFloat,BiggestInt proc toBiggestFloat(i: BiggestInt): BiggestFloat 1306 +nim toInt system.html#toInt,float proc toInt(f: float): int 1310 +nim toBiggestInt system.html#toBiggestInt,BiggestFloat proc toBiggestInt(f: BiggestFloat): BiggestInt 1327 +nim `/` system.html#/,int,int proc `/`(x, y: int): float 1331 +nim abs system.html#abs,T proc abs[T: float64 | float32](x: T): T 1350 +nim abs system.html#abs,int proc abs(x: int): int 1363 +nim abs system.html#abs,int8 proc abs(x: int8): int8 1365 +nim abs system.html#abs,int16 proc abs(x: int16): int16 1367 +nim abs system.html#abs,int32 proc abs(x: int32): int32 1369 +nim abs system.html#abs,int64 proc abs(x: int64): int64 1371 +nim swap system.html#swap,T,T proc swap[T](a, b: var T) 1394 +nim zeroMem system.html#zeroMem,pointer,Natural proc zeroMem(p: pointer; size: Natural) 2 +nim copyMem system.html#copyMem,pointer,pointer,Natural proc copyMem(dest, source: pointer; size: Natural) 9 +nim moveMem system.html#moveMem,pointer,pointer,Natural proc moveMem(dest, source: pointer; size: Natural) 17 +nim equalMem system.html#equalMem,pointer,pointer,Natural proc equalMem(a, b: pointer; size: Natural): bool 27 +nim cmpMem system.html#cmpMem,pointer,pointer,Natural proc cmpMem(a, b: pointer; size: Natural): int 36 +nim allocImpl system.html#allocImpl,Natural proc allocImpl(size: Natural): pointer 51 +nim alloc0Impl system.html#alloc0Impl,Natural proc alloc0Impl(size: Natural): pointer 52 +nim deallocImpl system.html#deallocImpl,pointer proc deallocImpl(p: pointer) 53 +nim reallocImpl system.html#reallocImpl,pointer,Natural proc reallocImpl(p: pointer; newSize: Natural): pointer 54 +nim realloc0Impl system.html#realloc0Impl,pointer,Natural,Natural proc realloc0Impl(p: pointer; oldSize, newSize: Natural): pointer 55 +nim allocSharedImpl system.html#allocSharedImpl,Natural proc allocSharedImpl(size: Natural): pointer 57 +nim allocShared0Impl system.html#allocShared0Impl,Natural proc allocShared0Impl(size: Natural): pointer 58 +nim deallocSharedImpl system.html#deallocSharedImpl,pointer proc deallocSharedImpl(p: pointer) 59 +nim reallocSharedImpl system.html#reallocSharedImpl,pointer,Natural proc reallocSharedImpl(p: pointer; newSize: Natural): pointer 60 +nim reallocShared0Impl system.html#reallocShared0Impl,pointer,Natural,Natural proc reallocShared0Impl(p: pointer; oldSize, newSize: Natural): pointer 61 +nim AllocStats system.html#AllocStats object AllocStats 67 +nim `-` system.html#-,AllocStats,AllocStats proc `-`(a, b: AllocStats): AllocStats 71 +nim dumpAllocstats system.html#dumpAllocstats.t,untyped template dumpAllocstats(code: untyped) 75 +nim getAllocStats system.html#getAllocStats proc getAllocStats(): AllocStats 88 +nim alloc system.html#alloc.t,Natural template alloc(size: Natural): pointer 90 +nim createU system.html#createU,typedesc proc createU(T: typedesc; size = 1.Positive): ptr T:type 106 +nim alloc0 system.html#alloc0.t,Natural template alloc0(size: Natural): pointer 121 +nim create system.html#create,typedesc proc create(T: typedesc; size = 1.Positive): ptr T:type 134 +nim realloc system.html#realloc.t,pointer,Natural template realloc(p: pointer; newSize: Natural): pointer 146 +nim realloc0 system.html#realloc0.t,pointer,Natural,Natural template realloc0(p: pointer; oldSize, newSize: Natural): pointer 160 +nim resize system.html#resize,ptr.T,Natural proc resize[T](p: ptr T; newSize: Natural): ptr T 177 +nim dealloc system.html#dealloc,pointer proc dealloc(p: pointer) 190 +nim allocShared system.html#allocShared.t,Natural template allocShared(size: Natural): pointer 204 +nim createSharedU system.html#createSharedU,typedesc proc createSharedU(T: typedesc; size = 1.Positive): ptr T:type 220 +nim allocShared0 system.html#allocShared0.t,Natural template allocShared0(size: Natural): pointer 236 +nim createShared system.html#createShared,typedesc proc createShared(T: typedesc; size = 1.Positive): ptr T:type 250 +nim reallocShared system.html#reallocShared.t,pointer,Natural template reallocShared(p: pointer; newSize: Natural): pointer 263 +nim reallocShared0 system.html#reallocShared0.t,pointer,Natural,Natural template reallocShared0(p: pointer; oldSize, newSize: Natural): pointer 274 +nim resizeShared system.html#resizeShared,ptr.T,Natural proc resizeShared[T](p: ptr T; newSize: Natural): ptr T 288 +nim deallocShared system.html#deallocShared,pointer proc deallocShared(p: pointer) 299 +nim freeShared system.html#freeShared,ptr.T proc freeShared[T](p: ptr T) 310 +nim getOccupiedMem system.html#getOccupiedMem proc getOccupiedMem(): int 406 +nim getFreeMem system.html#getFreeMem proc getFreeMem(): int 409 +nim getTotalMem system.html#getTotalMem proc getTotalMem(): int 413 +nim getOccupiedSharedMem system.html#getOccupiedSharedMem proc getOccupiedSharedMem(): int 437 +nim getFreeSharedMem system.html#getFreeSharedMem proc getFreeSharedMem(): int 442 +nim getTotalSharedMem system.html#getTotalSharedMem proc getTotalSharedMem(): int 447 +nim `|` system.html#|,typedesc,typedesc proc `|`(a, b: typedesc): typedesc 1432 +nim countdown system.html#countdown.i,T,T,Positive iterator countdown[T](a, b: T; step: Positive = 1): T 6 +nim countup system.html#countup.i,T,T,Positive iterator countup[T](a, b: T; step: Positive = 1): T 46 +nim `..` system.html#...i,T,T iterator `..`[T](a, b: T): T 81 +nim `..` system.html#...i,int64,int64 iterator `..`(a, b: int64): int64 121 +nim `..` system.html#...i,int32,int32 iterator `..`(a, b: int32): int32 122 +nim `..` system.html#...i,uint64,uint64 iterator `..`(a, b: uint64): uint64 123 +nim `..` system.html#...i,uint32,uint32 iterator `..`(a, b: uint32): uint32 124 +nim `..<` system.html#..<.i,T,T iterator `..<`[T](a, b: T): T 126 +nim `..<` system.html#..<.i,int64,int64 iterator `..<`(a, b: int64): int64 142 +nim `..<` system.html#..<.i,int32,int32 iterator `..<`(a, b: int32): int32 143 +nim `..<` system.html#..<.i,uint64,uint64 iterator `..<`(a, b: uint64): uint64 144 +nim `..<` system.html#..<.i,uint32,uint32 iterator `..<`(a, b: uint32): uint32 145 +nim `||` system.html#||.i,S,T,staticstring iterator `||`[S, T](a: S; b: T; annotation: static string = "parallel for"): T 147 +nim `||` system.html#||.i,S,T,Positive,staticstring iterator `||`[S, T](a: S; b: T; step: Positive;\n annotation: static string = "parallel for"): T 164 +nim len system.html#len,HSlice[U: Ordinal,V: Ordinal] proc len[U: Ordinal; V: Ordinal](x: HSlice[U, V]): int 1437 +nim isNil system.html#isNil,ref.T proc isNil[T](x: ref T): bool 1445 +nim isNil system.html#isNil,ptr.T proc isNil[T](x: ptr T): bool 1447 +nim isNil system.html#isNil,pointer proc isNil(x: pointer): bool 1448 +nim isNil system.html#isNil,cstring proc isNil(x: cstring): bool 1449 +nim isNil system.html#isNil,T proc isNil[T: proc | iterator {.closure.}](x: T): bool 1450 +nim `@` system.html#@,openArray[T] proc `@`[T](a: openArray[T]): seq[T] 1456 +nim `&` system.html#&,sinkseq[T],sinkseq[T] proc `&`[T](x, y: sink seq[T]): seq[T] 1475 +nim `&` system.html#&,sinkseq[T],sinkT proc `&`[T](x: sink seq[T]; y: sink T): seq[T] 1491 +nim `&` system.html#&,sinkT,sinkseq[T] proc `&`[T](x: sink T; y: sink seq[T]): seq[T] 1506 +nim instantiationInfo system.html#instantiationInfo,int proc instantiationInfo(index = -1; fullPaths = false): tuple[filename: string,\n line: int, column: int] 1564 +nim prepareMutation system.html#prepareMutation,string proc prepareMutation(s: var string) 197 +nim capacity system.html#capacity,string proc capacity(self: string): int 215 +nim NimSeqV2 system.html#NimSeqV2 object NimSeqV2 28 +nim shrink system.html#shrink,seq[T],Natural proc shrink[T](x: var seq[T]; newLen: Natural) 125 +nim grow system.html#grow,seq[T],Natural,T proc grow[T](x: var seq[T]; newLen: Natural; value: T) 138 +nim add system.html#add,seq[T],sinkT proc add[T](x: var seq[T]; y: sink T) 150 +nim capacity system.html#capacity,seq[T] proc capacity[T](self: seq[T]): int 191 +nim setLenUninit system.html#setLenUninit,seq[T],Natural proc setLenUninit[T](s: var seq[T]; newlen: Natural) 202 +nim newSeqUninitialized system.html#newSeqUninitialized,Natural proc newSeqUninitialized[T: SomeNumber](len: Natural): seq[T] 1649 +nim newSeqUninit system.html#newSeqUninit,Natural proc newSeqUninit[T](len: Natural): seq[T] 1668 +nim newStringUninit system.html#newStringUninit,Natural proc newStringUninit(len: Natural): string 1688 +nim writeStackTrace system.html#writeStackTrace proc writeStackTrace() 1715 +nim PFrame system.html#PFrame type PFrame 1724 +nim TFrame system.html#TFrame object TFrame 1727 +nim isUniqueRef system.html#isUniqueRef,ref.T proc isUniqueRef[T](x: ref T): bool 133 +nim `=dispose` system.html#=dispose.t template `=dispose`[T](x: owned(ref T)) 190 +nim getThreadId system.html#getThreadId proc getThreadId(): int 30 +nim GC_runOrc system.html#GC_runOrc proc GC_runOrc() 455 +nim GC_enableOrc system.html#GC_enableOrc proc GC_enableOrc() 460 +nim GC_disableOrc system.html#GC_disableOrc proc GC_disableOrc() 466 +nim GC_prepareOrc system.html#GC_prepareOrc proc GC_prepareOrc(): int 472 +nim GC_partialCollect system.html#GC_partialCollect,int proc GC_partialCollect(limit: int) 474 +nim GC_fullCollect system.html#GC_fullCollect proc GC_fullCollect() 477 +nim GC_enableMarkAndSweep system.html#GC_enableMarkAndSweep proc GC_enableMarkAndSweep() 482 +nim GC_disableMarkAndSweep system.html#GC_disableMarkAndSweep proc GC_disableMarkAndSweep() 486 +nim GC_unref system.html#GC_unref,ref.T proc GC_unref[T](x: ref T) 239 +nim GC_ref system.html#GC_ref,ref.T proc GC_ref[T](x: ref T) 244 +nim setupForeignThreadGc system.html#setupForeignThreadGc.t template setupForeignThreadGc() 253 +nim tearDownForeignThreadGc system.html#tearDownForeignThreadGc.t template tearDownForeignThreadGc() 257 +nim newException system.html#newException.t,typedesc,string,ref.Exception template newException(exceptn: typedesc; message: string;\n parentException: ref Exception = nil): untyped 1743 +nim find system.html#find,T,S proc find[T, S](a: T; item: S): int 1757 +nim contains system.html#contains,openArray[T],T proc contains[T](a: openArray[T]; item: T): bool 1766 +nim pop system.html#pop,seq[T] proc pop[T](s: var seq[T]): T 1780 +nim `==` system.html#==,T,T_2 proc `==`[T: tuple | object](x, y: T): bool 1799 +nim `<=` system.html#<=,T,T proc `<=`[T: tuple](x, y: T): bool 1806 +nim `<` system.html#<,T,T proc `<`[T: tuple](x, y: T): bool 1815 +nim gcThroughput system.html#gcThroughput GC_Strategy.gcThroughput 10 +nim gcResponsiveness system.html#gcResponsiveness GC_Strategy.gcResponsiveness 10 +nim gcOptimizeTime system.html#gcOptimizeTime GC_Strategy.gcOptimizeTime 10 +nim gcOptimizeSpace system.html#gcOptimizeSpace GC_Strategy.gcOptimizeSpace 10 +nim GC_Strategy system.html#GC_Strategy enum GC_Strategy 10 +nim globalRaiseHook system.html#globalRaiseHook var globalRaiseHook 1840 +nim localRaiseHook system.html#localRaiseHook var localRaiseHook 1849 +nim outOfMemHook system.html#outOfMemHook var outOfMemHook 1859 +nim unhandledExceptionHook system.html#unhandledExceptionHook var unhandledExceptionHook 1879 +nim add system.html#add,string,cstring proc add(x: var string; y: cstring) 1886 +nim add system.html#add,cstring,cstring proc add(x: var cstring; y: cstring) 1901 +nim echo system.html#echo,varargs[typed,] proc echo(x: varargs[typed, `$`]) 1921 +nim debugEcho system.html#debugEcho,varargs[typed,] proc debugEcho(x: varargs[typed, `$`]) 1936 +nim getTypeInfo system.html#getTypeInfo,T proc getTypeInfo[T](x: T): pointer 1948 +nim likely system.html#likely.t,bool template likely(val: bool): bool 1960 +nim unlikely system.html#unlikely.t,bool template unlikely(val: bool): bool 1984 +nim delete system.html#delete,seq[T],Natural proc delete[T](x: var seq[T]; i: Natural) 2016 +nim NimVersion system.html#NimVersion const NimVersion 2049 +nim cstringArrayToSeq system.html#cstringArrayToSeq,cstringArray,Natural proc cstringArrayToSeq(a: cstringArray; len: Natural): seq[string] 2121 +nim cstringArrayToSeq system.html#cstringArrayToSeq,cstringArray proc cstringArrayToSeq(a: cstringArray): seq[string] 2128 +nim allocCStringArray system.html#allocCStringArray,openArray[string] proc allocCStringArray(a: openArray[string]): cstringArray 2138 +nim deallocCStringArray system.html#deallocCStringArray,cstringArray proc deallocCStringArray(a: cstringArray) 2148 +nim nimThreadDestructionHandlers system.html#nimThreadDestructionHandlers var nimThreadDestructionHandlers 2 +nim onThreadDestruction system.html#onThreadDestruction,proc) proc onThreadDestruction(handler: proc () {.closure, gcsafe, raises: [].}) 31 +nim nimThreadProcWrapperBody system.html#nimThreadProcWrapperBody.t,untyped template nimThreadProcWrapperBody(closure: untyped): untyped 97 +nim setControlCHook system.html#setControlCHook,proc) proc setControlCHook(hook: proc () {.noconv.}) 2180 +nim unsetControlCHook system.html#unsetControlCHook proc unsetControlCHook() 2195 +nim getStackTrace system.html#getStackTrace proc getStackTrace(): string 2199 +nim getStackTrace system.html#getStackTrace,ref.Exception proc getStackTrace(e: ref Exception): string 2202 +nim errorMessageWriter system.html#errorMessageWriter var errorMessageWriter 19 +nim getFrameState system.html#getFrameState proc getFrameState(): FrameState 100 +nim setFrameState system.html#setFrameState,FrameState proc setFrameState(state: FrameState) 106 +nim getFrame system.html#getFrame proc getFrame(): PFrame 116 +nim setFrame system.html#setFrame,PFrame proc setFrame(s: PFrame) 133 +nim stackTraceAvailable system.html#stackTraceAvailable proc stackTraceAvailable(): bool 329 +nim onUnhandledException system.html#onUnhandledException var onUnhandledException 370 +nim getStackTraceEntries system.html#getStackTraceEntries,ref.Exception proc getStackTraceEntries(e: ref Exception): lent seq[StackTraceEntry] 548 +nim getStackTraceEntries system.html#getStackTraceEntries proc getStackTraceEntries(): seq[StackTraceEntry] 553 +nim formatErrorIndexBound system.html#formatErrorIndexBound.t,T,T,T template formatErrorIndexBound[T](i, a, b: T): string 4 +nim formatErrorIndexBound system.html#formatErrorIndexBound.t,T,T template formatErrorIndexBound[T](i, n: T): string 11 +nim formatFieldDefect system.html#formatFieldDefect.t,, template formatFieldDefect(f, discVal): string 14 +nim iterToProc system.html#iterToProc,typed,typedesc,untyped proc iterToProc(iter: typed; envType: typedesc; procName: untyped) 490 +nim getMaxMem system.html#getMaxMem proc getMaxMem(): int 1265 +nim ForeignCell system.html#ForeignCell object ForeignCell 115 +nim protect system.html#protect,pointer proc protect(x: pointer): ForeignCell 118 +nim dispose system.html#dispose,ForeignCell proc dispose(x: ForeignCell) 119 +nim isNotForeign system.html#isNotForeign,ForeignCell proc isNotForeign(x: ForeignCell): bool 120 +nim GC_getStatistics system.html#GC_getStatistics proc GC_getStatistics(): string 257 +nim getCurrentException system.html#getCurrentException proc getCurrentException(): ref Exception 2295 +nim getCurrentExceptionMsg system.html#getCurrentExceptionMsg proc getCurrentExceptionMsg(): string 2304 +nim setCurrentException system.html#setCurrentException,ref.Exception proc setCurrentException(exc: ref Exception) 2309 +nim rawProc system.html#rawProc,T proc rawProc[T: proc {.closure.} | iterator {.closure.}](x: T): pointer 2323 +nim rawEnv system.html#rawEnv,T proc rawEnv[T: proc {.closure.} | iterator {.closure.}](x: T): pointer 2365 +nim finished system.html#finished,T proc finished[T: iterator {.closure.}](x: T): bool 2373 +nim quit system.html#quit,int proc quit(errorcode: int = QuitSuccess) 2399 +nim quit system.html#quit,string proc quit(errormsg: string; errorcode = QuitFailure) 2452 +nim BackwardsIndex system.html#BackwardsIndex type BackwardsIndex 5 +nim `^` system.html#^.t,int template `^`(x: int): BackwardsIndex 9 +nim `[]` system.html#[],openArray[T],BackwardsIndex proc `[]`[T](s: openArray[T]; i: BackwardsIndex): T 22 +nim `[]` system.html#[],array[Idx,T],BackwardsIndex proc `[]`[Idx, T](a: array[Idx, T]; i: BackwardsIndex): T 25 +nim `[]` system.html#[],string,BackwardsIndex proc `[]`(s: string; i: BackwardsIndex): char 27 +nim `[]` system.html#[],openArray[T],BackwardsIndex_2 proc `[]`[T](s: var openArray[T]; i: BackwardsIndex): var T 29 +nim `[]` system.html#[],array[Idx,T],BackwardsIndex_2 proc `[]`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex): var T 31 +nim `[]` system.html#[],string,BackwardsIndex_2 proc `[]`(s: var string; i: BackwardsIndex): var char 33 +nim `[]=` system.html#[]=,openArray[T],BackwardsIndex,T proc `[]=`[T](s: var openArray[T]; i: BackwardsIndex; x: T) 35 +nim `[]=` system.html#[]=,array[Idx,T],BackwardsIndex,T proc `[]=`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex; x: T) 37 +nim `[]=` system.html#[]=,string,BackwardsIndex,char proc `[]=`(s: var string; i: BackwardsIndex; x: char) 39 +nim `..^` system.html#..^.t,untyped,untyped template `..^`(a, b: untyped): untyped 42 +nim `..<` system.html#..<.t,untyped,untyped template `..<`(a, b: untyped): untyped 47 +nim `[]` system.html#[].t,string,int template `[]`(s: string; i: int): char 55 +nim `[]=` system.html#[]=.t,string,int,char template `[]=`(s: string; i: int; val: char) 56 +nim `[]` system.html#[],string,HSlice[T: Ordinal,U: Ordinal] proc `[]`[T, U: Ordinal](s: string; x: HSlice[T, U]): string 76 +nim `[]=` system.html#[]=,string,HSlice[T: Ordinal,U: Ordinal],string proc `[]=`[T, U: Ordinal](s: var string; x: HSlice[T, U]; b: string) 88 +nim `[]` system.html#[],array[Idx,T],HSlice[U: Ordinal,V: Ordinal] proc `[]`[Idx, T; U, V: Ordinal](a: array[Idx, T]; x: HSlice[U, V]): seq[T] 106 +nim `[]=` system.html#[]=,array[Idx,T],HSlice[U: Ordinal,V: Ordinal],openArray[T] proc `[]=`[Idx, T; U, V: Ordinal](a: var array[Idx, T]; x: HSlice[U, V];\n b: openArray[T]) 121 +nim `[]` system.html#[],openArray[T],HSlice[U: Ordinal,V: Ordinal] proc `[]`[T; U, V: Ordinal](s: openArray[T]; x: HSlice[U, V]): seq[T] 135 +nim `[]=` system.html#[]=,seq[T],HSlice[U: Ordinal,V: Ordinal],openArray[T] proc `[]=`[T; U, V: Ordinal](s: var seq[T]; x: HSlice[U, V]; b: openArray[T]) 150 +nim `&=` system.html#&=,string,string proc `&=`(x: var string; y: string) 2469 +nim `&=` system.html#&=.t,typed,typed template `&=`(x, y: typed) 2476 +nim rangeCheck system.html#rangeCheck.t template rangeCheck(cond) 2483 +nim NimNode system.html#NimNode type NimNode 2520 +nim ForLoopStmt system.html#ForLoopStmt object ForLoopStmt 2524 +nim varargsLen system.html#varargsLen.m,varargs[untyped] macro varargsLen(x: varargs[untyped]): int 2528 +nim repr system.html#repr,HSlice[T,U] proc repr[T, U](x: HSlice[T, U]): string 2537 +nim insert system.html#insert,string,string proc insert(x: var string; item: string; i = 0.Natural) 2548 +nim addEscapedChar system.html#addEscapedChar,string,char proc addEscapedChar(s: var string; c: char) 2573 +nim addQuoted system.html#addQuoted,string,T proc addQuoted[T](s: var string; x: T) 2615 +nim locals system.html#locals proc locals(): RootObj 2664 +nim deepCopy system.html#deepCopy,T,T proc deepCopy[T](x: var T; y: T) 2693 +nim deepCopy system.html#deepCopy,T proc deepCopy[T](y: T): T 2703 +nim procCall system.html#procCall,untyped proc procCall(x: untyped) 2709 +nim `==` system.html#==,cstring,cstring proc `==`(x, y: cstring): bool 2719 +nim closureScope system.html#closureScope.t,untyped template closureScope(body: untyped): untyped 2728 +nim once system.html#once.t,untyped template once(body: untyped): untyped 2755 +nim substr system.html#substr,openArray[char] proc substr(s: openArray[char]): string 2772 +nim substr system.html#substr,string,int,int proc substr(s: string; first, last: int): string 2784 +nim substr system.html#substr,string,int proc substr(s: string; first = 0): string 2805 +nim toOpenArray system.html#toOpenArray,ptr.UncheckedArray[T],int,int proc toOpenArray[T](x: ptr UncheckedArray[T]; first, last: int): openArray[T] 2812 +nim toOpenArray system.html#toOpenArray,cstring,int,int proc toOpenArray(x: cstring; first, last: int): openArray[char] 2814 +nim toOpenArrayByte system.html#toOpenArrayByte,cstring,int,int proc toOpenArrayByte(x: cstring; first, last: int): openArray[byte] 2816 +nim toOpenArray system.html#toOpenArray,seq[T],int,int proc toOpenArray[T](x: seq[T]; first, last: int): openArray[T] 2819 +nim toOpenArray system.html#toOpenArray,openArray[T],int,int proc toOpenArray[T](x: openArray[T]; first, last: int): openArray[T] 2833 +nim toOpenArray system.html#toOpenArray,array[I,T],I,I proc toOpenArray[I, T](x: array[I, T]; first, last: I): openArray[T] 2835 +nim toOpenArray system.html#toOpenArray,string,int,int proc toOpenArray(x: string; first, last: int): openArray[char] 2837 +nim toOpenArrayByte system.html#toOpenArrayByte,string,int,int proc toOpenArrayByte(x: string; first, last: int): openArray[byte] 2840 +nim toOpenArrayByte system.html#toOpenArrayByte,openArray[char],int,int proc toOpenArrayByte(x: openArray[char]; first, last: int): openArray[byte] 2842 +nim toOpenArrayByte system.html#toOpenArrayByte,seq[char],int,int proc toOpenArrayByte(x: seq[char]; first, last: int): openArray[byte] 2844 +nim toOpenArrayChar system.html#toOpenArrayChar,openArray[byte],int,int proc toOpenArrayChar(x: openArray[byte]; first, last: int): openArray[char] 2847 +nim arrayWith system.html#arrayWith,T,staticint proc arrayWith[T](y: T; size: static int): array[size, T] 2968 +nim arrayWithDefault system.html#arrayWithDefault,staticint proc arrayWithDefault[T](size: static int): array[size, T] 2974 +heading System module system.html#system-module System module 0 +heading Strings and characters system.html#system-module-strings-and-characters Strings and characters 0 +heading Seqs system.html#system-module-seqs Seqs 0 +heading Sets system.html#system-module-sets Sets 0 +heading Numbers system.html#system-module-numbers Numbers 0 +heading Ordinals system.html#system-module-ordinals Ordinals 0 +heading Misc system.html#system-module-misc Misc 0 +idx for-loop macro system.html#forminusloop-macro_1 Misc 0 +idx out of memory system.html#out-of-memory_1 Misc 0 +idx wasMoved system.html#wasmoved_1 Misc 0 +idx slice system.html#slice_1 Misc 0 +idx slice system.html#slice_2 Misc 0 +idx caller info system.html#caller-info_1 Misc 0 +idx runnable example system.html#runnable-example_1 Misc 0 +idx cut system.html#cut_1 Misc 0 +idx limit system.html#limit_1 Misc 0 +idx splice system.html#splice_1 Misc 0 +idx splice system.html#splice_2 Misc 0 +idx dup system.html#dup_1 Misc 0 +idx trace system.html#trace_1 Misc 0 +idx resource system.html#resource_1 Misc 0 +idx destructor system.html#destructor_1 Misc 0 +idx sink system.html#sink_1 Misc 0 +idx INT_MAX system.html#int-max_1 Misc 0 +idx MAX_INT system.html#max-int_1 Misc 0 +idx INT_MIN system.html#int-min_1 Misc 0 +idx MIN_INT system.html#min-int_1 Misc 0 +idx method system.html#method_1 Misc 0 +idx super system.html#super_1 Misc 0 +idx OpenMP system.html#openmp_1 Misc 0 +idx OpenMP system.html#openmp_2 Misc 0 +idx roof system.html#roof_1 Misc 0 +nimgrp .. system.html#..-procs-all proc 428 +nimgrp ashr system.html#ashr-procs-all proc 171 +nimgrp setlen system.html#setLen-procs-all proc 945 +nimgrp / system.html#/-procs-all proc 318 +nimgrp len system.html#len-procs-all proc 667 +nimgrp += system.html#+=-procs-all proc 299 +nimgrp substr system.html#substr-procs-all proc 2772 +nimgrp +% system.html#+%-procs-all proc 352 +nimgrp and system.html#and-procs-all proc 79 +nimgrp *% system.html#*%-procs-all proc 374 +nimgrp []= system.html#[]=-procs-all proc 375 +nimgrp shr system.html#shr-procs-all proc 135 +nimgrp capacity system.html#capacity-procs-all proc 215 +nimgrp <% system.html#<%-procs-all proc 188 +nimgrp <= system.html#<=-procs-all proc 41 +nimgrp add system.html#add-procs-all proc 1016 +nimgrp <=% system.html#<=%-procs-all proc 179 +nimgrp quit system.html#quit-procs-all proc 2399 +nimgrp div system.html#div-procs-all proc 96 +nimgrp cstringarraytoseq system.html#cstringArrayToSeq-procs-all proc 2121 +nimgrp toopenarray system.html#toOpenArray-procs-all proc 2812 +nimgrp insert system.html#insert-procs-all proc 1231 +nimgrp - system.html#--procs-all proc 56 +nimgrp newseq system.html#newSeq-procs-all proc 616 +nimgrp [] system.html#[]-procs-all proc 373 +nimgrp & system.html#&-procs-all proc 988 +nimgrp < system.html#<-procs-all proc 84 +nimgrp mod system.html#mod-procs-all proc 113 +nimgrp getstacktraceentries system.html#getStackTraceEntries-procs-all proc 548 +nimgrp min system.html#min-procs-all proc 223 +nimgrp == system.html#==-procs-all proc 2 +nimgrp alignof system.html#alignof-procs-all proc 599 +nimgrp =destroy system.html#=destroy-procs-all proc 391 +nimgrp * system.html#*-procs-all proc 89 +nimgrp *= system.html#*=-procs-all proc 307 +nimgrp contains system.html#contains-procs-all proc 70 +nimgrp new system.html#new-procs-all proc 131 +nimgrp max system.html#max-procs-all proc 242 +nimgrp xor system.html#xor-procs-all proc 89 +nimgrp abs system.html#abs-procs-all proc 1350 +nimgrp -= system.html#-=-procs-all proc 303 +nimgrp sizeof system.html#sizeof-procs-all proc 580 +nimgrp high system.html#high-procs-all proc 207 +nimgrp not system.html#not-procs-all proc 76 +nimgrp or system.html#or-procs-all proc 84 +nimgrp isnil system.html#isNil-procs-all proc 1445 +nimgrp low system.html#low-procs-all proc 285 +nimgrp + system.html#+-procs-all proc 49 +nimgrp /% system.html#/%-procs-all proc 385 +nimgrp compileoption system.html#compileOption-procs-all proc 116 +nimgrp toopenarraybyte system.html#toOpenArrayByte-procs-all proc 2816 +nimgrp deepcopy system.html#deepCopy-procs-all proc 2693 +nimgrp shl system.html#shl-procs-all proc 158 +nimgrp -% system.html#-%-procs-all proc 363 +nimgrp cmp system.html#cmp-procs-all proc 878 +nimgrp @ system.html#@-procs-all proc 902 +nimgrp /= system.html#/=-procs-all proc 342 +nimgrp getstacktrace system.html#getStackTrace-procs-all proc 2199 +nimgrp %% system.html#%%-procs-all proc 396 +nimgrp .. system.html#..-iterators-all iterator 81 +nimgrp || system.html#||-iterators-all iterator 147 +nimgrp ..< system.html#..<-iterators-all iterator 126 +nimgrp formaterrorindexbound system.html#formatErrorIndexBound-templates-all template 4 +nimgrp offsetof system.html#offsetOf-templates-all template 604 diff --git a/tables.html b/tables.html new file mode 100644 index 0000000000000..23dff7ae74bbd --- /dev/null +++ b/tables.html @@ -0,0 +1,3661 @@ + + + + + + + +std/tables + + + + + + + + + + + + + + + + +
+
+

std/tables

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

The tables module implements variants of an efficient hash table (also often named dictionary in other programming languages) that is a mapping from keys to values.

+

There are several different types of hash tables available:

+
  • Table is the usual hash table,
  • +
  • OrderedTable is like Table but remembers insertion order,
  • +
  • CountTable is a mapping from a key to its number of occurrences
  • +
+

For consistency with every other data type in Nim these have value semantics, this means that = performs a copy of the hash table.

+

For ref semantics use their Ref variants: TableRef, OrderedTableRef, and CountTableRef.

+

To give an example, when a is a Table, then var b = a gives b as a new independent table. b is initialised with the contents of a. Changing b does not affect a and vice versa:

+ +

Example:

+
import std/tables
+var
+  a = {1: "one", 2: "two"}.toTable  # creates a Table
+  b = a
+
+assert a == b
+
+b[3] = "three"
+assert 3 notin a
+assert 3 in b
+assert a != b
On the other hand, when a is a TableRef instead, then changes to b also affect a. Both a and b ref the same data structure: +

Example:

+
import std/tables
+var
+  a = {1: "one", 2: "two"}.newTable  # creates a TableRef
+  b = a
+
+assert a == b
+
+b[3] = "three"
+
+assert 3 in a
+assert 3 in b
+assert a == b

+ +

Basic usage

+

Table

+

Example:

+
import std/tables
+from std/sequtils import zip
+
+let
+  names = ["John", "Paul", "George", "Ringo"]
+  years = [1940, 1942, 1943, 1940]
+
+var beatles = initTable[string, int]()
+
+for pairs in zip(names, years):
+  let (name, birthYear) = pairs
+  beatles[name] = birthYear
+
+assert beatles == {"George": 1943, "Ringo": 1940, "Paul": 1942, "John": 1940}.toTable
+
+
+var beatlesByYear = initTable[int, seq[string]]()
+
+for pairs in zip(years, names):
+  let (birthYear, name) = pairs
+  if not beatlesByYear.hasKey(birthYear):
+    # if a key doesn't exist, we create one with an empty sequence
+    # before we can add elements to it
+    beatlesByYear[birthYear] = @[]
+  beatlesByYear[birthYear].add(name)
+
+assert beatlesByYear == {1940: @["John", "Ringo"], 1942: @["Paul"], 1943: @["George"]}.toTable
+

OrderedTable

OrderedTable is used when it is important to preserve the insertion order of keys.

+ +

Example:

+
import std/tables
+let
+  a = [('z', 1), ('y', 2), ('x', 3)]
+  ot = a.toOrderedTable  # ordered tables
+
+assert $ot == """{'z': 1, 'y': 2, 'x': 3}"""
+

CountTable

CountTable is useful for counting number of items of some container (e.g. string, sequence or array), as it is a mapping where the items are the keys, and their number of occurrences are the values. For that purpose toCountTable proc comes handy:

+ +

Example:

+
import std/tables
+let myString = "abracadabra"
+let letterFrequencies = toCountTable(myString)
+assert $letterFrequencies == "{'a': 5, 'd': 1, 'b': 2, 'r': 2, 'c': 1}"
The same could have been achieved by manually iterating over a container and increasing each key's value with inc proc: +

Example:

+
import std/tables
+let myString = "abracadabra"
+var letterFrequencies = initCountTable[char]()
+for c in myString:
+  letterFrequencies.inc(c)
+assert $letterFrequencies == "{'d': 1, 'r': 2, 'c': 1, 'a': 5, 'b': 2}"

+ +

Hashing

If you are using simple standard types like int or string for the keys of the table you won't have any problems, but as soon as you try to use a more complex object as a key you will be greeted by a strange compiler error:

+
Error: type mismatch: got (Person)
+but expected one of:
+hashes.hash(x: openArray[A]): Hash
+hashes.hash(x: int): Hash
+hashes.hash(x: float): Hash
+

What is happening here is that the types used for table keys require to have a hash() proc which will convert them to a Hash value, and the compiler is listing all the hash functions it knows. Additionally there has to be a == operator that provides the same semantics as its corresponding hash proc.

+

After you add hash and == for your custom type everything will work. Currently, however, hash for objects is not defined, whereas system.== for objects does exist and performs a "deep" comparison (every field is compared) which is usually what you want. So in the following example implementing only hash suffices:

+ +

Example:

+
import std/tables
+import std/hashes
+
+type
+  Person = object
+    firstName, lastName: string
+
+proc hash(x: Person): Hash =
+  ## Piggyback on the already available string hash proc.
+  ##
+  ## Without this proc nothing works!
+  result = x.firstName.hash !& x.lastName.hash
+  result = !$result
+
+var
+  salaries = initTable[Person, int]()
+  p1, p2: Person
+
+p1.firstName = "Jon"
+p1.lastName = "Ross"
+salaries[p1] = 30_000
+
+p2.firstName = "소진"
+p2.lastName = "박"
+salaries[p2] = 45_000

+ +

See also

  • json module for table-like structure which allows heterogeneous members
  • +
  • strtabs module for efficient hash tables mapping from strings to strings
  • +
  • hashes module for helper functions for hashing
  • +
+

+ +
+

Types

+
+
+
CountTable[A] = object
+
+ +

Hash table that counts the number of each key.

+

For creating an empty CountTable, use initCountTable proc.

+ + Source   +Edit   + +
+
+
+
CountTableRef[A] = ref CountTable[A]
+
+ +

Ref version of CountTable.

+

For creating a new empty CountTableRef, use newCountTable proc.

+ + Source   +Edit   + +
+
+
+
OrderedTable[A; B] = object
+
+ +

Hash table that remembers insertion order.

+

For creating an empty OrderedTable, use initOrderedTable proc.

+ + Source   +Edit   + +
+
+
+
OrderedTableRef[A; B] = ref OrderedTable[A, B]
+
+ +

Ref version of OrderedTable.

+

For creating a new empty OrderedTableRef, use newOrderedTable proc.

+ + Source   +Edit   + +
+
+
+
Table[A; B] = object
+
+ +

Generic hash table, consisting of a key-value pair.

+

data and counter are internal implementation details which can't be accessed.

+

For creating an empty Table, use initTable proc.

+ + Source   +Edit   + +
+
+
+
TableRef[A; B] = ref Table[A, B]
+
+ +

Ref version of Table.

+

For creating a new empty TableRef, use newTable proc.

+ + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
defaultInitialSize = 32
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`[A, B](t: OrderedTable[A, B]): string
+
+ + The $ operator for ordered hash tables. Used internally when calling echo on a table. + Source   +Edit   + +
+
+
+
proc `$`[A, B](t: OrderedTableRef[A, B]): string
+
+ + The $ operator for hash tables. Used internally when calling echo on a table. + Source   +Edit   + +
+
+
+
proc `$`[A, B](t: Table[A, B]): string
+
+ + The $ operator for hash tables. Used internally when calling echo on a table. + Source   +Edit   + +
+
+
+
proc `$`[A, B](t: TableRef[A, B]): string
+
+ + The $ operator for hash tables. Used internally when calling echo on a table. + Source   +Edit   + +
+
+
+
proc `$`[A](t: CountTable[A]): string
+
+ + The $ operator for count tables. Used internally when calling echo on a table. + Source   +Edit   + +
+
+
+
proc `$`[A](t: CountTableRef[A]): string
+
+ + The $ operator for count tables. Used internally when calling echo on a table. + Source   +Edit   + +
+
+ +
+
+
+
proc `==`[A, B](s, t: OrderedTable[A, B]): bool
+
+ + The == operator for ordered hash tables. Returns true if both the content and the order are equal. +

Example:

+
let
+  a = {'a': 5, 'b': 9, 'c': 13}.toOrderedTable
+  b = {'b': 9, 'c': 13, 'a': 5}.toOrderedTable
+doAssert a != b
+ Source   +Edit   + +
+
+
+
proc `==`[A, B](s, t: OrderedTableRef[A, B]): bool
+
+ + The == operator for ordered hash tables. Returns true if either both tables are nil, or neither is nil and the content and the order of both are equal. +

Example:

+
let
+  a = {'a': 5, 'b': 9, 'c': 13}.newOrderedTable
+  b = {'b': 9, 'c': 13, 'a': 5}.newOrderedTable
+doAssert a != b
+ Source   +Edit   + +
+
+
+
proc `==`[A, B](s, t: Table[A, B]): bool
+
+ + The == operator for hash tables. Returns true if the content of both tables contains the same key-value pairs. Insert order does not matter. +

Example:

+
let
+  a = {'a': 5, 'b': 9, 'c': 13}.toTable
+  b = {'b': 9, 'c': 13, 'a': 5}.toTable
+doAssert a == b
+ Source   +Edit   + +
+
+
+
proc `==`[A, B](s, t: TableRef[A, B]): bool
+
+ + The == operator for hash tables. Returns true if either both tables are nil, or neither is nil and the content of both tables contains the same key-value pairs. Insert order does not matter. +

Example:

+
let
+  a = {'a': 5, 'b': 9, 'c': 13}.newTable
+  b = {'b': 9, 'c': 13, 'a': 5}.newTable
+doAssert a == b
+ Source   +Edit   + +
+
+
+
proc `==`[A](s, t: CountTable[A]): bool
+
+ + The == operator for count tables. Returns true if both tables contain the same keys with the same count. Insert order does not matter. + Source   +Edit   + +
+
+
+
proc `==`[A](s, t: CountTableRef[A]): bool
+
+ + The == operator for count tables. Returns true if either both tables are nil, or neither is nil and both contain the same keys with the same count. Insert order does not matter. + Source   +Edit   + +
+
+ +
+
+
+
proc `[]`[A, B](t: OrderedTable[A, B]; key: A): lent B
+
+ +

Retrieves the value at t[key].

+

If key is not in t, the KeyError exception is raised. One can check with hasKey proc whether the key exists.

+

See also:

+
  • getOrDefault proc to return a default value (e.g. zero for int) if the key doesn't exist
  • +
  • getOrDefault proc to return a custom value if the key doesn't exist
  • +
  • []= proc for inserting a new (key, value) pair in the table
  • +
  • hasKey proc for checking if a key is in the table
  • +
+ +

Example:

+
let a = {'a': 5, 'b': 9}.toOrderedTable
+doAssert a['a'] == 5
+doAssertRaises(KeyError):
+  echo a['z']
+ Source   +Edit   + +
+
+
+
proc `[]`[A, B](t: OrderedTableRef[A, B]; key: A): var B
+
+ +

Retrieves the value at t[key].

+

If key is not in t, the KeyError exception is raised. One can check with hasKey proc whether the key exists.

+

See also:

+
  • getOrDefault proc to return a default value (e.g. zero for int) if the key doesn't exist
  • +
  • getOrDefault proc to return a custom value if the key doesn't exist
  • +
  • []= proc for inserting a new (key, value) pair in the table
  • +
  • hasKey proc for checking if a key is in the table
  • +
+ +

Example:

+
let a = {'a': 5, 'b': 9}.newOrderedTable
+doAssert a['a'] == 5
+doAssertRaises(KeyError):
+  echo a['z']
+ Source   +Edit   + +
+
+
+
proc `[]`[A, B](t: Table[A, B]; key: A): lent B
+
+ +

Retrieves the value at t[key].

+

If key is not in t, the KeyError exception is raised. One can check with hasKey proc whether the key exists.

+

See also:

+
  • getOrDefault proc to return a default value (e.g. zero for int) if the key doesn't exist
  • +
  • getOrDefault proc to return a custom value if the key doesn't exist
  • +
  • []= proc for inserting a new (key, value) pair in the table
  • +
  • hasKey proc for checking if a key is in the table
  • +
+ +

Example:

+
let a = {'a': 5, 'b': 9}.toTable
+doAssert a['a'] == 5
+doAssertRaises(KeyError):
+  echo a['z']
+ Source   +Edit   + +
+
+
+
proc `[]`[A, B](t: TableRef[A, B]; key: A): var B
+
+ +

Retrieves the value at t[key].

+

If key is not in t, the KeyError exception is raised. One can check with hasKey proc whether the key exists.

+

See also:

+
  • getOrDefault proc to return a default value (e.g. zero for int) if the key doesn't exist
  • +
  • getOrDefault proc to return a custom value if the key doesn't exist
  • +
  • []= proc for inserting a new (key, value) pair in the table
  • +
  • hasKey proc for checking if a key is in the table
  • +
+ +

Example:

+
let a = {'a': 5, 'b': 9}.newTable
+doAssert a['a'] == 5
+doAssertRaises(KeyError):
+  echo a['z']
+ Source   +Edit   + +
+
+
+
proc `[]`[A, B](t: var OrderedTable[A, B]; key: A): var B
+
+ +

Retrieves the value at t[key]. The value can be modified.

+

If key is not in t, the KeyError exception is raised.

+

See also:

+
  • getOrDefault proc to return a default value (e.g. zero for int) if the key doesn't exist
  • +
  • getOrDefault proc to return a custom value if the key doesn't exist
  • +
  • []= proc for inserting a new (key, value) pair in the table
  • +
  • hasKey proc for checking if a key is in the table
  • +
+ + Source   +Edit   + +
+
+
+
proc `[]`[A, B](t: var Table[A, B]; key: A): var B
+
+ +

Retrieves the value at t[key]. The value can be modified.

+

If key is not in t, the KeyError exception is raised.

+

See also:

+
  • getOrDefault proc to return a default value (e.g. zero for int) if the key doesn't exist
  • +
  • getOrDefault proc to return a custom value if the key doesn't exist
  • +
  • []= proc for inserting a new (key, value) pair in the table
  • +
  • hasKey proc for checking if a key is in the table
  • +
+ + Source   +Edit   + +
+
+
+
proc `[]`[A](t: CountTable[A]; key: A): int
+
+ +

Retrieves the value at t[key] if key is in t. Otherwise 0 is returned.

+

See also:

+
  • getOrDefault to return a custom value if the key doesn't exist
  • +
  • []= proc for inserting a new (key, value) pair in the table
  • +
  • hasKey proc for checking if a key is in the table
  • +
+ + Source   +Edit   + +
+
+
+
proc `[]`[A](t: CountTableRef[A]; key: A): int
+
+ +

Retrieves the value at t[key] if key is in t. Otherwise 0 is returned.

+

See also:

+
  • getOrDefault to return a custom value if the key doesn't exist
  • +
  • inc proc to inc even if missing
  • +
  • []= proc for inserting a new (key, value) pair in the table
  • +
  • hasKey proc for checking if a key is in the table
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
proc `[]=`[A, B](t: OrderedTableRef[A, B]; key: A; val: sink B)
+
+ +

Inserts a (key, value) pair into t.

+

See also:

+ + +

Example:

+
var a = newOrderedTable[char, int]()
+a['x'] = 7
+a['y'] = 33
+doAssert a == {'x': 7, 'y': 33}.newOrderedTable
+ Source   +Edit   + +
+
+
+
proc `[]=`[A, B](t: TableRef[A, B]; key: A; val: sink B)
+
+ +

Inserts a (key, value) pair into t.

+

See also:

+ + +

Example:

+
var a = newTable[char, int]()
+a['x'] = 7
+a['y'] = 33
+doAssert a == {'x': 7, 'y': 33}.newTable
+ Source   +Edit   + +
+
+
+
proc `[]=`[A, B](t: var OrderedTable[A, B]; key: A; val: sink B)
+
+ +

Inserts a (key, value) pair into t.

+

See also:

+ + +

Example:

+
var a = initOrderedTable[char, int]()
+a['x'] = 7
+a['y'] = 33
+doAssert a == {'x': 7, 'y': 33}.toOrderedTable
+ Source   +Edit   + +
+
+
+
proc `[]=`[A, B](t: var Table[A, B]; key: A; val: sink B)
+
+ +

Inserts a (key, value) pair into t.

+

See also:

+ + +

Example:

+
var a = initTable[char, int]()
+a['x'] = 7
+a['y'] = 33
+doAssert a == {'x': 7, 'y': 33}.toTable
+ Source   +Edit   + +
+
+
+
proc `[]=`[A](t: CountTableRef[A]; key: A; val: int)
+
+ +

Inserts a (key, value) pair into t.

+

See also:

+
  • [] proc for retrieving a value of a key
  • +
  • inc proc for incrementing a value of a key
  • +
+ + Source   +Edit   + +
+
+
+
proc `[]=`[A](t: var CountTable[A]; key: A; val: int)
+
+ +

Inserts a (key, value) pair into t.

+

See also:

+
  • [] proc for retrieving a value of a key
  • +
  • inc proc for incrementing a value of a key
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
proc add[A, B](t: OrderedTableRef[A, B]; key: A; val: sink B) {....deprecated: "Deprecated since v1.4; it was more confusing than useful, use `[]=`".}
+
+
+ Deprecated: Deprecated since v1.4; it was more confusing than useful, use `[]=` +
+ +

Puts a new (key, value) pair into t even if t[key] already exists.

+

This can introduce duplicate keys into the table!

+

Use []= proc for inserting a new (key, value) pair in the table without introducing duplicates.

+ + Source   +Edit   + +
+
+
+
proc add[A, B](t: TableRef[A, B]; key: A; val: sink B) {....deprecated: "Deprecated since v1.4; it was more confusing than useful, use `[]=`".}
+
+
+ Deprecated: Deprecated since v1.4; it was more confusing than useful, use `[]=` +
+ +

Puts a new (key, value) pair into t even if t[key] already exists.

+

This can introduce duplicate keys into the table!

+

Use []= proc for inserting a new (key, value) pair in the table without introducing duplicates.

+ + Source   +Edit   + +
+
+
+
proc add[A, B](t: var OrderedTable[A, B]; key: A; val: sink B) {....deprecated: "Deprecated since v1.4; it was more confusing than useful, use `[]=`".}
+
+
+ Deprecated: Deprecated since v1.4; it was more confusing than useful, use `[]=` +
+ +

Puts a new (key, value) pair into t even if t[key] already exists.

+

This can introduce duplicate keys into the table!

+

Use []= proc for inserting a new (key, value) pair in the table without introducing duplicates.

+ + Source   +Edit   + +
+
+
+
proc add[A, B](t: var Table[A, B]; key: A; val: sink B) {....deprecated: "Deprecated since v1.4; it was more confusing than useful, use `[]=`".}
+
+
+ Deprecated: Deprecated since v1.4; it was more confusing than useful, use `[]=` +
+ +

Puts a new (key, value) pair into t even if t[key] already exists.

+

This can introduce duplicate keys into the table!

+

Use []= proc for inserting a new (key, value) pair in the table without introducing duplicates.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc clear[A, B](t: OrderedTableRef[A, B])
+
+ +

Resets the table so that it is empty.

+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9, 'c': 13}.newOrderedTable
+doAssert len(a) == 3
+clear(a)
+doAssert len(a) == 0
+ Source   +Edit   + +
+
+
+
proc clear[A, B](t: TableRef[A, B])
+
+ +

Resets the table so that it is empty.

+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9, 'c': 13}.newTable
+doAssert len(a) == 3
+clear(a)
+doAssert len(a) == 0
+ Source   +Edit   + +
+
+
+
proc clear[A, B](t: var OrderedTable[A, B])
+
+ +

Resets the table so that it is empty.

+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9, 'c': 13}.toOrderedTable
+doAssert len(a) == 3
+clear(a)
+doAssert len(a) == 0
+ Source   +Edit   + +
+
+
+
proc clear[A, B](t: var Table[A, B])
+
+ +

Resets the table so that it is empty.

+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9, 'c': 13}.toTable
+doAssert len(a) == 3
+clear(a)
+doAssert len(a) == 0
+ Source   +Edit   + +
+
+
+
proc clear[A](t: CountTableRef[A])
+
+ +

Resets the table so that it is empty.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc clear[A](t: var CountTable[A])
+
+ +

Resets the table so that it is empty.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc contains[A, B](t: OrderedTable[A, B]; key: A): bool
+
+ + Alias of hasKey proc for use with the in operator. +

Example:

+
let a = {'a': 5, 'b': 9}.toOrderedTable
+doAssert 'b' in a == true
+doAssert a.contains('z') == false
+ Source   +Edit   + +
+
+
+
proc contains[A, B](t: OrderedTableRef[A, B]; key: A): bool
+
+ + Alias of hasKey proc for use with the in operator. +

Example:

+
let a = {'a': 5, 'b': 9}.newOrderedTable
+doAssert 'b' in a == true
+doAssert a.contains('z') == false
+ Source   +Edit   + +
+
+
+
proc contains[A, B](t: Table[A, B]; key: A): bool
+
+ + Alias of hasKey proc for use with the in operator. +

Example:

+
let a = {'a': 5, 'b': 9}.toTable
+doAssert 'b' in a == true
+doAssert a.contains('z') == false
+ Source   +Edit   + +
+
+
+
proc contains[A, B](t: TableRef[A, B]; key: A): bool
+
+ + Alias of hasKey proc for use with the in operator. +

Example:

+
let a = {'a': 5, 'b': 9}.newTable
+doAssert 'b' in a == true
+doAssert a.contains('z') == false
+ Source   +Edit   + +
+
+
+
proc contains[A](t: CountTable[A]; key: A): bool
+
+ + Alias of hasKey proc for use with the in operator. + Source   +Edit   + +
+
+
+
proc contains[A](t: CountTableRef[A]; key: A): bool
+
+ + Alias of hasKey proc for use with the in operator. + Source   +Edit   + +
+
+ +
+
+
+
proc del[A, B](t: OrderedTableRef[A, B]; key: A)
+
+ +

Deletes key from hash table t. Does nothing if the key does not exist.

+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9, 'c': 13}.newOrderedTable
+a.del('a')
+doAssert a == {'b': 9, 'c': 13}.newOrderedTable
+a.del('z')
+doAssert a == {'b': 9, 'c': 13}.newOrderedTable
+ Source   +Edit   + +
+
+
+
proc del[A, B](t: TableRef[A, B]; key: A)
+
+ + Deletes key from hash table t. Does nothing if the key does not exist.
Warning: +If duplicate keys were added (via the now deprecated add proc), this may need to be called multiple times.
+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9, 'c': 13}.newTable
+a.del('a')
+doAssert a == {'b': 9, 'c': 13}.newTable
+a.del('z')
+doAssert a == {'b': 9, 'c': 13}.newTable
+ Source   +Edit   + +
+
+
+
proc del[A, B](t: var OrderedTable[A, B]; key: A)
+
+ +

Deletes key from hash table t. Does nothing if the key does not exist.

+

O(n) complexity.

+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9, 'c': 13}.toOrderedTable
+a.del('a')
+doAssert a == {'b': 9, 'c': 13}.toOrderedTable
+a.del('z')
+doAssert a == {'b': 9, 'c': 13}.toOrderedTable
+ Source   +Edit   + +
+
+
+
proc del[A, B](t: var Table[A, B]; key: A)
+
+ + Deletes key from hash table t. Does nothing if the key does not exist.
Warning: +If duplicate keys were added (via the now deprecated add proc), this may need to be called multiple times.
+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9, 'c': 13}.toTable
+a.del('a')
+doAssert a == {'b': 9, 'c': 13}.toTable
+a.del('z')
+doAssert a == {'b': 9, 'c': 13}.toTable
+ Source   +Edit   + +
+
+
+
proc del[A](t: CountTableRef[A]; key: A)
+
+ +

Deletes key from table t. Does nothing if the key does not exist.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc del[A](t: var CountTable[A]; key: A)
+
+ +

Deletes key from table t. Does nothing if the key does not exist.

+

See also:

+ + +

Example:

+
var a = toCountTable("aabbbccccc")
+a.del('b')
+assert a == toCountTable("aaccccc")
+a.del('b')
+assert a == toCountTable("aaccccc")
+a.del('c')
+assert a == toCountTable("aa")
+ Source   +Edit   + +
+
+ +
+
+
+
proc getOrDefault[A, B](t: OrderedTable[A, B]; key: A): B
+
+ +

Retrieves the value at t[key] if key is in t. Otherwise, the default initialization value for type B is returned (e.g. 0 for any integer type).

+

See also:

+ + +

Example:

+
let a = {'a': 5, 'b': 9}.toOrderedTable
+doAssert a.getOrDefault('a') == 5
+doAssert a.getOrDefault('z') == 0
+ Source   +Edit   + +
+
+
+
proc getOrDefault[A, B](t: OrderedTable[A, B]; key: A; def: B): B
+
+ +

Retrieves the value at t[key] if key is in t. Otherwise, def is returned.

+

See also:

+ + +

Example:

+
let a = {'a': 5, 'b': 9}.toOrderedTable
+doAssert a.getOrDefault('a', 99) == 5
+doAssert a.getOrDefault('z', 99) == 99
+ Source   +Edit   + +
+
+
+
proc getOrDefault[A, B](t: OrderedTableRef[A, B]; key: A): B
+
+ +

Retrieves the value at t[key] if key is in t. Otherwise, the default initialization value for type B is returned (e.g. 0 for any integer type).

+

See also:

+ + +

Example:

+
let a = {'a': 5, 'b': 9}.newOrderedTable
+doAssert a.getOrDefault('a') == 5
+doAssert a.getOrDefault('z') == 0
+ Source   +Edit   + +
+
+
+
proc getOrDefault[A, B](t: OrderedTableRef[A, B]; key: A; def: B): B
+
+ +

Retrieves the value at t[key] if key is in t. Otherwise, def is returned.

+

See also:

+ + +

Example:

+
let a = {'a': 5, 'b': 9}.newOrderedTable
+doAssert a.getOrDefault('a', 99) == 5
+doAssert a.getOrDefault('z', 99) == 99
+ Source   +Edit   + +
+
+
+
proc getOrDefault[A, B](t: Table[A, B]; key: A): B
+
+ +

Retrieves the value at t[key] if key is in t. Otherwise, the default initialization value for type B is returned (e.g. 0 for any integer type).

+

See also:

+ + +

Example:

+
let a = {'a': 5, 'b': 9}.toTable
+doAssert a.getOrDefault('a') == 5
+doAssert a.getOrDefault('z') == 0
+ Source   +Edit   + +
+
+
+
proc getOrDefault[A, B](t: Table[A, B]; key: A; def: B): B
+
+ +

Retrieves the value at t[key] if key is in t. Otherwise, def is returned.

+

See also:

+ + +

Example:

+
let a = {'a': 5, 'b': 9}.toTable
+doAssert a.getOrDefault('a', 99) == 5
+doAssert a.getOrDefault('z', 99) == 99
+ Source   +Edit   + +
+
+
+
proc getOrDefault[A, B](t: TableRef[A, B]; key: A): B
+
+ +

Retrieves the value at t[key] if key is in t. Otherwise, the default initialization value for type B is returned (e.g. 0 for any integer type).

+

See also:

+ + +

Example:

+
let a = {'a': 5, 'b': 9}.newTable
+doAssert a.getOrDefault('a') == 5
+doAssert a.getOrDefault('z') == 0
+ Source   +Edit   + +
+
+
+
proc getOrDefault[A, B](t: TableRef[A, B]; key: A; def: B): B
+
+ +

Retrieves the value at t[key] if key is in t. Otherwise, def is returned.

+

See also:

+ + +

Example:

+
let a = {'a': 5, 'b': 9}.newTable
+doAssert a.getOrDefault('a', 99) == 5
+doAssert a.getOrDefault('z', 99) == 99
+ Source   +Edit   + +
+
+
+
proc getOrDefault[A](t: CountTable[A]; key: A; def: int = 0): int
+
+ +

Retrieves the value at t[key] if key is in t. Otherwise, the integer value of def is returned.

+

See also:

+
  • [] proc for retrieving a value of a key
  • +
  • hasKey proc for checking if a key is in the table
  • +
+ + Source   +Edit   + +
+
+
+
proc getOrDefault[A](t: CountTableRef[A]; key: A; def: int): int
+
+ +

Retrieves the value at t[key] if key is in t. Otherwise, the integer value of def is returned.

+

See also:

+
  • [] proc for retrieving a value of a key
  • +
  • hasKey proc for checking if a key is in the table
  • +
+ + Source   +Edit   + +
+
+ +
+
+
+
proc hash[K, V](s: OrderedTable[K, V]): Hash
+
+ + + Source   +Edit   + +
+
+
+
proc hash[K, V](s: Table[K, V]): Hash
+
+ + + Source   +Edit   + +
+
+
+
proc hash[V](s: CountTable[V]): Hash
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasKey[A, B](t: OrderedTable[A, B]; key: A): bool
+
+ +

Returns true if key is in the table t.

+

See also:

+ + +

Example:

+
let a = {'a': 5, 'b': 9}.toOrderedTable
+doAssert a.hasKey('a') == true
+doAssert a.hasKey('z') == false
+ Source   +Edit   + +
+
+
+
proc hasKey[A, B](t: OrderedTableRef[A, B]; key: A): bool
+
+ +

Returns true if key is in the table t.

+

See also:

+ + +

Example:

+
let a = {'a': 5, 'b': 9}.newOrderedTable
+doAssert a.hasKey('a') == true
+doAssert a.hasKey('z') == false
+ Source   +Edit   + +
+
+
+
proc hasKey[A, B](t: Table[A, B]; key: A): bool
+
+ +

Returns true if key is in the table t.

+

See also:

+ + +

Example:

+
let a = {'a': 5, 'b': 9}.toTable
+doAssert a.hasKey('a') == true
+doAssert a.hasKey('z') == false
+ Source   +Edit   + +
+
+
+
proc hasKey[A, B](t: TableRef[A, B]; key: A): bool
+
+ +

Returns true if key is in the table t.

+

See also:

+ + +

Example:

+
let a = {'a': 5, 'b': 9}.newTable
+doAssert a.hasKey('a') == true
+doAssert a.hasKey('z') == false
+ Source   +Edit   + +
+
+
+
proc hasKey[A](t: CountTable[A]; key: A): bool
+
+ +

Returns true if key is in the table t.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc hasKey[A](t: CountTableRef[A]; key: A): bool
+
+ +

Returns true if key is in the table t.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hasKeyOrPut[A, B](t: OrderedTableRef[A, B]; key: A; val: B): bool
+
+ +

Returns true if key is in the table, otherwise inserts value.

+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9}.newOrderedTable
+if a.hasKeyOrPut('a', 50):
+  a['a'] = 99
+if a.hasKeyOrPut('z', 50):
+  a['z'] = 99
+doAssert a == {'a': 99, 'b': 9, 'z': 50}.newOrderedTable
+ Source   +Edit   + +
+
+
+
proc hasKeyOrPut[A, B](t: TableRef[A, B]; key: A; val: B): bool
+
+ +

Returns true if key is in the table, otherwise inserts value.

+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9}.newTable
+if a.hasKeyOrPut('a', 50):
+  a['a'] = 99
+if a.hasKeyOrPut('z', 50):
+  a['z'] = 99
+doAssert a == {'a': 99, 'b': 9, 'z': 50}.newTable
+ Source   +Edit   + +
+
+
+
proc hasKeyOrPut[A, B](t: var OrderedTable[A, B]; key: A; val: B): bool
+
+ +

Returns true if key is in the table, otherwise inserts value.

+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9}.toOrderedTable
+if a.hasKeyOrPut('a', 50):
+  a['a'] = 99
+if a.hasKeyOrPut('z', 50):
+  a['z'] = 99
+doAssert a == {'a': 99, 'b': 9, 'z': 50}.toOrderedTable
+ Source   +Edit   + +
+
+
+
proc hasKeyOrPut[A, B](t: var Table[A, B]; key: A; val: B): bool
+
+ +

Returns true if key is in the table, otherwise inserts value.

+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9}.toTable
+if a.hasKeyOrPut('a', 50):
+  a['a'] = 99
+if a.hasKeyOrPut('z', 50):
+  a['z'] = 99
+doAssert a == {'a': 99, 'b': 9, 'z': 50}.toTable
+ Source   +Edit   + +
+
+ +
+
+
+
proc inc[A](t: CountTableRef[A]; key: A; val = 1)
+
+ + + Source   +Edit   + +
+
+
+
proc inc[A](t: var CountTable[A]; key: A; val = 1)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc indexBy[A, B, C](collection: A; index: proc (x: B): C): Table[C, B]
+
+ + Index the collection with the proc provided. + Source   +Edit   + +
+
+ +
+
+
+
proc initCountTable[A](initialSize = defaultInitialSize): CountTable[A]
+
+ +

Creates a new count table that is empty.

+

Starting from Nim v0.20, tables are initialized by default and it is not necessary to call this function explicitly.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initOrderedTable[A, B](initialSize = defaultInitialSize): OrderedTable[A, B]
+
+ +

Creates a new ordered hash table that is empty.

+

Starting from Nim v0.20, tables are initialized by default and it is not necessary to call this function explicitly.

+

See also:

+ + +

Example:

+
let
+  a = initOrderedTable[int, string]()
+  b = initOrderedTable[char, seq[int]]()
+ Source   +Edit   + +
+
+ +
+
+
+
proc initTable[A, B](initialSize = defaultInitialSize): Table[A, B]
+
+ +

Creates a new hash table that is empty.

+

Starting from Nim v0.20, tables are initialized by default and it is not necessary to call this function explicitly.

+

See also:

+ + +

Example:

+
let
+  a = initTable[int, string]()
+  b = initTable[char, seq[int]]()
+ Source   +Edit   + +
+
+ +
+
+
+
proc largest[A](t: CountTable[A]): tuple[key: A, val: int]
+
+ +

Returns the (key, value) pair with the largest val. Efficiency: O(n)

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc largest[A](t: CountTableRef[A]): tuple[key: A, val: int]
+
+ +

Returns the (key, value) pair with the largest val. Efficiency: O(n)

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc len[A, B](t: OrderedTable[A, B]): int {.inline.}
+
+ + Returns the number of keys in t. +

Example:

+
let a = {'a': 5, 'b': 9}.toOrderedTable
+doAssert len(a) == 2
+ Source   +Edit   + +
+
+
+
proc len[A, B](t: OrderedTableRef[A, B]): int {.inline.}
+
+ + Returns the number of keys in t. +

Example:

+
let a = {'a': 5, 'b': 9}.newOrderedTable
+doAssert len(a) == 2
+ Source   +Edit   + +
+
+
+
proc len[A, B](t: Table[A, B]): int
+
+ + Returns the number of keys in t. +

Example:

+
let a = {'a': 5, 'b': 9}.toTable
+doAssert len(a) == 2
+ Source   +Edit   + +
+
+
+
proc len[A, B](t: TableRef[A, B]): int
+
+ + Returns the number of keys in t. +

Example:

+
let a = {'a': 5, 'b': 9}.newTable
+doAssert len(a) == 2
+ Source   +Edit   + +
+
+
+
proc len[A](t: CountTable[A]): int
+
+ + Returns the number of keys in t. + Source   +Edit   + +
+
+
+
proc len[A](t: CountTableRef[A]): int
+
+ + Returns the number of keys in t. + Source   +Edit   + +
+
+ +
+
+
+
proc merge[A](s, t: CountTableRef[A])
+
+ + Merges the second table into the first one. +

Example:

+
let
+  a = newCountTable("aaabbc")
+  b = newCountTable("bcc")
+a.merge(b)
+doAssert a == newCountTable("aaabbbccc")
+ Source   +Edit   + +
+
+
+
proc merge[A](s: var CountTable[A]; t: CountTable[A])
+
+ + Merges the second table into the first one (must be declared as var). +

Example:

+
var a = toCountTable("aaabbc")
+let b = toCountTable("bcc")
+a.merge(b)
+doAssert a == toCountTable("aaabbbccc")
+ Source   +Edit   + +
+
+ +
+
+
+
proc mgetOrPut[A, B](t: OrderedTableRef[A, B]; key: A): var B
+
+ + Retrieves the value at t[key] or puts the default initialization value for type B (e.g. 0 for any integer type). +

Example:

+
var a = {'a': 5}.toOrderedTable
+doAssert a.mgetOrPut('a') == 5
+a.mgetOrPut('z').inc
+doAssert a == {'a': 5, 'z': 1}.toOrderedTable
+ Source   +Edit   + +
+
+
+
proc mgetOrPut[A, B](t: OrderedTableRef[A, B]; key: A; val: B): var B
+
+ +

Retrieves value at t[key] or puts val if not present, either way returning a value which can be modified.

+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9}.newOrderedTable
+doAssert a.mgetOrPut('a', 99) == 5
+doAssert a.mgetOrPut('z', 99) == 99
+doAssert a == {'a': 5, 'b': 9, 'z': 99}.newOrderedTable
+ Source   +Edit   + +
+
+
+
proc mgetOrPut[A, B](t: TableRef[A, B]; key: A): var B
+
+ + Retrieves the value at t[key] or puts the default initialization value for type B (e.g. 0 for any integer type). +

Example:

+
var a = {'a': 5}.newTable
+doAssert a.mgetOrPut('a') == 5
+a.mgetOrPut('z').inc
+doAssert a == {'a': 5, 'z': 1}.newTable
+ Source   +Edit   + +
+
+
+
proc mgetOrPut[A, B](t: TableRef[A, B]; key: A; val: B): var B
+
+ +

Retrieves value at t[key] or puts val if not present, either way returning a value which can be modified.

+

Note that while the value returned is of type var B, it is easy to accidentally create an copy of the value at t[key]. Remember that seqs and strings are value types, and therefore cannot be copied into a separate variable for modification. See the example below.

+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9}.newTable
+doAssert a.mgetOrPut('a', 99) == 5
+doAssert a.mgetOrPut('z', 99) == 99
+doAssert a == {'a': 5, 'b': 9, 'z': 99}.newTable
+
+# An example of accidentally creating a copy
+var t = newTable[int, seq[int]]()
+# In this example, we expect t[10] to be modified,
+# but it is not.
+var copiedSeq = t.mgetOrPut(10, @[10])
+copiedSeq.add(20)
+doAssert t[10] == @[10]
+# Correct
+t.mgetOrPut(25, @[25]).add(35)
+doAssert t[25] == @[25, 35]
+ Source   +Edit   + +
+
+
+
proc mgetOrPut[A, B](t: var OrderedTable[A, B]; key: A): var B
+
+ + Retrieves the value at t[key] or puts the default initialization value for type B (e.g. 0 for any integer type). +

Example:

+
var a = {'a': 5}.toOrderedTable
+doAssert a.mgetOrPut('a') == 5
+a.mgetOrPut('z').inc
+doAssert a == {'a': 5, 'z': 1}.toOrderedTable
+ Source   +Edit   + +
+
+
+
proc mgetOrPut[A, B](t: var OrderedTable[A, B]; key: A; val: B): var B
+
+ +

Retrieves value at t[key] or puts val if not present, either way returning a value which can be modified.

+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9}.toOrderedTable
+doAssert a.mgetOrPut('a', 99) == 5
+doAssert a.mgetOrPut('z', 99) == 99
+doAssert a == {'a': 5, 'b': 9, 'z': 99}.toOrderedTable
+ Source   +Edit   + +
+
+
+
proc mgetOrPut[A, B](t: var Table[A, B]; key: A): var B
+
+ + Retrieves the value at t[key] or puts the default initialization value for type B (e.g. 0 for any integer type). +

Example:

+
var a = {'a': 5}.newTable
+doAssert a.mgetOrPut('a') == 5
+a.mgetOrPut('z').inc
+doAssert a == {'a': 5, 'z': 1}.newTable
+ Source   +Edit   + +
+
+
+
proc mgetOrPut[A, B](t: var Table[A, B]; key: A; val: B): var B
+
+ +

Retrieves value at t[key] or puts val if not present, either way returning a value which can be modified.

+

Note that while the value returned is of type var B, it is easy to accidentally create a copy of the value at t[key]. Remember that seqs and strings are value types, and therefore cannot be copied into a separate variable for modification. See the example below.

+

See also:

+ + +

Example:

+
var a = {'a': 5, 'b': 9}.toTable
+doAssert a.mgetOrPut('a', 99) == 5
+doAssert a.mgetOrPut('z', 99) == 99
+doAssert a == {'a': 5, 'b': 9, 'z': 99}.toTable
+
+# An example of accidentally creating a copy
+var t = initTable[int, seq[int]]()
+# In this example, we expect t[10] to be modified,
+# but it is not.
+var copiedSeq = t.mgetOrPut(10, @[10])
+copiedSeq.add(20)
+doAssert t[10] == @[10]
+# Correct
+t.mgetOrPut(25, @[25]).add(35)
+doAssert t[25] == @[25, 35]
+ Source   +Edit   + +
+
+ +
+
+
+
proc newCountTable[A](initialSize = defaultInitialSize): CountTableRef[A]
+
+ +

Creates a new ref count table that is empty.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc newCountTable[A](keys: openArray[A]): CountTableRef[A]
+
+ + Creates a new ref count table with every member of a container keys having a count of how many times it occurs in that container. + Source   +Edit   + +
+
+ +
+
+
+
proc newOrderedTable[A, B](initialSize = defaultInitialSize): OrderedTableRef[A,
+    B]
+
+ +

Creates a new ordered ref hash table that is empty.

+

See also:

+ + +

Example:

+
let
+  a = newOrderedTable[int, string]()
+  b = newOrderedTable[char, seq[int]]()
+ Source   +Edit   + +
+
+
+
proc newOrderedTable[A, B](pairs: openArray[(A, B)]): OrderedTableRef[A, B]
+
+ +

Creates a new ordered ref hash table that contains the given pairs.

+

pairs is a container consisting of (key, value) tuples.

+

See also:

+ + +

Example:

+
let a = [('a', 5), ('b', 9)]
+let b = newOrderedTable(a)
+assert b == {'a': 5, 'b': 9}.newOrderedTable
+ Source   +Edit   + +
+
+ +
+
+
+
proc newTable[A, B](initialSize = defaultInitialSize): TableRef[A, B]
+
+ +

Creates a new ref hash table that is empty.

+

See also:

+ + +

Example:

+
let
+  a = newTable[int, string]()
+  b = newTable[char, seq[int]]()
+ Source   +Edit   + +
+
+
+
proc newTable[A, B](pairs: openArray[(A, B)]): TableRef[A, B]
+
+ +

Creates a new ref hash table that contains the given pairs.

+

pairs is a container consisting of (key, value) tuples.

+

See also:

+ + +

Example:

+
let a = [('a', 5), ('b', 9)]
+let b = newTable(a)
+assert b == {'a': 5, 'b': 9}.newTable
+ Source   +Edit   + +
+
+ +
+
+
+
proc newTableFrom[A, B, C](collection: A; index: proc (x: B): C): TableRef[C, B]
+
+ + Index the collection with the proc provided. + Source   +Edit   + +
+
+ +
+
+
+
proc pop[A, B](t: OrderedTableRef[A, B]; key: A; val: var B): bool
+
+ +

Deletes the key from the table. Returns true, if the key existed, and sets val to the mapping of the key. Otherwise, returns false, and the val is unchanged.

+

See also:

+ + +

Example:

+
var
+  a = {'c': 5, 'b': 9, 'a': 13}.newOrderedTable
+  i: int
+doAssert a.pop('b', i) == true
+doAssert a == {'c': 5, 'a': 13}.newOrderedTable
+doAssert i == 9
+i = 0
+doAssert a.pop('z', i) == false
+doAssert a == {'c': 5, 'a': 13}.newOrderedTable
+doAssert i == 0
+ Source   +Edit   + +
+
+
+
proc pop[A, B](t: TableRef[A, B]; key: A; val: var B): bool
+
+ + Deletes the key from the table. Returns true, if the key existed, and sets val to the mapping of the key. Otherwise, returns false, and the val is unchanged.
Warning: +If duplicate keys were added (via the now deprecated add proc), this may need to be called multiple times.
+

See also:

+ + +

Example:

+
var
+  a = {'a': 5, 'b': 9, 'c': 13}.newTable
+  i: int
+doAssert a.pop('b', i) == true
+doAssert a == {'a': 5, 'c': 13}.newTable
+doAssert i == 9
+i = 0
+doAssert a.pop('z', i) == false
+doAssert a == {'a': 5, 'c': 13}.newTable
+doAssert i == 0
+ Source   +Edit   + +
+
+
+
proc pop[A, B](t: var OrderedTable[A, B]; key: A; val: var B): bool
+
+ +

Deletes the key from the table. Returns true, if the key existed, and sets val to the mapping of the key. Otherwise, returns false, and the val is unchanged.

+

O(n) complexity.

+

See also:

+ + +

Example:

+
var
+  a = {'c': 5, 'b': 9, 'a': 13}.toOrderedTable
+  i: int
+doAssert a.pop('b', i) == true
+doAssert a == {'c': 5, 'a': 13}.toOrderedTable
+doAssert i == 9
+i = 0
+doAssert a.pop('z', i) == false
+doAssert a == {'c': 5, 'a': 13}.toOrderedTable
+doAssert i == 0
+ Source   +Edit   + +
+
+
+
proc pop[A, B](t: var Table[A, B]; key: A; val: var B): bool
+
+ + Deletes the key from the table. Returns true, if the key existed, and sets val to the mapping of the key. Otherwise, returns false, and the val is unchanged.
Warning: +If duplicate keys were added (via the now deprecated add proc), this may need to be called multiple times.
+

See also:

+ + +

Example:

+
var
+  a = {'a': 5, 'b': 9, 'c': 13}.toTable
+  i: int
+doAssert a.pop('b', i) == true
+doAssert a == {'a': 5, 'c': 13}.toTable
+doAssert i == 9
+i = 0
+doAssert a.pop('z', i) == false
+doAssert a == {'a': 5, 'c': 13}.toTable
+doAssert i == 0
+ Source   +Edit   + +
+
+
+
proc pop[A](t: CountTableRef[A]; key: A; val: var int): bool
+
+ +

Deletes the key from the table. Returns true, if the key existed, and sets val to the mapping of the key. Otherwise, returns false, and the val is unchanged.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc pop[A](t: var CountTable[A]; key: A; val: var int): bool
+
+ +

Deletes the key from the table. Returns true, if the key existed, and sets val to the mapping of the key. Otherwise, returns false, and the val is unchanged.

+

See also:

+ + +

Example:

+
var a = toCountTable("aabbbccccc")
+var i = 0
+assert a.pop('b', i)
+assert i == 3
+i = 99
+assert not a.pop('b', i)
+assert i == 99
+ Source   +Edit   + +
+
+ +
+
+
+
proc smallest[A](t: CountTable[A]): tuple[key: A, val: int]
+
+ +

Returns the (key, value) pair with the smallest val. Efficiency: O(n)

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc smallest[A](t: CountTableRef[A]): tuple[key: A, val: int]
+
+ +

Returns the (key, value) pair with the smallest val. Efficiency: O(n)

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sort[A, B](t: OrderedTableRef[A, B]; cmp: proc (x, y: (A, B)): int;
+                order = SortOrder.Ascending) {.effectsOf: cmp.}
+
+ +

Sorts t according to the function cmp.

+

This modifies the internal list that kept the insertion order, so insertion order is lost after this call but key lookup and insertions remain possible after sort (in contrast to the sort proc for count tables).

+ +

Example:

+
import std/[algorithm]
+var a = newOrderedTable[char, int]()
+for i, c in "cab":
+  a[c] = 10*i
+doAssert a == {'c': 0, 'a': 10, 'b': 20}.newOrderedTable
+a.sort(system.cmp)
+doAssert a == {'a': 10, 'b': 20, 'c': 0}.newOrderedTable
+a.sort(system.cmp, order = SortOrder.Descending)
+doAssert a == {'c': 0, 'b': 20, 'a': 10}.newOrderedTable
+ Source   +Edit   + +
+
+
+
proc sort[A, B](t: var OrderedTable[A, B]; cmp: proc (x, y: (A, B)): int;
+                order = SortOrder.Ascending) {.effectsOf: cmp.}
+
+ +

Sorts t according to the function cmp.

+

This modifies the internal list that kept the insertion order, so insertion order is lost after this call but key lookup and insertions remain possible after sort (in contrast to the sort proc for count tables).

+ +

Example:

+
import std/[algorithm]
+var a = initOrderedTable[char, int]()
+for i, c in "cab":
+  a[c] = 10*i
+doAssert a == {'c': 0, 'a': 10, 'b': 20}.toOrderedTable
+a.sort(system.cmp)
+doAssert a == {'a': 10, 'b': 20, 'c': 0}.toOrderedTable
+a.sort(system.cmp, order = SortOrder.Descending)
+doAssert a == {'c': 0, 'b': 20, 'a': 10}.toOrderedTable
+ Source   +Edit   + +
+
+
+
proc sort[A](t: CountTableRef[A]; order = SortOrder.Descending)
+
+ +

Sorts the count table so that, by default, the entry with the highest counter comes first.

+

This is destructive! You must not modify `t` afterwards!

+

You can use the iterators pairs, keys, and values to iterate over t in the sorted order.

+ + Source   +Edit   + +
+
+
+
proc sort[A](t: var CountTable[A]; order = SortOrder.Descending)
+
+ + Sorts the count table so that, by default, the entry with the highest counter comes first.
Warning: +This is destructive! Once sorted, you must not modify t afterwards!
+

You can use the iterators pairs, keys, and values to iterate over t in the sorted order.

+ +

Example:

+
import std/[algorithm, sequtils]
+var a = toCountTable("abracadabra")
+doAssert a == "aaaaabbrrcd".toCountTable
+a.sort()
+doAssert toSeq(a.values) == @[5, 2, 2, 1, 1]
+a.sort(SortOrder.Ascending)
+doAssert toSeq(a.values) == @[1, 1, 2, 2, 5]
+ Source   +Edit   + +
+
+ +
+
+
+
proc take[A, B](t: TableRef[A, B]; key: A; val: var B): bool {.inline.}
+
+ + Alias for: + + Source   +Edit   + +
+
+
+
proc take[A, B](t: var Table[A, B]; key: A; val: var B): bool {.inline.}
+
+ + Alias for: + + Source   +Edit   + +
+
+ +
+
+
+
proc toCountTable[A](keys: openArray[A]): CountTable[A]
+
+ + Creates a new count table with every member of a container keys having a count of how many times it occurs in that container. + Source   +Edit   + +
+
+ +
+
+
+
proc toOrderedTable[A, B](pairs: openArray[(A, B)]): OrderedTable[A, B]
+
+ +

Creates a new ordered hash table that contains the given pairs.

+

pairs is a container consisting of (key, value) tuples.

+

See also:

+ + +

Example:

+
let a = [('a', 5), ('b', 9)]
+let b = toOrderedTable(a)
+assert b == {'a': 5, 'b': 9}.toOrderedTable
+ Source   +Edit   + +
+
+ +
+
+
+
proc toTable[A, B](pairs: openArray[(A, B)]): Table[A, B]
+
+ +

Creates a new hash table that contains the given pairs.

+

pairs is a container consisting of (key, value) tuples.

+

See also:

+ + +

Example:

+
let a = [('a', 5), ('b', 9)]
+let b = toTable(a)
+assert b == {'a': 5, 'b': 9}.toTable
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator allValues[A, B](t: Table[A, B]; key: A): B {....deprecated: "Deprecated since v1.4; tables with duplicated keys are deprecated".}
+
+
+ Deprecated: Deprecated since v1.4; tables with duplicated keys are deprecated +
+ +

Iterates over any value in the table t that belongs to the given key.

+

Used if you have a table with duplicate keys (as a result of using add proc).

+ +

Example:

+
import std/[sequtils, algorithm]
+
+var a = {'a': 3, 'b': 5}.toTable
+for i in 1..3: a.add('z', 10*i)
+doAssert toSeq(a.pairs).sorted == @[('a', 3), ('b', 5), ('z', 10), ('z', 20), ('z', 30)]
+doAssert sorted(toSeq(a.allValues('z'))) == @[10, 20, 30]
+ Source   +Edit   + +
+
+ +
+
+
+
iterator keys[A, B](t: OrderedTable[A, B]): lent A
+
+ +

Iterates over any key in the table t in insertion order.

+

See also:

+ + +

Example:

+
var a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.toOrderedTable
+for k in a.keys:
+  a[k].add(99)
+doAssert a == {'o': @[1, 5, 7, 9, 99],
+               'e': @[2, 4, 6, 8, 99]}.toOrderedTable
+ Source   +Edit   + +
+
+
+
iterator keys[A, B](t: OrderedTableRef[A, B]): lent A
+
+ +

Iterates over any key in the table t in insertion order.

+

See also:

+ + +

Example:

+
let a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.newOrderedTable
+for k in a.keys:
+  a[k].add(99)
+doAssert a == {'o': @[1, 5, 7, 9, 99], 'e': @[2, 4, 6, 8,
+    99]}.newOrderedTable
+ Source   +Edit   + +
+
+
+
iterator keys[A, B](t: Table[A, B]): lent A
+
+ +

Iterates over any key in the table t.

+

See also:

+ + +

Example:

+
var a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.toTable
+for k in a.keys:
+  a[k].add(99)
+doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.toTable
+ Source   +Edit   + +
+
+
+
iterator keys[A, B](t: TableRef[A, B]): lent A
+
+ +

Iterates over any key in the table t.

+

See also:

+ + +

Example:

+
let a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.newTable
+for k in a.keys:
+  a[k].add(99)
+doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.newTable
+ Source   +Edit   + +
+
+
+
iterator keys[A](t: CountTable[A]): lent A
+
+ +

Iterates over any key in the table t.

+

See also:

+ + +

Example:

+
var a = toCountTable("abracadabra")
+for k in keys(a):
+  a[k] = 2
+doAssert a == toCountTable("aabbccddrr")
+ Source   +Edit   + +
+
+
+
iterator keys[A](t: CountTableRef[A]): A
+
+ +

Iterates over any key in the table t.

+

See also:

+ + +

Example:

+
let a = newCountTable("abracadabra")
+for k in keys(a):
+  a[k] = 2
+doAssert a == newCountTable("aabbccddrr")
+ Source   +Edit   + +
+
+ +
+
+
+
iterator mpairs[A, B](t: OrderedTableRef[A, B]): (A, var B)
+
+ +

Iterates over any (key, value) pair in the table t in insertion order. The values can be modified.

+

See also:

+ + +

Example:

+
let a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.newOrderedTable
+for k, v in a.mpairs:
+  v.add(v[0] + 10)
+doAssert a == {'o': @[1, 5, 7, 9, 11],
+               'e': @[2, 4, 6, 8, 12]}.newOrderedTable
+ Source   +Edit   + +
+
+
+
iterator mpairs[A, B](t: TableRef[A, B]): (A, var B)
+
+ +

Iterates over any (key, value) pair in the table t. The values can be modified.

+

See also:

+ + +

Example:

+
let a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.newTable
+for k, v in a.mpairs:
+  v.add(v[0] + 10)
+doAssert a == {'e': @[2, 4, 6, 8, 12], 'o': @[1, 5, 7, 9, 11]}.newTable
+ Source   +Edit   + +
+
+
+
iterator mpairs[A, B](t: var OrderedTable[A, B]): (A, var B)
+
+ +

Iterates over any (key, value) pair in the table t (must be declared as var) in insertion order. The values can be modified.

+

See also:

+ + +

Example:

+
var a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.toOrderedTable
+for k, v in a.mpairs:
+  v.add(v[0] + 10)
+doAssert a == {'o': @[1, 5, 7, 9, 11],
+               'e': @[2, 4, 6, 8, 12]}.toOrderedTable
+ Source   +Edit   + +
+
+
+
iterator mpairs[A, B](t: var Table[A, B]): (A, var B)
+
+ +

Iterates over any (key, value) pair in the table t (must be declared as var). The values can be modified.

+

See also:

+ + +

Example:

+
var a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.toTable
+for k, v in a.mpairs:
+  v.add(v[0] + 10)
+doAssert a == {'e': @[2, 4, 6, 8, 12], 'o': @[1, 5, 7, 9, 11]}.toTable
+ Source   +Edit   + +
+
+
+
iterator mpairs[A](t: CountTableRef[A]): (A, var int)
+
+ +

Iterates over any (key, value) pair in the table t. The values can be modified.

+

See also:

+ + +

Example:

+
let a = newCountTable("abracadabra")
+for k, v in mpairs(a):
+  v = 2
+doAssert a == newCountTable("aabbccddrr")
+ Source   +Edit   + +
+
+
+
iterator mpairs[A](t: var CountTable[A]): (A, var int)
+
+ +

Iterates over any (key, value) pair in the table t (must be declared as var). The values can be modified.

+

See also:

+ + +

Example:

+
var a = toCountTable("abracadabra")
+for k, v in mpairs(a):
+  v = 2
+doAssert a == toCountTable("aabbccddrr")
+ Source   +Edit   + +
+
+ +
+
+
+
iterator mvalues[A, B](t: OrderedTableRef[A, B]): var B
+
+ +

Iterates over any value in the table t in insertion order. The values can be modified.

+

See also:

+ + +

Example:

+
let a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.newOrderedTable
+for v in a.mvalues:
+  v.add(99)
+doAssert a == {'o': @[1, 5, 7, 9, 99],
+               'e': @[2, 4, 6, 8, 99]}.newOrderedTable
+ Source   +Edit   + +
+
+
+
iterator mvalues[A, B](t: TableRef[A, B]): var B
+
+ +

Iterates over any value in the table t. The values can be modified.

+

See also:

+ + +

Example:

+
let a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.newTable
+for v in a.mvalues:
+  v.add(99)
+doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.newTable
+ Source   +Edit   + +
+
+
+
iterator mvalues[A, B](t: var OrderedTable[A, B]): var B
+
+ +

Iterates over any value in the table t (must be declared as var) in insertion order. The values can be modified.

+

See also:

+ + +

Example:

+
var a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.toOrderedTable
+for v in a.mvalues:
+  v.add(99)
+doAssert a == {'o': @[1, 5, 7, 9, 99],
+               'e': @[2, 4, 6, 8, 99]}.toOrderedTable
+ Source   +Edit   + +
+
+
+
iterator mvalues[A, B](t: var Table[A, B]): var B
+
+ +

Iterates over any value in the table t (must be declared as var). The values can be modified.

+

See also:

+ + +

Example:

+
var a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.toTable
+for v in a.mvalues:
+  v.add(99)
+doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.toTable
+ Source   +Edit   + +
+
+
+
iterator mvalues[A](t: CountTableRef[A]): var int
+
+ +

Iterates over any value in the table t. The values can be modified.

+

See also:

+ + +

Example:

+
var a = newCountTable("abracadabra")
+for v in mvalues(a):
+  v = 2
+doAssert a == newCountTable("aabbccddrr")
+ Source   +Edit   + +
+
+
+
iterator mvalues[A](t: var CountTable[A]): var int
+
+ +

Iterates over any value in the table t (must be declared as var). The values can be modified.

+

See also:

+ + +

Example:

+
var a = toCountTable("abracadabra")
+for v in mvalues(a):
+  v = 2
+doAssert a == toCountTable("aabbccddrr")
+ Source   +Edit   + +
+
+ +
+
+
+
iterator pairs[A, B](t: OrderedTable[A, B]): (A, B)
+
+ +

Iterates over any (key, value) pair in the table t in insertion order.

+

See also:

+ +

Examples:

+

let a = {
+  'o': [1, 5, 7, 9],
+  'e': [2, 4, 6, 8]
+  }.toOrderedTable
+
+for k, v in a.pairs:
+  echo "key: ", k
+  echo "value: ", v
+
+# key: o
+# value: [1, 5, 7, 9]
+# key: e
+# value: [2, 4, 6, 8]

+ + Source   +Edit   + +
+
+
+
iterator pairs[A, B](t: OrderedTableRef[A, B]): (A, B)
+
+ +

Iterates over any (key, value) pair in the table t in insertion order.

+

See also:

+ +

Examples:

+

let a = {
+  'o': [1, 5, 7, 9],
+  'e': [2, 4, 6, 8]
+  }.newOrderedTable
+
+for k, v in a.pairs:
+  echo "key: ", k
+  echo "value: ", v
+
+# key: o
+# value: [1, 5, 7, 9]
+# key: e
+# value: [2, 4, 6, 8]

+ + Source   +Edit   + +
+
+
+
iterator pairs[A, B](t: Table[A, B]): (A, B)
+
+ +

Iterates over any (key, value) pair in the table t.

+

See also:

+ +

Examples:

+

let a = {
+  'o': [1, 5, 7, 9],
+  'e': [2, 4, 6, 8]
+  }.toTable
+
+for k, v in a.pairs:
+  echo "key: ", k
+  echo "value: ", v
+
+# key: e
+# value: [2, 4, 6, 8]
+# key: o
+# value: [1, 5, 7, 9]

+ + Source   +Edit   + +
+
+
+
iterator pairs[A, B](t: TableRef[A, B]): (A, B)
+
+ +

Iterates over any (key, value) pair in the table t.

+

See also:

+ +

Examples:

+

let a = {
+  'o': [1, 5, 7, 9],
+  'e': [2, 4, 6, 8]
+  }.newTable
+
+for k, v in a.pairs:
+  echo "key: ", k
+  echo "value: ", v
+
+# key: e
+# value: [2, 4, 6, 8]
+# key: o
+# value: [1, 5, 7, 9]

+ + Source   +Edit   + +
+
+
+
iterator pairs[A](t: CountTable[A]): (A, int)
+
+ +

Iterates over any (key, value) pair in the table t.

+

See also:

+ +

Examples:

+

let a = toCountTable("abracadabra")
+
+for k, v in pairs(a):
+  echo "key: ", k
+  echo "value: ", v
+
+# key: a
+# value: 5
+# key: b
+# value: 2
+# key: c
+# value: 1
+# key: d
+# value: 1
+# key: r
+# value: 2

+ + Source   +Edit   + +
+
+
+
iterator pairs[A](t: CountTableRef[A]): (A, int)
+
+ +

Iterates over any (key, value) pair in the table t.

+

See also:

+ +

Examples:

+

let a = newCountTable("abracadabra")
+
+for k, v in pairs(a):
+  echo "key: ", k
+  echo "value: ", v
+
+# key: a
+# value: 5
+# key: b
+# value: 2
+# key: c
+# value: 1
+# key: d
+# value: 1
+# key: r
+# value: 2

+ + Source   +Edit   + +
+
+ +
+
+
+
iterator values[A, B](t: OrderedTable[A, B]): lent B
+
+ +

Iterates over any value in the table t in insertion order.

+

See also:

+ + +

Example:

+
let a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.toOrderedTable
+for v in a.values:
+  doAssert v.len == 4
+ Source   +Edit   + +
+
+
+
iterator values[A, B](t: OrderedTableRef[A, B]): lent B
+
+ +

Iterates over any value in the table t in insertion order.

+

See also:

+ + +

Example:

+
let a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.newOrderedTable
+for v in a.values:
+  doAssert v.len == 4
+ Source   +Edit   + +
+
+
+
iterator values[A, B](t: Table[A, B]): lent B
+
+ +

Iterates over any value in the table t.

+

See also:

+ + +

Example:

+
let a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.toTable
+for v in a.values:
+  doAssert v.len == 4
+ Source   +Edit   + +
+
+
+
iterator values[A, B](t: TableRef[A, B]): lent B
+
+ +

Iterates over any value in the table t.

+

See also:

+ + +

Example:

+
let a = {
+  'o': @[1, 5, 7, 9],
+  'e': @[2, 4, 6, 8]
+  }.newTable
+for v in a.values:
+  doAssert v.len == 4
+ Source   +Edit   + +
+
+
+
iterator values[A](t: CountTable[A]): int
+
+ +

Iterates over any value in the table t.

+

See also:

+ + +

Example:

+
let a = toCountTable("abracadabra")
+for v in values(a):
+  assert v < 10
+ Source   +Edit   + +
+
+
+
iterator values[A](t: CountTableRef[A]): int
+
+ +

Iterates over any value in the table t.

+

See also:

+ + +

Example:

+
let a = newCountTable("abracadabra")
+for v in values(a):
+  assert v < 10
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template withValue[A, B](t: var Table[A, B]; key: A;
+                         value, body1, body2: untyped)
+
+ +

Retrieves the value at t[key].

+

value can be modified in the scope of the withValue call.

+ +

Example:

+
type
+  User = object
+    name: string
+    uid: int
+
+var t = initTable[int, User]()
+let u = User(name: "Hello", uid: 99)
+t[1] = u
+
+t.withValue(1, value):
+  # block is executed only if `key` in `t`
+  value.name = "Nim"
+  value.uid = 1314
+
+t.withValue(521, value):
+  doAssert false
+do:
+  # block is executed when `key` not in `t`
+  t[1314] = User(name: "exist", uid: 521)
+
+assert t[1].name == "Nim"
+assert t[1].uid == 1314
+assert t[1314].name == "exist"
+assert t[1314].uid == 521
+ Source   +Edit   + +
+
+
+
template withValue[A, B](t: var Table[A, B]; key: A; value, body: untyped)
+
+ +

Retrieves the value at t[key].

+

value can be modified in the scope of the withValue call.

+ +

Example:

+
type
+  User = object
+    name: string
+    uid: int
+
+var t = initTable[int, User]()
+let u = User(name: "Hello", uid: 99)
+t[1] = u
+
+t.withValue(1, value):
+  # block is executed only if `key` in `t`
+  value.name = "Nim"
+  value.uid = 1314
+
+t.withValue(2, value):
+  value.name = "No"
+  value.uid = 521
+
+assert t[1].name == "Nim"
+assert t[1].uid == 1314
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/tables.idx b/tables.idx new file mode 100644 index 0000000000000..8bb72f3424e38 --- /dev/null +++ b/tables.idx @@ -0,0 +1,198 @@ +nimTitle tables tables.html module std/tables 0 +nim Table tables.html#Table object Table 206 +nim TableRef tables.html#TableRef type TableRef 215 +nim defaultInitialSize tables.html#defaultInitialSize const defaultInitialSize 15 +nim initTable tables.html#initTable proc initTable[A, B](initialSize = defaultInitialSize): Table[A, B] 268 +nim `[]=` tables.html#[]=,Table[A,B],A,sinkB proc `[]=`[A, B](t: var Table[A, B]; key: A; val: sink B) 284 +nim toTable tables.html#toTable,openArray[] proc toTable[A, B](pairs: openArray[(A, B)]): Table[A, B] 300 +nim `[]` tables.html#[],Table[A,B],A proc `[]`[A, B](t: Table[A, B]; key: A): lent B 316 +nim `[]` tables.html#[],Table[A,B],A_2 proc `[]`[A, B](t: var Table[A, B]; key: A): var B 339 +nim hasKey tables.html#hasKey,Table[A,B],A proc hasKey[A, B](t: Table[A, B]; key: A): bool 355 +nim contains tables.html#contains,Table[A,B],A proc contains[A, B](t: Table[A, B]; key: A): bool 373 +nim hasKeyOrPut tables.html#hasKeyOrPut,Table[A,B],A,B proc hasKeyOrPut[A, B](t: var Table[A, B]; key: A; val: B): bool 383 +nim getOrDefault tables.html#getOrDefault,Table[A,B],A proc getOrDefault[A, B](t: Table[A, B]; key: A): B 403 +nim getOrDefault tables.html#getOrDefault,Table[A,B],A,B proc getOrDefault[A, B](t: Table[A, B]; key: A; def: B): B 422 +nim mgetOrPut tables.html#mgetOrPut,Table[A,B],A,B proc mgetOrPut[A, B](t: var Table[A, B]; key: A; val: B): var B 439 +nim mgetOrPut tables.html#mgetOrPut,Table[A,B],A proc mgetOrPut[A, B](t: var Table[A, B]; key: A): var B 477 +nim len tables.html#len,Table[A,B] proc len[A, B](t: Table[A, B]): int 489 +nim add tables.html#add,Table[A,B],A,sinkB proc add[A, B](t: var Table[A, B]; key: A; val: sink B) 497 +nim del tables.html#del,Table[A,B],A proc del[A, B](t: var Table[A, B]; key: A) 511 +nim pop tables.html#pop,Table[A,B],A,B proc pop[A, B](t: var Table[A, B]; key: A; val: var B): bool 529 +nim take tables.html#take,Table[A,B],A,B proc take[A, B](t: var Table[A, B]; key: A; val: var B): bool 560 +nim clear tables.html#clear,Table[A,B] proc clear[A, B](t: var Table[A, B]) 565 +nim `$` tables.html#$,Table[A,B] proc `$`[A, B](t: Table[A, B]): string 579 +nim `==` tables.html#==,Table[A,B],Table[A,B] proc `==`[A, B](s, t: Table[A, B]): bool 584 +nim indexBy tables.html#indexBy,A,proc(B) proc indexBy[A, B, C](collection: A; index: proc (x: B): C): Table[C, B] 595 +nim withValue tables.html#withValue.t,Table[A,B],A,untyped,untyped template withValue[A, B](t: var Table[A, B]; key: A; value, body: untyped) 604 +nim withValue tables.html#withValue.t,Table[A,B],A,untyped,untyped,untyped template withValue[A, B](t: var Table[A, B]; key: A; value, body1, body2: untyped) 638 +nim pairs tables.html#pairs.i,Table[A,B] iterator pairs[A, B](t: Table[A, B]): (A, B) 680 +nim mpairs tables.html#mpairs.i,Table[A,B] iterator mpairs[A, B](t: var Table[A, B]): (A, var B) 711 +nim keys tables.html#keys.i,Table[A,B] iterator keys[A, B](t: Table[A, B]): lent A 733 +nim values tables.html#values.i,Table[A,B] iterator values[A, B](t: Table[A, B]): lent B 754 +nim mvalues tables.html#mvalues.i,Table[A,B] iterator mvalues[A, B](t: var Table[A, B]): var B 775 +nim allValues tables.html#allValues.i,Table[A,B],A iterator allValues[A, B](t: Table[A, B]; key: A): B 797 +nim newTable tables.html#newTable proc newTable[A, B](initialSize = defaultInitialSize): TableRef[A, B] 826 +nim newTable tables.html#newTable,openArray[] proc newTable[A, B](pairs: openArray[(A, B)]): TableRef[A, B] 842 +nim newTableFrom tables.html#newTableFrom,A,proc(B) proc newTableFrom[A, B, C](collection: A; index: proc (x: B): C): TableRef[C, B] 859 +nim `[]` tables.html#[],TableRef[A,B],A proc `[]`[A, B](t: TableRef[A, B]; key: A): var B 867 +nim `[]=` tables.html#[]=,TableRef[A,B],A,sinkB proc `[]=`[A, B](t: TableRef[A, B]; key: A; val: sink B) 891 +nim hasKey tables.html#hasKey,TableRef[A,B],A proc hasKey[A, B](t: TableRef[A, B]; key: A): bool 907 +nim contains tables.html#contains,TableRef[A,B],A proc contains[A, B](t: TableRef[A, B]; key: A): bool 925 +nim hasKeyOrPut tables.html#hasKeyOrPut,TableRef[A,B],A,B proc hasKeyOrPut[A, B](t: TableRef[A, B]; key: A; val: B): bool 935 +nim getOrDefault tables.html#getOrDefault,TableRef[A,B],A proc getOrDefault[A, B](t: TableRef[A, B]; key: A): B 955 +nim getOrDefault tables.html#getOrDefault,TableRef[A,B],A,B proc getOrDefault[A, B](t: TableRef[A, B]; key: A; def: B): B 974 +nim mgetOrPut tables.html#mgetOrPut,TableRef[A,B],A,B proc mgetOrPut[A, B](t: TableRef[A, B]; key: A; val: B): var B 992 +nim mgetOrPut tables.html#mgetOrPut,TableRef[A,B],A proc mgetOrPut[A, B](t: TableRef[A, B]; key: A): var B 1028 +nim len tables.html#len,TableRef[A,B] proc len[A, B](t: TableRef[A, B]): int 1040 +nim add tables.html#add,TableRef[A,B],A,sinkB proc add[A, B](t: TableRef[A, B]; key: A; val: sink B) 1048 +nim del tables.html#del,TableRef[A,B],A proc del[A, B](t: TableRef[A, B]; key: A) 1058 +nim pop tables.html#pop,TableRef[A,B],A,B proc pop[A, B](t: TableRef[A, B]; key: A; val: var B): bool 1076 +nim take tables.html#take,TableRef[A,B],A,B proc take[A, B](t: TableRef[A, B]; key: A; val: var B): bool 1102 +nim clear tables.html#clear,TableRef[A,B] proc clear[A, B](t: TableRef[A, B]) 1107 +nim `$` tables.html#$,TableRef[A,B] proc `$`[A, B](t: TableRef[A, B]): string 1121 +nim `==` tables.html#==,TableRef[A,B],TableRef[A,B] proc `==`[A, B](s, t: TableRef[A, B]): bool 1126 +nim pairs tables.html#pairs.i,TableRef[A,B] iterator pairs[A, B](t: TableRef[A, B]): (A, B) 1142 +nim mpairs tables.html#mpairs.i,TableRef[A,B] iterator mpairs[A, B](t: TableRef[A, B]): (A, var B) 1173 +nim keys tables.html#keys.i,TableRef[A,B] iterator keys[A, B](t: TableRef[A, B]): lent A 1195 +nim values tables.html#values.i,TableRef[A,B] iterator values[A, B](t: TableRef[A, B]): lent B 1216 +nim mvalues tables.html#mvalues.i,TableRef[A,B] iterator mvalues[A, B](t: TableRef[A, B]): var B 1237 +nim OrderedTable tables.html#OrderedTable object OrderedTable 1273 +nim OrderedTableRef tables.html#OrderedTableRef type OrderedTableRef 1280 +nim initOrderedTable tables.html#initOrderedTable proc initOrderedTable[A, B](initialSize = defaultInitialSize): OrderedTable[A, B] 1335 +nim `[]=` tables.html#[]=,OrderedTable[A,B],A,sinkB proc `[]=`[A, B](t: var OrderedTable[A, B]; key: A; val: sink B) 1352 +nim toOrderedTable tables.html#toOrderedTable,openArray[] proc toOrderedTable[A, B](pairs: openArray[(A, B)]): OrderedTable[A, B] 1368 +nim `[]` tables.html#[],OrderedTable[A,B],A proc `[]`[A, B](t: OrderedTable[A, B]; key: A): lent B 1385 +nim `[]` tables.html#[],OrderedTable[A,B],A_2 proc `[]`[A, B](t: var OrderedTable[A, B]; key: A): var B 1409 +nim hasKey tables.html#hasKey,OrderedTable[A,B],A proc hasKey[A, B](t: OrderedTable[A, B]; key: A): bool 1425 +nim contains tables.html#contains,OrderedTable[A,B],A proc contains[A, B](t: OrderedTable[A, B]; key: A): bool 1444 +nim hasKeyOrPut tables.html#hasKeyOrPut,OrderedTable[A,B],A,B proc hasKeyOrPut[A, B](t: var OrderedTable[A, B]; key: A; val: B): bool 1454 +nim getOrDefault tables.html#getOrDefault,OrderedTable[A,B],A proc getOrDefault[A, B](t: OrderedTable[A, B]; key: A): B 1474 +nim getOrDefault tables.html#getOrDefault,OrderedTable[A,B],A,B proc getOrDefault[A, B](t: OrderedTable[A, B]; key: A; def: B): B 1493 +nim mgetOrPut tables.html#mgetOrPut,OrderedTable[A,B],A,B proc mgetOrPut[A, B](t: var OrderedTable[A, B]; key: A; val: B): var B 1510 +nim mgetOrPut tables.html#mgetOrPut,OrderedTable[A,B],A proc mgetOrPut[A, B](t: var OrderedTable[A, B]; key: A): var B 1530 +nim len tables.html#len,OrderedTable[A,B] proc len[A, B](t: OrderedTable[A, B]): int 1542 +nim add tables.html#add,OrderedTable[A,B],A,sinkB proc add[A, B](t: var OrderedTable[A, B]; key: A; val: sink B) 1550 +nim del tables.html#del,OrderedTable[A,B],A proc del[A, B](t: var OrderedTable[A, B]; key: A) 1560 +nim pop tables.html#pop,OrderedTable[A,B],A,B proc pop[A, B](t: var OrderedTable[A, B]; key: A; val: var B): bool 1593 +nim clear tables.html#clear,OrderedTable[A,B] proc clear[A, B](t: var OrderedTable[A, B]) 1623 +nim sort tables.html#sort,OrderedTable[A,B],proc(,) proc sort[A, B](t: var OrderedTable[A, B]; cmp: proc (x, y: (A, B)): int;\n order = SortOrder.Ascending) 1639 +nim `$` tables.html#$,OrderedTable[A,B] proc `$`[A, B](t: OrderedTable[A, B]): string 1698 +nim `==` tables.html#==,OrderedTable[A,B],OrderedTable[A,B] proc `==`[A, B](s, t: OrderedTable[A, B]): bool 1703 +nim pairs tables.html#pairs.i,OrderedTable[A,B] iterator pairs[A, B](t: OrderedTable[A, B]): (A, B) 1730 +nim mpairs tables.html#mpairs.i,OrderedTable[A,B] iterator mpairs[A, B](t: var OrderedTable[A, B]): (A, var B) 1762 +nim keys tables.html#keys.i,OrderedTable[A,B] iterator keys[A, B](t: OrderedTable[A, B]): lent A 1784 +nim values tables.html#values.i,OrderedTable[A,B] iterator values[A, B](t: OrderedTable[A, B]): lent B 1805 +nim mvalues tables.html#mvalues.i,OrderedTable[A,B] iterator mvalues[A, B](t: var OrderedTable[A, B]): var B 1825 +nim newOrderedTable tables.html#newOrderedTable proc newOrderedTable[A, B](initialSize = defaultInitialSize): OrderedTableRef[A, B] 1852 +nim newOrderedTable tables.html#newOrderedTable,openArray[] proc newOrderedTable[A, B](pairs: openArray[(A, B)]): OrderedTableRef[A, B] 1868 +nim `[]` tables.html#[],OrderedTableRef[A,B],A proc `[]`[A, B](t: OrderedTableRef[A, B]; key: A): var B 1887 +nim `[]=` tables.html#[]=,OrderedTableRef[A,B],A,sinkB proc `[]=`[A, B](t: OrderedTableRef[A, B]; key: A; val: sink B) 1910 +nim hasKey tables.html#hasKey,OrderedTableRef[A,B],A proc hasKey[A, B](t: OrderedTableRef[A, B]; key: A): bool 1926 +nim contains tables.html#contains,OrderedTableRef[A,B],A proc contains[A, B](t: OrderedTableRef[A, B]; key: A): bool 1944 +nim hasKeyOrPut tables.html#hasKeyOrPut,OrderedTableRef[A,B],A,B proc hasKeyOrPut[A, B](t: OrderedTableRef[A, B]; key: A; val: B): bool 1954 +nim getOrDefault tables.html#getOrDefault,OrderedTableRef[A,B],A proc getOrDefault[A, B](t: OrderedTableRef[A, B]; key: A): B 1974 +nim getOrDefault tables.html#getOrDefault,OrderedTableRef[A,B],A,B proc getOrDefault[A, B](t: OrderedTableRef[A, B]; key: A; def: B): B 1993 +nim mgetOrPut tables.html#mgetOrPut,OrderedTableRef[A,B],A,B proc mgetOrPut[A, B](t: OrderedTableRef[A, B]; key: A; val: B): var B 2011 +nim mgetOrPut tables.html#mgetOrPut,OrderedTableRef[A,B],A proc mgetOrPut[A, B](t: OrderedTableRef[A, B]; key: A): var B 2031 +nim len tables.html#len,OrderedTableRef[A,B] proc len[A, B](t: OrderedTableRef[A, B]): int 2043 +nim add tables.html#add,OrderedTableRef[A,B],A,sinkB proc add[A, B](t: OrderedTableRef[A, B]; key: A; val: sink B) 2051 +nim del tables.html#del,OrderedTableRef[A,B],A proc del[A, B](t: OrderedTableRef[A, B]; key: A) 2061 +nim pop tables.html#pop,OrderedTableRef[A,B],A,B proc pop[A, B](t: OrderedTableRef[A, B]; key: A; val: var B): bool 2075 +nim clear tables.html#clear,OrderedTableRef[A,B] proc clear[A, B](t: OrderedTableRef[A, B]) 2098 +nim sort tables.html#sort,OrderedTableRef[A,B],proc(,) proc sort[A, B](t: OrderedTableRef[A, B]; cmp: proc (x, y: (A, B)): int;\n order = SortOrder.Ascending) 2111 +nim `$` tables.html#$,OrderedTableRef[A,B] proc `$`[A, B](t: OrderedTableRef[A, B]): string 2132 +nim `==` tables.html#==,OrderedTableRef[A,B],OrderedTableRef[A,B] proc `==`[A, B](s, t: OrderedTableRef[A, B]): bool 2137 +nim pairs tables.html#pairs.i,OrderedTableRef[A,B] iterator pairs[A, B](t: OrderedTableRef[A, B]): (A, B) 2153 +nim mpairs tables.html#mpairs.i,OrderedTableRef[A,B] iterator mpairs[A, B](t: OrderedTableRef[A, B]): (A, var B) 2185 +nim keys tables.html#keys.i,OrderedTableRef[A,B] iterator keys[A, B](t: OrderedTableRef[A, B]): lent A 2207 +nim values tables.html#values.i,OrderedTableRef[A,B] iterator values[A, B](t: OrderedTableRef[A, B]): lent B 2228 +nim mvalues tables.html#mvalues.i,OrderedTableRef[A,B] iterator mvalues[A, B](t: OrderedTableRef[A, B]): var B 2248 +nim CountTable tables.html#CountTable object CountTable 2281 +nim CountTableRef tables.html#CountTableRef type CountTableRef 2289 +nim inc tables.html#inc,CountTable[A],A,int proc inc[A](t: var CountTable[A]; key: A; val = 1) 2325 +nim initCountTable tables.html#initCountTable proc initCountTable[A](initialSize = defaultInitialSize): CountTable[A] 2329 +nim toCountTable tables.html#toCountTable,openArray[A] proc toCountTable[A](keys: openArray[A]): CountTable[A] 2342 +nim `[]` tables.html#[],CountTable[A],A proc `[]`[A](t: CountTable[A]; key: A): int 2348 +nim `[]=` tables.html#[]=,CountTable[A],A,int proc `[]=`[A](t: var CountTable[A]; key: A; val: int) 2366 +nim len tables.html#len,CountTable[A] proc len[A](t: CountTable[A]): int 2402 +nim smallest tables.html#smallest,CountTable[A] proc smallest[A](t: CountTable[A]): tuple[key: A, val: int] 2406 +nim largest tables.html#largest,CountTable[A] proc largest[A](t: CountTable[A]): tuple[key: A, val: int] 2418 +nim hasKey tables.html#hasKey,CountTable[A],A proc hasKey[A](t: CountTable[A]; key: A): bool 2429 +nim contains tables.html#contains,CountTable[A],A proc contains[A](t: CountTable[A]; key: A): bool 2441 +nim getOrDefault tables.html#getOrDefault,CountTable[A],A,int proc getOrDefault[A](t: CountTable[A]; key: A; def: int = 0): int 2446 +nim del tables.html#del,CountTable[A],A proc del[A](t: var CountTable[A]; key: A) 2456 +nim pop tables.html#pop,CountTable[A],A,int proc pop[A](t: var CountTable[A]; key: A; val: var int): bool 2473 +nim clear tables.html#clear,CountTable[A] proc clear[A](t: var CountTable[A]) 2497 +nim sort tables.html#sort,CountTable[A] proc sort[A](t: var CountTable[A]; order = SortOrder.Descending) 2509 +nim merge tables.html#merge,CountTable[A],CountTable[A] proc merge[A](s: var CountTable[A]; t: CountTable[A]) 2530 +nim `$` tables.html#$,CountTable[A] proc `$`[A](t: CountTable[A]): string 2556 +nim `==` tables.html#==,CountTable[A],CountTable[A] proc `==`[A](s, t: CountTable[A]): bool 2561 +nim pairs tables.html#pairs.i,CountTable[A] iterator pairs[A](t: CountTable[A]): (A, int) 2567 +nim mpairs tables.html#mpairs.i,CountTable[A] iterator mpairs[A](t: var CountTable[A]): (A, var int) 2601 +nim keys tables.html#keys.i,CountTable[A] iterator keys[A](t: CountTable[A]): lent A 2620 +nim values tables.html#values.i,CountTable[A] iterator values[A](t: CountTable[A]): int 2638 +nim mvalues tables.html#mvalues.i,CountTable[A] iterator mvalues[A](t: var CountTable[A]): var int 2656 +nim inc tables.html#inc,CountTableRef[A],A,int proc inc[A](t: CountTableRef[A]; key: A; val = 1) 2685 +nim newCountTable tables.html#newCountTable proc newCountTable[A](initialSize = defaultInitialSize): CountTableRef[A] 2687 +nim newCountTable tables.html#newCountTable,openArray[A] proc newCountTable[A](keys: openArray[A]): CountTableRef[A] 2699 +nim `[]` tables.html#[],CountTableRef[A],A proc `[]`[A](t: CountTableRef[A]; key: A): int 2706 +nim `[]=` tables.html#[]=,CountTableRef[A],A,int proc `[]=`[A](t: CountTableRef[A]; key: A; val: int) 2720 +nim smallest tables.html#smallest,CountTableRef[A] proc smallest[A](t: CountTableRef[A]): tuple[key: A, val: int] 2741 +nim largest tables.html#largest,CountTableRef[A] proc largest[A](t: CountTableRef[A]): tuple[key: A, val: int] 2748 +nim hasKey tables.html#hasKey,CountTableRef[A],A proc hasKey[A](t: CountTableRef[A]; key: A): bool 2755 +nim contains tables.html#contains,CountTableRef[A],A proc contains[A](t: CountTableRef[A]; key: A): bool 2766 +nim getOrDefault tables.html#getOrDefault,CountTableRef[A],A,int proc getOrDefault[A](t: CountTableRef[A]; key: A; def: int): int 2771 +nim len tables.html#len,CountTableRef[A] proc len[A](t: CountTableRef[A]): int 2781 +nim del tables.html#del,CountTableRef[A],A proc del[A](t: CountTableRef[A]; key: A) 2785 +nim pop tables.html#pop,CountTableRef[A],A,int proc pop[A](t: CountTableRef[A]; key: A; val: var int): bool 2793 +nim clear tables.html#clear,CountTableRef[A] proc clear[A](t: CountTableRef[A]) 2804 +nim sort tables.html#sort,CountTableRef[A] proc sort[A](t: CountTableRef[A]; order = SortOrder.Descending) 2812 +nim merge tables.html#merge,CountTableRef[A],CountTableRef[A] proc merge[A](s, t: CountTableRef[A]) 2823 +nim `$` tables.html#$,CountTableRef[A] proc `$`[A](t: CountTableRef[A]): string 2834 +nim `==` tables.html#==,CountTableRef[A],CountTableRef[A] proc `==`[A](s, t: CountTableRef[A]): bool 2839 +nim pairs tables.html#pairs.i,CountTableRef[A] iterator pairs[A](t: CountTableRef[A]): (A, int) 2848 +nim mpairs tables.html#mpairs.i,CountTableRef[A] iterator mpairs[A](t: CountTableRef[A]): (A, var int) 2882 +nim keys tables.html#keys.i,CountTableRef[A] iterator keys[A](t: CountTableRef[A]): A 2901 +nim values tables.html#values.i,CountTableRef[A] iterator values[A](t: CountTableRef[A]): int 2919 +nim mvalues tables.html#mvalues.i,CountTableRef[A] iterator mvalues[A](t: CountTableRef[A]): var int 2937 +nim hash tables.html#hash,Table[K,V] proc hash[K, V](s: Table[K, V]): Hash 2955 +nim hash tables.html#hash,OrderedTable[K,V] proc hash[K, V](s: OrderedTable[K, V]): Hash 2961 +nim hash tables.html#hash,CountTable[V] proc hash[V](s: CountTable[V]): Hash 2967 +idx hash table tables.html#hash-table_1 Module tables 0 +idx dictionary tables.html#dictionary_1 Module tables 0 +heading Basic usage tables.html#basic-usage Basic usage 0 +heading Table tables.html#basic-usage-table Table 0 +heading OrderedTable tables.html#basic-usage-orderedtable OrderedTable 0 +heading CountTable tables.html#basic-usage-counttable CountTable 0 +heading Hashing tables.html#basic-usage-hashing Hashing 0 +heading See also tables.html#see-also See also 0 +nimgrp haskey tables.html#hasKey-procs-all proc 355 +nimgrp == tables.html#==-procs-all proc 584 +nimgrp sort tables.html#sort-procs-all proc 1639 +nimgrp smallest tables.html#smallest-procs-all proc 2406 +nimgrp del tables.html#del-procs-all proc 511 +nimgrp $ tables.html#$-procs-all proc 579 +nimgrp newtable tables.html#newTable-procs-all proc 826 +nimgrp newcounttable tables.html#newCountTable-procs-all proc 2687 +nimgrp []= tables.html#[]=-procs-all proc 284 +nimgrp take tables.html#take-procs-all proc 560 +nimgrp getordefault tables.html#getOrDefault-procs-all proc 403 +nimgrp contains tables.html#contains-procs-all proc 373 +nimgrp haskeyorput tables.html#hasKeyOrPut-procs-all proc 383 +nimgrp inc tables.html#inc-procs-all proc 2325 +nimgrp [] tables.html#[]-procs-all proc 316 +nimgrp clear tables.html#clear-procs-all proc 565 +nimgrp largest tables.html#largest-procs-all proc 2418 +nimgrp len tables.html#len-procs-all proc 489 +nimgrp add tables.html#add-procs-all proc 497 +nimgrp pop tables.html#pop-procs-all proc 529 +nimgrp neworderedtable tables.html#newOrderedTable-procs-all proc 1852 +nimgrp mgetorput tables.html#mgetOrPut-procs-all proc 439 +nimgrp merge tables.html#merge-procs-all proc 2530 +nimgrp hash tables.html#hash-procs-all proc 2955 +nimgrp values tables.html#values-iterators-all iterator 754 +nimgrp mpairs tables.html#mpairs-iterators-all iterator 711 +nimgrp mvalues tables.html#mvalues-iterators-all iterator 775 +nimgrp pairs tables.html#pairs-iterators-all iterator 680 +nimgrp keys tables.html#keys-iterators-all iterator 733 +nimgrp withvalue tables.html#withValue-templates-all template 604 diff --git a/tasks.html b/tasks.html new file mode 100644 index 0000000000000..846b4c702ad53 --- /dev/null +++ b/tasks.html @@ -0,0 +1,254 @@ + + + + + + + +std/tasks + + + + + + + + + + + + + + + + +
+
+

std/tasks

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module provides basic primitives for creating parallel programs. A Task should be only owned by a single Thread, it cannot be shared by threads. +

Example:

+
import std/tasks
+block:
+  var num = 0
+  proc hello(a: int) = inc num, a
+
+  let b = toTask hello(13)
+  b.invoke()
+  assert num == 13
+  # A task can be invoked multiple times
+  b.invoke()
+  assert num == 26
+
+block:
+  type
+    Runnable = ref object
+      data: int
+
+  var data: int
+  proc hello(a: Runnable) {.nimcall.} =
+    a.data += 2
+    data = a.data
+
+
+  when false:
+    # the parameters of call must be isolated.
+    let x = Runnable(data: 12)
+    let b = toTask hello(x) # error ----> expression cannot be isolated: x
+    b.invoke()
+
+  let b = toTask(hello(Runnable(data: 12)))
+  b.invoke()
+  assert data == 14
+  b.invoke()
+  assert data == 16

+ +
+

Types

+
+
+
Task = object
+
+ + Task contains the callback and its arguments. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `=copy`(x: var Task; y: Task) {.error.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `=destroy`(t: Task) {.inline, ...gcsafe, raises: [], tags: [RootEffect],
+                           forbids: [].}
+
+ + Frees the resources allocated for a Task. + Source   +Edit   + +
+
+ +
+
+
+
proc invoke(task: Task; res: pointer = nil) {.inline, ...gcsafe,
+    raises: [Exception], tags: [RootEffect], forbids: [].}
+
+ + Invokes the task. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro toTask(e: typed{nkCall | nkInfix | nkPrefix | nkPostfix | nkCommand |
+    nkCallStrLit}): Task
+
+ + Converts the call and its arguments to Task. +

Example:

+
proc hello(a: int) = echo a
+
+let b = toTask hello(13)
+assert b is Task
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/tasks.idx b/tasks.idx new file mode 100644 index 0000000000000..e17ec3650856b --- /dev/null +++ b/tasks.idx @@ -0,0 +1,6 @@ +nimTitle tasks tasks.html module std/tasks 0 +nim Task tasks.html#Task object Task 63 +nim `=copy` tasks.html#=copy,Task,Task proc `=copy`(x: var Task; y: Task) 69 +nim `=destroy` tasks.html#=destroy,Task proc `=destroy`(t: Task) 73 +nim invoke tasks.html#invoke,Task,pointer proc invoke(task: Task; res: pointer = nil) 87 +nim toTask tasks.html#toTask.m macro toTask(e: typed{nkCall | nkInfix | nkPrefix | nkPostfix | nkCommand |\n nkCallStrLit}): Task 126 diff --git a/tempfiles.html b/tempfiles.html new file mode 100644 index 0000000000000..6809163c4bddd --- /dev/null +++ b/tempfiles.html @@ -0,0 +1,199 @@ + + + + + + + +std/tempfiles + + + + + + + + + + + + + + + + +
+
+

std/tempfiles

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module creates temporary files and directories.

+

Experimental API, subject to change.

+

+
+

Imports

+
+ os, random, syncio, posix +
+
+
+

Procs

+
+
+
+
proc createTempDir(prefix, suffix: string; dir = ""): string {.
+    ...raises: [OSError, IOError],
+    tags: [ReadEnvEffect, ReadIOEffect, WriteDirEffect, ReadDirEffect],
+    forbids: [].}
+
+ +

Creates a new temporary directory in the directory dir.

+

This generates a dir name using genTempPath(prefix, suffix, dir), creates the directory and returns it, possibly after retrying to ensure it doesn't already exist.

+

If failing to create a temporary directory, OSError will be raised.

+
Note: +It is the caller's responsibility to remove the directory when no longer needed.
+
Note: +dir must exist (empty dir will resolve to getTempDir).
+ +

Example:

+
import std/os
+doAssertRaises(OSError): discard createTempDir("", "", "nonexistent")
+let dir = createTempDir("tmpprefix_", "_end")
+# dir looks like: getTempDir() / "tmpprefix_YEl9VuVj_end"
+assert dirExists(dir)
+removeDir(dir)
+ Source   +Edit   + +
+
+ +
+
+
+
proc createTempFile(prefix, suffix: string; dir = ""): tuple[cfile: File,
+    path: string] {....raises: [OSError], tags: [ReadEnvEffect, ReadIOEffect],
+                    forbids: [].}
+
+ +

Creates a new temporary file in the directory dir.

+

This generates a path name using genTempPath(prefix, suffix, dir) and returns a file handle to an open file and the path of that file, possibly after retrying to ensure it doesn't already exist.

+

If failing to create a temporary file, OSError will be raised.

+
Note: +It is the caller's responsibility to close result.cfile and remove result.file when no longer needed.
+
Note: +dir must exist (empty dir will resolve to getTempDir).
+ +

Example:

+
import std/os
+doAssertRaises(OSError): discard createTempFile("", "", "nonexistent")
+let (cfile, path) = createTempFile("tmpprefix_", "_end.tmp")
+# path looks like: getTempDir() / "tmpprefix_FDCIRZA0_end.tmp"
+cfile.write "foo"
+cfile.setFilePos 0
+assert readAll(cfile) == "foo"
+close cfile
+assert readFile(path) == "foo"
+removeFile(path)
+ Source   +Edit   + +
+
+ +
+
+
+
proc genTempPath(prefix, suffix: string; dir = ""): string {....raises: [],
+    tags: [ReadEnvEffect, ReadIOEffect], forbids: [].}
+
+ +

Generates a path name in dir.

+

The path begins with prefix and ends with suffix.

+
Note: +dir must exist (empty dir will resolve to getTempDir).
+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/tempfiles.idx b/tempfiles.idx new file mode 100644 index 0000000000000..aba72e9953860 --- /dev/null +++ b/tempfiles.idx @@ -0,0 +1,4 @@ +nimTitle tempfiles tempfiles.html module std/tempfiles 0 +nim genTempPath tempfiles.html#genTempPath,string,string,string proc genTempPath(prefix, suffix: string; dir = ""): string 126 +nim createTempFile tempfiles.html#createTempFile,string,string,string proc createTempFile(prefix, suffix: string; dir = ""): tuple[cfile: File,\n path: string] 135 +nim createTempDir tempfiles.html#createTempDir,string,string,string proc createTempDir(prefix, suffix: string; dir = ""): string 168 diff --git a/terminal.html b/terminal.html new file mode 100644 index 0000000000000..37ce7b02f9bdb --- /dev/null +++ b/terminal.html @@ -0,0 +1,1293 @@ + + + + + + + +std/terminal + + + + + + + + + + + + + + + + +
+
+

std/terminal

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module contains a few procedures to control the terminal (also called console). On UNIX, the implementation simply uses ANSI escape sequences and does not depend on any other module, on Windows it uses the Windows API. Changing the style is permanent even after program termination! Use the code exitprocs.addExitProc(resetAttributes) to restore the defaults. Similarly, if you hide the cursor, make sure to unhide it with showCursor before quitting. +

Progress bar

Basic progress bar example:

+ +

Example: cmd: -r:off

+
import std/terminal
+import std/[os, strutils]
+
+for i in 0..100:
+  stdout.styledWriteLine(fgRed, "0% ", fgWhite, '#'.repeat i, if i > 50: fgGreen else: fgYellow, "\t", $i , "%")
+  sleep 42
+  cursorUp 1
+  eraseLine()
+
+stdout.resetAttributes()
+

Playing with colorful and styled text

Procs like styledWriteLine, styledEcho etc. have a temporary effect on text parameters. Style parameters only affect the text parameter right after them. After being called, these procs will reset the default style of the terminal. While setBackGroundColor, setForeGroundColor etc. have a lasting influence on the terminal, you can use resetAttributes to reset the default style of the terminal. +

Example: cmd: -r:off

+
import std/terminal
+stdout.styledWriteLine({styleBright, styleBlink, styleUnderscore}, "styled text ")
+stdout.styledWriteLine(fgRed, "red text ")
+stdout.styledWriteLine(fgWhite, bgRed, "white text in red background")
+stdout.styledWriteLine(" ordinary text without style ")
+
+stdout.setBackGroundColor(bgCyan, true)
+stdout.setForeGroundColor(fgBlue)
+stdout.write("blue text in cyan background")
+stdout.resetAttributes()
+
+# You can specify multiple text parameters. Style parameters
+# only affect the text parameter right after them.
+styledEcho styleBright, fgGreen, "[PASS]", resetStyle, fgGreen, " Yay!"
+
+stdout.styledWriteLine(fgRed, "red text ", styleBright, "bold red", fgDefault, " bold text")

+ +
+

Types

+
+
+
BackgroundColor = enum
+  bgBlack = 40,             ## black
+  bgRed,                    ## red
+  bgGreen,                  ## green
+  bgYellow,                 ## yellow
+  bgBlue,                   ## blue
+  bgMagenta,                ## magenta
+  bgCyan,                   ## cyan
+  bgWhite,                  ## white
+  bg8Bit,                   ## 256-color (not supported, see `enableTrueColors` instead.)
+  bgDefault                  ## default terminal background color
+
+ + Terminal's background colors. + Source   +Edit   + +
+
+
+
ForegroundColor = enum
+  fgBlack = 30,             ## black
+  fgRed,                    ## red
+  fgGreen,                  ## green
+  fgYellow,                 ## yellow
+  fgBlue,                   ## blue
+  fgMagenta,                ## magenta
+  fgCyan,                   ## cyan
+  fgWhite,                  ## white
+  fg8Bit,                   ## 256-color (not supported, see `enableTrueColors` instead.)
+  fgDefault                  ## default terminal foreground color
+
+ + Terminal's foreground colors. + Source   +Edit   + +
+
+
+
Style = enum
+  styleBright = 1,          ## bright text
+  styleDim,                 ## dim text
+  styleItalic,              ## italic (or reverse on terminals not supporting)
+  styleUnderscore,          ## underscored text
+  styleBlink,               ## blinking/bold text
+  styleBlinkRapid,          ## rapid blinking/bold text (not widely supported)
+  styleReverse,             ## reverse
+  styleHidden,              ## hidden text
+  styleStrikethrough         ## strikethrough
+
+ + Different styles for text output. + Source   +Edit   + +
+
+
+
TerminalCmd = enum
+  resetStyle,               ## reset attributes
+  fgColor,                  ## set foreground's true color
+  bgColor                    ## set background's true color
+
+ + commands that can be expressed as arguments + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
ansiResetCode = "\e[0m"
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc ansiBackgroundColorCode(color: Color): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ansiForegroundColorCode(color: Color): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc ansiForegroundColorCode(fg: ForegroundColor; bright = false): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ansiStyleCode(style: int): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cursorBackward(f: File; count = 1) {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + Moves the cursor backward by count columns. +

Example: cmd: -r:off

+
stdout.cursorBackward(2)
+write(stdout, "Hello World!") # anything written at that location will be erased/replaced with this
+ Source   +Edit   + +
+
+ +
+
+
+
proc cursorDown(f: File; count = 1) {....raises: [IOError], tags: [WriteIOEffect],
+                                      forbids: [].}
+
+ + Moves the cursor down by count rows. +

Example: cmd: -r:off

+
stdout.cursorDown(2)
+write(stdout, "Hello World!") # anything written at that location will be erased/replaced with this
+ Source   +Edit   + +
+
+ +
+
+
+
proc cursorForward(f: File; count = 1) {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + Moves the cursor forward by count columns. +

Example: cmd: -r:off

+
stdout.cursorForward(2)
+write(stdout, "Hello World!") # anything written at that location will be erased/replaced with this
+ Source   +Edit   + +
+
+ +
+
+
+
proc cursorUp(f: File; count = 1) {....raises: [IOError], tags: [WriteIOEffect],
+                                    forbids: [].}
+
+ + Moves the cursor up by count rows. +

Example: cmd: -r:off

+
stdout.cursorUp(2)
+write(stdout, "Hello World!") # anything written at that location will be erased/replaced with this
+ Source   +Edit   + +
+
+ +
+
+
+
proc disableTrueColors() {....raises: [], tags: [RootEffect], forbids: [].}
+
+ + Disables true color. + Source   +Edit   + +
+
+ +
+
+
+
proc enableTrueColors() {....raises: [], tags: [RootEffect, ReadEnvEffect],
+                          forbids: [].}
+
+ + Enables true color. + Source   +Edit   + +
+
+ +
+
+
+
proc eraseLine(f: File) {....raises: [IOError], tags: [WriteIOEffect], forbids: [].}
+
+ + Erases the entire current line. +

Example: cmd: -r:off

+
write(stdout, "never mind")
+stdout.eraseLine() # nothing will be printed on the screen
+ Source   +Edit   + +
+
+ +
+
+
+
proc eraseScreen(f: File) {....raises: [IOError], tags: [WriteIOEffect],
+                            forbids: [].}
+
+ + Erases the screen with the background colour and moves the cursor to home. + Source   +Edit   + +
+
+ +
+
+
+
proc getch(): char {....raises: [IOError, EOFError], tags: [ReadIOEffect],
+                     forbids: [].}
+
+ + Reads a single character from the terminal, blocking until it is entered. The character is not printed to the terminal. + Source   +Edit   + +
+
+ +
+
+
+
proc getCursorPos(): tuple[x, y: int] {....raises: [ValueError, IOError],
+                                        tags: [WriteIOEffect, ReadIOEffect],
+                                        forbids: [].}
+
+ + Returns cursor position (x, y) writes to stdout and expects the terminal to respond via stdin + Source   +Edit   + +
+
+ +
+
+
+
proc hideCursor(f: File) {....raises: [IOError], tags: [WriteIOEffect], forbids: [].}
+
+ + Hides the cursor. + Source   +Edit   + +
+
+ +
+
+
+
proc isatty(f: File): bool {....raises: [], tags: [], forbids: [].}
+
+ + Returns true if f is associated with a terminal device. + Source   +Edit   + +
+
+ +
+
+
+
proc isTrueColorSupported(): bool {....raises: [], tags: [RootEffect], forbids: [].}
+
+ + Returns true if a terminal supports true color. + Source   +Edit   + +
+
+ +
+
+
+
proc readPasswordFromStdin(prompt = "password: "): string {....raises: [IOError],
+    tags: [ReadIOEffect, WriteIOEffect], forbids: [].}
+
+ + Reads a password from stdin without printing it. + Source   +Edit   + +
+
+
+
proc readPasswordFromStdin(prompt: string; password: var string): bool {.
+    ...tags: [ReadIOEffect, WriteIOEffect], raises: [IOError], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc resetAttributes() {.noconv, ...raises: [IOError], tags: [WriteIOEffect],
+                         forbids: [].}
+
+ + Resets all attributes on stdout. It is advisable to register this as a quit proc with exitprocs.addExitProc(resetAttributes). + Source   +Edit   + +
+
+
+
proc resetAttributes(f: File) {....raises: [IOError], tags: [WriteIOEffect],
+                                forbids: [].}
+
+ + Resets all attributes. + Source   +Edit   + +
+
+ +
+
+
+
proc setBackgroundColor(f: File; bg: BackgroundColor; bright = false) {.
+    ...raises: [IOError], tags: [WriteIOEffect], forbids: [].}
+
+ + Sets the terminal's background color. + Source   +Edit   + +
+
+
+
proc setBackgroundColor(f: File; color: Color) {....raises: [IOError],
+    tags: [RootEffect, WriteIOEffect], forbids: [].}
+
+ + Sets the terminal's background true color. + Source   +Edit   + +
+
+ +
+
+
+
proc setCursorPos(f: File; x, y: int) {....raises: [IOError],
+                                        tags: [WriteIOEffect], forbids: [].}
+
+ + Sets the terminal's cursor to the (x,y) position. (0,0) is the upper left of the screen. + Source   +Edit   + +
+
+ +
+
+
+
proc setCursorXPos(f: File; x: int) {....raises: [IOError], tags: [WriteIOEffect],
+                                      forbids: [].}
+
+ + Sets the terminal's cursor to the x position. The y position is not changed. + Source   +Edit   + +
+
+ +
+
+
+
proc setForegroundColor(f: File; color: Color) {....raises: [IOError],
+    tags: [RootEffect, WriteIOEffect], forbids: [].}
+
+ + Sets the terminal's foreground true color. + Source   +Edit   + +
+
+
+
proc setForegroundColor(f: File; fg: ForegroundColor; bright = false) {.
+    ...raises: [IOError], tags: [WriteIOEffect], forbids: [].}
+
+ + Sets the terminal's foreground color. + Source   +Edit   + +
+
+ +
+
+
+
proc setStyle(f: File; style: set[Style]) {....raises: [IOError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + Sets the terminal style. + Source   +Edit   + +
+
+ +
+
+
+
proc showCursor(f: File) {....raises: [IOError], tags: [WriteIOEffect], forbids: [].}
+
+ + Shows the cursor. + Source   +Edit   + +
+
+ +
+
+
+
proc terminalHeight(): int {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns some reasonable terminal height from either standard file descriptors, controlling terminal, environment variables or tradition. Zero is returned if the height could not be determined. + Source   +Edit   + +
+
+ +
+
+
+
proc terminalHeightIoctl(fds: openArray[int]): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + Returns terminal height from first fd that supports the ioctl. + Source   +Edit   + +
+
+ +
+
+
+
proc terminalSize(): tuple[w, h: int] {....raises: [], tags: [ReadEnvEffect],
+                                        forbids: [].}
+
+ + Returns the terminal width and height as a tuple. Internally calls terminalWidth and terminalHeight, so the same assumptions apply. + Source   +Edit   + +
+
+ +
+
+
+
proc terminalWidth(): int {....raises: [], tags: [ReadEnvEffect], forbids: [].}
+
+ + Returns some reasonable terminal width from either standard file descriptors, controlling terminal, environment variables or tradition. + Source   +Edit   + +
+
+ +
+
+
+
proc terminalWidthIoctl(fds: openArray[int]): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + Returns terminal width from first fd that supports the ioctl. + Source   +Edit   + +
+
+ +
+
+
+
proc writeStyled(txt: string; style: set[Style] = {styleBright}) {.
+    ...raises: [IOError], tags: [WriteIOEffect], forbids: [].}
+
+ + Writes the text txt in a given style to stdout. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro styledWrite(f: File; m: varargs[typed]): untyped
+
+ + Similar to write, but treating terminal style arguments specially. When some argument is Style, set[Style], ForegroundColor, BackgroundColor or TerminalCmd then it is not sent directly to f, but instead corresponding terminal style proc is called. +

Example: cmd: -r:off

+
stdout.styledWrite(fgRed, "red text ")
+stdout.styledWrite(fgGreen, "green text")
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template ansiBackgroundColorCode(color: static[Color]): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template ansiForegroundColorCode(color: static[Color]): string
+
+ + + Source   +Edit   + +
+
+
+
template ansiForegroundColorCode(fg: static[ForegroundColor];
+                                 bright: static[bool] = false): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template ansiStyleCode(style: static[Style]): string
+
+ + + Source   +Edit   + +
+
+
+
template ansiStyleCode(style: Style): string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template cursorBackward(count = 1)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template cursorDown(count = 1)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template cursorForward(count = 1)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template cursorUp(count = 1)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template eraseLine()
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template eraseScreen()
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template hideCursor()
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template setBackgroundColor(bg: BackgroundColor; bright = false)
+
+ + + Source   +Edit   + +
+
+
+
template setBackgroundColor(color: Color)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template setCursorPos(x, y: int)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template setCursorXPos(x: int)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template setForegroundColor(color: Color)
+
+ + + Source   +Edit   + +
+
+
+
template setForegroundColor(fg: ForegroundColor; bright = false)
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template setStyle(style: set[Style])
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template showCursor()
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template styledEcho(args: varargs[untyped])
+
+ + Echoes styles arguments to stdout using styledWriteLine. + Source   +Edit   + +
+
+ +
+
+
+
template styledWriteLine(f: File; args: varargs[untyped])
+
+ + Calls styledWrite and appends a newline at the end. +

Example:

+
proc error(msg: string) =
+  styledWriteLine(stderr, fgRed, "Error: ", resetStyle, msg)
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/terminal.idx b/terminal.idx new file mode 100644 index 0000000000000..39cd20283e33c --- /dev/null +++ b/terminal.idx @@ -0,0 +1,107 @@ +nimTitle terminal terminal.html module std/terminal 0 +nim ansiResetCode terminal.html#ansiResetCode const ansiResetCode 98 +nim getCursorPos terminal.html#getCursorPos proc getCursorPos(): tuple[x, y: int] 274 +nim terminalWidthIoctl terminal.html#terminalWidthIoctl,openArray[int] proc terminalWidthIoctl(fds: openArray[int]): int 316 +nim terminalHeightIoctl terminal.html#terminalHeightIoctl,openArray[int] proc terminalHeightIoctl(fds: openArray[int]): int 325 +nim terminalWidth terminal.html#terminalWidth proc terminalWidth(): int 336 +nim terminalHeight terminal.html#terminalHeight proc terminalHeight(): int 366 +nim terminalSize terminal.html#terminalSize proc terminalSize(): tuple[w, h: int] 400 +nim hideCursor terminal.html#hideCursor,File proc hideCursor(f: File) 415 +nim showCursor terminal.html#showCursor,File proc showCursor(f: File) 422 +nim setCursorPos terminal.html#setCursorPos,File,int,int proc setCursorPos(f: File; x, y: int) 429 +nim setCursorXPos terminal.html#setCursorXPos,File,int proc setCursorXPos(f: File; x: int) 438 +nim cursorUp terminal.html#cursorUp,File,int proc cursorUp(f: File; count = 1) 470 +nim cursorDown terminal.html#cursorDown,File,int proc cursorDown(f: File; count = 1) 483 +nim cursorForward terminal.html#cursorForward,File,int proc cursorForward(f: File; count = 1) 496 +nim cursorBackward terminal.html#cursorBackward,File,int proc cursorBackward(f: File; count = 1) 509 +nim eraseLine terminal.html#eraseLine,File proc eraseLine(f: File) 553 +nim eraseScreen terminal.html#eraseScreen,File proc eraseScreen(f: File) 579 +nim resetAttributes terminal.html#resetAttributes,File proc resetAttributes(f: File) 606 +nim styleBright terminal.html#styleBright Style.styleBright 620 +nim styleDim terminal.html#styleDim Style.styleDim 620 +nim styleItalic terminal.html#styleItalic Style.styleItalic 620 +nim styleUnderscore terminal.html#styleUnderscore Style.styleUnderscore 620 +nim styleBlink terminal.html#styleBlink Style.styleBlink 620 +nim styleBlinkRapid terminal.html#styleBlinkRapid Style.styleBlinkRapid 620 +nim styleReverse terminal.html#styleReverse Style.styleReverse 620 +nim styleHidden terminal.html#styleHidden Style.styleHidden 620 +nim styleStrikethrough terminal.html#styleStrikethrough Style.styleStrikethrough 620 +nim Style terminal.html#Style enum Style 620 +nim ansiStyleCode terminal.html#ansiStyleCode,int proc ansiStyleCode(style: int): string 631 +nim ansiStyleCode terminal.html#ansiStyleCode.t,Style template ansiStyleCode(style: Style): string 634 +nim ansiStyleCode terminal.html#ansiStyleCode.t,static[Style] template ansiStyleCode(style: static[Style]): string 638 +nim setStyle terminal.html#setStyle,File,set[Style] proc setStyle(f: File; style: set[Style]) 641 +nim writeStyled terminal.html#writeStyled,string,set[Style] proc writeStyled(txt: string; style: set[Style] = {styleBright}) 656 +nim fgBlack terminal.html#fgBlack ForegroundColor.fgBlack 674 +nim fgRed terminal.html#fgRed ForegroundColor.fgRed 674 +nim fgGreen terminal.html#fgGreen ForegroundColor.fgGreen 674 +nim fgYellow terminal.html#fgYellow ForegroundColor.fgYellow 674 +nim fgBlue terminal.html#fgBlue ForegroundColor.fgBlue 674 +nim fgMagenta terminal.html#fgMagenta ForegroundColor.fgMagenta 674 +nim fgCyan terminal.html#fgCyan ForegroundColor.fgCyan 674 +nim fgWhite terminal.html#fgWhite ForegroundColor.fgWhite 674 +nim fg8Bit terminal.html#fg8Bit ForegroundColor.fg8Bit 674 +nim fgDefault terminal.html#fgDefault ForegroundColor.fgDefault 674 +nim ForegroundColor terminal.html#ForegroundColor enum ForegroundColor 674 +nim bgBlack terminal.html#bgBlack BackgroundColor.bgBlack 686 +nim bgRed terminal.html#bgRed BackgroundColor.bgRed 686 +nim bgGreen terminal.html#bgGreen BackgroundColor.bgGreen 686 +nim bgYellow terminal.html#bgYellow BackgroundColor.bgYellow 686 +nim bgBlue terminal.html#bgBlue BackgroundColor.bgBlue 686 +nim bgMagenta terminal.html#bgMagenta BackgroundColor.bgMagenta 686 +nim bgCyan terminal.html#bgCyan BackgroundColor.bgCyan 686 +nim bgWhite terminal.html#bgWhite BackgroundColor.bgWhite 686 +nim bg8Bit terminal.html#bg8Bit BackgroundColor.bg8Bit 686 +nim bgDefault terminal.html#bgDefault BackgroundColor.bgDefault 686 +nim BackgroundColor terminal.html#BackgroundColor enum BackgroundColor 686 +nim setForegroundColor terminal.html#setForegroundColor,File,ForegroundColor proc setForegroundColor(f: File; fg: ForegroundColor; bright = false) 701 +nim setBackgroundColor terminal.html#setBackgroundColor,File,BackgroundColor proc setBackgroundColor(f: File; bg: BackgroundColor; bright = false) 730 +nim ansiForegroundColorCode terminal.html#ansiForegroundColorCode,ForegroundColor proc ansiForegroundColorCode(fg: ForegroundColor; bright = false): string 759 +nim ansiForegroundColorCode terminal.html#ansiForegroundColorCode.t,static[ForegroundColor],static[bool] template ansiForegroundColorCode(fg: static[ForegroundColor];\n bright: static[bool] = false): string 764 +nim ansiForegroundColorCode terminal.html#ansiForegroundColorCode,Color proc ansiForegroundColorCode(color: Color): string 768 +nim ansiForegroundColorCode terminal.html#ansiForegroundColorCode.t,static[Color] template ansiForegroundColorCode(color: static[Color]): string 772 +nim ansiBackgroundColorCode terminal.html#ansiBackgroundColorCode,Color proc ansiBackgroundColorCode(color: Color): string 777 +nim ansiBackgroundColorCode terminal.html#ansiBackgroundColorCode.t,static[Color] template ansiBackgroundColorCode(color: static[Color]): string 781 +nim setForegroundColor terminal.html#setForegroundColor,File,Color proc setForegroundColor(f: File; color: Color) 786 +nim setBackgroundColor terminal.html#setBackgroundColor,File,Color proc setBackgroundColor(f: File; color: Color) 791 +nim isatty terminal.html#isatty,File proc isatty(f: File): bool 803 +nim resetStyle terminal.html#resetStyle TerminalCmd.resetStyle 815 +nim fgColor terminal.html#fgColor TerminalCmd.fgColor 815 +nim bgColor terminal.html#bgColor TerminalCmd.bgColor 815 +nim TerminalCmd terminal.html#TerminalCmd enum TerminalCmd 815 +nim styledWrite terminal.html#styledWrite.m,File,varargs[typed] macro styledWrite(f: File; m: varargs[typed]): untyped 836 +nim styledWriteLine terminal.html#styledWriteLine.t,File,varargs[untyped] template styledWriteLine(f: File; args: varargs[untyped]) 865 +nim styledEcho terminal.html#styledEcho.t,varargs[untyped] template styledEcho(args: varargs[untyped]) 874 +nim getch terminal.html#getch proc getch(): char 878 +nim readPasswordFromStdin terminal.html#readPasswordFromStdin,string,string proc readPasswordFromStdin(prompt: string; password: var string): bool 927 +nim readPasswordFromStdin terminal.html#readPasswordFromStdin,string proc readPasswordFromStdin(prompt = "password: "): string 941 +nim hideCursor terminal.html#hideCursor.t template hideCursor() 948 +nim showCursor terminal.html#showCursor.t template showCursor() 949 +nim setCursorPos terminal.html#setCursorPos.t,int,int template setCursorPos(x, y: int) 950 +nim setCursorXPos terminal.html#setCursorXPos.t,int template setCursorXPos(x: int) 951 +nim cursorUp terminal.html#cursorUp.t,int template cursorUp(count = 1) 954 +nim cursorDown terminal.html#cursorDown.t,int template cursorDown(count = 1) 955 +nim cursorForward terminal.html#cursorForward.t,int template cursorForward(count = 1) 956 +nim cursorBackward terminal.html#cursorBackward.t,int template cursorBackward(count = 1) 957 +nim eraseLine terminal.html#eraseLine.t template eraseLine() 958 +nim eraseScreen terminal.html#eraseScreen.t template eraseScreen() 959 +nim setStyle terminal.html#setStyle.t,set[Style] template setStyle(style: set[Style]) 960 +nim setForegroundColor terminal.html#setForegroundColor.t,ForegroundColor template setForegroundColor(fg: ForegroundColor; bright = false) 962 +nim setBackgroundColor terminal.html#setBackgroundColor.t,BackgroundColor template setBackgroundColor(bg: BackgroundColor; bright = false) 964 +nim setForegroundColor terminal.html#setForegroundColor.t,Color template setForegroundColor(color: Color) 966 +nim setBackgroundColor terminal.html#setBackgroundColor.t,Color template setBackgroundColor(color: Color) 968 +nim resetAttributes terminal.html#resetAttributes proc resetAttributes() 970 +nim isTrueColorSupported terminal.html#isTrueColorSupported proc isTrueColorSupported(): bool 976 +nim enableTrueColors terminal.html#enableTrueColors proc enableTrueColors() 983 +nim disableTrueColors terminal.html#disableTrueColors proc disableTrueColors() 1016 +heading Progress bar terminal.html#progress-bar Progress bar 0 +heading Playing with colorful and styled text terminal.html#progress-bar-playing-with-colorful-and-styled-text Playing with colorful and styled text 0 +nimgrp readpasswordfromstdin terminal.html#readPasswordFromStdin-procs-all proc 927 +nimgrp setforegroundcolor terminal.html#setForegroundColor-procs-all proc 701 +nimgrp setbackgroundcolor terminal.html#setBackgroundColor-procs-all proc 730 +nimgrp ansiforegroundcolorcode terminal.html#ansiForegroundColorCode-procs-all proc 759 +nimgrp resetattributes terminal.html#resetAttributes-procs-all proc 606 +nimgrp ansistylecode terminal.html#ansiStyleCode-templates-all template 634 +nimgrp setforegroundcolor terminal.html#setForegroundColor-templates-all template 962 +nimgrp setbackgroundcolor terminal.html#setBackgroundColor-templates-all template 964 +nimgrp ansiforegroundcolorcode terminal.html#ansiForegroundColorCode-templates-all template 764 diff --git a/termios.html b/termios.html new file mode 100644 index 0000000000000..8a0c7f2328c26 --- /dev/null +++ b/termios.html @@ -0,0 +1,1737 @@ + + + + + + + +std/termios + + + + + + + + + + + + + + + + +
+
+

std/termios

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
+

Imports

+
+ posix +
+
+
+

Types

+
+
+
Cflag = cuint
+
+ + + Source   +Edit   + +
+
+
+
IOctl_WinSize = object
+  ws_row*, ws_col*, ws_xpixel*, ws_ypixel*: cushort
+
+ + + Source   +Edit   + +
+
+
+
Speed = cuint
+
+ + + Source   +Edit   + +
+
+
+
Termios {.importc: "struct termios", header: "<termios.h>".} = object
+  c_iflag*: Cflag
+  c_oflag*: Cflag
+  c_cflag*: Cflag
+  c_lflag*: Cflag
+  c_line*: cuchar
+  c_cc*: array[NCCS, cuchar]
+  c_ispeed*: Speed
+  c_ospeed*: Speed
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
B0 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B50 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B75 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B110 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B134 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B150 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B200 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B300 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B600 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B1200 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B1800 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B2400 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B4800 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B9600 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B19200 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B38400 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B57600 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B115200 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B230400 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B460800 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B500000 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B576000 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B921600 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B1000000 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B1152000 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B1500000 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B2000000 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B2500000 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B3000000 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B3500000 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
B4000000 {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
BRKINT {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
BS0 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
BS1 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
BSDLY {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
CLOCAL {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
CR0 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
CR1 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
CR2 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
CR3 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
CRDLY {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
CREAD {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
CS5 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
CS6 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
CS7 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
CS8 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
CSIZE {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
CSTOPB {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
ECHO {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
ECHOE {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
ECHOK {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
ECHONL {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
EXTA {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
EXTB {.importc, header: "<termios.h>".}: Speed
+
+ + + Source   +Edit   + +
+
+
+
FF0 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
FF1 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
FFDLY {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
HUPCL {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
ICANON {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
ICRNL {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
IEXTEN {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
IGNBRK {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
IGNCR {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
IGNPAR {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
INLCR {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
INPCK {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
ISIG {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
ISTRIP {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
IUCLC {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
IXANY {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
IXOFF {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
IXON {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
NL0 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
NL1 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
NLDLY {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
NOFLSH {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
OCRNL {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
OFDEL {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
OFILL {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
ONLCR {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
ONLRET {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
ONOCR {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
OPOST {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
PARENB {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
PARMRK {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
PARODD {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
TAB0 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
TAB1 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
TAB2 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
TAB3 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
TABDLY {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
TCIFLUSH {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
TCIOFF {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
TCIOFLUSH {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
TCION {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
TCOFLUSH {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
TCOOFF {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
TCOON {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
TCSADRAIN {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
TCSAFLUSH {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
TCSANOW {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
TIOCGWINSZ {.importc, header: "<sys/ioctl.h>".}: culong
+
+ + + Source   +Edit   + +
+
+
+
TOSTOP {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
VEOF {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
VEOL {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
VERASE {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
VINTR {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
VKILL {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
VMIN {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
VQUIT {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
VSTART {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
VSTOP {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
VSUSP {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+
+
VT0 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
VT1 {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
VTDLY {.importc, header: "<termios.h>".}: Cflag
+
+ + + Source   +Edit   + +
+
+
+
VTIME {.importc, header: "<termios.h>".}: cint
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
NCCS = 32
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc cfGetIspeed(termios: ptr Termios): Speed {.importc: "cfgetispeed",
+    header: "<termios.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cfGetOspeed(termios: ptr Termios): Speed {.importc: "cfgetospeed",
+    header: "<termios.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cfSetIspeed(termios: ptr Termios; speed: Speed): cint {.
+    importc: "cfsetispeed", header: "<termios.h>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cfSetOspeed(termios: ptr Termios; speed: Speed): cint {.
+    importc: "cfsetospeed", header: "<termios.h>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ioctl(fd: cint; request: culong; reply: ptr IOctl_WinSize): int {.
+    importc: "ioctl", header: "<stdio.h>", varargs, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc tcDrain(fd: cint): cint {.importc: "tcdrain", header: "<termios.h>",
+                               ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc tcFlow(fd: cint; action: cint): cint {.importc: "tcflow",
+    header: "<termios.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc tcFlush(fd: cint; queue_selector: cint): cint {.importc: "tcflush",
+    header: "<termios.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc tcGetAttr(fd: cint; termios: ptr Termios): cint {.importc: "tcgetattr",
+    header: "<termios.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc tcSendBreak(fd: cint; duration: cint): cint {.importc: "tcsendbreak",
+    header: "<termios.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc tcSetAttr(fd: cint; optional_actions: cint; termios: ptr Termios): cint {.
+    importc: "tcsetattr", header: "<termios.h>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template cceq(val, c): untyped
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/testament.html b/testament.html new file mode 100644 index 0000000000000..cd6f167c23704 --- /dev/null +++ b/testament.html @@ -0,0 +1,347 @@ + + + + + + + +Testament + + + + + + + + + + + + + + + + +
+
+

Testament

+
+ +
+ Source   +Edit   + +
+ +

Testament is an advanced automatic unittests runner for Nim tests, is used for the development of Nim itself, offers process isolation for your tests, it can generate statistics about test cases, supports multiple targets (C, C++, ObjectiveC, JavaScript, etc.), simulated Dry-Runs, has logging, can generate HTML reports, skip tests from a file, and more, so can be useful to run your tests, even the most complex ones.

+ +

Test files location

By default, Testament looks for test files on "./tests/category/*.nim". You can overwrite this pattern glob using pattern <glob>. The default working directory path can be changed using --directory:"folder/subfolder/".

+

Testament uses the nim compiler on PATH. You can change that using --nim:"folder/subfolder/nim". Running JavaScript tests with --targets:"js" requires a working NodeJS on PATH.

+ +

Commands

p|pat|pattern <glob> run all the tests matching the given pattern all run all tests inside of category folders c|cat|category <category> run all the tests of a certain category r|run <test> run single test file html generate testresults.html from the database

+ +

Options

--print
print results to the console
+
--verbose
print commands (compiling and running tests)
+
--simulate
see what tests would be run but don't run them (for debugging)
+
--failing
only show failing/ignored tests
+
--targets:"c cpp js objc" run tests for specified targets (default: c)
+
--nim:path
use a particular nim executable (default: $PATH/nim)
+
--directory:dir
Change to directory dir before reading the tests or doing anything else.
+
--colors:on|off
Turn messages coloring on|off.
+
--backendLogging:on|off
Disable or enable backend logging. By default turned on.
+
--megatest:on|off
Enable or disable megatest. Default is on.
+
--valgrind:on|off
Enable or disable valgrind support. Default is on.
+
--skipFrom:file
Read tests to skip from file - one test per line, # comments ignored
+
+

Running a single test

This is a minimal example to understand the basics, not very useful for production, but easy to understand:

+

$ mkdir -p tests/category
+$ echo "assert 42 == 42" > tests/category/test0.nim
+$ testament run tests/category/test0.nim
+PASS: tests/category/test0.nim c                           ( 0.2 sec)
+$ testament r tests/category/test0
+PASS: tests/category/test0.nim C                           ( 0.2 sec)

+ +

Running all tests from a directory

This will run all tests in the top level tests/ directory. NOTE: these tests are skipped by testament all.

+

$ testament pattern "tests/*.nim"

+

To search for tests deeper in a directory, use

+

$ testament pattern "tests/**/*.nim"    # one level deeper
+$ testament pattern "tests/**/**/*.nim" # two levels deeper

+ +

HTML Reports

Generate HTML Reports testresults.html from unittests, you have to run at least 1 test before generating a report:

+

$ testament html

+ +

Writing Unit tests

Example "template" to edit and write a Testament unittest:

+

discard """
+  
+  # What actions to expect completion on.
+  # Options:
+  #   "compile": expect successful compilation
+  #   "run": expect successful compilation and execution
+  #   "reject": expect failed compilation. The "reject" action can catch
+  #             {.error.} pragmas but not {.fatal.} pragmas because
+  #             {.error.} calls are expected to originate from the test-file,
+  #             and can explicitly be specified using the "file", "line" and
+  #             "column" options.
+  #             {.fatal.} pragmas guarantee that compilation will be aborted.
+  action: "run"
+  
+  # For testing failed compilations you can specify the expected origin of the
+  # compilation error.
+  # With the "file", "line" and "column" options you can define the file,
+  # line and column that a compilation-error should have originated from.
+  # Use only with action: "reject" as it expects a failed compilation.
+  # Requires errormsg or msg to be defined.
+  # file: ""
+  # line: ""
+  # column: ""
+  
+  # The exit code that the test is expected to return. Typically, the default
+  # value of 0 is fine. Note that if the test will be run by valgrind, then
+  # the test will exit with either a code of 0 on success or 1 on failure.
+  exitcode: 0
+  
+  # Provide an `output` string to assert that the test prints to standard out
+  # exactly the expected string. Provide an `outputsub` string to assert that
+  # the string given here is a substring of the standard out output of the
+  # test (the output includes both the compiler and test execution output).
+  output: ""
+  outputsub: ""
+  
+  # Whether to sort the compiler output lines before comparing them to the
+  # expected output.
+  sortoutput: true
+  
+  # Provide a `nimout` string to assert that the compiler during compilation
+  # prints the defined lines to the standard out.
+  # The lines must match in order, but there may be more lines that appear
+  # before, after, or in between them.
+  nimout: '''
+a very long,
+multi-line
+string'''
+  
+  # This is the Standard Input the test should take, if any.
+  input: ""
+  
+  # Error message the test should print, if any.
+  errormsg: ""
+  
+  # Can be run in batch mode, or not.
+  batchable: true
+  
+  # Can be run Joined with other tests to run all together, or not.
+  joinable: true
+  
+  # On Linux 64-bit machines, whether to use Valgrind to check for bad memory
+  # accesses or memory leaks. On other architectures, the test will be run
+  # as-is, without Valgrind.
+  # Options:
+  #   true: run the test with Valgrind
+  #   false: run the without Valgrind
+  #   "leaks": run the test with Valgrind, but do not check for memory leaks
+  valgrind: false   # Can use Valgrind to check for memory leaks, or not (Linux 64Bit only).
+  
+  # Checks that the specified piece of C-code is within the generated C-code.
+  ccodecheck: "'Assert error message'"
+  
+  # Command the test should use to run. If left out or an empty string is
+  # provided, the command is taken to be:
+  # "nim $target --hints:on -d:testing --nimblePath:build/deps/pkgs $options $file"
+  # Subject to variable interpolation.
+  cmd: "nim c -r $file"
+  
+  # Maximum generated temporary intermediate code file size for the test.
+  maxcodesize: 666
+  
+  # Timeout seconds to run the test. Fractional values are supported.
+  timeout: 1.5
+  
+  # Targets to run the test into (c, cpp, objc, js). Defaults to c.
+  targets: "c js"
+  
+  # flags with which to run the test, delimited by `;`
+  matrix: "; -d:release; -d:caseFoo -d:release"
+  
+  # Conditions that will skip this test. Use of multiple "disabled" clauses
+  # is permitted.
+  disabled: "bsd"   # Can disable OSes...
+  disabled: "win"
+  disabled: "32bit" # ...or architectures
+  disabled: "i386"
+  disabled: "azure" # ...or pipeline runners
+  disabled: true    # ...or can disable the test entirely
+
+"""
+assert true
+assert 42 == 42, "Assert error message"

+ + +

Inline hints, warnings and errors (notes)

Testing the line, column, kind and message of hints, warnings and errors can be written inline like so:

+

{.warning: "warning!!"} #[tt.Warning
+         ^ warning!! [User] ]#

+

The opening #[tt. marks the message line. The ^ marks the message column.

+

Inline messages can be combined with nimout when nimoutFull is false (default). This allows testing for expected messages from other modules:

+

discard """
+  nimout: "config.nims(1, 1) Hint: some hint message [User]"
+"""
+{.warning: "warning!!"} #[tt.Warning
+         ^ warning!! [User] ]#

+

Multiple messages for a line can be checked by delimiting messages with ';':

+

discard """
+  matrix: "--errorMax:0 --styleCheck:error"
+"""
+
+proc generic_proc*[T](a_a: int) = #[tt.Error
+     ^ 'generic_proc' should be: 'genericProc'; tt.Error
+                      ^ 'a_a' should be: 'aA' ]#
+  discard

+

Use --errorMax:0 in matrix, or cmd: "nim check $file" when testing for multiple 'Error' messages.

+ +

Output message variable interpolation

errormsg, nimout, and inline messages are subject to these variable interpolations:

+
  • ${/} - platform's directory separator
  • +
  • $file - the filename (without directory) of the test
  • +
+

All other $ characters need escaped as $$.

+ +

Cmd variable interpolation

The cmd option is subject to these variable interpolations:

+
  • $target - the compilation target, e.g. c.
  • +
  • $options - the options for the compiler.
  • +
  • $file - the file path of the test.
  • +
  • $filedir - the directory of the test file.
  • +
+
discard """
+  cmd: "nim $target --nimblePath:./nimbleDir/simplePkgs $options $file"
+"""

All other $ characters need escaped as $$.

+ +

Unit test Examples

Expected to fail:

+

discard """
+  errormsg: "undeclared identifier: 'not_defined'"
+"""
+assert not_defined == "not_defined", "not_defined is not defined"

+

Expected to fail with error thrown from another file:

+

# test.nim
+discard """
+  action: "reject"
+  errorMsg: "I break"
+  file: "breakPragma.nim"
+"""
+import ./breakPragma
+
+proc x() {.justDo.} = discard
+
+# breakPragma.nim
+import std/macros
+
+macro justDo*(procDef: typed): untyped =
+  error("I break")
+  return procDef

+

Expecting generated C to contain a given piece of code:

+

discard """
+  # Checks that the string "Assert error message" is in the generated
+  # C code.
+  ccodecheck: "'Assert error message'"
+"""
+assert 42 == 42, "Assert error message"

+

Non-Zero exit code:

+

discard """
+  exitcode: 1
+"""
+quit "Non-Zero exit code", 1

+

Standard output checking:

+

discard """
+  
+  output: '''
+0
+1
+2
+3
+4
+5
+'''
+
+"""
+for i in 0..5: echo i

+

JavaScript tests:

+

discard """
+  targets: "js"
+"""
+when defined(js):
+  import std/jsconsole
+  console.log("My Frontend Project")

+

Compile-time tests:

+

discard """
+  action: "compile"
+"""
+static: assert 9 == 9, "Compile time assert"

+

Tests without Spec:

+

assert 1 == 1

+

See also:

+ +

+ +
+
+ + +
+
+ + + + diff --git a/testament.idx b/testament.idx new file mode 100644 index 0000000000000..840168d334971 --- /dev/null +++ b/testament.idx @@ -0,0 +1,12 @@ +markupTitle Testament testament.html Testament 0 +heading Test files location testament.html#test-files-location Test files location 0 +heading Commands testament.html#commands Commands 0 +heading Options testament.html#options Options 0 +heading Running a single test testament.html#running-a-single-test Running a single test 0 +heading Running all tests from a directory testament.html#running-all-tests-from-a-directory Running all tests from a directory 0 +heading HTML Reports testament.html#html-reports HTML Reports 0 +heading Writing Unit tests testament.html#writing-unit-tests Writing Unit tests 0 +heading Inline hints, warnings and errors (notes) testament.html#writing-unit-tests-inline-hints-warnings-and-errors-notes Inline hints, warnings and errors (notes) 0 +heading Output message variable interpolation testament.html#writing-unit-tests-output-message-variable-interpolation Output message variable interpolation 0 +heading Cmd variable interpolation testament.html#writing-unit-tests-cmd-variable-interpolation Cmd variable interpolation 0 +heading Unit test Examples testament.html#unit-test-examples Unit test Examples 0 diff --git a/theindex.html b/theindex.html new file mode 100644 index 0000000000000..2cead12526e96 --- /dev/null +++ b/theindex.html @@ -0,0 +1,27497 @@ + + + + + + + +Index + + + + + + + + + + + + + + + + +
+
+

Index

+ Documents: API naming design, atlas.md, Contributing, DrNim User Guide, Embedded Stack Trace Profiler (ESTP) User Guide, Hot code reloading, Internals of the Nim Compiler, manual_experimental_strictnotnil.md, Nim Backend Integration, Nim Compiler User Guide, Nim Destructors and Move Semantics, Nim DocGen Tools Guide, Nim Documentation Overview, Nim Experimental Features, Nim IDE Integration Guide, Nim IDE Integration Guide, Nim maintenance script, Nim Manual, Nim Standard Library, Nim Tutorial (Part I), Nim Tutorial (Part II), Nim Tutorial (Part III), Nim's Memory Management, Nim-flavored Markdown and reStructuredText, nimgrep User's manual, niminst User's manual, NimScript, Packaging Nim, refc.md, Source Code Filters, Standard Library Style Guide, Testament, Tools available with Nim, var_t_return.md.

Modules: algorithm, appdirs, asciitables, assertions, async, asyncdispatch, asyncfile, asyncftpclient, asyncfutures, asynchttpserver, asyncjs, asyncmacro, asyncnet, asyncstreams, atomics, base64, bcrypt, bitops, bitops_utils, browsers, cgi, chains, cmdline, colors, compilesettings, complex, cookies, coro, cpuinfo, cpuload, critbits, cstrutils, ctypes, db_common, db_mysql, db_odbc, db_postgres, db_sqlite, decls, decode_helpers, deques, diff, digitsutils, dirs, distros, dochelpers, dollars, dom, dragonbox, dynlib, editdistance, effecttraits, encodings, endians, enumerate, enumutils, envvars, epoll, exceptions, exitprocs, fenv, files, formatfloat, genasts, gitutils, globs, hashes, heapqueue, highlite, hotcodereloading, htmlgen, htmlparser, httpclient, httpcore, importutils, inotify, intsets, isolation, iterators, jsbigints, jsconsole, jscore, jsfetch, jsffi, jsformdata, jsheaders, json, jsonutils, jsre, jsutils, kqueue, lenientops, lexbase, linenoise, lists, locks, logging, logic, macrocache, macros, marshal, math, md5, memfiles, mimetypes, miscdollars, monotimes, nativesockets, net, nimhcr, nimprof, nimrtl, nimscript, nre, ntpath, objectdollar, oids, options, os, osappdirs, oscommon, osdirs, oserrors, osfiles, ospaths2, osproc, osseps, ossymlinks, outparams, packedsets, parsecfg, parsecsv, parsejson, parseopt, parsesql, parseutils, parsexml, pathnorm, paths, pegs, posix_utils, prelude, punycode, random, rationals, rdstdin, re, registry, repr_v2, reservedmem, rlocks, ropes, rst, rstast, rstgen, rstidx, rtarrays, schubfach, segfaults, selectors, sequtils, sets, setutils, sexp, sha1, sha2, sha3, sharedlist, sharedtables, since, smtp, socketstreams, ssl_certs, ssl_config, stackframes, staticos, stats, strbasics, streams, streamwrapper, strformat, strimpl, strmisc, strscans, strtabs, strutils, sugar, symlinks, syncio, sysatomics, syslocks, sysrand, system, tables, tasks, tempfiles, terminal, threadpool, threadtypes, time_t, times, typedthreads, typeinfo, typetraits, underscored_calls, unicode, unidecode, unittest, uri, util, varints, vmutils, volatile, widestrs, win_getsysteminfo, win_setenv, winlean, with, wordwrap, wrapnils, xmlparser, xmltree.

API symbols

+
.nosinks:
+
[ESC]:
+
`!$`:
+
`!&`:
+
`!*\`:
+
`!*`:
+
`!=`:
+
`!`:
+
`$$`:
+
`$`:
+
`%%`:
+
`%*`:
+
`%=`:
+
`%`:
+
`&=`:
+
`&`:
+
`'big`:
+
`*%`:
+
`**`:
+
`*=`:
+
`*`:
+
`+%`:
+
`++`:
+
`+=`:
+
`+`:
+
`-%`:
+
`-+-`:
+
`--`:
+
`-=`:
+
`->`:
+
`-`:
+
`.()`:
+
`..<`:
+
`..^`:
+
`..`:
+
`.=`:
+
`.`:
+
`/%`:
+
`/../`:
+
`//`:
+
`/=`:
+
`/`:
+
`<%`:
+
`<->`:
+
`<=%`:
+
`<=`:
+
`<>`:
+
`<`:
+
`==`:
+
`=>`:
+
`=`:
+
`=copy`:
+
`=destroy`:
+
`=dispose`:
+
`=dup`:
+
`=sink`:
+
`=trace`:
+
`=wasMoved`:
+
`=~`:
+
`>%`:
+
`>=%`:
+
`>=`:
+
`>`:
+
`?.`:
+
`??.`:
+
`?`:
+
`@`:
+
`[]=`:
+
`[]`:
+
`^`:
+
`addr`:
+
`and`:
+
`div`:
+
`in`:
+
`is`:
+
`isnot`:
+
`mod`:
+
`not`:
+
`notin`:
+
`object`:
+
`of`:
+
`or`:
+
`ptr`:
+
`ref`:
+
`shl`:
+
`shr`:
+
`static`:
+
`template`:
+
`type`:
+
`var`:
+
`xor`:
+
`{}=`:
+
`{}`:
+
`|`:
+
`||`:
+
a:
+
abbr:
+
abbrev:
+
abort:
+
abortOnError:
+
abs:
+
abs2:
+
absolute:
+
absolutePath:
+
abstract syntax tree:
+
accept:
+
acceptAddr:
+
AcceptNoClient:
+
AcceptNoHandshake:
+
acceptRequest:
+
AcceptSuccess:
+
AccessViolationDefect:
+
acos:
+
acosh:
+
acquire:
+
acquireSys:
+
activeDescriptors:
+
add:
+
addAnchorNim:
+
addCallback:
+
addCompletion:
+
addEscaped:
+
addEscapedChar:
+
addEvent:
+
addEventListener:
+
AddEventListenerOptions:
+
addExitProc:
+
addf:
+
addFileExt:
+
addFilename:
+
addFiles:
+
addFirst:
+
addFloat:
+
addFloatRoundtrip:
+
addFloatSprintf:
+
addHandler:
+
addIdentIfAbsent:
+
addIfNotNil:
+
addInt:
+
addLast:
+
addMoved:
+
addNodes:
+
addNormalizePath:
+
addOutputFormatter:
+
addPragma:
+
addProcess:
+
addQuoted:
+
addRead:
+
address:
+
AddrInfo:
+
addSep:
+
addTimer:
+
addUnique:
+
addWrite:
+
advice:
+
affinity:
+
AF_INET:
+
AF_INET6:
+
after:
+
afterCodeReload:
+
AF_UNIX:
+
AF_UNSPEC:
+
AI_V4MAPPED:
+
akArray:
+
akBool:
+
akChar:
+
akCString:
+
akEnum:
+
akFloat:
+
akFloat128:
+
akFloat32:
+
akFloat64:
+
akInt:
+
akInt16:
+
akInt32:
+
akInt64:
+
akInt8:
+
akNone:
+
akObject:
+
akPointer:
+
akProc:
+
akPtr:
+
akRange:
+
akRef:
+
akSequence:
+
akSet:
+
akString:
+
akTuple:
+
akUInt:
+
akUInt16:
+
akUInt32:
+
akUInt64:
+
akUInt8:
+
alert:
+
aliasing:
+
align:
+
alignLeft:
+
alignof:
+
alignString:
+
alignTable:
+
alive:
+
all:
+
AllChars:
+
allCharsInSet:
+
allIt:
+
alloc:
+
alloc0:
+
alloc0Impl:
+
allocateAndInitializeSid:
+
allocCStringArray:
+
allocImpl:
+
allocShared:
+
allocShared0:
+
allocShared0Impl:
+
allocSharedImpl:
+
AllocStats:
+
allowEmptyAttribs:
+
allowUnquotedAttribs:
+
allValues:
+
almostEqual:
+
AltSep:
+
AnchorElement:
+
annotation:
+
annotation-xml:
+
ansiBackgroundColorCode:
+
ansiForegroundColorCode:
+
ansiResetCode:
+
ansiStyleCode:
+
any:
+
Any:
+
any character:
+
any rune:
+
anyIt:
+
AnyKind:
+
anyRune:
+
apostrophe:
+
append:
+
appendChild:
+
appendData:
+
appendMoved:
+
apply:
+
applyIt:
+
appType:
+
arccos:
+
arccosh:
+
arccot:
+
arccoth:
+
arccsc:
+
arccsch:
+
arcsec:
+
arcsech:
+
arcsin:
+
arcsinh:
+
arctan:
+
arctan2:
+
arctanh:
+
area:
+
argc:
+
argv:
+
ariaAttr:
+
arithmetic bit shifts:
+
ArithmeticDefect:
+
arity:
+
array:
+
array properties:
+
ArrayBuffer:
+
arrayWith:
+
arrayWithDefault:
+
arrow like:
+
article:
+
Ascending:
+
ashr:
+
aside:
+
asin:
+
asinh:
+
assert:
+
AssertionDefect:
+
assign:
+
assignedElements:
+
assignedNodes:
+
assume:
+
AST:
+
asterisk:
+
astGenRepr:
+
astToStr:
+
async:
+
asyncCheck:
+
AsyncEvent:
+
AsyncFD:
+
AsyncFile:
+
AsyncFtpClient:
+
AsyncHttpClient:
+
AsyncHttpServer:
+
AsyncResponse:
+
AsyncSmtp:
+
AsyncSocket:
+
atan:
+
atan2:
+
atanh:
+
atEnd:
+
atom:
+
Atomic:
+
ATOMIC_ACQ_REL:
+
ATOMIC_ACQUIRE:
+
atomicAddFetch:
+
atomicAlwaysLockFree:
+
atomicAndFetch:
+
atomicClear:
+
atomicCompareExchange:
+
atomicCompareExchangeN:
+
ATOMIC_CONSUME:
+
atomicDec:
+
atomicExchange:
+
atomicExchangeN:
+
atomicFetchAdd:
+
atomicFetchAnd:
+
atomicFetchNand:
+
atomicFetchOr:
+
atomicFetchSub:
+
atomicFetchXor:
+
AtomicFlag:
+
atomicInc:
+
atomicIsLockFree:
+
atomicLoad:
+
atomicLoadN:
+
atomicNandFetch:
+
AtomicNodes:
+
atomicOrFetch:
+
ATOMIC_RELAXED:
+
ATOMIC_RELEASE:
+
ATOMIC_SEQ_CST:
+
atomicSignalFence:
+
atomicStore:
+
atomicStoreN:
+
atomicSubFetch:
+
atomicTestAndSet:
+
atomicThreadFence:
+
atomicXorFetch:
+
AtomMemModel:
+
AtomType:
+
attachShadow:
+
AtTarget:
+
attr:
+
AttributeNode:
+
attrKey:
+
attrs:
+
attrs=:
+
attrsLen:
+
attrValue:
+
audio:
+
auth:
+
author:
+
auto:
+
Automatic type conversion:
+
autovivification:
+
AuxilaryButton:
+
await:
+
awaitAndThen:
+
b:
+
back:
+
backend:
+
BackgroundColor:
+
backref:
+
backrefIgnoreCase:
+
backrefIgnoreStyle:
+
backslash:
+
backspace:
+
BackwardsIndex:
+
base:
+
base type:
+
BaseLexer:
+
basename:
+
baseName:
+
basename=:
+
baseTypeKind:
+
baseTypeSize:
+
bcrypt:
+
bdi:
+
bdo:
+
before:
+
beforeCodeReload:
+
between:
+
bg8Bit:
+
bgBlack:
+
bgBlue:
+
bgColor:
+
bgCyan:
+
bgDefault:
+
bgGreen:
+
bgMagenta:
+
bgRed:
+
bgWhite:
+
bgYellow:
+
big:
+
bigEndian:
+
bigEndian16:
+
bigEndian32:
+
bigEndian64:
+
BiggestFloat:
+
BiggestInt:
+
BiggestUInt:
+
BigUint64Array:
+
bin:
+
BinaryPrefixMode:
+
binarySearch:
+
bind many:
+
bind once:
+
bindAddr:
+
binDir:
+
bindMethod:
+
bindNull:
+
bindParam:
+
bindParams:
+
bindSocket:
+
bindSym:
+
BindSymRule:
+
bindUnix:
+
binom:
+
bitand:
+
bitnot:
+
bitor:
+
bitslice:
+
bitsliced:
+
BitsRange:
+
BitsType:
+
bitxor:
+
Blob:
+
blob:
+
blockquote:
+
BlockTags:
+
blockUntil:
+
blockUntilAny:
+
blur:
+
body:
+
body=:
+
bool:
+
booldefine:
+
boolVal:
+
boot:
+
borrow:
+
BoundingRect:
+
bounds:
+
bpColloquial:
+
bpIEC:
+
br:
+
brClosed:
+
brForceOpen:
+
broadcast:
+
broadcastSysCond:
+
brOpen:
+
BubblingPhase:
+
BufferSize:
+
buildCPU:
+
buildOS:
+
button:
+
byaddr:
+
BY_HANDLE_FILE_INFORMATION:
+
byte:
+
BYTE:
+
ByteAddress:
+
C++:
+
CacheCounter:
+
CacheSeq:
+
CacheTable:
+
Callback:
+
callback=:
+
caller info:
+
calling conventions:
+
CallNodes:
+
callsite:
+
callSoon:
+
cancelAnimationFrame:
+
canShare:
+
canvas:
+
capacity:
+
capitalize:
+
capitalizeAscii:
+
caption:
+
capture:
+
captureBetween:
+
CaptureBounds:
+
captureBounds:
+
captureCount:
+
captureNameId:
+
Captures:
+
captures:
+
Captures:
+
CapturingPhase:
+
card:
+
carriage return:
+
cas:
+
case:
+
castToUnsigned:
+
catch:
+
CatchableError:
+
cbrt:
+
cchar:
+
cd:
+
CDATANode:
+
cdecl:
+
cdouble:
+
cdup:
+
ceil:
+
ceilDiv:
+
Cell:
+
center:
+
Certificate:
+
cfgEof:
+
cfgError:
+
CfgEvent:
+
CfgEventKind:
+
cfgKeyValuePair:
+
cfgOption:
+
CfgParser:
+
cfgSectionStart:
+
cfloat:
+
cfSymlinkAsIs:
+
cfSymlinkFollow:
+
cfSymlinkIgnore:
+
CgiError:
+
cgiError:
+
ch:
+
chaining:
+
changeFileExt:
+
char:
+
character with decimal value d:
+
character with hex value HH:
+
charChoice:
+
charData:
+
charSet:
+
check:
+
checked:
+
checked=:
+
checkedSymAddr:
+
checkpoint:
+
checkReply:
+
checkTokenMembership:
+
checkValidity:
+
child:
+
children:
+
chmod:
+
chomp:
+
chr:
+
cint:
+
CiphersIntermediate:
+
CiphersModern:
+
CiphersOld:
+
cite:
+
clamp:
+
class:
+
class=:
+
classify:
+
ClassList:
+
clean:
+
clear:
+
clearBit:
+
clearBits:
+
clearCallbacks:
+
clearData:
+
clearInterval:
+
clearMask:
+
clearMasked:
+
clearScreen:
+
clearTimeout:
+
click:
+
clientData:
+
clientData=:
+
clientGetPskFunc:
+
clientGetPskFunc=:
+
clientHeight:
+
clientWidth:
+
ClipboardEvent:
+
clone:
+
cloneNode:
+
clong:
+
clongdouble:
+
clonglong:
+
close:
+
closeHandle:
+
closeSocket:
+
closesocket:
+
closest:
+
closure:
+
closure iterator:
+
closureScope:
+
clz32:
+
cmdArgument:
+
cmdEnd:
+
CmdLineKind:
+
cmdLineRest:
+
cmdLongOption:
+
cmdShortOption:
+
cmp:
+
cmpic:
+
cmpIgnoreCase:
+
cmpIgnoreCaseImpl:
+
cmpIgnoreStyle:
+
cmpIgnoreStyleImpl:
+
cmpMem:
+
cmpNimIdentifier:
+
cmpPaths:
+
cmpRunesIgnoreCase:
+
code:
+
col:
+
colAliceBlue:
+
colAntiqueWhite:
+
colAqua:
+
colAquamarine:
+
colAzure:
+
colBeige:
+
colBisque:
+
colBlack:
+
colBlanchedAlmond:
+
colBlue:
+
colBlueViolet:
+
colBrown:
+
colBurlyWood:
+
colCadetBlue:
+
colChartreuse:
+
colChocolate:
+
colCoral:
+
colCornflowerBlue:
+
colCornsilk:
+
colCrimson:
+
colCyan:
+
colDarkBlue:
+
colDarkCyan:
+
colDarkGoldenRod:
+
colDarkGray:
+
colDarkGreen:
+
colDarkGrey:
+
colDarkKhaki:
+
colDarkMagenta:
+
colDarkOliveGreen:
+
colDarkorange:
+
colDarkOrchid:
+
colDarkRed:
+
colDarkSalmon:
+
colDarkSeaGreen:
+
colDarkSlateBlue:
+
colDarkSlateGray:
+
colDarkSlateGrey:
+
colDarkTurquoise:
+
colDarkViolet:
+
colDeepPink:
+
colDeepSkyBlue:
+
colDimGray:
+
colDimGrey:
+
colDodgerBlue:
+
colFireBrick:
+
colFloralWhite:
+
colForestGreen:
+
colFuchsia:
+
colGainsboro:
+
colGhostWhite:
+
colGold:
+
colGoldenRod:
+
colGray:
+
colGreen:
+
colGreenYellow:
+
colGrey:
+
colgroup:
+
colHoneyDew:
+
colHotPink:
+
colIndianRed:
+
colIndigo:
+
colIvory:
+
colKhaki:
+
collaborative tasking:
+
colLavender:
+
colLavenderBlush:
+
colLawnGreen:
+
collect:
+
colLemonChiffon:
+
colLightBlue:
+
colLightCoral:
+
colLightCyan:
+
colLightGoldenRodYellow:
+
colLightGray:
+
colLightGreen:
+
colLightGrey:
+
colLightPink:
+
colLightSalmon:
+
colLightSeaGreen:
+
colLightSkyBlue:
+
colLightSlateGray:
+
colLightSlateGrey:
+
colLightSteelBlue:
+
colLightYellow:
+
colLime:
+
colLimeGreen:
+
colLinen:
+
colMagenta:
+
colMaroon:
+
colMediumAquaMarine:
+
colMediumBlue:
+
colMediumOrchid:
+
colMediumPurple:
+
colMediumSeaGreen:
+
colMediumSlateBlue:
+
colMediumSpringGreen:
+
colMediumTurquoise:
+
colMediumVioletRed:
+
colMidnightBlue:
+
colMintCream:
+
colMistyRose:
+
colMoccasin:
+
colNavajoWhite:
+
colNavy:
+
colOldLace:
+
colOlive:
+
colOliveDrab:
+
Color:
+
colOrange:
+
colOrangeRed:
+
colOrchid:
+
colPaleGoldenRod:
+
colPaleGreen:
+
colPaleTurquoise:
+
colPaleVioletRed:
+
colPapayaWhip:
+
colPeachPuff:
+
colPeru:
+
colPink:
+
colPlum:
+
colPowderBlue:
+
colPurple:
+
colRebeccaPurple:
+
colRed:
+
colRosyBrown:
+
colRoyalBlue:
+
ColRstInit:
+
ColRstOffset:
+
colSaddleBrown:
+
colSalmon:
+
colSandyBrown:
+
colSeaGreen:
+
colSeaShell:
+
colSienna:
+
colSilver:
+
colSkyBlue:
+
colSlateBlue:
+
colSlateGray:
+
colSlateGrey:
+
colSnow:
+
colSpringGreen:
+
colSteelBlue:
+
colTan:
+
colTeal:
+
colThistle:
+
colTomato:
+
colTurquoise:
+
colViolet:
+
colWheat:
+
colWhite:
+
colWhiteSmoke:
+
colYellow:
+
colYellowGreen:
+
combine:
+
comma separated value:
+
command line:
+
command line argument:
+
command line arguments:
+
commandLineParams:
+
comment pieces:
+
CommentNode:
+
commitedLen:
+
commitHead:
+
commonAttr:
+
commonPrefixLen:
+
compareDocumentPosition:
+
compareExchange:
+
compareExchangeWeak:
+
compile:
+
compile-time:
+
CompileDate:
+
compileOption:
+
compiler:
+
compiles:
+
CompileTime:
+
complement:
+
complete:
+
completePass2:
+
CompletionCallback:
+
CompletionData:
+
Completions:
+
Complex:
+
complex:
+
complex statements:
+
Complex32:
+
complex32:
+
Complex64:
+
complex64:
+
computeDelta:
+
computePow10:
+
concat:
+
Cond:
+
Config:
+
confirm:
+
conjugate:
+
connect:
+
connectUnix:
+
Console:
+
console:
+
ConsoleLogger:
+
ConsoleOutputFormatter:
+
constant:
+
constant expression:
+
constructDouble:
+
constructor:
+
contains:
+
containsOrIncl:
+
contentLength:
+
contentType:
+
continuesWith:
+
control flow analysis:
+
convert:
+
converter:
+
convertSexp:
+
ConvertThreadToFiber:
+
ConvertThreadToFiberEx:
+
copy:
+
copyChildrenTo:
+
copyDir:
+
copyDirWithPermissions:
+
copyFile:
+
copyFileToDir:
+
copyFileW:
+
copyFileWithPermissions:
+
CopyFlag:
+
copyLineInfo:
+
copyMem:
+
copyNimNode:
+
copyNimTree:
+
copySign:
+
copyWithin:
+
coreAttr:
+
CoroutineRef:
+
correlation:
+
cos:
+
cosh:
+
CostFactor:
+
cot:
+
coth:
+
count:
+
countdown:
+
countIt:
+
countLeadingZeroBits:
+
countLines:
+
countProcessors:
+
countReset:
+
countSetBits:
+
CountTable:
+
CountTableRef:
+
countTrailingZeroBits:
+
countup:
+
cpDir:
+
cpFile:
+
cppDefine:
+
CPU:
+
cpuEndian:
+
cpuRelax:
+
CpuSet:
+
cpusetIncl:
+
cpusetZero:
+
cpuTime:
+
create:
+
CREATE_ALWAYS:
+
createAsyncNativeSocket:
+
createAttribute:
+
createComment:
+
createDir:
+
createDirectoryW:
+
createElement:
+
createElementNS:
+
createEvent:
+
CreateFiber:
+
CreateFiberEx:
+
createFileA:
+
createFileMappingW:
+
createFileW:
+
createHardlink:
+
createHardLinkW:
+
createIoCompletionPort:
+
createMessage:
+
createNamedPipe:
+
createNativeSocket:
+
CREATE_NEW:
+
CREATE_NO_WINDOW:
+
createPipe:
+
createProcessW:
+
createShared:
+
createSharedU:
+
createSymbolicLinkW:
+
createSymlink:
+
createTempDir:
+
createTempFile:
+
createTextNode:
+
createThread:
+
createU:
+
CREATE_UNICODE_ENVIRONMENT:
+
crit bit tree:
+
CritBitTree:
+
csc:
+
csch:
+
cschar:
+
cshort:
+
csize_t:
+
csource:
+
cstring:
+
cstringArray:
+
cstringArrayToSeq:
+
CSV:
+
CsvError:
+
CsvParser:
+
CsvRow:
+
cuchar:
+
cuint:
+
culong:
+
culonglong:
+
cumsum:
+
cumsummed:
+
CurDir:
+
current working directory:
+
currentSourcePath:
+
cursorBackward:
+
cursorDown:
+
cursorForward:
+
cursorUp:
+
cushort:
+
CustomRef:
+
cut:
+
CVerifyNone:
+
CVerifyPeer:
+
CVerifyPeerUseEnvVars:
+
cycle:
+
dangerous release build:
+
dangling else problem:
+
data:
+
data flow variable:
+
datalist:
+
DataTransfer:
+
DataTransferDropEffect:
+
DataTransferEffectAllowed:
+
DataTransferItem:
+
DataTransferItemKind:
+
Date:
+
DateLib:
+
DateTime:
+
dateTime:
+
DateTimeLocale:
+
Days:
+
days:
+
dbArray:
+
dbBindParamError:
+
dbBit:
+
dbBlob:
+
dbBool:
+
dbBox:
+
dbCircle:
+
DbColumn:
+
DbColumns:
+
dbComposite:
+
DbConn:
+
dbDate:
+
dbDatetime:
+
dbDecimal:
+
DbEffect:
+
dbEnum:
+
DbError:
+
dbError:
+
dbFixedChar:
+
dbFloat:
+
dbGeometry:
+
dbInet:
+
dbInt:
+
dbJson:
+
dbLine:
+
dbLseg:
+
dbMacAddress:
+
dbNull:
+
dbPath:
+
dbPoint:
+
dbPolygon:
+
dbQuote:
+
dbSerial:
+
dbSet:
+
dbTime:
+
dbTimeInterval:
+
dbTimestamp:
+
DbType:
+
DbTypeKind:
+
dbUInt:
+
dbUnknown:
+
dbUrl:
+
dbUser1:
+
dbUser2:
+
dbUser3:
+
dbUser4:
+
dbUser5:
+
dbUuid:
+
dbVarchar:
+
dbXml:
+
dd:
+
DeadThreadDefect:
+
dealloc:
+
deallocCStringArray:
+
deallocImpl:
+
deallocShared:
+
deallocSharedImpl:
+
debug:
+
debug build:
+
debugEcho:
+
debugger:
+
debugRecv:
+
debugSend:
+
dec:
+
decimalLength:
+
declared:
+
declaredInScope:
+
decode:
+
decodeData:
+
decodePercent:
+
decodeQuery:
+
decodeURI:
+
decodeURIComponent:
+
decodeUrl:
+
decodeZigzag:
+
dedent:
+
deduplicate:
+
deepCopy:
+
default:
+
defaultConfig:
+
defaultConsoleFormatter:
+
defaultFilename:
+
defaultFindFile:
+
defaultFindRefFile:
+
defaultFmtStr:
+
defaultInitialSize:
+
DefaultLocale:
+
defaultMsgHandler:
+
defaultOnProgressChanged:
+
Defect:
+
defined:
+
defUserAgent:
+
degToRad:
+
deinitCond:
+
deinitGeneralTokenizer:
+
deinitLock:
+
deinitRLock:
+
deinitSharedList:
+
deinitSharedTable:
+
deinitSys:
+
deinitSysCond:
+
del:
+
delEnv:
+
delete:
+
deleteContent:
+
deleteData:
+
DeleteFiber:
+
deleteFileA:
+
deleteFileW:
+
deleteFromDocument:
+
delOutputFormatter:
+
delSection:
+
delSectionKey:
+
Deque:
+
deque:
+
Descending:
+
description:
+
deserialization:
+
destroyContext:
+
destructor:
+
DETACHED_PROCESS:
+
details:
+
detectOs:
+
DeviceId:
+
dfn:
+
dFri:
+
dial:
+
dialog:
+
dictionary:
+
diff:
+
difference:
+
diffFiles:
+
diffInt:
+
diffStrings:
+
diffText:
+
digest:
+
digestLength:
+
digits:
+
Digits:
+
dir:
+
directory:
+
dirExists:
+
DirSep:
+
dirty:
+
dirxml:
+
disableCache:
+
disabled=:
+
disableExternalCapture:
+
disableParamFiltering:
+
disableProfiling:
+
disableTrueColors:
+
disarm:
+
discardable:
+
discriminator:
+
disjoint:
+
disjoint checker:
+
dispatchEvent:
+
dispose:
+
distance:
+
distinctBase:
+
distribute:
+
Distribution:
+
DivByZeroDefect:
+
divmod:
+
dl:
+
DLL:
+
dMon:
+
doAssert:
+
doAssertRaises:
+
doc:
+
doCreateThread:
+
Document:
+
document:
+
Documentation comments:
+
documentation generation tools:
+
DocumentFragmentNode:
+
DocumentNode:
+
DocumentOrShadowRoot:
+
DocumentTypeNode:
+
Domain:
+
domain-specific languages:
+
DOMAIN_ALIAS_RID_ADMINS:
+
DomApiVersion:
+
DomEvent:
+
DomException:
+
DomParser:
+
doNothing:
+
doShutdownThread:
+
doslikeFileSystem:
+
Double:
+
DoublyLinkedList:
+
DoublyLinkedNode:
+
DoublyLinkedNodeObj:
+
DoublyLinkedRing:
+
downloadFile:
+
Drag:
+
DragEnd:
+
DragEnter:
+
DragEvent:
+
DragEventTypes:
+
DragExit:
+
DragLeave:
+
dragonbox_Assert:
+
DragOver:
+
DragStart:
+
drain:
+
Drop:
+
dSat:
+
dSun:
+
dt:
+
dThu:
+
dtoaMinBufferLength:
+
dTue:
+
dump:
+
dumpAllocstats:
+
dumpAstGen:
+
dumpLisp:
+
dumpToString:
+
dumpTree:
+
dup:
+
duplicateHandle:
+
DUPLICATE_SAME_ACCESS:
+
Duration:
+
DurationParts:
+
DurationZero:
+
dWed:
+
DWORD:
+
dynamic type:
+
DynlibFormat:
+
E:
+
eat:
+
echo:
+
echoForeignDeps:
+
edit distance:
+
editDistance:
+
editDistanceAscii:
+
effect system:
+
ehlo:
+
EInvalidPeg:
+
Element:
+
elementFromPoint:
+
elementName:
+
ElementNode:
+
elements:
+
elementsFromPoint:
+
elementType:
+
em:
+
embed:
+
EmbedElement:
+
emOption:
+
emText:
+
emulatedThreadVars:
+
emUrl:
+
enableCache:
+
enableExternalCapture:
+
enableProfiling:
+
enableTrueColors:
+
encode:
+
encodeMime:
+
encodeQuery:
+
encodeURI:
+
encodeURIComponent:
+
encodeUrl:
+
encodeZigzag:
+
EncodingConverter:
+
EncodingError:
+
endAnchor:
+
endian:
+
Endianness:
+
EndOfFile:
+
endOfFile:
+
endsWith:
+
endsWithImpl:
+
ensureMove:
+
ensures:
+
entityName:
+
EntityNode:
+
EntityRefNode:
+
entityToRune:
+
entityToUtf8:
+
entries:
+
enumerate:
+
enumLen:
+
EnumMode:
+
environment variable:
+
environments variables:
+
envPairs:
+
EOFError:
+
EParseError:
+
epochTime:
+
epoll:
+
epoll_create:
+
epoll_create1:
+
epoll_ctl:
+
EPOLL_CTL_ADD:
+
EPOLL_CTL_DEL:
+
EPOLL_CTL_MOD:
+
EpollData:
+
EPOLLERR:
+
EPOLLET:
+
EpollEvent:
+
EPOLLEXCLUSIVE:
+
EPOLLHUP:
+
EPOLLIN:
+
EPOLLMSG:
+
EPOLLONESHOT:
+
EPOLLOUT:
+
EPOLLPRI:
+
EPOLLRDBAND:
+
EPOLLRDHUP:
+
EPOLLRDNORM:
+
epoll_wait:
+
EPOLLWAKEUP:
+
EPOLLWRBAND:
+
EPOLLWRNORM:
+
epsilon:
+
eqIdent:
+
equalMem:
+
equalsFile:
+
eraseLine:
+
eraseScreen:
+
erf:
+
erfc:
+
errAttributeValueExpected:
+
errBracketRiExpected:
+
errColonExpected:
+
errCommaExpected:
+
errCurlyRiExpected:
+
errEndOfCDataExpected:
+
errEndOfCommentExpected:
+
errEOC_Expected:
+
errEofExpected:
+
errEqExpected:
+
errExprExpected:
+
errGtExpected:
+
errInvalidToken:
+
errNameExpected:
+
errNone:
+
Error:
+
error:
+
ERROR_ACCESS_DENIED:
+
ERROR_BAD_ARGUMENTS:
+
ERROR_FILE_EXISTS:
+
ERROR_FILE_NOT_FOUND:
+
errorHandle:
+
ERROR_HANDLE_EOF:
+
ERROR_IO_PENDING:
+
ERROR_LOCK_VIOLATION:
+
errorMessages:
+
errorMessageWriter:
+
errorMsg:
+
errorMsgExpected:
+
ERROR_NETNAME_DELETED:
+
ERROR_NO_MORE_FILES:
+
ERROR_PATH_NOT_FOUND:
+
errorStr:
+
errorStream:
+
errParensRiExpected:
+
errQmGtExpected:
+
errQuoteExpected:
+
errSemicolonExpected:
+
errStringExpected:
+
esc:
+
escape:
+
escape sequences:
+
escapeJson:
+
escapeJsonUnquoted:
+
EscapeMode:
+
escapePeg:
+
escapeRe:
+
escChar:
+
euclDiv:
+
euclMod:
+
EV_ADD:
+
EV_CLEAR:
+
EV_DELETE:
+
EV_DISABLE:
+
EV_DISPATCH:
+
EV_DROP:
+
EV_ENABLE:
+
Event:
+
eventAttr:
+
eventParser:
+
EventPhase:
+
EventTarget:
+
EV_EOF:
+
EV_ERROR:
+
EV_FLAG1:
+
EvLines:
+
EV_NODATA:
+
EV_ONESHOT:
+
EV_RECEIPT:
+
EvRetr:
+
EV_SET:
+
EvStore:
+
EV_SYSFLAGS:
+
EvTransferProgress:
+
exception:
+
Exception:
+
exception handlers:
+
exchange:
+
excl:
+
exclFilePermissions:
+
exec:
+
execAffectedRows:
+
execCmd:
+
execCmdEx:
+
ExecIOEffect:
+
execProcess:
+
execProcesses:
+
execShellCmd:
+
executable:
+
ExeExt:
+
ExeExts:
+
exists:
+
existsCookie:
+
existsDir:
+
existsEnv:
+
existsFile:
+
existsOrCreateDir:
+
exitStatusLikeShell:
+
exp:
+
expandFilename:
+
expandMacros:
+
expandSymlink:
+
expandTabs:
+
expandTilde:
+
expect:
+
expectIdent:
+
expectKind:
+
expectLen:
+
expectMinLen:
+
expm1:
+
exponentBias:
+
exponentMask:
+
extendSeq:
+
extract:
+
extractDocCommentsAndRunnables:
+
extractFilename:
+
extractRGB:
+
ExtSep:
+
fac:
+
fail:
+
failed:
+
FAILED:
+
failedAssertImpl:
+
failureOccurred:
+
fakeDot:
+
fastcall:
+
fastLog2:
+
fastRows:
+
fastRuneAt:
+
fastToUTF8Copy:
+
fatal:
+
fchDefault:
+
fchForceCache:
+
fchNoCache:
+
fchNoStore:
+
fchReload:
+
fcInclude:
+
fcInf:
+
fcNan:
+
fcNegInf:
+
fcNegZero:
+
fcNormal:
+
fcOmit:
+
fcSameOrigin:
+
fcSubnormal:
+
fcZero:
+
FD_ACCEPT:
+
FD_ADDRESS_LIST_CHANGE:
+
FD_ALL_EVENTS:
+
FD_CLOSE:
+
FD_CONNECT:
+
FD_GROUP_QQS:
+
FD_ISSET:
+
FD_OOB:
+
FD_QQS:
+
FD_READ:
+
FD_ROUTING_INTERFACE_CHANGE:
+
FD_SET:
+
FD_SETSIZE:
+
FD_WRITE:
+
FD_ZERO:
+
FE_ALL_EXCEPT:
+
feclearexcept:
+
FE_DFL_ENV:
+
FE_DIVBYZERO:
+
FE_DOWNWARD:
+
fegetenv:
+
fegetexceptflag:
+
fegetround:
+
feholdexcept:
+
FE_INEXACT:
+
FE_INVALID:
+
fence:
+
FE_OVERFLOW:
+
feraiseexcept:
+
fesetenv:
+
fesetexceptflag:
+
fesetround:
+
fetch:
+
fetchAdd:
+
fetchAnd:
+
FetchCaches:
+
FetchCredentials:
+
FetchModes:
+
FetchOptions:
+
fetchOr:
+
FetchRedirects:
+
FetchReferrerPolicies:
+
fetchSub:
+
fetchXor:
+
fetestexcept:
+
FE_TONEAREST:
+
FE_TOWARDZERO:
+
FE_UNDERFLOW:
+
feupdateenv:
+
FE_UPWARD:
+
ffDecimal:
+
ffDefault:
+
FFI:
+
ffScientific:
+
fg8Bit:
+
fgBlack:
+
fgBlue:
+
fgColor:
+
fgCyan:
+
fgDefault:
+
fgGreen:
+
fgMagenta:
+
fgRed:
+
fgWhite:
+
fgYellow:
+
FIBER_FLAG_FLOAT_SWITCH:
+
FieldDefect:
+
fieldPairs:
+
fields:
+
fieldset:
+
FifthButton:
+
figcaption:
+
figure:
+
File:
+
FILE_ATTRIBUTE_ARCHIVE:
+
FILE_ATTRIBUTE_COMPRESSED:
+
FILE_ATTRIBUTE_DEVICE:
+
FILE_ATTRIBUTE_DIRECTORY:
+
FILE_ATTRIBUTE_HIDDEN:
+
FILE_ATTRIBUTE_NORMAL:
+
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED:
+
FILE_ATTRIBUTE_OFFLINE:
+
FILE_ATTRIBUTE_READONLY:
+
FILE_ATTRIBUTE_REPARSE_POINT:
+
FILE_ATTRIBUTE_SPARSE_FILE:
+
FILE_ATTRIBUTE_SYSTEM:
+
FILE_ATTRIBUTE_TEMPORARY:
+
FILE_BEGIN:
+
fileExists:
+
FILE_FLAG_BACKUP_SEMANTICS:
+
FILE_FLAG_DELETE_ON_CLOSE:
+
FILE_FLAG_FIRST_PIPE_INSTANCE:
+
FILE_FLAG_NO_BUFFERING:
+
FILE_FLAG_OPEN_NO_RECALL:
+
FILE_FLAG_OPEN_REPARSE_POINT:
+
FILE_FLAG_OVERLAPPED:
+
FILE_FLAG_POSIX_SEMANTICS:
+
FILE_FLAG_RANDOM_ACCESS:
+
FILE_FLAG_SEQUENTIAL_SCAN:
+
FILE_FLAG_WRITE_THROUGH:
+
FileHandle:
+
FileId:
+
FileIndex:
+
FileInfo:
+
FileLogger:
+
FILE_MAP_READ:
+
FILE_MAP_WRITE:
+
FileMode:
+
fileNewer:
+
FilePermission:
+
FILE_READ_DATA:
+
FileReader:
+
fileReaderDone:
+
fileReaderEmpty:
+
fileReaderLoading:
+
FileReaderState:
+
FileSeekPos:
+
FILE_SHARE_DELETE:
+
FILE_SHARE_READ:
+
FILE_SHARE_WRITE:
+
FileStream:
+
FileStreamObj:
+
FileSystemCaseSensitive:
+
FILETIME:
+
FILE_WRITE_DATA:
+
fill:
+
filter:
+
filterIt:
+
finalize:
+
finally:
+
find:
+
findAll:
+
findBounds:
+
findChild:
+
findClose:
+
findExe:
+
FindFileHandler:
+
findFirstFileW:
+
findIter:
+
findNextFileW:
+
FindRefFileHandler:
+
finished:
+
FIONBIO:
+
firstSetBit:
+
FixedTimeUnit:
+
flags:
+
flatMap:
+
flatten:
+
flipBit:
+
flipBits:
+
flipMask:
+
flipMasked:
+
float:
+
float32:
+
float32ToChars:
+
float64:
+
Float64Array:
+
floatChecks:
+
FloatClass:
+
FloatDivByZeroDefect:
+
FloatFormatMode:
+
FloatInexactDefect:
+
FloatingDecimal64:
+
FloatingPointDefect:
+
FloatInvalidOpDefect:
+
FloatOverflowDefect:
+
FloatUnderflowDefect:
+
floatVal:
+
floatVal=:
+
floor:
+
floorDiv:
+
floorDivPow2:
+
floorLog10Pow2:
+
floorLog10ThreeQuartersPow2:
+
floorLog2Pow10:
+
floorMod:
+
FlowVar:
+
FlowVarBase:
+
flush:
+
flushFile:
+
flushFileBuffers:
+
flushViewOfFile:
+
fmAppend:
+
fmCors:
+
fmNoCors:
+
fmRead:
+
fmReadWrite:
+
fmReadWriteExisting:
+
fmSameOrigin:
+
fmt:
+
fmWrite:
+
focus:
+
foldl:
+
foldr:
+
FontFaceSet:
+
FontFaceSetReady:
+
footer:
+
for:
+
for-loop macro:
+
forall:
+
ForegroundColor:
+
ForeignCell:
+
foreignCmd:
+
foreignDep:
+
foreignDepInstallCmd:
+
foreignDeps:
+
ForLoopStmt:
+
form:
+
form feed:
+
format:
+
formatBiggestFloat:
+
formatDigits:
+
formatEng:
+
formatErrorIndexBound:
+
formatFieldDefect:
+
FormatFlag:
+
formatFloat:
+
formatIndexEntry:
+
formatMessageW:
+
formatNamedVars:
+
formatSize:
+
formatStr:
+
formatValue:
+
formData:
+
FormData:
+
FormElement:
+
forward:
+
forwardImpl:
+
FourthButton:
+
fpGroupExec:
+
fpGroupRead:
+
fpGroupWrite:
+
fpOthersExec:
+
fpOthersRead:
+
fpOthersWrite:
+
fpRadix:
+
fpUserExec:
+
fpUserRead:
+
fpUserWrite:
+
Frame:
+
free:
+
freeAddrInfo:
+
freeEnvironmentStringsW:
+
freeShared:
+
freeSid:
+
frError:
+
frexp:
+
frFollow:
+
frManual:
+
fromBin:
+
fromHex:
+
fromJson:
+
fromJsonHook:
+
fromOct:
+
fromSockAddr:
+
fromUnix:
+
fromUnixFloat:
+
fromWinTime:
+
fround:
+
frpNoReferrer:
+
frpNoReferrerWhenDowngrade:
+
frpOrigin:
+
frpOriginWhenCrossOrigin:
+
frpUnsafeUrl:
+
fspCur:
+
fspEnd:
+
fspSet:
+
fsync:
+
FtpEvent:
+
FtpEventType:
+
FtpJobType:
+
fullSet:
+
functional:
+
functions:
+
Future:
+
FutureBase:
+
FutureError:
+
FutureStream:
+
FutureVar:
+
gamma:
+
gauss:
+
GC safe:
+
gcd:
+
GC_disableMarkAndSweep:
+
GC_disableOrc:
+
GC_enableMarkAndSweep:
+
GC_enableOrc:
+
GC_fullCollect:
+
GC_getStatistics:
+
gcOptimizeSpace:
+
gcOptimizeTime:
+
GC_partialCollect:
+
GC_prepareOrc:
+
GC_ref:
+
gcResponsiveness:
+
GC_runOrc:
+
gcsafe:
+
GC_Strategy:
+
GcThread:
+
gcThroughput:
+
GC_unref:
+
genAst:
+
GenAstOpt:
+
genAstOpt:
+
genEnumCaseStmt:
+
GeneralTokenizer:
+
generatedTime:
+
generateSalt:
+
generic character types:
+
generic type parameter:
+
GENERIC_ALL:
+
genericHead:
+
genericParams:
+
GENERIC_READ:
+
GENERIC_WRITE:
+
genOid:
+
genSym:
+
gensym:
+
genTempPath:
+
get:
+
getAddrInfo:
+
getaddrinfo:
+
getAddrString:
+
getAlign:
+
getAll:
+
getAllocStats:
+
getAllRows:
+
getAppDir:
+
getAppFilename:
+
getArgument:
+
getAsFile:
+
getAst:
+
getAttribute:
+
getAttributeNode:
+
getBiggestFloat:
+
getBiggestInt:
+
getBiggestUint:
+
getBool:
+
getBoundingClientRect:
+
getCacheDir:
+
getCallSoonProc:
+
getch:
+
getChar:
+
getClockStr:
+
getColNumber:
+
getColumn:
+
getCommand:
+
getCommandLineW:
+
getComputedStyle:
+
getConfigDir:
+
getCons:
+
getContent:
+
getContentLength:
+
getContentType:
+
getCookie:
+
getCreationTime:
+
getCString:
+
getCurrentCompilerExe:
+
getCurrentDir:
+
getCurrentDirectoryW:
+
getCurrentEncoding:
+
getCurrentException:
+
getCurrentExceptionMsg:
+
GetCurrentFiber:
+
getCurrentLine:
+
getCurrentProcess:
+
getCurrentProcessId:
+
getCursorPos:
+
getCustomPragmaVal:
+
getData:
+
getDataDir:
+
getDataUri:
+
getDateStr:
+
getDay:
+
getDayOfWeek:
+
getDayOfYear:
+
getDaysInMonth:
+
getDaysInYear:
+
getDocumentRoot:
+
getElementById:
+
getElementsByClass:
+
getElementsByClassName:
+
getElementsByName:
+
getElementsByTagName:
+
getElems:
+
getEnumField:
+
getEnumOrdinal:
+
getEnv:
+
getEnvironmentStringsW:
+
getExitCodeProcess:
+
getExt:
+
getExtraData:
+
getFd:
+
getFields:
+
getFieldValue:
+
getFileAttributesW:
+
getFileHandle:
+
getFileInfo:
+
getFileInformationByHandle:
+
getFilename:
+
getFilePermissions:
+
getFilePos:
+
getFileSize:
+
getFloat:
+
getFloat32:
+
getFloat64:
+
getFNum:
+
getForbidsList:
+
getFrame:
+
getFrameState:
+
getFreeMem:
+
getFreeSharedMem:
+
getFullPathNameW:
+
getFullYear:
+
getGatewayInterface:
+
getGlobalDispatcher:
+
getHandleInformation:
+
getHandlers:
+
getHomeDir:
+
getHostByAddr:
+
gethostbyaddr:
+
getHostByName:
+
gethostbyname:
+
getHostname:
+
gethostname:
+
getHours:
+
getHttpAccept:
+
getHttpAcceptCharset:
+
getHttpAcceptEncoding:
+
getHttpAcceptLanguage:
+
getHttpConnection:
+
getHttpCookie:
+
getHttpHost:
+
getHttpReferer:
+
getHttpUserAgent:
+
getImpl:
+
getImplTransformed:
+
getInt:
+
getInt16:
+
getInt32:
+
getInt64:
+
getInt8:
+
getIoHandler:
+
getIsoWeekAndYear:
+
getItem:
+
getLastAccessTime:
+
getLastError:
+
getLastModificationTime:
+
getLine:
+
getLocalAddr:
+
getLogFilter:
+
getMaxMem:
+
getMD5:
+
getMilliseconds:
+
getMimetype:
+
getMinutes:
+
getModifierState:
+
getModuleFileNameW:
+
getMonoTime:
+
getMonth:
+
getnameinfo:
+
getNextToken:
+
getNum:
+
getOccupiedMem:
+
getOccupiedSharedMem:
+
getOffset:
+
getopt:
+
getOrDefault:
+
get_osfhandle:
+
getOsFileHandle:
+
getOverlappedResult:
+
getPathInfo:
+
getPathTranslated:
+
getPeerAddr:
+
getPeerCertificates:
+
getpeername:
+
getPFrame:
+
getPointer:
+
getPort:
+
getPosition:
+
getPrimaryIPAddr:
+
getProcessTimes:
+
getProgramResult:
+
getProjectPath:
+
getPropertyPriority:
+
getPropertyValue:
+
getProtoByName:
+
getprotobyname:
+
getprotobynumber:
+
getProtoName:
+
getPskIdentity:
+
getQueryString:
+
getQueuedCompletionStatus:
+
getRaisesList:
+
getRangeAt:
+
getRawData:
+
getRemoteAddr:
+
getRemoteHost:
+
getRemoteIdent:
+
getRemotePort:
+
getRemoteUser:
+
getRequestMethod:
+
getRequestURI:
+
getRootNode:
+
getRow:
+
getScriptFilename:
+
getScriptName:
+
getSeconds:
+
getSectionValue:
+
getSelection:
+
getServByName:
+
getservbyname:
+
getServByPort:
+
getservbyport:
+
getServerAddr:
+
getServerAdmin:
+
getServerName:
+
getServerPort:
+
getServerProtocol:
+
getServerSignature:
+
getServerSoftware:
+
getSize:
+
getSockDomain:
+
getSocket:
+
getSocketError:
+
getsockname:
+
getSockName:
+
getsockname:
+
getSockOpt:
+
getsockopt:
+
getSockOptInt:
+
getSourceLanguage:
+
getStackTrace:
+
getStackTraceEntries:
+
getStdHandle:
+
getStr:
+
getString:
+
getSymbol:
+
getSymlinkFileKind:
+
getSystemInfo:
+
getSystemTimeAsFileTime:
+
getSystemTimePreciseAsFileTime:
+
getSystemTimes:
+
getTagsList:
+
getTempDir:
+
getThreadId:
+
getTime:
+
getTimezoneOffset:
+
getTok:
+
getTotalMem:
+
getTotalSharedMem:
+
getType:
+
getTypeImpl:
+
getTypeInfo:
+
getTypeInst:
+
getUInt:
+
getUInt16:
+
getUInt32:
+
getUInt64:
+
getUInt8:
+
getUnicodeValue:
+
getUTCDate:
+
getUTCDay:
+
getUTCFullYear:
+
getUTCHours:
+
getUTCMilliseconds:
+
getUTCMinutes:
+
getUTCMonth:
+
getUTCSeconds:
+
getValue:
+
getVersion:
+
getVersionExA:
+
getVersionExW:
+
getWeeksInIsoYear:
+
getYear:
+
glob:
+
globalRaiseHook:
+
go:
+
gorge:
+
gorgeEx:
+
gotHandshake:
+
graphemeLen:
+
group:
+
groupCollapsed:
+
groupEnd:
+
grow:
+
gtAssembler:
+
gtBinNumber:
+
gtCharLit:
+
gtCommand:
+
gtComment:
+
gtDecNumber:
+
gtDirective:
+
gtEof:
+
gtEscapeSequence:
+
gtFloatNumber:
+
gtHexNumber:
+
gtHyperlink:
+
gtIdentifier:
+
gtKey:
+
gtKeyword:
+
gtLabel:
+
gtLongComment:
+
gtLongStringLit:
+
gtNone:
+
gtOctNumber:
+
gtOperator:
+
gtOption:
+
gtOther:
+
gtPreprocessor:
+
gtProgram:
+
gtProgramOutput:
+
gtPrompt:
+
gtPunctuation:
+
gtRawData:
+
gtReference:
+
gtRegularExpression:
+
gtRule:
+
gtStringLit:
+
gtTagEnd:
+
gtTagStart:
+
gtValue:
+
gtWhitespace:
+
guard:
+
GUID:
+
h1:
+
h2:
+
h3:
+
h4:
+
h5:
+
h6:
+
Hamming weight:
+
handle:
+
Handle:
+
handleCR:
+
handleEvent:
+
HANDLE_FLAG_INHERIT:
+
handleHexChar:
+
handleLF:
+
handleRefillChar:
+
handshakeAsClient:
+
handshakeAsServer:
+
hard realtime:
+
hasAllocStack:
+
hasAnyModuleChanged:
+
hasAnyModuleChanged():
+
hasArgOfName:
+
hasAttribute:
+
hasAttributeNS:
+
hasBigUint64Array:
+
hasChildNodes:
+
hasClosure:
+
hasCustomPragma:
+
hasData:
+
hasDataBuffered:
+
hasDefaultValue:
+
Hash:
+
hash:
+
Hash:
+
hash:
+
hash set:
+
hash table:
+
hashData:
+
hashIdentity:
+
hashIgnoreCase:
+
hashIgnoreStyle:
+
HashSet:
+
hashWangYi1:
+
hasJsBigInt:
+
hasKey:
+
hasKeyOrPut:
+
hasModuleChanged:
+
hasModuleChanged():
+
hasNext:
+
hasNoSideEffects:
+
hasNxt:
+
hasOverlappedIoCompleted:
+
hasOwnProperty:
+
hasPendingOperations:
+
hasPointerCapture:
+
hasSharedHeap:
+
hasWorkingInt64:
+
hcrAddEventHandler:
+
hcrAddModule:
+
hcrGeneration:
+
hcrGetGlobal:
+
hcrGetProc:
+
hcrHasModuleChanged:
+
hcrInit:
+
hcrMarkGlobals:
+
HcrModuleInitializer:
+
hcrPerformCodeReload:
+
HcrProcGetter:
+
hcrRegisterGlobal:
+
hcrRegisterProc:
+
hcrReloadNeeded:
+
HDC:
+
head:
+
header:
+
headerLimit:
+
Headers:
+
HeapQueue:
+
helo:
+
hexbyte:
+
HexDigits:
+
HGLRC:
+
hi32:
+
hiddenBit:
+
hideCursor:
+
high:
+
HIGH_PRIORITY_CLASS:
+
hint:
+
History:
+
historyAdd:
+
historyLoad:
+
historySave:
+
historySetMaxLen:
+
HKEY:
+
HKEY_CURRENT_USER:
+
HKEY_LOCAL_MACHINE:
+
HoleyEnum:
+
home:
+
hostCPU:
+
Hostent:
+
hostOS:
+
hotCodeReloading:
+
hotcodereloading:
+
hour:
+
hour=:
+
HourRange:
+
Hours:
+
hours:
+
hr:
+
HSlice:
+
html:
+
HTML:
+
HTMLSlotElement:
+
HtmlTag:
+
htmlTag:
+
htonl:
+
htons:
+
Http100:
+
Http101:
+
Http102:
+
Http103:
+
Http200:
+
Http201:
+
Http202:
+
Http203:
+
Http204:
+
Http205:
+
Http206:
+
Http207:
+
Http208:
+
Http226:
+
Http300:
+
Http301:
+
Http302:
+
Http303:
+
Http304:
+
Http305:
+
Http307:
+
Http308:
+
Http400:
+
Http401:
+
Http402:
+
Http403:
+
Http404:
+
Http405:
+
Http406:
+
Http407:
+
Http408:
+
Http409:
+
Http410:
+
Http411:
+
Http412:
+
Http413:
+
Http414:
+
Http415:
+
Http416:
+
Http417:
+
Http418:
+
Http421:
+
Http422:
+
Http423:
+
Http424:
+
Http425:
+
Http426:
+
Http428:
+
Http429:
+
Http431:
+
Http451:
+
Http500:
+
Http501:
+
Http502:
+
Http503:
+
Http504:
+
Http505:
+
Http506:
+
Http507:
+
Http508:
+
Http510:
+
Http511:
+
HttpClient:
+
HttpClientBase:
+
HttpCode:
+
HttpConnect:
+
HttpDelete:
+
HttpGet:
+
HttpHead:
+
HttpHeaders:
+
HttpHeaderValues:
+
HttpMethod:
+
httpNewLine:
+
HttpOptions:
+
HttpPatch:
+
HttpPost:
+
HttpPut:
+
HttpRequestError:
+
HttpTrace:
+
HttpVer10:
+
HttpVer11:
+
HttpVersion:
+
hygienic:
+
hypot:
+
i:
+
iconv:
+
id:
+
id=:
+
ident:
+
ident=:
+
identChars:
+
IdentChars:
+
identifiedTouch:
+
identifier:
+
identStartChars:
+
IdentStartChars:
+
IDLE_PRIORITY_CLASS:
+
idx:
+
ieHeading:
+
ieIdxRole:
+
ieMarkupTitle:
+
ieNim:
+
ieNimGroup:
+
ieNimTitle:
+
iframe:
+
ignoreMsg:
+
ikDollar:
+
ikExpr:
+
ikStr:
+
ikVar:
+
im:
+
ImageElement:
+
img:
+
immediate:
+
implicit block:
+
implicitly generic:
+
import:
+
imul:
+
in-place:
+
In6_addr:
+
IN_ACCESS:
+
InAddr:
+
INADDR_ANY:
+
INADDR_BROADCAST:
+
INADDR_LOOPBACK:
+
INADDR_NONE:
+
IN_ALL_EVENTS:
+
IN_ATTRIB:
+
inc:
+
incl:
+
inclFilePermissions:
+
IN_CLOSE:
+
IN_CLOSE_NOWRITE:
+
IN_CLOSE_WRITE:
+
inclSetElement:
+
incomplete:
+
IN_CREATE:
+
inDays:
+
IN_DELETE:
+
IN_DELETE_SELF:
+
indent:
+
indentation:
+
indentation sensitive:
+
index:
+
indexBy:
+
IndexDefect:
+
IndexedDocs:
+
IndexEntry:
+
IndexEntryKind:
+
IndexExt:
+
IN_DONT_FOLLOW:
+
inet_addr:
+
inet_ntoa:
+
inet_ntop:
+
IN_EXCL_UNLINK:
+
Inf:
+
infChecks:
+
INFINITE:
+
infix:
+
info:
+
information hiding:
+
inHours:
+
IN_IGNORED:
+
IN_ISDIR:
+
init:
+
initCond:
+
initCountTable:
+
initDateTime:
+
initDecodeTable:
+
initDeque:
+
initDoublyLinkedList:
+
initDoublyLinkedRing:
+
initDuration:
+
initGeneralTokenizer:
+
initHashSet:
+
initHeapQueue:
+
initIntSet:
+
initLock:
+
initOptParser:
+
initOrderedSet:
+
initOrderedTable:
+
initPackedSet:
+
initRand:
+
initRational:
+
initRLock:
+
initRstGenerator:
+
initRtArray:
+
initSet:
+
initSha:
+
initSha_224:
+
initSha_256:
+
initSha3:
+
initSha3_224:
+
initSha3_256:
+
initSha3_384:
+
initSha3_512:
+
initSha_384:
+
initSha3StateStatic:
+
initSha_512:
+
initShake:
+
initShaStateStatic:
+
initSinglyLinkedList:
+
initSinglyLinkedRing:
+
initSkipTable:
+
initSysCond:
+
initSysLock:
+
initSysLockAttr:
+
initTable:
+
initTime:
+
initTimeFormat:
+
initTimeInterval:
+
initToJsonOptions:
+
initUri:
+
inject:
+
inline:
+
inline iterator:
+
InlineTags:
+
IN_MASK_ADD:
+
inMicroseconds:
+
inMilliseconds:
+
inMinutes:
+
IN_MODIFY:
+
IN_MOVE:
+
IN_MOVED_FROM:
+
IN_MOVED_TO:
+
IN_MOVE_SELF:
+
inNanoseconds:
+
innerText:
+
IN_ONESHOT:
+
IN_ONLYDIR:
+
IN_OPEN:
+
inotify_add_watch:
+
InotifyEvent:
+
inotify_events:
+
inotify_init:
+
inotify_init1:
+
inotify_rm_watch:
+
input:
+
InputElement:
+
inputHandle:
+
inputStream:
+
IN_Q_OVERFLOW:
+
ins:
+
inSeconds:
+
insert:
+
insertAdjacentElement:
+
insertAdjacentHTML:
+
insertAdjacentText:
+
insertBefore:
+
insertData:
+
insertId:
+
insertID:
+
insertNode:
+
insertSep:
+
installDirs:
+
installExt:
+
installFiles:
+
instantiationInfo:
+
InstantRow:
+
instantRows:
+
int:
+
int16:
+
int32:
+
int64:
+
int8:
+
intdefine:
+
intensity:
+
intercept:
+
internalErrorFlag:
+
interpolatedFragments:
+
InterpolatedKind:
+
interpolation:
+
intersection:
+
Interval:
+
INT_MAX:
+
INT_MIN:
+
IntSet:
+
intToStr:
+
intVal:
+
intVal=:
+
IN_UNMOUNT:
+
inv:
+
invalidFilenameChars:
+
invalidFilenames:
+
INVALID_FILE_SIZE:
+
INVALID_HANDLE_VALUE:
+
INVALID_SET_FILE_POINTER:
+
INVALID_SOCKET:
+
InvalidUnicodeError:
+
invariant:
+
inViewport:
+
invoke:
+
invokeNew:
+
invokeNewSeq:
+
inWeeks:
+
inZone:
+
IOC_IN:
+
IOC_INOUT:
+
IOC_OUT:
+
IOCPARM_MASK:
+
ioctlsocket:
+
IOC_WS2:
+
IOEffect:
+
IOError:
+
IOSelectorsException:
+
ioselSupportedPlatform:
+
IpAddress:
+
IpAddressFamily:
+
IPPROTO_ICMP:
+
IPPROTO_ICMPV6:
+
IPPROTO_IP:
+
IPPROTO_IPV6:
+
IPPROTO_NONE:
+
IPPROTO_RAW:
+
IPPROTO_TCP:
+
IPPROTO_UDP:
+
IPv4_any:
+
IPv4_broadcast:
+
IPv4_loopback:
+
IPv6_any:
+
IPv6_loopback:
+
is1xx:
+
is2xx:
+
is3xx:
+
is4xx:
+
is5xx:
+
isAbsolute:
+
isAdmin:
+
isAlpha:
+
isAlphaAscii:
+
isAlphaNumeric:
+
isatty:
+
isClosed:
+
isColor:
+
isCombining:
+
isDefaultNamespace:
+
isDigit:
+
isDisconnectionError:
+
isDocumentationTitle:
+
isDst:
+
isDst=:
+
isEmpty:
+
isEmptyOrWhitespace:
+
isEqualNode:
+
isExported:
+
isFinite:
+
isFutureLoggingEnabled:
+
isGcSafe:
+
isGitRepo:
+
isHidden:
+
isInf:
+
isInitialized:
+
isInstantiationOf:
+
isInteger:
+
isIntegralEndpoint:
+
isIntegralMidpoint:
+
isIpAddress:
+
isLeapDay:
+
isLeapYear:
+
isLower:
+
isLowerAscii:
+
isMainModule:
+
isNamedTuple:
+
isNaN:
+
isNil:
+
isNone:
+
isNotForeign:
+
isNull:
+
isolate:
+
Isolated:
+
IsoWeekRange:
+
IsoYear:
+
isPowerOfTwo:
+
isReady:
+
isRefSkipDistinct:
+
isRelativeTo:
+
isRootDir:
+
isSafeInteger:
+
isSameNode:
+
isSome:
+
isSorted:
+
isSpace:
+
isSpaceAscii:
+
isSsl:
+
isSuccess:
+
isTitle:
+
isTrueColorSupported:
+
isUndefined:
+
isUniqueRef:
+
isUpper:
+
isUpperAscii:
+
isValid:
+
isValidFilename:
+
isValidSha1Hash:
+
isWhiteSpace:
+
isZero:
+
Item:
+
item:
+
items:
+
itemsWithPrefix:
+
iterable:
+
iterAndMutate:
+
iterator:
+
iterToProc:
+
JArray:
+
javaEnabled:
+
JavaScript:
+
JBool:
+
JFloat:
+
JInt:
+
JNull:
+
JObject:
+
join:
+
joinPath:
+
joinThread:
+
joinThreads:
+
joptEnumOrd:
+
joptEnumString:
+
joptEnumSymbol:
+
Joptions:
+
joptJsonNodeAsCopy:
+
joptJsonNodeAsObject:
+
joptJsonNodeAsRef:
+
JRetr:
+
JRetrText:
+
js:
+
jsArguments:
+
jsAssert:
+
JsAssoc:
+
JsBigInt:
+
jsConstructorName:
+
jsDelete:
+
jsDirname:
+
JsError:
+
JsEvalError:
+
jsFilename:
+
jsFromAst:
+
JsKey:
+
jsNew:
+
jsNoBigInt64:
+
jsNull:
+
JsObject:
+
JSON:
+
json:
+
JSON:
+
jsonArrayEnd:
+
jsonArrayStart:
+
jsonEof:
+
jsonError:
+
JsonError:
+
JsonEventKind:
+
jsonFalse:
+
jsonFloat:
+
jsonInt:
+
JsonKindError:
+
JsonLib:
+
JsonNode:
+
JsonNodeKind:
+
JsonNodeMode:
+
JsonNodeObj:
+
jsonNull:
+
jsonObjectEnd:
+
jsonObjectStart:
+
JsonParser:
+
JsonParsingError:
+
jsonString:
+
jsonTo:
+
jsonTrue:
+
JsRangeError:
+
JsReferenceError:
+
JsRoot:
+
JsSyntaxError:
+
JStore:
+
JString:
+
JsTypeError:
+
jsTypeOf:
+
jsUndefined:
+
JsURIError:
+
JUnitOutputFormatter:
+
kbd:
+
kDirtyTemplate:
+
keepIf:
+
keepItIf:
+
KEvent:
+
kevent:
+
KeyboardEvent:
+
KeyboardEventKey:
+
KeyError:
+
KEY_EVENT_RECORD:
+
keygen:
+
keys:
+
keysWithPrefix:
+
kill:
+
kind:
+
kNoNewLit:
+
koch:
+
kqueue:
+
kurtosis:
+
kurtosisS:
+
l-value:
+
l-values:
+
label:
+
LacksDevPackages:
+
lambda lifting:
+
langC:
+
langCmd:
+
langConsole:
+
langCpp:
+
langCsharp:
+
langJava:
+
langNim:
+
langNone:
+
langPython:
+
LangSymbol:
+
langSymbolGroup:
+
langYaml:
+
largest:
+
last:
+
lastModified:
+
lastPathPart:
+
lastRune:
+
lastSon:
+
lcm:
+
leaves:
+
legend:
+
len:
+
lent:
+
letters:
+
Letters:
+
Level:
+
LevelNames:
+
Levenshtein:
+
lgamma:
+
li:
+
libCandidates:
+
LibHandle:
+
LibraryError:
+
license:
+
likely:
+
limit:
+
line:
+
line feed:
+
LineInfo:
+
lineInfo:
+
lineInfoObj:
+
LinenoiseData:
+
LineRstInit:
+
lines:
+
link:
+
LinkElement:
+
lispRepr:
+
list:
+
listDirs:
+
listen:
+
listFiles:
+
littleEndian:
+
littleEndian16:
+
littleEndian32:
+
littleEndian64:
+
ln:
+
lnCtrlC:
+
lnCtrlD:
+
lnCtrlUnkown:
+
lo32:
+
load:
+
loadConfig:
+
loadHtml:
+
loadLib:
+
loadLibPattern:
+
loadUnidecodeTable:
+
loadXml:
+
local:
+
local type inference:
+
localFree:
+
localRaiseHook:
+
locals:
+
Location:
+
LocationBar:
+
locations:
+
Lock:
+
locks:
+
log:
+
log10:
+
log1p:
+
log2:
+
Logger:
+
LONG:
+
lookupNamespaceURI:
+
lookupPrefix:
+
low:
+
lowerBound:
+
LowercaseLetters:
+
LPFIBER_START_ROUTINE:
+
LPFILETIME:
+
LPINT:
+
lvlAll:
+
lvlDebug:
+
lvlError:
+
lvlFatal:
+
lvlInfo:
+
lvlNone:
+
lvlNotice:
+
lvlWarn:
+
maction:
+
main:
+
malloc:
+
mantissaDigits:
+
map:
+
mapIt:
+
mapLiterals:
+
mapMem:
+
mApr:
+
mapViewOfFileEx:
+
mark:
+
Markdown:
+
marquee:
+
mask:
+
masked:
+
match:
+
matchBounds:
+
matches:
+
matchLen:
+
matchMedia:
+
math:
+
Math:
+
MathLib:
+
mAug:
+
max:
+
max10Exponent:
+
maxDescriptors:
+
MaxDistinguishedThread:
+
maxExponent:
+
MaxFloat32Precision:
+
MaxFloat64Precision:
+
MaxFloatPrecision:
+
maxIeeeExponent:
+
maximumPositiveValue:
+
MAXIMUM_WAIT_OBJECTS:
+
maxIndex:
+
MAX_INT:
+
maxLen:
+
MaxLineLength:
+
MAX_PATH:
+
MaxReBufSize:
+
maxSafeInteger:
+
MaxSubpatterns:
+
maxSymlinkLen:
+
MaxThreadPoolSize:
+
maxVarIntLen:
+
mcError:
+
mcHint:
+
mcWarning:
+
MD5Context:
+
MD5Digest:
+
md5Final:
+
md5Init:
+
md5Update:
+
mDec:
+
mean:
+
meCannotOpenFile:
+
MediaQueryList:
+
meExpected:
+
meFootnoteMismatch:
+
meGeneralParseError:
+
meGridTableNotImplemented:
+
meIllformedTable:
+
meInvalidDirective:
+
meInvalidField:
+
MemAccessFlags:
+
meMarkdownIllformedTable:
+
memExec:
+
memExecRead:
+
memExecReadWrite:
+
MemFile:
+
meMissingClosing:
+
MemMapFileStream:
+
MemMapFileStreamObj:
+
memory mapped files:
+
memoryLock:
+
memoryLockAll:
+
MemoryOrder:
+
memoryUnlock:
+
memoryUnlockAll:
+
memRead:
+
memReadWrite:
+
MemSlice:
+
memSlices:
+
menclose:
+
meNewSectionExpected:
+
MenuBar:
+
merge:
+
mergeIndexes:
+
merror:
+
meSandboxedDirective:
+
message:
+
Message:
+
meta:
+
metaAuthor:
+
MetaEnum:
+
metaNone:
+
metaSubtitle:
+
metaTitle:
+
metaTitleRaw:
+
metaVersion:
+
meter:
+
method:
+
methodGet:
+
methodNone:
+
methodPost:
+
methods:
+
mFeb:
+
mfenced:
+
mfrac:
+
mget:
+
mgetOrPut:
+
mglyph:
+
mi:
+
Microseconds:
+
microseconds:
+
Milliseconds:
+
milliseconds:
+
MimeDB:
+
mimes:
+
MimeType:
+
min:
+
min10Exponent:
+
minExponent:
+
MinFloatNormal:
+
minimumPositiveValue:
+
minIndex:
+
MIN_INT:
+
minmax:
+
minute:
+
minute=:
+
MinuteRange:
+
Minutes:
+
minutes:
+
missingOrExcl:
+
mitems:
+
mix:
+
mixin:
+
mJan:
+
mJul:
+
mJun:
+
mkDir:
+
mkdtemp:
+
mkstemp:
+
mlabeledtr:
+
mmap:
+
mMar:
+
mMay:
+
mmultiscripts:
+
mn:
+
mNov:
+
mo:
+
mOct:
+
mode:
+
modeCaseInsensitive:
+
modeCaseSensitive:
+
modeStyleInsensitive:
+
MonoTime:
+
Month:
+
month:
+
monthday:
+
MonthdayRange:
+
monthdayZero=:
+
Months:
+
months:
+
monthZero=:
+
MouseButtons:
+
MouseEvent:
+
move:
+
moveBy:
+
moveDir:
+
moveFile:
+
MOVEFILE_COPY_ALLOWED:
+
MOVEFILE_CREATE_HARDLINK:
+
MOVEFILE_DELAY_UNTIL_REBOOT:
+
moveFileExW:
+
MOVEFILE_FAIL_IF_NOT_TRACKABLE:
+
MOVEFILE_REPLACE_EXISTING:
+
moveFileW:
+
MOVEFILE_WRITE_THROUGH:
+
moveMem:
+
mover:
+
moveTo:
+
mpadded:
+
mpairs:
+
mpairsWithPrefix:
+
mphantom:
+
mroot:
+
mrow:
+
ms:
+
mSep:
+
MsgClass:
+
MsgHandler:
+
MsgKind:
+
MSG_PEEK:
+
mspace:
+
msqrt:
+
mstyle:
+
msub:
+
msubsup:
+
msup:
+
mtable:
+
mtd:
+
mtext:
+
mul128:
+
mulParity:
+
mulShift:
+
MultipartData:
+
MultipartEntries:
+
multipleOfPow2:
+
multipleOfPow5:
+
MultipleValueSetting:
+
multiReplace:
+
multisync:
+
munder:
+
munderover:
+
mvalues:
+
mvaluesWithPrefix:
+
mvDir:
+
mvFile:
+
mwAmbiguousLink:
+
mwBrokenLink:
+
mwRedefinitionOfLabel:
+
mwRstStyle:
+
mwUnknownSubstitution:
+
mwUnsupportedField:
+
mwUnsupportedLanguage:
+
mwUnusedImportdoc:
+
mySQL:
+
name:
+
name=:
+
namespace:
+
NaN:
+
nanChecks:
+
nanosecond:
+
nanosecond=:
+
NanosecondRange:
+
Nanoseconds:
+
nanoseconds:
+
narrowing type conversion:
+
nativeToUnixPath:
+
natural:
+
Natural:
+
nav:
+
Navigator:
+
navigator:
+
NegInf:
+
nestList:
+
new:
+
newArrayBuffer:
+
newAssignment:
+
newAsyncEvent:
+
newAsyncFile:
+
newAsyncFtpClient:
+
newAsyncHttpClient:
+
newAsyncHttpServer:
+
newAsyncSmtp:
+
newAsyncSocket:
+
newBigUint64Array:
+
newBlockStmt:
+
newCall:
+
newCData:
+
newColonExpr:
+
newComment:
+
newCommentStmtNode:
+
newConfig:
+
newConsoleLogger:
+
newConsoleOutputFormatter:
+
newConstStmt:
+
newContext:
+
newCountTable:
+
newCustom:
+
newDate:
+
newDispatcher:
+
newDomException:
+
newDomParser:
+
newDotExpr:
+
newDoublyLinkedNode:
+
newElement:
+
newEmptyNode:
+
newEntity:
+
newEnum:
+
newEvent:
+
newException:
+
newfetchOptions:
+
newFileLogger:
+
newFileReader:
+
newFileStream:
+
newFloat64Array:
+
newFloatLitNode:
+
newFormData:
+
newFuture:
+
newFutureStream:
+
newFutureVar:
+
newHeaders:
+
newHttpClient:
+
newHttpHeaders:
+
newIdentDefs:
+
newIdentNode:
+
newIfStmt:
+
newIntLitNode:
+
newJArray:
+
newJBool:
+
newJFloat:
+
newJInt:
+
newJNull:
+
newJObject:
+
newJsAssoc:
+
newJsObject:
+
newJString:
+
newJUnitOutputFormatter:
+
newLetStmt:
+
newline:
+
newLine:
+
newline:
+
NewLines:
+
Newlines:
+
newLit:
+
newMemMapFileStream:
+
newMimetypes:
+
newMultipartData:
+
newNilLit:
+
newNimNode:
+
newNode:
+
newNonTerminal:
+
newOrderedTable:
+
newOSError:
+
newPar:
+
newPipeOutStream:
+
newProc:
+
newPromise:
+
newProxy:
+
newReadSocketStream:
+
newRegExp:
+
newRequest:
+
newResponse:
+
newRollingFileLogger:
+
newRstLeaf:
+
newRstNode:
+
newRstSharedState:
+
newSCons:
+
newSelectEvent:
+
newSelector:
+
newSeq:
+
newSeqOfCap:
+
newSeqUninit:
+
newSeqUninitialized:
+
newSeqWith:
+
newSFloat:
+
newSha1State:
+
newSinglyLinkedNode:
+
newSInt:
+
newSList:
+
newSmtp:
+
newSNil:
+
newSocket:
+
newSString:
+
newSSymbol:
+
newStmtList:
+
newString:
+
newStringOfCap:
+
newStringStream:
+
newStringTable:
+
newStringUninit:
+
newStrLitNode:
+
newTable:
+
newTableFrom:
+
newText:
+
newTimezone:
+
newTree:
+
newUint32Array:
+
newUint8Array:
+
newVarStmt:
+
newVerbatimText:
+
newWideCString:
+
newWriteSocketStream:
+
newXmlTree:
+
next:
+
nextPermutation:
+
nextPowerOfTwo:
+
nextSplitPoint:
+
NilAccessDefect:
+
NimAsyncContinueSuffix:
+
nimcache:
+
nimcacheDir:
+
nimcall:
+
nimGC_setStackBottom:
+
NimIdent:
+
nimIdentBackticksNormalize:
+
nimIdentNormalize:
+
NimMajor:
+
nimMaxDescriptorsFallback:
+
NimMinor:
+
NimNode:
+
NimNodeKind:
+
NimNodeKinds:
+
NimPatch:
+
NimSeqV2:
+
NimSym:
+
NimSymKind:
+
nimThreadDestructionHandlers:
+
nimThreadProcWrapperBody:
+
NimTypeKind:
+
NimVersion:
+
nimvm:
+
nkAsgn:
+
nkBitStringLit:
+
nkCall:
+
nkCheck:
+
nkColumnDef:
+
nkColumnList:
+
nkColumnReference:
+
nkConstraint:
+
nkCreateIndex:
+
nkCreateIndexIfNotExists:
+
nkCreateTable:
+
nkCreateTableIfNotExists:
+
nkCreateType:
+
nkCreateTypeIfNotExists:
+
nkDefault:
+
nkDelete:
+
nkDesc:
+
nkDot:
+
nkDotDot:
+
nkEnumDef:
+
nkExcept:
+
nkForeignKey:
+
nkFrom:
+
nkFromItemPair:
+
nkGroup:
+
nkHaving:
+
nkHexStringLit:
+
nkIdent:
+
nkIdentity:
+
nkInfix:
+
nkInsert:
+
nkIntegerLit:
+
nkIntersect:
+
nkJoin:
+
nkLimit:
+
nkNaturalJoin:
+
nkNone:
+
nkNotNull:
+
nkNull:
+
nkNumericLit:
+
nkOffset:
+
nkOrder:
+
nkPrefix:
+
nkPrGroup:
+
nkPrimaryKey:
+
nkQuotedIdent:
+
nkReferences:
+
nkSelect:
+
nkSelectColumns:
+
nkSelectDistinct:
+
nkSelectPair:
+
nkStmtList:
+
nkStringLit:
+
nkUnion:
+
nkUnique:
+
nkUpdate:
+
nkUsing:
+
nkValueList:
+
nkWhere:
+
nnkAccQuoted:
+
nnkAddr:
+
nnkArgList:
+
nnkAsgn:
+
nnkAsmStmt:
+
nnkBind:
+
nnkBindStmt:
+
nnkBlockExpr:
+
nnkBlockStmt:
+
nnkBlockType:
+
nnkBracket:
+
nnkBracketExpr:
+
nnkBreakState:
+
nnkBreakStmt:
+
nnkCall:
+
nnkCallKinds:
+
nnkCallStrLit:
+
nnkCaseStmt:
+
nnkCast:
+
nnkCharLit:
+
nnkChckRange:
+
nnkChckRange64:
+
nnkChckRangeF:
+
nnkCheckedFieldExpr:
+
nnkClosedSymChoice:
+
nnkClosure:
+
nnkComesFrom:
+
nnkCommand:
+
nnkCommentStmt:
+
nnkConstDef:
+
nnkConstSection:
+
nnkConstTy:
+
nnkContinueStmt:
+
nnkConv:
+
nnkConverterDef:
+
nnkCStringToString:
+
nnkCurly:
+
nnkCurlyExpr:
+
nnkDefer:
+
nnkDerefExpr:
+
nnkDiscardStmt:
+
nnkDistinctTy:
+
nnkDo:
+
nnkDotCall:
+
nnkDotExpr:
+
nnkElifBranch:
+
nnkElifExpr:
+
nnkElse:
+
nnkElseExpr:
+
nnkEmpty:
+
nnkEnumFieldDef:
+
nnkEnumTy:
+
nnkError:
+
nnkExceptBranch:
+
nnkExportExceptStmt:
+
nnkExportStmt:
+
nnkExprColonExpr:
+
nnkExprEqExpr:
+
nnkFastAsgn:
+
nnkFinally:
+
nnkFloat128Lit:
+
nnkFloat32Lit:
+
nnkFloat64Lit:
+
nnkFloatLit:
+
nnkFormalParams:
+
nnkForStmt:
+
nnkFromStmt:
+
nnkFuncDef:
+
nnkGenericParams:
+
nnkGotoState:
+
nnkHiddenAddr:
+
nnkHiddenCallConv:
+
nnkHiddenDeref:
+
nnkHiddenStdConv:
+
nnkHiddenSubConv:
+
nnkHiddenTryStmt:
+
nnkIdent:
+
nnkIdentDefs:
+
nnkIfExpr:
+
nnkIfStmt:
+
nnkImportAs:
+
nnkImportExceptStmt:
+
nnkImportStmt:
+
nnkIncludeStmt:
+
nnkInfix:
+
nnkInt16Lit:
+
nnkInt32Lit:
+
nnkInt64Lit:
+
nnkInt8Lit:
+
nnkIntLit:
+
nnkIteratorDef:
+
nnkIteratorTy:
+
nnkLambda:
+
nnkLetSection:
+
nnkLiterals:
+
nnkMacroDef:
+
nnkMethodDef:
+
nnkMixinStmt:
+
nnkModuleRef:
+
nnkMutableTy:
+
nnkNilLit:
+
nnkNilRodNode:
+
nnkNone:
+
nnkObjConstr:
+
nnkObjDownConv:
+
nnkObjectTy:
+
nnkObjUpConv:
+
nnkOfBranch:
+
nnkOfInherit:
+
nnkOpenSym:
+
nnkOpenSymChoice:
+
nnkOutTy:
+
nnkPar:
+
nnkParForStmt:
+
nnkPattern:
+
nnkPostfix:
+
nnkPragma:
+
nnkPragmaBlock:
+
nnkPragmaExpr:
+
nnkPrefix:
+
nnkProcDef:
+
nnkProcTy:
+
nnkPtrTy:
+
nnkRaiseStmt:
+
nnkRange:
+
nnkRecCase:
+
nnkRecList:
+
nnkRecWhen:
+
nnkRefTy:
+
nnkReplayAction:
+
nnkReturnStmt:
+
nnkRStrLit:
+
nnkSharedTy:
+
nnkSinkAsgn:
+
nnkState:
+
nnkStaticExpr:
+
nnkStaticStmt:
+
nnkStaticTy:
+
nnkStmtList:
+
nnkStmtListExpr:
+
nnkStmtListType:
+
nnkStringToCString:
+
nnkStrLit:
+
nnkSym:
+
nnkTableConstr:
+
nnkTemplateDef:
+
nnkTripleStrLit:
+
nnkTryStmt:
+
nnkTupleClassTy:
+
nnkTupleConstr:
+
nnkTupleTy:
+
nnkType:
+
nnkTypeClassTy:
+
nnkTypeDef:
+
nnkTypeOfExpr:
+
nnkTypeSection:
+
nnkUInt16Lit:
+
nnkUInt32Lit:
+
nnkUInt64Lit:
+
nnkUInt8Lit:
+
nnkUIntLit:
+
nnkUsingStmt:
+
nnkVarSection:
+
nnkVarTuple:
+
nnkVarTy:
+
nnkWhenStmt:
+
nnkWhileStmt:
+
nnkWith:
+
nnkWithout:
+
nnkYieldStmt:
+
no heap sharing restriction:
+
NoButton:
+
noconv:
+
Node:
+
nodeID:
+
nodejs:
+
nodes:
+
nodestroy:
+
NodeType:
+
NO_ERROR:
+
noinit:
+
noinline:
+
None:
+
none:
+
NonTerminal:
+
nonterminal:
+
NonTerminalFlag:
+
normalize:
+
normalizedPath:
+
normalizeExe:
+
normalizePath:
+
normalizePathEnd:
+
NORMAL_PRIORITY_CLASS:
+
noscript:
+
noSideEffect:
+
NotationNode:
+
NOTE_ATTRIB:
+
NOTE_CHILD:
+
NOTE_DELETE:
+
NOTE_EXEC:
+
NOTE_EXIT:
+
NOTE_EXTEND:
+
NOTE_FORK:
+
NOTE_LINK:
+
NOTE_LOWAT:
+
NOTE_MSECONDS:
+
NOTE_PCTRLMASK:
+
NOTE_PDATAMASK:
+
NOTE_RENAME:
+
NOTE_REVOKE:
+
NOTE_TRACK:
+
NOTE_TRACKERR:
+
NOTE_WRITE:
+
notice:
+
now:
+
NRVO:
+
nskConditional:
+
nskConst:
+
nskConverter:
+
nskDynLib:
+
nskEnumField:
+
nskField:
+
nskForVar:
+
nskFunc:
+
nskGenericParam:
+
nskIterator:
+
nskLabel:
+
nskLet:
+
nskMacro:
+
nskMethod:
+
nskModule:
+
nskParam:
+
nskProc:
+
nskResult:
+
nskStub:
+
nskTemp:
+
nskTemplate:
+
nskType:
+
nskUnknown:
+
nskVar:
+
nt:
+
ntDeclared:
+
ntohl:
+
ntohs:
+
ntUsed:
+
ntyAlias:
+
ntyAnd:
+
ntyAnything:
+
ntyArray:
+
ntyBool:
+
ntyBuiltinTypeClass:
+
ntyChar:
+
ntyCompositeTypeClass:
+
ntyCString:
+
ntyDistinct:
+
ntyEmpty:
+
ntyEnum:
+
ntyError:
+
ntyExpr:
+
ntyFloat:
+
ntyFloat128:
+
ntyFloat32:
+
ntyFloat64:
+
ntyForward:
+
ntyFromExpr:
+
ntyGenericBody:
+
ntyGenericInst:
+
ntyGenericInvocation:
+
ntyGenericParam:
+
ntyInferred:
+
ntyInt:
+
ntyInt16:
+
ntyInt32:
+
ntyInt64:
+
ntyInt8:
+
ntyNil:
+
ntyNone:
+
ntyNot:
+
ntyObject:
+
ntyOpenArray:
+
ntyOptDeprecated:
+
ntyOr:
+
ntyOrdinal:
+
ntyPointer:
+
ntyProc:
+
ntyPtr:
+
ntyRange:
+
ntyRef:
+
ntySequence:
+
ntySet:
+
ntyStatic:
+
ntyStmt:
+
ntyString:
+
ntyTuple:
+
ntyTypeDesc:
+
ntyUInt:
+
ntyUInt16:
+
ntyUInt32:
+
ntyUInt64:
+
ntyUInt8:
+
ntyUncheckedArray:
+
ntyUnused0:
+
ntyUnused1:
+
ntyUnused2:
+
ntyUserTypeClass:
+
ntyUserTypeClassInst:
+
ntyVar:
+
ntyVarargs:
+
ntyVoid:
+
nxt:
+
object construction expression:
+
ObjectAssignmentDefect:
+
ObjectConversionDefect:
+
Objective C:
+
off:
+
offsetHeight:
+
offsetLeft:
+
offsetOf:
+
offsetTop:
+
offsetWidth:
+
Oid:
+
OK:
+
ol:
+
old:
+
on:
+
once:
+
onFailedAssert:
+
OnReject:
+
onThreadDestruction:
+
onUnhandledException:
+
open:
+
OPEN_ALWAYS:
+
openarray:
+
openArray:
+
openarray:
+
openAsync:
+
openDefaultBrowser:
+
OPEN_EXISTING:
+
openFileStream:
+
OpenMP:
+
openProcess:
+
Operators:
+
OptAcceptConn:
+
OptBroadcast:
+
OptDebug:
+
OptDontRoute:
+
optgroup:
+
option:
+
Option:
+
option:
+
OptionElement:
+
OptKeepAlive:
+
OptNoDelay:
+
OptOOBInline:
+
OptParser:
+
OptReuseAddr:
+
OptReusePort:
+
ord:
+
OrderedSet:
+
OrderedTable:
+
OrderedTableRef:
+
Ordinal:
+
OrdinalEnum:
+
OSError:
+
OSErrorCode:
+
osErrorMsg:
+
osInvalidSocket:
+
osLastError:
+
osOpenCmd:
+
osReleaseFile:
+
OSVERSIONINFO:
+
out of memory:
+
outHtml:
+
outLatex:
+
OutOfMemDefect:
+
outOfMemHook:
+
outParamsAt:
+
output:
+
OutputFormatter:
+
outputHandle:
+
OutputLevel:
+
outputStream:
+
OutputTarget:
+
OverflowDefect:
+
OVERLAPPED:
+
owned:
+
owner:
+
p:
+
packageName:
+
PackedSet:
+
PAGE_EXECUTE:
+
PAGE_EXECUTE_READ:
+
PAGE_EXECUTE_READWRITE:
+
PAGE_NOACCESS:
+
PAGE_READONLY:
+
PAGE_READWRITE:
+
pairs:
+
pairsWithPrefix:
+
panic:
+
parallel:
+
parallelReplace:
+
param:
+
paramCount:
+
parameter constraint:
+
params:
+
params=:
+
paramStr:
+
ParDir:
+
parentDir:
+
parentDirs:
+
parityBits:
+
parse:
+
parseBiggestFloat:
+
parseBiggestInt:
+
parseBiggestUInt:
+
parseBin:
+
parseBinInt:
+
parseBool:
+
parseChar:
+
parseCmdLine:
+
parseColor:
+
parseCookies:
+
parseEnum:
+
parseEscapedUTF16:
+
parseExpr:
+
parseFile:
+
parseFloat:
+
parseFromString:
+
parseHeader:
+
parseHex:
+
parseHexInt:
+
parseHexStr:
+
parseHtml:
+
parseIdent:
+
parseIdxFile:
+
parseInt:
+
parseIpAddress:
+
parseJson:
+
parseJsonFragments:
+
parseOct:
+
parseOctInt:
+
parseOid:
+
parsePeg:
+
parseSalt:
+
parseSaturatedNatural:
+
parseSecureHash:
+
parseSexp:
+
parseSize:
+
parseSql:
+
parseStandardFormatSpecifier:
+
parseStmt:
+
parseTableCells:
+
parseTime:
+
parseUInt:
+
parseUntil:
+
parseUri:
+
parseWhile:
+
parseXml:
+
partial case-insensitivity:
+
partition:
+
patch:
+
patchContent:
+
patchFile:
+
Path:
+
path analysis:
+
PathComponent:
+
PathEntry:
+
PathIter:
+
PathSep:
+
patricia trie:
+
PBOOL:
+
pcDir:
+
pcFile:
+
pcLinkToDir:
+
pcLinkToFile:
+
pdf:
+
PDispatcher:
+
PDWORD:
+
peek:
+
peekableErrorStream:
+
peekableOutputStream:
+
peekBool:
+
peekChar:
+
peekData:
+
peekExitCode:
+
peekFirst:
+
peekFloat32:
+
peekFloat64:
+
peekInt16:
+
peekInt32:
+
peekInt64:
+
peekInt8:
+
peekLast:
+
peekLine:
+
peekNamedPipe:
+
peekStr:
+
peekUint16:
+
peekUint32:
+
peekUint64:
+
peekUint8:
+
Peg:
+
peg:
+
PegKind:
+
Performance:
+
PerformanceMemory:
+
PerformanceTiming:
+
performCodeReload:
+
performCodeReload():
+
PersonalBar:
+
PFrame:
+
PGcThread:
+
phase:
+
physicalExponent:
+
physicalSignificand:
+
PI:
+
picture:
+
piName:
+
pinnedSpawn:
+
pinToCpu:
+
PIPE_ACCESS_DUPLEX:
+
PIPE_ACCESS_INBOUND:
+
PIPE_ACCESS_OUTBOUND:
+
PIPE_NOWAIT:
+
PipeOutStream:
+
piRest:
+
pkAndPredicate:
+
pkAny:
+
pkAnyRune:
+
pkBackRef:
+
pkBackRefIgnoreCase:
+
pkBackRefIgnoreStyle:
+
pkCapture:
+
pkCapturedSearch:
+
pkChar:
+
pkCharChoice:
+
pkEmpty:
+
pkGreedyAny:
+
pkGreedyRep:
+
pkGreedyRepChar:
+
pkGreedyRepSet:
+
pkLetter:
+
pkList:
+
pkLower:
+
pkNewLine:
+
pkNonTerminal:
+
pkNotPredicate:
+
pkOption:
+
pkOrderedChoice:
+
pkRule:
+
pkSearch:
+
pkSequence:
+
pkStartAnchor:
+
pkTerminal:
+
pkTerminalIgnoreCase:
+
pkTerminalIgnoreStyle:
+
pkTitle:
+
pkUpper:
+
pkWhitespace:
+
play:
+
Plugin:
+
poDaemon:
+
poEchoCmd:
+
poEvalCommand:
+
pointer:
+
poInteractive:
+
pointerBase:
+
polar:
+
poll:
+
pop:
+
poParentStreams:
+
popcount:
+
popFirst:
+
popLast:
+
Port:
+
portal:
+
Positive:
+
post:
+
postcondition:
+
postContent:
+
poStdErrToStdOut:
+
postfix:
+
PostgreSQL:
+
postQueuedCompletionStatus:
+
poUsePath:
+
POVERLAPPED:
+
POVERLAPPED_COMPLETION_ROUTINE:
+
pow:
+
pragma:
+
pragma=:
+
pre:
+
precondition:
+
pred:
+
preferSpawn:
+
prefix:
+
prepare:
+
prepareMutation:
+
preparePass2:
+
prepend:
+
prependMoved:
+
pretty:
+
prettyLink:
+
preventDefault:
+
prevPermutation:
+
PrimaryButton:
+
print:
+
PrintableChars:
+
PRINT_ALL:
+
printDecimalDigitsBackwards:
+
PRINT_FAILURES:
+
printKeyCodes:
+
PRINT_NONE:
+
privateAccess:
+
procCall:
+
procedures:
+
Process:
+
PROCESS_CREATE_PROCESS:
+
PROCESS_CREATE_THREAD:
+
PROCESS_DUP_HANDLE:
+
processedRows:
+
processID:
+
PROCESS_INFORMATION:
+
ProcessingInstructionNode:
+
ProcessOption:
+
PROCESS_QUERY_INFORMATION:
+
PROCESS_QUERY_LIMITED_INFORMATION:
+
PROCESS_SET_INFORMATION:
+
PROCESS_SET_LIMITED_INFORMATION:
+
PROCESS_SET_QUOTA:
+
PROCESS_SET_SESSIONID:
+
PROCESS_SUSPEND_RESUME:
+
PROCESS_TERMINATE:
+
PROCESS_VM_OPERATION:
+
PROCESS_VM_READ:
+
PROCESS_VM_WRITE:
+
procName:
+
prod:
+
product:
+
program:
+
programResult:
+
progress:
+
ProgressChangedProc:
+
projectDir:
+
projectName:
+
projectPath:
+
PromiseJs:
+
prompt:
+
protect:
+
Protocol:
+
ProtocolError:
+
Protoent:
+
protSSLv2:
+
protSSLv23:
+
protSSLv3:
+
protTLSv1:
+
Proxy:
+
PRstNode:
+
PRstSharedState:
+
PSID:
+
pskIdentityHint=:
+
Pthread_attr:
+
pthread_attr_destroy:
+
pthread_attr_init:
+
pthread_attr_setstack:
+
pthread_attr_setstacksize:
+
pthread_cancel:
+
pthread_create:
+
pthreadh:
+
pthread_join:
+
PULONG:
+
PULONG_PTR:
+
PunctuationChars:
+
PunyError:
+
push:
+
push/pop:
+
pushpop:
+
pushState:
+
put:
+
putContent:
+
putEnv:
+
pwd:
+
PWOHandleArray:
+
q:
+
querySelector:
+
querySelectorAll:
+
querySetting:
+
querySettingSeq:
+
queueMicrotask:
+
quit:
+
QuitFailure:
+
QuitSuccess:
+
quotation mark:
+
quote:
+
quoteShell:
+
quoteShellCommand:
+
quoteShellPosix:
+
quoteShellWindows:
+
radix tree:
+
radToDeg:
+
raiseAssert:
+
raiseInvalidLibrary:
+
raiseOSError:
+
raiseParseErr:
+
raises:
+
raiseSSLError:
+
Rand:
+
rand:
+
random:
+
randomize:
+
randState:
+
Range:
+
range:
+
rangeBase:
+
rangeCheck:
+
RangeDefect:
+
Rational:
+
rawData:
+
rawData2:
+
rawEnv:
+
rawMatch:
+
rawProc:
+
rawTag:
+
rawText:
+
rb:
+
rdFileSize:
+
rdFileTime:
+
re:
+
re-raised:
+
read:
+
readAll:
+
readAllFromStdin:
+
readAsBinaryString:
+
readAsDataURL:
+
readAsText:
+
readBool:
+
readBuffer:
+
readBytes:
+
readChar:
+
readChars:
+
readConsoleInput:
+
readData:
+
readDataStr:
+
ReadDbEffect:
+
ReadDirEffect:
+
ReadDisconnected:
+
ReadEnvEffect:
+
readError:
+
readFile:
+
readFloat32:
+
readFloat64:
+
ReadFullLine:
+
readHeaderRow:
+
readIndexDir:
+
readInt16:
+
readInt32:
+
readInt64:
+
readInt8:
+
ReadIOEffect:
+
readLine:
+
readLineFromStdin:
+
ReadLineResult:
+
readLines:
+
readLineStatus:
+
ReadNone:
+
ReadPartialLine:
+
readPasswordFromStdin:
+
readRow:
+
ReadSocketStream:
+
ReadSocketStreamObj:
+
readStr:
+
readToStream:
+
readUint16:
+
readUint32:
+
readUint64:
+
readUint8:
+
readVu64:
+
ReadyKey:
+
readyState:
+
realloc:
+
realloc0:
+
realloc0Impl:
+
reallocImpl:
+
reallocShared:
+
reallocShared0:
+
reallocShared0Impl:
+
reallocSharedImpl:
+
REALTIME_PRIORITY_CLASS:
+
reciprocal:
+
rect:
+
Recursive module dependencies:
+
recv:
+
recvFrom:
+
recvfrom:
+
recvFromInto:
+
recvInto:
+
recvLine:
+
recvLineInto:
+
reDotAll:
+
reduce:
+
reExtended:
+
Regex:
+
RegexDesc:
+
RegexError:
+
RegexFlag:
+
RegexInternalError:
+
RegexMatch:
+
RegExp:
+
register:
+
registerEvent:
+
registerHandle:
+
registerProcess:
+
registerProtocolHandler:
+
registerSignal:
+
registerTimer:
+
registerVnode:
+
registerWaitForSingleObject:
+
reIgnoreCase:
+
relativePath:
+
release:
+
release build:
+
releasePointerCapture:
+
releaseSys:
+
reload:
+
remainingArgs:
+
remove:
+
removeAllRanges:
+
removeAttribute:
+
removeAttributeNode:
+
removeAttributeNS:
+
removeChild:
+
removeDir:
+
removeDirectoryW:
+
removeEventListener:
+
removeFile:
+
removeHandler:
+
removeItem:
+
removePrefix:
+
removeProperty:
+
removeSuffix:
+
reMultiLine:
+
rename:
+
rename files:
+
renderCodeLang:
+
renderIndexTerm:
+
renderNimCode:
+
renderRstToJson:
+
renderRstToOut:
+
renderRstToRst:
+
renderRstToText:
+
renderSql:
+
renderTocEntries:
+
reopen:
+
repeat:
+
replace:
+
replaceChild:
+
replaceChildren:
+
replaceData:
+
replacef:
+
replaceWith:
+
replaceWord:
+
ReplyError:
+
reportComments:
+
reportValidity:
+
reportWhitespace:
+
repr:
+
reprDiscriminant:
+
Request:
+
request:
+
Request:
+
requestAnimationFrame:
+
RequestMethod:
+
requestPointerLock:
+
require:
+
requires:
+
requiresData:
+
requiresInit:
+
ReraiseDefect:
+
ReservedMem:
+
ReservedMemSeq:
+
reset:
+
resetAttributes:
+
resetOutputFormatters:
+
resetStream:
+
resetStyle:
+
resize:
+
resizeBy:
+
resizeShared:
+
resizeTo:
+
resolveSubs:
+
resource:
+
ResourceExhaustedError:
+
respond:
+
Response:
+
reStructuredText:
+
reStudy:
+
result:
+
resultAsString:
+
resume:
+
resumeThread:
+
retrFile:
+
retrText:
+
retryCall:
+
reverse:
+
reverseBits:
+
reversed:
+
rex:
+
rfind:
+
rgb:
+
RLock:
+
rmDir:
+
rmFile:
+
rnAdmonition:
+
rnBlockQuote:
+
rnBulletItem:
+
rnBulletList:
+
rnCitation:
+
rnCodeBlock:
+
rnCodeFragment:
+
rnContainer:
+
rnContents:
+
rnDefaultRole:
+
rnDefBody:
+
rnDefItem:
+
rnDefList:
+
rnDefName:
+
rnDescription:
+
rnDirArg:
+
rnDirective:
+
rnEmphasis:
+
rnEnumItem:
+
rnEnumList:
+
rnField:
+
rnFieldBody:
+
rnFieldList:
+
rnFieldName:
+
rnFigure:
+
rnFootnote:
+
rnFootnoteGroup:
+
rnFootnoteRef:
+
rnGridTable:
+
rnHeadline:
+
rnHyperlink:
+
rnIdx:
+
rnImage:
+
rnIndex:
+
rnInlineCode:
+
rnInlineLiteral:
+
rnInlineTarget:
+
rnInner:
+
rnInternalRef:
+
rnInterpretedText:
+
rnLeaf:
+
rnLineBlock:
+
rnLineBlockItem:
+
rnLiteralBlock:
+
rnMarkdownBlockQuote:
+
rnMarkdownBlockQuoteItem:
+
rnMarkdownHeadline:
+
rnMarkdownTable:
+
rnMdDefList:
+
rnNimdocRef:
+
rnOption:
+
rnOptionArgument:
+
rnOptionGroup:
+
rnOptionList:
+
rnOptionListItem:
+
rnOptionString:
+
rnOverline:
+
rnPandocRef:
+
rnParagraph:
+
rnRaw:
+
rnRawHtml:
+
rnRawLatex:
+
rnRstRef:
+
rnSmiley:
+
rnStandaloneHyperlink:
+
rnStrongEmphasis:
+
rnSub:
+
rnSubstitutionDef:
+
rnSubstitutionReferences:
+
rnSup:
+
rnTable:
+
rnTableDataCell:
+
rnTableHeaderCell:
+
rnTableRow:
+
rnTitle:
+
rnTransition:
+
rnTripleEmphasis:
+
rnUnknownRole:
+
RollingFileLogger:
+
roNimFile:
+
roof:
+
RootEffect:
+
RootNodeOptions:
+
RootObj:
+
RootRef:
+
Rope:
+
rope:
+
roPreferMarkdown:
+
roSandboxDisabled:
+
roSupportMarkdown:
+
roSupportRawDirective:
+
roSupportSmilies:
+
rotatedLeft:
+
rotateLeft:
+
rotateLeftBits:
+
rotateRightBits:
+
round:
+
routeEvent:
+
RoutineNodes:
+
Row:
+
rowEntry:
+
rows:
+
rp:
+
rpartition:
+
rsplit:
+
RstFileTable:
+
RstGenerator:
+
rstMessage:
+
RstNode:
+
RstNodeKind:
+
RstNodeSeq:
+
rstnodeToRefname:
+
rstParse:
+
RstParseOption:
+
RstParseOptions:
+
rstParsePass1:
+
rstToHtml:
+
rstToLatex:
+
rt:
+
RtArray:
+
rtc:
+
RTTI:
+
ruby:
+
rule:
+
run:
+
Rune:
+
runeAt:
+
runeAtPos:
+
runeLen:
+
runeLenAt:
+
runeOffset:
+
runeReverseOffset:
+
runes:
+
runeStrAtPos:
+
runeSubStr:
+
runeToEntity:
+
runForever:
+
runnable example:
+
runnableExamples:
+
running:
+
RunningRegress:
+
RunningStat:
+
runtime:
+
runtime checks:
+
runtime type information:
+
s:
+
safe:
+
safecall:
+
safeProtocol:
+
Salt:
+
SaltedHash:
+
sameFile:
+
sameFileContent:
+
SameSite:
+
sameType:
+
samp:
+
sample:
+
scanf:
+
scanp:
+
scanSSLCertificates:
+
scanTuple:
+
SCons:
+
scope:
+
Screen:
+
screen:
+
script:
+
ScriptExt:
+
ScriptMode:
+
ScrollBars:
+
scrollBy:
+
scrollHeight:
+
scrollIntoView:
+
scrollIntoViewIfNeeded:
+
ScrollIntoViewOptions:
+
scrollLeft:
+
scrollTo:
+
scrollTop:
+
scrollTop=:
+
scrollWidth:
+
searchExtPos:
+
sec:
+
sech:
+
second:
+
second=:
+
SecondaryButton:
+
SecondRange:
+
Seconds:
+
seconds:
+
section:
+
sections:
+
SecureHash:
+
secureHash:
+
secureHashFile:
+
SECURITY_ATTRIBUTES:
+
SECURITY_BUILTIN_DOMAIN_RID:
+
SECURITY_NT_AUTHORITY:
+
select:
+
SelectEvent:
+
selectInto:
+
Selection:
+
Selector:
+
selectRead:
+
selectWrite:
+
selfExe:
+
selfExec:
+
semantic analysis:
+
semantics:
+
send:
+
sendBeacon:
+
sendHeaders:
+
sendMail:
+
sendSignal:
+
sendTo:
+
sendto:
+
separate compilation:
+
seq:
+
sequence:
+
serialization:
+
serve:
+
Servent:
+
serverGetPskFunc:
+
serverGetPskFunc=:
+
sessionIdContext=:
+
set:
+
setAffinity:
+
setAttr:
+
setAttribute:
+
setAttributeNode:
+
setBackgroundColor:
+
setBiggestFloat:
+
setBiggestInt:
+
setBiggestUint:
+
setBit:
+
setBits:
+
setBlocking:
+
setCallSoonProc:
+
setCommand:
+
setCompletionCallback:
+
setControlCHook:
+
setCookie:
+
setCurrentDir:
+
setCurrentDirectoryW:
+
setCurrentException:
+
setCurrFilename:
+
setCursorPos:
+
setCursorXPos:
+
setCustomValidity:
+
setData:
+
setDragImage:
+
setEncoding:
+
setEndOfFile:
+
setEnvironmentVariableW:
+
setEvent:
+
setExtraData:
+
setFileAttributesW:
+
setFilePermissions:
+
setFilePointer:
+
setFilePos:
+
setFileSize:
+
setFileTime:
+
setForegroundColor:
+
setFrame:
+
setFrameMsg:
+
setFrameState:
+
setFullYear:
+
setGlobalDispatcher:
+
setHandleInformation:
+
setHTML:
+
setIndexTerm:
+
setInheritable:
+
setInterval:
+
setItem:
+
setLastError:
+
setLastModificationTime:
+
setLen:
+
setLenUninit:
+
setLineInfo:
+
setLogFilter:
+
setMask:
+
setMasked:
+
setMaxPoolSize:
+
setMinPoolSize:
+
setMultiLine:
+
setObjectRuntimeType:
+
setPointer:
+
setPosition:
+
setProgramResult:
+
setProperty:
+
setRangeText:
+
setSamplingFrequency:
+
setSectionKey:
+
setSelectionRange:
+
setSlice:
+
setSockOpt:
+
setsockopt:
+
setSockOptInt:
+
setStackTraceStdout:
+
setStdHandle:
+
setStdIoUnbuffered:
+
setString:
+
setStyle:
+
setSysLockType:
+
setter:
+
setTestData:
+
setTimeout:
+
setUnicodeValue:
+
setupForeignThreadGc:
+
sexp:
+
sexpDot:
+
sexpEof:
+
sexpError:
+
SexpError:
+
SexpEventKind:
+
sexpFloat:
+
sexpInt:
+
sexpListEnd:
+
sexpListStart:
+
sexpNil:
+
SexpNode:
+
SexpNodeKind:
+
SexpNodeObj:
+
SexpParser:
+
SexpParsingError:
+
sexpString:
+
sexpSymbol:
+
SFloat:
+
sgn:
+
Sha1Digest:
+
Sha1State:
+
Sha_224:
+
Sha_256:
+
Sha3_224:
+
Sha3_256:
+
Sha3_384:
+
Sha3_512:
+
Sha_384:
+
Sha3Digest_224:
+
Sha3Digest_256:
+
Sha3Digest_384:
+
Sha3Digest_512:
+
Sha3Instance:
+
Sha3State:
+
Sha3StateStatic:
+
Sha_512:
+
ShaDigest_224:
+
ShaDigest_256:
+
ShaDigest_384:
+
ShaDigest_512:
+
shadow:
+
ShadowRoot:
+
ShadowRootInit:
+
ShaInstance:
+
Shake128:
+
Shake256:
+
Shake512:
+
ShakeInstance:
+
shakeOut:
+
ShakeState:
+
shared object:
+
SharedList:
+
SharedTable:
+
ShaState:
+
ShaStateStatic:
+
shell command:
+
shellExecuteW:
+
shift:
+
shouldAcceptRequest:
+
showCursor:
+
shrink:
+
shuffle:
+
shutdown:
+
SID:
+
SID_IDENTIFIER_AUTHORITY:
+
sigil-like:
+
sign:
+
signal:
+
signalFence:
+
signalSysCond:
+
signatureHash:
+
signBit:
+
signbit:
+
significandMask:
+
significandSize:
+
signMask:
+
simple assertions:
+
simple statements:
+
sin:
+
since:
+
single assignment:
+
SingleTags:
+
SingleValueSetting:
+
SinglyLinkedList:
+
SinglyLinkedNode:
+
SinglyLinkedNodeObj:
+
SinglyLinkedRing:
+
sinh:
+
sink:
+
SInt:
+
SIO_GET_EXTENSION_FUNCTION_POINTER:
+
size:
+
sizeof:
+
skewness:
+
skewnessS:
+
skip:
+
skipDirs:
+
skipExt:
+
skipFiles:
+
skipIgnoreCase:
+
SKIPPED:
+
skipRandomNumbers:
+
skipRange:
+
SkipTable:
+
skipUntil:
+
skipWhile:
+
skipWhitespace:
+
sleep:
+
sleepAsync:
+
slice:
+
Slice:
+
slice:
+
SList:
+
slope:
+
slot:
+
SlotOptions:
+
slurp:
+
small:
+
smallest:
+
Smtp:
+
SNil:
+
SO_ACCEPTCONN:
+
SOBool:
+
SO_BROADCAST:
+
SockAddr:
+
Sockaddr_in:
+
Sockaddr_in6:
+
Sockaddr_storage:
+
SOCK_DGRAM:
+
Socket:
+
socket:
+
socketError:
+
SocketFlag:
+
SocketHandle:
+
SocketImpl:
+
SockLen:
+
SOCK_RAW:
+
SOCK_SEQPACKET:
+
SOCK_STREAM:
+
SockType:
+
SO_DEBUG:
+
SO_DONTLINGER:
+
SO_DONTROUTE:
+
SO_ERROR:
+
SO_EXCLUSIVEADDRUSE:
+
SO_KEEPALIVE:
+
SO_LINGER:
+
SOL_SOCKET:
+
SOMAXCONN:
+
some:
+
SomeFloat:
+
SomeInteger:
+
SomeLinkedCollection:
+
SomeLinkedList:
+
SomeLinkedNode:
+
SomeLinkedRing:
+
SomeNumber:
+
SomeOrdinal:
+
SomeSet:
+
SomeSignedInt:
+
SomeUnsignedInt:
+
SO_OOBINLINE:
+
SO_REUSEADDR:
+
SO_REUSEPORT:
+
sort:
+
sorted:
+
sortedByIt:
+
SortOrder:
+
SO_UPDATE_ACCEPT_CONTEXT:
+
source:
+
source files:
+
SourceLanguage:
+
sourceLanguageToAlpha:
+
sourceLanguageToStr:
+
SO_USELOOPBACK:
+
spaces:
+
span:
+
sparse bit set:
+
spawn:
+
spawnX:
+
splice:
+
split:
+
splitDecimal:
+
splitDrive:
+
splitFile:
+
splitLines:
+
splitPath:
+
splitWhitespace:
+
sql:
+
SQL injection attack:
+
SQLite:
+
SqlLexer:
+
SqlNode:
+
SqlNodeKind:
+
SqlNodeObj:
+
SqlParseError:
+
SqlParser:
+
SqlPrepared:
+
SqlQuery:
+
sqrt:
+
srcDir:
+
SslAcceptResult:
+
SslClientGetPskFunc:
+
SslContext:
+
SslCVerifyMode:
+
SslError:
+
sslHandle:
+
SslHandshakeType:
+
SslProtVersion:
+
SslServerGetPskFunc:
+
SString:
+
SSymbol:
+
StackOverflowDefect:
+
stackTraceAvailable:
+
StackTraceEntry:
+
standardDeviation:
+
standardDeviationS:
+
StandardFormatSpecifier:
+
start:
+
startAnchor:
+
STARTF_USESHOWWINDOW:
+
STARTF_USESTDHANDLES:
+
startProcess:
+
startsWith:
+
startsWithImpl:
+
startTls:
+
STARTUPINFO:
+
stat:
+
static error:
+
static type:
+
staticDirExists:
+
staticExec:
+
staticFileExists:
+
StaticParam:
+
staticRead:
+
Status:
+
StatusBar:
+
STATUS_PENDING:
+
stdcall:
+
stderr:
+
STD_ERROR_HANDLE:
+
stdin:
+
STD_INPUT_HANDLE:
+
stdmsg:
+
stdout:
+
STD_OUTPUT_HANDLE:
+
STILL_ACTIVE:
+
stop:
+
stopImmediatePropagation:
+
stopPropagation:
+
Storage:
+
StorageEvent:
+
store:
+
str:
+
strdefine:
+
Stream:
+
StreamObj:
+
string:
+
string interpolation:
+
stringify:
+
StringStream:
+
StringStreamObj:
+
StringTableMode:
+
StringTableObj:
+
StringTableRef:
+
strip:
+
stripGenericParams:
+
stripLineEnd:
+
strong:
+
Structured:
+
strVal:
+
strVal=:
+
StudyError:
+
Style:
+
style:
+
Style:
+
style-insensitive:
+
styleBlink:
+
styleBlinkRapid:
+
styleBright:
+
styledEcho:
+
styleDim:
+
styledWrite:
+
styledWriteLine:
+
styleHidden:
+
styleItalic:
+
styleReverse:
+
styleStrikethrough:
+
styleUnderscore:
+
sub:
+
submit:
+
substituteLog:
+
substitution:
+
substr:
+
succ:
+
success:
+
suite:
+
suiteEnded:
+
suiteStarted:
+
sum:
+
summary:
+
sup:
+
super:
+
supportsCopyMem:
+
suspend:
+
suspendThread:
+
swap:
+
swapCase:
+
swapEndian16:
+
swapEndian32:
+
swapEndian64:
+
switch:
+
SwitchToFiber:
+
SW_SHOWNORMAL:
+
symAddr:
+
symBodyHash:
+
symbol:
+
symbol=:
+
symbolName:
+
symbolRank:
+
symbols:
+
symKind:
+
symlinkExists:
+
symmetricDifference:
+
sync:
+
SYNCHRONIZE:
+
SyntaxError:
+
syscall:
+
SysCond:
+
SysLock:
+
SysLockAttr:
+
SysLockType_Reentrant:
+
system:
+
system.procCall:
+
SystemInfo:
+
SysThread:
+
table:
+
Table:
+
TableRef:
+
tabulator:
+
tag:
+
tag=:
+
tagA:
+
tagAbbr:
+
tagAcronym:
+
tagAddress:
+
tagApplet:
+
tagArea:
+
tagArticle:
+
tagAside:
+
tagAudio:
+
tagB:
+
tagBase:
+
tagBasefont:
+
tagBdi:
+
tagBdo:
+
tagBig:
+
tagBlockquote:
+
tagBody:
+
tagBr:
+
tagButton:
+
tagCanvas:
+
tagCaption:
+
tagCenter:
+
tagCite:
+
tagCode:
+
tagCol:
+
tagColgroup:
+
tagCommand:
+
tagDatalist:
+
tagDd:
+
tagDel:
+
tagDetails:
+
tagDfn:
+
tagDialog:
+
tagDir:
+
tagDiv:
+
tagDl:
+
tagDt:
+
tagEm:
+
tagEmbed:
+
tagFieldset:
+
tagFigcaption:
+
tagFigure:
+
tagFont:
+
tagFooter:
+
tagForm:
+
tagFrame:
+
tagFrameset:
+
tagH1:
+
tagH2:
+
tagH3:
+
tagH4:
+
tagH5:
+
tagH6:
+
tagHead:
+
tagHeader:
+
tagHgroup:
+
tagHr:
+
tagHtml:
+
tagI:
+
tagIframe:
+
tagImg:
+
tagInput:
+
tagIns:
+
tagIsindex:
+
tagKbd:
+
tagKeygen:
+
tagLabel:
+
tagLegend:
+
tagLi:
+
tagLink:
+
tagMap:
+
tagMark:
+
tagMenu:
+
tagMeta:
+
tagMeter:
+
tagNav:
+
tagNobr:
+
tagNoframes:
+
tagNoscript:
+
tagObject:
+
tagOl:
+
tagOptgroup:
+
tagOption:
+
tagOutput:
+
tagP:
+
tagParam:
+
tagPre:
+
tagProgress:
+
tagQ:
+
tagRp:
+
tagRt:
+
tagRuby:
+
tagS:
+
tagSamp:
+
tagScript:
+
tagSection:
+
tagSelect:
+
tagSmall:
+
tagSource:
+
tagSpan:
+
tagStrike:
+
tagStrong:
+
tagStyle:
+
tagSub:
+
tagSummary:
+
tagSup:
+
tagTable:
+
tagTbody:
+
tagTd:
+
tagTextarea:
+
tagTfoot:
+
tagTh:
+
tagThead:
+
tagTime:
+
tagTitle:
+
tagToStr:
+
tagTr:
+
tagTrack:
+
tagTt:
+
tagU:
+
tagUl:
+
tagUnknown:
+
tagVar:
+
tagVideo:
+
tagWbr:
+
tailDir:
+
take:
+
tan:
+
tanh:
+
task:
+
Task:
+
TAU:
+
tbody:
+
TCP_NODELAY:
+
td:
+
tearDownForeignThreadGc:
+
term:
+
termIgnoreCase:
+
termIgnoreStyle:
+
TerminalCmd:
+
terminalHeight:
+
terminalHeightIoctl:
+
terminalSize:
+
terminalWidth:
+
terminalWidthIoctl:
+
terminate:
+
terminateProcess:
+
test:
+
testAndSet:
+
testBit:
+
testEnded:
+
TestResult:
+
testStarted:
+
TestStatus:
+
text:
+
text=:
+
textarea:
+
TextAreaElement:
+
TextNode:
+
TFdSet:
+
Tfenv:
+
Tfexcept:
+
tfoot:
+
TFrame:
+
th:
+
thead:
+
then:
+
thiscall:
+
thisDir:
+
Thread:
+
thread-local:
+
ThreadId:
+
ThreadLocalStorage:
+
ThreadPoolAdvice:
+
ThreadPoolState:
+
ticks:
+
time:
+
Time:
+
TimeEffect:
+
timeEnd:
+
TimeFormat:
+
TimeFormatParseError:
+
TimeInterval:
+
TimeIntervalParts:
+
timeLog:
+
TimeOut:
+
TimeoutError:
+
TimeParseError:
+
Timespec:
+
timeStamp:
+
TimeUnit:
+
Timeval:
+
Timezone:
+
timezone:
+
timezone=:
+
title:
+
tkBracketLe:
+
tkBracketRi:
+
tkColon:
+
tkComma:
+
tkCurlyLe:
+
tkCurlyRi:
+
tkEof:
+
tkError:
+
tkFalse:
+
tkFloat:
+
tkInt:
+
tkNull:
+
tkString:
+
tkTrue:
+
TLineInfo:
+
TNimSymKinds:
+
TNimTypeKinds:
+
to:
+
toAny:
+
toBiggestFloat:
+
toBiggestInt:
+
toBin:
+
toCaseInsensitive:
+
toChars:
+
toCInt:
+
toCountTable:
+
toCritBitTree:
+
toCstring:
+
toDateString:
+
toDecimal64:
+
toDecimal64AsymmetricInterval:
+
toDeque:
+
toDll:
+
toDoublyLinkedList:
+
toDoublyLinkedRing:
+
toExe:
+
toFILETIME:
+
toFloat:
+
toggle:
+
toggleAttribute:
+
toHashSet:
+
toHeapQueue:
+
toHex:
+
toInt:
+
toIntSet:
+
toISOString:
+
toJs:
+
toJsKey:
+
toJSON:
+
toJson:
+
toJsonHook:
+
ToJsonOptions:
+
TokenClass:
+
tokenClassToStr:
+
tokenize:
+
TokKind:
+
toKnownDomain:
+
toLangSymbol:
+
toLocation:
+
toLower:
+
toLowerAscii:
+
toMask:
+
toMD5:
+
toNimIdent:
+
toNumber:
+
toOct:
+
toOctal:
+
ToolBar:
+
toOpenArray:
+
toOpenArrayByte:
+
toOpenArrayChar:
+
toOrderedSet:
+
toOrderedTable:
+
toOSFlags:
+
toPackedSet:
+
toParts:
+
toRational:
+
toRunes:
+
toSeq:
+
toSet:
+
toSigned:
+
toSinglyLinkedList:
+
toSinglyLinkedRing:
+
toSockAddr:
+
toSockType:
+
toString:
+
toStrLit:
+
toTable:
+
toTask:
+
toTime:
+
toTimeString:
+
toTitle:
+
Touch:
+
TouchEvent:
+
TouchList:
+
toUgly:
+
toUnix:
+
toUnixFloat:
+
toUnsigned:
+
toUpper:
+
toUpperAscii:
+
toUTCString:
+
toUTF8:
+
toWideCString:
+
toWinTime:
+
toXmlAttributes:
+
tr:
+
trace:
+
traced:
+
track:
+
trailingZeros2Digits:
+
transformFile:
+
translate:
+
traverseForIndex:
+
treeRepr:
+
trigger:
+
trimZeros:
+
trunc:
+
tryAcquire:
+
tryAcquireSys:
+
tryExec:
+
tryInsert:
+
tryInsertId:
+
tryInsertID:
+
tryMoveFSObject:
+
tryRemoveFile:
+
trySend:
+
tt:
+
tuple unpacking:
+
tupleLen:
+
tupleObjectDollar:
+
TWSABuf:
+
type:
+
type casts:
+
type constraints:
+
type conversions:
+
type parameters:
+
type suffix:
+
type variable:
+
typed:
+
typedesc:
+
typeKind:
+
typeof:
+
typeOfIter:
+
TypeOfMode:
+
typeOfProc:
+
u:
+
UIEvent:
+
uint:
+
uint16:
+
uint32:
+
Uint32Array:
+
uint64:
+
uint64x2:
+
uint8:
+
Uint8Array:
+
ul:
+
ULONG:
+
ULONG_PTR:
+
Uname:
+
uname:
+
unchecked runtime error:
+
UncheckedArray:
+
underscoredCalls:
+
unescape:
+
unhandledExceptionHook:
+
unicode codepoint:
+
unicode codepoint with hex value HHHH:
+
unicodeLetter:
+
unicodeLower:
+
unicodeTitle:
+
unicodeUpper:
+
unicodeWhitespace:
+
unidecode:
+
unindent:
+
union:
+
units:
+
unixToNativePath:
+
unlikely:
+
unlink:
+
unloadLib:
+
unmapMem:
+
unmapViewOfFile:
+
Unmarshals:
+
unown:
+
UnpackDefect:
+
UnpackError:
+
unpackInfix:
+
unpackPostfix:
+
unpackPrefix:
+
unpackVarargs:
+
unquoteIndexColumn:
+
unregister:
+
unregisterWait:
+
unresolved:
+
unsafeAddr:
+
unsafeColumnAt:
+
unsafeGet:
+
unsafeIsolate:
+
unsafeNew:
+
unsafeNewFetchOptions:
+
unsafeRead:
+
unsetControlCHook:
+
unsigned integer:
+
Unstructured:
+
untraced:
+
untyped:
+
unzip:
+
update:
+
updateHandle:
+
upperBound:
+
UppercaseLetters:
+
urandom:
+
Uri:
+
UriParseError:
+
uriParseError:
+
Url:
+
useEmpty:
+
useEnvironment:
+
useKey:
+
useRealtimeGC:
+
UTC:
+
utc:
+
utcOffset:
+
utcOffset=:
+
Utf16Char:
+
utf8:
+
utoa2Digits:
+
utoa8DigitsSkipTrailingZeros:
+
validateData:
+
validateUtf8:
+
validIdentifier:
+
ValidityState:
+
value:
+
value=:
+
ValueError:
+
values:
+
valuesWithPrefix:
+
ValueType:
+
varargs:
+
varargsLen:
+
variance:
+
varianceS:
+
verboseFmtStr:
+
verify:
+
version:
+
vertical tabulator:
+
vibrate:
+
video:
+
VisualViewport:
+
visualViewport:
+
vmTrace:
+
void:
+
volatileLoad:
+
volatileStore:
+
wait:
+
WAIT_FAILED:
+
waitFor:
+
waitForExit:
+
waitForMultipleObjects:
+
waitForSingleObject:
+
WAIT_OBJECT_0:
+
WAITORTIMERCALLBACK:
+
waitSysCond:
+
WAIT_TIMEOUT:
+
walkDir:
+
walkDirRec:
+
walkDirRecFilter:
+
walkDirs:
+
walkFiles:
+
walkPattern:
+
warn:
+
warning:
+
warningStr:
+
wasMoved:
+
wbr:
+
web:
+
WeekDay:
+
weekday:
+
weekday=:
+
Weeks:
+
weeks:
+
weirdTarget:
+
whichMsgClass:
+
whitespace:
+
Whitespace:
+
wide strings:
+
WideCString:
+
WideCStringObj:
+
widening type conversion:
+
WIN32_FIND_DATA:
+
WINBOOL:
+
WinChar:
+
Window:
+
window:
+
WinSizeT:
+
with:
+
withData:
+
withDir:
+
withKey:
+
withLock:
+
withRLock:
+
withTimeout:
+
withValue:
+
WOHandleArray:
+
wrapConnectedSocket:
+
wrapSocket:
+
wrapToInt:
+
wrapToUint:
+
wrapWords:
+
write:
+
writeBuffer:
+
writeBytes:
+
writeChars:
+
writeConfig:
+
writeContentType:
+
writeData:
+
WriteDbEffect:
+
WriteDirEffect:
+
WriteEnvEffect:
+
writeErrorMessage:
+
writeFile:
+
writeFloatToBuffer:
+
writeFloatToBufferRoundtrip:
+
writeFloatToBufferSprintf:
+
writeFromStream:
+
writeIndexFile:
+
WriteIOEffect:
+
writeLine:
+
writeln:
+
WriteSocketStream:
+
WriteSocketStreamObj:
+
writeStackTrace:
+
writeStyled:
+
writeVu64:
+
wsaCloseEvent:
+
wsaCreateEvent:
+
WSAData:
+
WSADESCRIPTION_LEN:
+
WSAEADDRINUSE:
+
WSAECONNABORTED:
+
WSAECONNRESET:
+
WSAEDISCON:
+
WSAEINPROGRESS:
+
WSAEINTR:
+
WSAENETRESET:
+
WSAENOTSOCK:
+
WSAESHUTDOWN:
+
WSAETIMEDOUT:
+
wsaEventSelect:
+
WSAEWOULDBLOCK:
+
wsaGetLastError:
+
WSAID_ACCEPTEX:
+
WSAID_CONNECTEX:
+
WSAID_GETACCEPTEXSOCKADDRS:
+
WSAIoctl:
+
WSAIORW:
+
WSANOTINITIALISED:
+
WSAPROC_ACCEPTEX:
+
WSAPROC_CONNECTEX:
+
WSAPROC_GETACCEPTEXSOCKADDRS:
+
WSARecv:
+
WSARecvFrom:
+
wsaResetEvent:
+
WSASend:
+
WSASendTo:
+
wsaStartup:
+
WSASYS_STATUS_LEN:
+
WT_EXECUTEDEFAULT:
+
WT_EXECUTEINIOTHREAD:
+
WT_EXECUTEINPERSISTENTIOTHREAD:
+
WT_EXECUTEINPERSISTENTTHREAD:
+
WT_EXECUTEINTIMERTHREAD:
+
WT_EXECUTEINUITHREAD:
+
WT_EXECUTEINWAITTHREAD:
+
WT_EXECUTELONGFUNCTION:
+
WT_EXECUTEONLYONCE:
+
WT_TRANSFER_IMPERSONATION:
+
XML:
+
xmlAttribute:
+
XmlAttributes:
+
xmlCData:
+
xmlCharData:
+
xmlCheckedTag:
+
xmlComment:
+
xmlElementClose:
+
xmlElementEnd:
+
xmlElementOpen:
+
xmlElementStart:
+
xmlEncode:
+
xmlEntity:
+
xmlEof:
+
xmlError:
+
XmlError:
+
XmlErrorKind:
+
XmlEventKind:
+
xmlHeader:
+
XmlNode:
+
XmlNodeKind:
+
XmlParseOption:
+
XmlParser:
+
xmlPI:
+
xmlSpecial:
+
xmlWhitespace:
+
xnCData:
+
xnComment:
+
xnElement:
+
xnEntity:
+
xnText:
+
xnVerbatimText:
+
year:
+
year=:
+
yearday:
+
yearday=:
+
YeardayRange:
+
Years:
+
years:
+
zeroDefault:
+
zeroMem:
+
zip:
+
ZonedTime:
+
zonedTimeFromAdjTime:
+
zonedTimeFromTime:
+
+ +
+
+ + + diff --git a/threadpool.html b/threadpool.html new file mode 100644 index 0000000000000..f403419eb1ccc --- /dev/null +++ b/threadpool.html @@ -0,0 +1,476 @@ + + + + + + + +std/threadpool + + + + + + + + + + + + + + + + +
+
+

std/threadpool

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+
+ Deprecated: use the nimble packages `malebolgia`, `taskpools` or `weave` instead +
+ +

Implements Nim's parallel & spawn statements.

+

Unstable API.

+ +

See also

+

+ +
+

Types

+
+
+
FlowVar[T] {.compilerproc.} = ref FlowVarObj[T]
+
+ + A data flow variable. + Source   +Edit   + +
+
+
+
FlowVarBase = ref FlowVarBaseObj
+
+ + Untyped base class for FlowVar[T]. + Source   +Edit   + +
+
+
+
ThreadId = range[0 .. MaxDistinguishedThread - 1]
+
+ + A thread identifier. + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
MaxDistinguishedThread {.intdefine.} = 32
+
+ + Maximum number of "distinguished" threads. + Source   +Edit   + +
+
+
+
MaxThreadPoolSize {.intdefine.} = 256
+
+ + Maximum size of the thread pool. 256 threads should be good enough for anybody ;-) + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `^`[T](fv: FlowVar[T]): T
+
+ + Blocks until the value is available and then returns this value. + Source   +Edit   + +
+
+ +
+
+
+
proc awaitAndThen[T](fv: FlowVar[T]; action: proc (x: T) {.closure.})
+
+ +

Blocks until fv is available and then passes its value to action.

+

Note that due to Nim's parameter passing semantics, this means that T doesn't need to be copied, so awaitAndThen can sometimes be more efficient than the ^ proc.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc blockUntil(fv: var FlowVarBaseObj) {....raises: [], tags: [], forbids: [].}
+
+ +

Waits until the value for fv arrives.

+

Usually it is not necessary to call this explicitly.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc blockUntilAny(flowVars: openArray[FlowVarBase]): int {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Awaits any of the given flowVars. Returns the index of one flowVar for which a value arrived.

+

A flowVar only supports one call to blockUntilAny at the same time. That means if you blockUntilAny([a,b]) and blockUntilAny([b,c]) the second call will only block until c. If there is no flowVar left to be able to wait on, -1 is returned.

+

Note: This results in non-deterministic behaviour and should be avoided.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc isReady(fv: FlowVarBase): bool {....raises: [], tags: [], forbids: [].}
+
+ +

Determines whether the specified FlowVarBase's value is available.

+

If true, awaiting fv will not block.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc parallel(body: untyped) {.magic: "Parallel", ...raises: [], tags: [],
+                               forbids: [].}
+
+ +

A parallel section can be used to execute a block in parallel.

+

body has to be in a DSL that is a particular subset of the language.

+

Please refer to the manual for further information.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc pinnedSpawn(id: ThreadId; call: sink typed) {.magic: "Spawn", ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Always spawns a new task on the worker thread with id, so that the call is always executed on the thread.

+

call has to be a proc call p(...) where p is gcsafe and has a return type that is either void or compatible with FlowVar[T].

+ + Source   +Edit   + +
+
+ +
+
+
+
proc preferSpawn(): bool {....raises: [], tags: [], forbids: [].}
+
+ +

Use this proc to determine quickly if a spawn or a direct call is preferable.

+

If it returns true, a spawn may make sense. In general it is not necessary to call this directly; use the spawnX template instead.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc setMaxPoolSize(size: range[1 .. MaxThreadPoolSize]) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Sets the maximum thread pool size. The default value of this is MaxThreadPoolSize. + Source   +Edit   + +
+
+ +
+
+
+
proc setMinPoolSize(size: range[1 .. MaxThreadPoolSize]) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Sets the minimum thread pool size. The default value of this is 4. + Source   +Edit   + +
+
+ +
+
+
+
proc spawn(call: sink typed) {.magic: "Spawn", ...raises: [], tags: [], forbids: [].}
+
+ +

Always spawns a new task, so that the call is never executed on the calling thread.

+

call has to be a proc call p(...) where p is gcsafe and has a return type that is either void or compatible with FlowVar[T].

+ + Source   +Edit   + +
+
+ +
+
+
+
proc sync() {....raises: [], tags: [TimeEffect], forbids: [].}
+
+ +

A simple barrier to wait for all spawned tasks.

+

If you need more elaborate waiting, you have to use an explicit barrier.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc unsafeRead[T](fv: FlowVar[ref T]): ptr T
+
+ + Blocks until the value is available and then returns this value. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template spawnX(call)
+
+ +

Spawns a new task if a CPU core is ready, otherwise executes the call in the calling thread.

+

Usually, it is advised to use the spawn proc in order to not block the producer for an unknown amount of time.

+

call has to be a proc call p(...) where p is gcsafe and has a return type that is either 'void' or compatible with FlowVar[T].

+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/threadpool.idx b/threadpool.idx new file mode 100644 index 0000000000000..802a9073fdba6 --- /dev/null +++ b/threadpool.idx @@ -0,0 +1,21 @@ +nimTitle threadpool threadpool.html module std/threadpool 0 +nim FlowVarBase threadpool.html#FlowVarBase type FlowVarBase 106 +nim FlowVar threadpool.html#FlowVar type FlowVar 119 +nim blockUntil threadpool.html#blockUntil,FlowVarBaseObj proc blockUntil(fv: var FlowVarBaseObj) 142 +nim awaitAndThen threadpool.html#awaitAndThen,FlowVar[T],proc(T) proc awaitAndThen[T](fv: FlowVar[T]; action: proc (x: T) {.closure.}) 234 +nim unsafeRead threadpool.html#unsafeRead,FlowVar[ref.T] proc unsafeRead[T](fv: FlowVar[ref T]): ptr T 252 +nim `^` threadpool.html#^,FlowVar[T] proc `^`[T](fv: FlowVar[T]): T 261 +nim blockUntilAny threadpool.html#blockUntilAny,openArray[FlowVarBase] proc blockUntilAny(flowVars: openArray[FlowVarBase]): int 270 +nim isReady threadpool.html#isReady,FlowVarBase proc isReady(fv: FlowVarBase): bool 299 +nim MaxThreadPoolSize threadpool.html#MaxThreadPoolSize const MaxThreadPoolSize 315 +nim MaxDistinguishedThread threadpool.html#MaxDistinguishedThread const MaxDistinguishedThread 317 +nim ThreadId threadpool.html#ThreadId type ThreadId 320 +nim setMinPoolSize threadpool.html#setMinPoolSize,range[] proc setMinPoolSize(size: range[1 .. MaxThreadPoolSize]) 401 +nim setMaxPoolSize threadpool.html#setMaxPoolSize,range[] proc setMaxPoolSize(size: range[1 .. MaxThreadPoolSize]) 405 +nim preferSpawn threadpool.html#preferSpawn proc preferSpawn(): bool 446 +nim spawn threadpool.html#spawn,sinktyped proc spawn(call: sink typed) 455 +nim pinnedSpawn threadpool.html#pinnedSpawn,ThreadId,sinktyped proc pinnedSpawn(id: ThreadId; call: sink typed) 463 +nim spawnX threadpool.html#spawnX.t template spawnX(call) 471 +nim parallel threadpool.html#parallel,untyped proc parallel(body: untyped) 482 +nim sync threadpool.html#sync proc sync() 591 +heading See also threadpool.html#see-also See also 0 diff --git a/threadtypes.html b/threadtypes.html new file mode 100644 index 0000000000000..f31a1ff8ff664 --- /dev/null +++ b/threadtypes.html @@ -0,0 +1,508 @@ + + + + + + + +std/private/threadtypes + + + + + + + + + + + + + + + + +
+
+

std/private/threadtypes

+
+ +
+ Source   +Edit   + +
+ +

+
+

Types

+
+
+
CpuSet {.importc: "cpu_set_t", header: "#define _GNU_SOURCE\n#include <sched.h>".} = object
+  when defined(linux) and defined(amd64):
+
+ + + Source   +Edit   + +
+
+
+
GcThread {.pure, inheritable.} = object
+  when emulatedThreadVars:
+    tls*: ThreadLocalStorage
+  else:
+    nil
+  when hasSharedHeap:
+    next*, prev*: PGcThread
+    stackBottom*, stackTop*: pointer
+    stackSize*: int
+  else:
+    nil
+
+ + + Source   +Edit   + +
+
+
+
PGcThread = ptr GcThread
+
+ + + Source   +Edit   + +
+
+
+
Pthread_attr {.importc: "pthread_attr_t", header: "<sys/types.h>".} = object
+
+ + + Source   +Edit   + +
+
+
+
SysThread {.importc: "pthread_t", header: "<sys/types.h>".} = distinct culong
+
+ + + Source   +Edit   + +
+
+
+
Thread[TArg] = object
+  core*: PGcThread
+  sys*: SysThread
+  when TArg is void:
+    dataFn*: proc () {.nimcall, ...gcsafe.}
+  else:
+    dataFn*: proc (m: TArg) {.nimcall, ...gcsafe.}
+    data*: TArg
+  when hasAllocStack:
+    rawStack*: pointer
+
+ + + Source   +Edit   + +
+
+
+
ThreadLocalStorage = array[0 .. (nimTlsSize div 8), float]
+
+ + + Source   +Edit   + +
+
+
+
Timespec {.importc: "struct timespec", header: "<time.h>".} = object
+  tv_sec*: Time
+  tv_nsec*: clong
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
emulatedThreadVars = false
+
+ + + Source   +Edit   + +
+
+
+
hasAllocStack = false
+
+ + + Source   +Edit   + +
+
+
+
hasSharedHeap = false
+
+ + + Source   +Edit   + +
+
+
+
pthreadh = "#define _GNU_SOURCE\n#include <pthread.h>"
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `=copy`[TArg](x: var Thread[TArg]; y: Thread[TArg]) {.error.}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cpusetIncl(cpu: cint; s: var CpuSet) {.importc: "CPU_SET",
+    header: "#define _GNU_SOURCE\n#include <sched.h>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc cpusetZero(s: var CpuSet) {.importc: "CPU_ZERO", header: "#define _GNU_SOURCE\n#include <sched.h>",
+                                 ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_destroy(a1: var Pthread_attr): cint {.importc,
+    header: "#define _GNU_SOURCE\n#include <pthread.h>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_init(a1: var Pthread_attr): cint {.importc,
+    header: "#define _GNU_SOURCE\n#include <pthread.h>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_setstack(a1: ptr Pthread_attr; a2: pointer; a3: int): cint {.
+    importc, header: "#define _GNU_SOURCE\n#include <pthread.h>", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_attr_setstacksize(a1: var Pthread_attr; a2: int): cint {.importc,
+    header: "#define _GNU_SOURCE\n#include <pthread.h>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_cancel(a1: SysThread): cint {.importc: "pthread_cancel",
+    header: "#define _GNU_SOURCE\n#include <pthread.h>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_create(a1: var SysThread; a2: var Pthread_attr;
+                    a3: proc (x: pointer): pointer {.noconv.}; a4: pointer): cint {.
+    importc: "pthread_create",
+    header: "#define _GNU_SOURCE\n#include <pthread.h>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc pthread_join(a1: SysThread; a2: ptr pointer): cint {.importc,
+    header: "#define _GNU_SOURCE\n#include <pthread.h>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setAffinity(thread: SysThread; setsize: csize_t; s: var CpuSet) {.
+    importc: "pthread_setaffinity_np",
+    header: "#define _GNU_SOURCE\n#include <pthread.h>", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/threadtypes.idx b/threadtypes.idx new file mode 100644 index 0000000000000..9794b19ce3916 --- /dev/null +++ b/threadtypes.idx @@ -0,0 +1,24 @@ +nimTitle threadtypes threadtypes.html module std/private/threadtypes 0 +nim hasSharedHeap threadtypes.html#hasSharedHeap const hasSharedHeap 3 +nim pthreadh threadtypes.html#pthreadh const pthreadh 65 +nim SysThread threadtypes.html#SysThread type SysThread 76 +nim Pthread_attr threadtypes.html#Pthread_attr object Pthread_attr 78 +nim Timespec threadtypes.html#Timespec object Timespec 91 +nim pthread_attr_init threadtypes.html#pthread_attr_init,Pthread_attr proc pthread_attr_init(a1: var Pthread_attr): cint 95 +nim pthread_attr_setstack threadtypes.html#pthread_attr_setstack,ptr.Pthread_attr,pointer,int proc pthread_attr_setstack(a1: ptr Pthread_attr; a2: pointer; a3: int): cint 97 +nim pthread_attr_setstacksize threadtypes.html#pthread_attr_setstacksize,Pthread_attr,int proc pthread_attr_setstacksize(a1: var Pthread_attr; a2: int): cint 99 +nim pthread_attr_destroy threadtypes.html#pthread_attr_destroy,Pthread_attr proc pthread_attr_destroy(a1: var Pthread_attr): cint 101 +nim pthread_create threadtypes.html#pthread_create,SysThread,Pthread_attr,proc(pointer),pointer proc pthread_create(a1: var SysThread; a2: var Pthread_attr;\n a3: proc (x: pointer): pointer {.noconv.}; a4: pointer): cint 104 +nim pthread_join threadtypes.html#pthread_join,SysThread,ptr.pointer proc pthread_join(a1: SysThread; a2: ptr pointer): cint 108 +nim pthread_cancel threadtypes.html#pthread_cancel,SysThread proc pthread_cancel(a1: SysThread): cint 111 +nim CpuSet threadtypes.html#CpuSet object CpuSet 114 +nim cpusetZero threadtypes.html#cpusetZero,CpuSet proc cpusetZero(s: var CpuSet) 118 +nim cpusetIncl threadtypes.html#cpusetIncl,cint,CpuSet proc cpusetIncl(cpu: cint; s: var CpuSet) 119 +nim setAffinity threadtypes.html#setAffinity,SysThread,csize_t,CpuSet proc setAffinity(thread: SysThread; setsize: csize_t; s: var CpuSet) 137 +nim emulatedThreadVars threadtypes.html#emulatedThreadVars const emulatedThreadVars 142 +nim ThreadLocalStorage threadtypes.html#ThreadLocalStorage type ThreadLocalStorage 148 +nim PGcThread threadtypes.html#PGcThread type PGcThread 149 +nim GcThread threadtypes.html#GcThread object GcThread 150 +nim hasAllocStack threadtypes.html#hasAllocStack const hasAllocStack 162 +nim Thread threadtypes.html#Thread object Thread 165 +nim `=copy` threadtypes.html#=copy,Thread[TArg],Thread[TArg] proc `=copy`[TArg](x: var Thread[TArg]; y: Thread[TArg]) 176 diff --git a/time_t.html b/time_t.html new file mode 100644 index 0000000000000..e987e94a629e3 --- /dev/null +++ b/time_t.html @@ -0,0 +1,105 @@ + + + + + + + +std/time_t + + + + + + + + + + + + + + + + +
+
+

std/time_t

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
+

Types

+
+
+
Time = Impl
+
+ + +Wrapper for time_t. On posix, this is an alias to posix.Time. + Source   +Edit   + +
+
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/time_t.idx b/time_t.idx new file mode 100644 index 0000000000000..4bb33cd382466 --- /dev/null +++ b/time_t.idx @@ -0,0 +1,2 @@ +nimTitle time_t time_t.html module std/time_t 0 +nim Time time_t.html#Time type Time 13 diff --git a/times.html b/times.html new file mode 100644 index 0000000000000..a709a15460f56 --- /dev/null +++ b/times.html @@ -0,0 +1,3409 @@ + + + + + + + +std/times + + + + + + + + + + + + + + + + +
+
+

std/times

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

The times module contains routines and types for dealing with time using the proleptic Gregorian calendar. It's also available for the JavaScript target.

+

Although the times module supports nanosecond time resolution, the resolution used by getTime() depends on the platform and backend (JS is limited to millisecond precision).

+ +

Examples

import std/[times, os]
+# Simple benchmarking
+let time = cpuTime()
+sleep(100) # Replace this with something to be timed
+echo "Time taken: ", cpuTime() - time
+
+# Current date & time
+let now1 = now()     # Current timestamp as a DateTime in local time
+let now2 = now().utc # Current timestamp as a DateTime in UTC
+let now3 = getTime() # Current timestamp as a Time
+
+# Arithmetic using Duration
+echo "One hour from now      : ", now() + initDuration(hours = 1)
+# Arithmetic using TimeInterval
+echo "One year from now      : ", now() + 1.years
+echo "One month from now     : ", now() + 1.months

+ +

Parsing and Formatting Dates

The DateTime type can be parsed and formatted using the different parse and format procedures.

+

let dt = parse("2000-01-01", "yyyy-MM-dd")
+echo dt.format("yyyy-MM-dd")

+

The different format patterns that are supported are documented below.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PatternDescriptionExample
dNumeric value representing the day of the month, it will be either one or two digits long.

1/04/2012 -> 1
21/04/2012 -> 21

ddSame as above, but is always two digits.

1/04/2012 -> 01
21/04/2012 -> 21

dddThree letter string which indicates the day of the week.

Saturday -> Sat
Monday -> Mon

ddddFull string for the day of the week.

Saturday -> Saturday
Monday -> Monday

GGThe last two digits of the Iso Week-Year

30/12/2012 -> 13

GGGGThe Iso week-calendar year padded to four digits

30/12/2012 -> 2013

hThe hours in one digit if possible. Ranging from 1-12.

5pm -> 5
2am -> 2

hhThe hours in two digits always. If the hour is one digit, 0 is prepended.

5pm -> 05
11am -> 11

HThe hours in one digit if possible, ranging from 0-23.

5pm -> 17
2am -> 2

HHThe hours in two digits always. 0 is prepended if the hour is one digit.

5pm -> 17
2am -> 02

mThe minutes in one digit if possible.

5:30 -> 30
2:01 -> 1

mmSame as above but always two digits, 0 is prepended if the minute is one digit.

5:30 -> 30
2:01 -> 01

MThe month in one digit if possible.

September -> 9
December -> 12

MMThe month in two digits always. 0 is prepended if the month value is one digit.

September -> 09
December -> 12

MMMAbbreviated three-letter form of the month.

September -> Sep
December -> Dec

MMMMFull month string, properly capitalized.

September -> September

sSeconds as one digit if possible.

00:00:06 -> 6

ssSame as above but always two digits. 0 is prepended if the second is one digit.

00:00:06 -> 06

tA when time is in the AM. P when time is in the PM.

5pm -> P
2am -> A

ttSame as above, but AM and PM instead of A and P respectively.

5pm -> PM
2am -> AM

yyThe last two digits of the year. When parsing, the current century is assumed.

2012 AD -> 12

yyyyThe year, padded to at least four digits. Is always positive, even when the year is BC. When the year is more than four digits, '+' is prepended.

2012 AD -> 2012
24 AD -> 0024
24 BC -> 00024
12345 AD -> +12345

YYYYThe year without any padding. Is always positive, even when the year is BC.

2012 AD -> 2012
24 AD -> 24
24 BC -> 24
12345 AD -> 12345

uuuuThe year, padded to at least four digits. Will be negative when the year is BC. When the year is more than four digits, '+' is prepended unless the year is BC.

2012 AD -> 2012
24 AD -> 0024
24 BC -> -0023
12345 AD -> +12345

UUUUThe year without any padding. Will be negative when the year is BC.

2012 AD -> 2012
24 AD -> 24
24 BC -> -23
12345 AD -> 12345

VThe Iso Week-Number as one or two digits

3/2/2012 -> 5
1/4/2012 -> 13

VVThe Iso Week-Number as two digits always. 0 is prepended if one digit.

3/2/2012 -> 05
1/4/2012 -> 13

zDisplays the timezone offset from UTC.

UTC+7 -> +7
UTC-5 -> -5

zzSame as above but with leading 0.

UTC+7 -> +07
UTC-5 -> -05

zzzSame as above but with :mm where mm represents minutes.

UTC+7 -> +07:00
UTC-5 -> -05:00

ZZZSame as above but with mm where mm represents minutes.

UTC+7 -> +0700
UTC-5 -> -0500

zzzzSame as above but with :ss where ss represents seconds.

UTC+7 -> +07:00:00
UTC-5 -> -05:00:00

ZZZZSame as above but with ss where ss represents seconds.

UTC+7 -> +070000
UTC-5 -> -050000

gEra: AD or BC

300 AD -> AD
300 BC -> BC

fffMilliseconds display

1000000 nanoseconds -> 1

ffffffMicroseconds display

1000000 nanoseconds -> 1000

fffffffffNanoseconds display

1000000 nanoseconds -> 1000000

Other strings can be inserted by putting them in ''. For example hh'->'mm will give 01->56. In addition to spaces, the following characters can be inserted without quoting them: : - , . ( ) / [ ]. A literal ' can be specified with ''.

+

However you don't need to necessarily separate format patterns, as an unambiguous format string like yyyyMMddhhmmss is also valid (although only for years in the range 1..9999).

+ +

Duration vs TimeInterval

The times module exports two similar types that are both used to represent some amount of time: Duration and TimeInterval. This section explains how they differ and when one should be preferred over the other (short answer: use Duration unless support for months and years is needed).

+ +

Duration

A Duration represents a duration of time stored as seconds and nanoseconds. A Duration is always fully normalized, so initDuration(hours = 1) and initDuration(minutes = 60) are equivalent.

+

Arithmetic with a Duration is very fast, especially when used with the Time type, since it only involves basic arithmetic. Because Duration is more performant and easier to understand it should generally preferred.

+ +

TimeInterval

A TimeInterval represents an amount of time expressed in calendar units, for example "1 year and 2 days". Since some units cannot be normalized (the length of a year is different for leap years for example), the TimeInterval type uses separate fields for every unit. The TimeInterval's returned from this module generally don't normalize anything, so even units that could be normalized (like seconds, milliseconds and so on) are left untouched.

+

Arithmetic with a TimeInterval can be very slow, because it requires timezone information.

+

Since it's slower and more complex, the TimeInterval type should be avoided unless the program explicitly needs the features it offers that Duration doesn't have.

+ +

How long is a day?

It should be especially noted that the handling of days differs between TimeInterval and Duration. The Duration type always treats a day as exactly 86400 seconds. For TimeInterval, it's more complex.

+

As an example, consider the amount of time between these two timestamps, both in the same timezone:

+
  • 2018-03-25T12:00+02:00
  • +
  • 2018-03-26T12:00+01:00
  • +
+

If only the date & time is considered, it appears that exactly one day has passed. However, the UTC offsets are different, which means that the UTC offset was changed somewhere in between. This happens twice each year for timezones that use daylight savings time. Because of this change, the amount of time that has passed is actually 25 hours.

+

The TimeInterval type uses calendar units, and will say that exactly one day has passed. The Duration type on the other hand normalizes everything to seconds, and will therefore say that 90000 seconds has passed, which is the same as 25 hours.

+ +

See also

+

+ +
+

Types

+
+
+
DateTime = object of RootObj
+
+ + +Represents a time in different parts. Although this type can represent leap seconds, they are generally not supported in this module. They are not ignored, but the DateTime's returned by procedures in this module will never have a leap second. + Source   +Edit   + +
+
+
+
DateTimeLocale = object
+  MMM*: array[mJan .. mDec, string]
+  MMMM*: array[mJan .. mDec, string]
+  ddd*: array[dMon .. dSun, string]
+  dddd*: array[dMon .. dSun, string]
+
+ + + Source   +Edit   + +
+
+
+
Duration = object
+
+ +

Represents a fixed duration of time, meaning a duration that has constant length independent of the context.

+

To create a new Duration, use initDuration. Instead of trying to access the private attributes, use inSeconds for converting to seconds and inNanoseconds for converting to nanoseconds.

+ + Source   +Edit   + +
+
+
+
DurationParts = array[FixedTimeUnit, int64]
+
+ + + Source   +Edit   + +
+
+
+
FixedTimeUnit = range[Nanoseconds .. Weeks]
+
+ + +Subrange of TimeUnit that only includes units of fixed duration. These are the units that can be represented by a Duration. + Source   +Edit   + +
+
+
+
HourRange = range[0 .. 23]
+
+ + + Source   +Edit   + +
+
+
+
IsoWeekRange = range[1 .. 53]
+
+ + An ISO 8601 calendar week number. + Source   +Edit   + +
+
+
+
IsoYear = distinct int
+
+ + An ISO 8601 calendar year number.
Warning: +The ISO week-based year can correspond to the following or previous year from 29 December to January 3.
+ + Source   +Edit   + +
+
+
+
MinuteRange = range[0 .. 59]
+
+ + + Source   +Edit   + +
+
+
+
Month = enum
+  mJan = (1, "January"), mFeb = "February", mMar = "March", mApr = "April",
+  mMay = "May", mJun = "June", mJul = "July", mAug = "August",
+  mSep = "September", mOct = "October", mNov = "November", mDec = "December"
+
+ + Represents a month. Note that the enum starts at 1, so ord(month) will give the month number in the range 1..12. + Source   +Edit   + +
+
+
+
MonthdayRange = range[1 .. 31]
+
+ + + Source   +Edit   + +
+
+
+
NanosecondRange = range[0 .. 999999999]
+
+ + + Source   +Edit   + +
+
+
+
SecondRange = range[0 .. 60]
+
+ + +Includes the value 60 to allow for a leap second. Note however that the second of a DateTime will never be a leap second. + Source   +Edit   + +
+
+
+
Time = object
+
+ + Represents a point in time. + Source   +Edit   + +
+
+
+
TimeFormat = object
+  ## \
+  ## Contains the patterns encoded as bytes.
+  ## Literal values are encoded in a special way.
+  ## They start with `Lit.byte`, then the length of the literal, then the
+  ## raw char values of the literal. For example, the literal `foo` would
+  ## be encoded as `@[Lit.byte, 3.byte, 'f'.byte, 'o'.byte, 'o'.byte]`.
+
+ +

Represents a format for parsing and printing time types.

+

To create a new TimeFormat use initTimeFormat proc.

+ + Source   +Edit   + +
+
+
+
TimeFormatParseError = object of ValueError
+
+ + +Raised when parsing a TimeFormat string fails. + Source   +Edit   + +
+
+
+
TimeInterval = object
+  nanoseconds*: int          ## The number of nanoseconds
+  microseconds*: int         ## The number of microseconds
+  milliseconds*: int         ## The number of milliseconds
+  seconds*: int              ## The number of seconds
+  minutes*: int              ## The number of minutes
+  hours*: int                ## The number of hours
+  days*: int                 ## The number of days
+  weeks*: int                ## The number of weeks
+  months*: int               ## The number of months
+  years*: int                ## The number of years
+
+ +

+Represents a non-fixed duration of time. Can be used to add and subtract non-fixed time units from a DateTime or Time.

+

Create a new TimeInterval with initTimeInterval proc.

+

Note that TimeInterval doesn't represent a fixed duration of time, since the duration of some units depend on the context (e.g a year can be either 365 or 366 days long). The non-fixed time units are years, months, days and week.

+

Note that TimeInterval's returned from the times module are never normalized. If you want to normalize a time unit, Duration should be used instead.

+ + Source   +Edit   + +
+
+
+
TimeIntervalParts = array[TimeUnit, int]
+
+ + + Source   +Edit   + +
+
+
+
TimeParseError = object of ValueError
+
+ + +Raised when parsing input using a TimeFormat fails. + Source   +Edit   + +
+
+
+
TimeUnit = enum
+  Nanoseconds, Microseconds, Milliseconds, Seconds, Minutes, Hours, Days, Weeks,
+  Months, Years
+
+ + Different units of time. + Source   +Edit   + +
+
+
+
Timezone = ref object
+
+ + +Timezone interface for supporting DateTimes of arbitrary timezones. The times module only supplies implementations for the system's local time and UTC. + Source   +Edit   + +
+
+
+
WeekDay = enum
+  dMon = "Monday", dTue = "Tuesday", dWed = "Wednesday", dThu = "Thursday",
+  dFri = "Friday", dSat = "Saturday", dSun = "Sunday"
+
+ + Represents a weekday. + Source   +Edit   + +
+
+
+
YeardayRange = range[0 .. 365]
+
+ + + Source   +Edit   + +
+
+
+
ZonedTime = object
+  time*: Time                ## The point in time being represented.
+  utcOffset*: int            ## The offset in seconds west of UTC,
+                             ## including any offset due to DST.
+  isDst*: bool               ## Determines whether DST is in effect.
+
+ + Represents a point in time with an associated UTC offset and DST flag. This type is only used for implementing timezones. + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
DefaultLocale = (MMM: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
+                       "Sep", "Oct", "Nov", "Dec"], MMMM: ["January",
+    "February", "March", "April", "May", "June", "July", "August", "September",
+    "October", "November", "December"],
+                 ddd: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], dddd: [
+    "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
+
+ + + Source   +Edit   + +
+
+
+
DurationZero = (seconds: 0, nanosecond: 0)
+
+ +

+Zero value for durations. Useful for comparisons.

+

doAssert initDuration(seconds = 1) > DurationZero
+doAssert initDuration(seconds = 0) == DurationZero

+ + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(dt: DateTime): string {....tags: [], raises: [], gcsafe, forbids: [].}
+
+ + Converts a DateTime object to a string representation. It uses the format yyyy-MM-dd'T'HH:mm:sszzz. +

Example:

+
let dt = dateTime(2000, mJan, 01, 12, 00, 00, 00, utc())
+doAssert $dt == "2000-01-01T12:00:00Z"
+doAssert $default(DateTime) == "Uninitialized DateTime"
+ Source   +Edit   + +
+
+
+
proc `$`(dur: Duration): string {....raises: [], tags: [], forbids: [].}
+
+ + Human friendly string representation of a Duration. +

Example:

+
doAssert $initDuration(seconds = 2) == "2 seconds"
+doAssert $initDuration(weeks = 1, days = 2) == "1 week and 2 days"
+doAssert $initDuration(hours = 1, minutes = 2, seconds = 3) ==
+  "1 hour, 2 minutes, and 3 seconds"
+doAssert $initDuration(milliseconds = -1500) ==
+  "-1 second and -500 milliseconds"
+ Source   +Edit   + +
+
+
+
proc `$`(f: TimeFormat): string {....raises: [], tags: [], forbids: [].}
+
+ + Returns the format string that was used to construct f. +

Example:

+
let f = initTimeFormat("yyyy-MM-dd")
+doAssert $f == "yyyy-MM-dd"
+ Source   +Edit   + +
+
+
+
proc `$`(p: IsoYear): string {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `$`(ti: TimeInterval): string {....raises: [], tags: [], forbids: [].}
+
+ + Get string representation of TimeInterval. +

Example:

+
doAssert $initTimeInterval(years = 1, nanoseconds = 123) ==
+  "1 year and 123 nanoseconds"
+doAssert $initTimeInterval() == "0 nanoseconds"
+ Source   +Edit   + +
+
+
+
proc `$`(time: Time): string {....tags: [], raises: [], gcsafe, forbids: [].}
+
+ + Converts a Time value to a string representation. It will use the local time zone and use the format yyyy-MM-dd'T'HH:mm:sszzz. +

Example:

+
let dt = dateTime(1970, mJan, 01, 00, 00, 00, 00, local())
+let tm = dt.toTime()
+doAssert $tm == "1970-01-01T00:00:00" & format(dt, "zzz")
+ Source   +Edit   + +
+
+
+
proc `$`(zone: Timezone): string {....raises: [], tags: [], forbids: [].}
+
+ + Returns the name of the timezone. + Source   +Edit   + +
+
+ +
+
+
+
proc `*`(a: Duration; b: int64): Duration {....gcsafe, noSideEffect, ...gcsafe,
+    extern: "ntMulDuration", raises: [], tags: [], forbids: [].}
+
+ + Multiply a duration by some scalar. +

Example:

+
doAssert initDuration(seconds = 1) * 5 == initDuration(seconds = 5)
+doAssert initDuration(minutes = 45) * 3 == initDuration(hours = 2, minutes = 15)
+ Source   +Edit   + +
+
+
+
proc `*`(a: int64; b: Duration): Duration {....gcsafe, noSideEffect, ...gcsafe,
+    extern: "ntMulInt64Duration", raises: [], tags: [], forbids: [].}
+
+ + Multiply a duration by some scalar. +

Example:

+
doAssert 5 * initDuration(seconds = 1) == initDuration(seconds = 5)
+doAssert 3 * initDuration(minutes = 45) == initDuration(hours = 2, minutes = 15)
+ Source   +Edit   + +
+
+ +
+
+
+
proc `*=`(a: var Duration; b: int) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `+`(a, b: Duration): Duration {....gcsafe, noSideEffect, ...gcsafe,
+                                     extern: "ntAddDuration", raises: [],
+                                     tags: [], forbids: [].}
+
+ + Add two durations together. +

Example:

+
doAssert initDuration(seconds = 1) + initDuration(days = 1) ==
+  initDuration(seconds = 1, days = 1)
+ Source   +Edit   + +
+
+
+
proc `+`(a: Time; b: Duration): Time {....gcsafe, noSideEffect, ...gcsafe,
+                                       extern: "ntAddTime", raises: [],
+                                       tags: [], forbids: [].}
+
+ + Add a duration of time to a Time. +

Example:

+
doAssert (fromUnix(0) + initDuration(seconds = 1)) == fromUnix(1)
+ Source   +Edit   + +
+
+
+
proc `+`(dt: DateTime; dur: Duration): DateTime {....raises: [], tags: [],
+    forbids: [].}
+
+ + +

Example:

+
let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc())
+let dur = initDuration(hours = 5)
+doAssert $(dt + dur) == "2017-03-30T05:00:00Z"
+ Source   +Edit   + +
+
+
+
proc `+`(dt: DateTime; interval: TimeInterval): DateTime {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Adds interval to dt. Components from interval are added in the order of their size, i.e. first the years component, then the months component and so on. The returned DateTime will have the same timezone as the input.

+

Note that when adding months, monthday overflow is allowed. This means that if the resulting month doesn't have enough days it, the month will be incremented and the monthday will be set to the number of days overflowed. So adding one month to 31 October will result in 31 November, which will overflow and result in 1 December.

+ +

Example:

+
let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc())
+doAssert $(dt + 1.months) == "2017-04-30T00:00:00Z"
+# This is correct and happens due to monthday overflow.
+doAssert $(dt - 1.months) == "2017-03-02T00:00:00Z"
+ Source   +Edit   + +
+
+
+
proc `+`(ti1, ti2: TimeInterval): TimeInterval {....raises: [], tags: [],
+    forbids: [].}
+
+ + Adds two TimeInterval objects together. + Source   +Edit   + +
+
+
+
proc `+`(time: Time; interval: TimeInterval): Time {....raises: [], tags: [],
+    forbids: [].}
+
+ + Adds interval to time. If interval contains any years, months, weeks or days the operation is performed in the local timezone. +

Example:

+
let tm = fromUnix(0)
+doAssert tm + 5.seconds == fromUnix(5)
+ Source   +Edit   + +
+
+ +
+
+
+
proc `+=`(a: var DateTime; b: Duration) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+=`(a: var DateTime; b: TimeInterval) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+=`(a: var TimeInterval; b: TimeInterval) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+=`(d1: var Duration; d2: Duration) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+=`(t: var Time; b: Duration) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `+=`(t: var Time; b: TimeInterval) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `-`(a, b: Duration): Duration {....gcsafe, noSideEffect, ...gcsafe,
+                                     extern: "ntSubDuration", raises: [],
+                                     tags: [], forbids: [].}
+
+ + Subtract a duration from another. +

Example:

+
doAssert initDuration(seconds = 1, days = 1) - initDuration(seconds = 1) ==
+  initDuration(days = 1)
+ Source   +Edit   + +
+
+
+
proc `-`(a, b: Time): Duration {....gcsafe, noSideEffect, ...gcsafe,
+                                 extern: "ntDiffTime", raises: [], tags: [],
+                                 forbids: [].}
+
+ + Computes the duration between two points in time. +

Example:

+
doAssert initTime(1000, 100) - initTime(500, 20) ==
+  initDuration(minutes = 8, seconds = 20, nanoseconds = 80)
+ Source   +Edit   + +
+
+
+
proc `-`(a: Duration): Duration {....gcsafe, noSideEffect, ...gcsafe,
+                                  extern: "ntReverseDuration", raises: [],
+                                  tags: [], forbids: [].}
+
+ + Reverse a duration. +

Example:

+
doAssert -initDuration(seconds = 1) == initDuration(seconds = -1)
+ Source   +Edit   + +
+
+
+
proc `-`(a: Time; b: Duration): Time {....gcsafe, noSideEffect, ...gcsafe,
+                                       extern: "ntSubTime", raises: [],
+                                       tags: [], forbids: [].}
+
+ + Subtracts a duration of time from a Time. +

Example:

+
doAssert (fromUnix(0) - initDuration(seconds = 1)) == fromUnix(-1)
+ Source   +Edit   + +
+
+
+
proc `-`(dt1, dt2: DateTime): Duration {....raises: [], tags: [], forbids: [].}
+
+ + Compute the duration between dt1 and dt2. +

Example:

+
let dt1 = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc())
+let dt2 = dateTime(2017, mMar, 25, 00, 00, 00, 00, utc())
+
+doAssert dt1 - dt2 == initDuration(days = 5)
+ Source   +Edit   + +
+
+
+
proc `-`(dt: DateTime; dur: Duration): DateTime {....raises: [], tags: [],
+    forbids: [].}
+
+ + +

Example:

+
let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc())
+let dur = initDuration(days = 5)
+doAssert $(dt - dur) == "2017-03-25T00:00:00Z"
+ Source   +Edit   + +
+
+
+
proc `-`(dt: DateTime; interval: TimeInterval): DateTime {....raises: [], tags: [],
+    forbids: [].}
+
+ + Subtract interval from dt. Components from interval are subtracted in the order of their size, i.e. first the years component, then the months component and so on. The returned DateTime will have the same timezone as the input. +

Example:

+
let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc())
+doAssert $(dt - 5.days) == "2017-03-25T00:00:00Z"
+ Source   +Edit   + +
+
+
+
proc `-`(ti1, ti2: TimeInterval): TimeInterval {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Subtracts TimeInterval ti1 from ti2.

+

Time components are subtracted one-by-one, see output:

+ +

Example:

+
let ti1 = initTimeInterval(hours = 24)
+let ti2 = initTimeInterval(hours = 4)
+doAssert (ti1 - ti2) == initTimeInterval(hours = 20)
+ Source   +Edit   + +
+
+
+
proc `-`(ti: TimeInterval): TimeInterval {....raises: [], tags: [], forbids: [].}
+
+ + Reverses a time interval +

Example:

+
let day = -initTimeInterval(hours = 24)
+doAssert day.hours == -24
+ Source   +Edit   + +
+
+
+
proc `-`(time: Time; interval: TimeInterval): Time {....raises: [], tags: [],
+    forbids: [].}
+
+ + Subtracts interval from Time time. If interval contains any years, months, weeks or days the operation is performed in the local timezone. +

Example:

+
let tm = fromUnix(5)
+doAssert tm - 5.seconds == fromUnix(0)
+ Source   +Edit   + +
+
+ +
+
+
+
proc `-=`(a: var DateTime; b: Duration) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-=`(a: var DateTime; b: TimeInterval) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-=`(a: var TimeInterval; b: TimeInterval) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-=`(dt: var Duration; ti: Duration) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-=`(t: var Time; b: Duration) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `-=`(t: var Time; b: TimeInterval) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc `<`(a, b: DateTime): bool {....raises: [], tags: [], forbids: [].}
+
+ + Returns true if a happened before b. + Source   +Edit   + +
+
+
+
proc `<`(a, b: Duration): bool {....gcsafe, noSideEffect, ...gcsafe,
+                                 extern: "ntLtDuration", raises: [], tags: [],
+                                 forbids: [].}
+
+ + Note that a duration can be negative, so even if a < b is true a might represent a larger absolute duration. Use abs(a) < abs(b) to compare the absolute duration. +

Example:

+
doAssert initDuration(seconds = 1) < initDuration(seconds = 2)
+doAssert initDuration(seconds = -2) < initDuration(seconds = 1)
+doAssert initDuration(seconds = -2).abs < initDuration(seconds = 1).abs == false
+ Source   +Edit   + +
+
+
+
proc `<`(a, b: Time): bool {....gcsafe, noSideEffect, ...gcsafe, extern: "ntLtTime",
+                             raises: [], tags: [], forbids: [].}
+
+ + Returns true if a < b, that is if a happened before b. +

Example:

+
doAssert initTime(50, 0) < initTime(99, 0)
+ Source   +Edit   + +
+
+ +
+
+
+
proc `<=`(a, b: DateTime): bool {....raises: [], tags: [], forbids: [].}
+
+ + Returns true if a happened before or at the same time as b. + Source   +Edit   + +
+
+
+
proc `<=`(a, b: Duration): bool {....gcsafe, noSideEffect, ...gcsafe,
+                                  extern: "ntLeDuration", raises: [], tags: [],
+                                  forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `<=`(a, b: Time): bool {....gcsafe, noSideEffect, ...gcsafe, extern: "ntLeTime",
+                              raises: [], tags: [], forbids: [].}
+
+ + Returns true if a <= b. + Source   +Edit   + +
+
+ +
+
+
+
proc `==`(a, b: DateTime): bool {....raises: [], tags: [], forbids: [].}
+
+ + Returns true if a and b represent the same point in time. + Source   +Edit   + +
+
+
+
proc `==`(a, b: Duration): bool {....gcsafe, noSideEffect, ...gcsafe,
+                                  extern: "ntEqDuration", raises: [], tags: [],
+                                  forbids: [].}
+
+ + +

Example:

+
let
+  d1 = initDuration(weeks = 1)
+  d2 = initDuration(days = 7)
+doAssert d1 == d2
+ Source   +Edit   + +
+
+
+
proc `==`(a, b: IsoYear): bool {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `==`(a, b: Time): bool {....gcsafe, noSideEffect, ...gcsafe, extern: "ntEqTime",
+                              raises: [], tags: [], forbids: [].}
+
+ + Returns true if a == b, that is if both times represent the same point in time. + Source   +Edit   + +
+
+
+
proc `==`(zone1, zone2: Timezone): bool {....raises: [], tags: [], forbids: [].}
+
+ + Two Timezone's are considered equal if their name is equal. +

Example:

+
doAssert local() == local()
+doAssert local() != utc()
+ Source   +Edit   + +
+
+ +
+
+
+
proc abs(a: Duration): Duration {....raises: [], tags: [], forbids: [].}
+
+ + +

Example:

+
doAssert initDuration(milliseconds = -1500).abs ==
+  initDuration(milliseconds = 1500)
+ Source   +Edit   + +
+
+ +
+
+
+
proc between(startDt, endDt: DateTime): TimeInterval {....raises: [], tags: [],
+    forbids: [].}
+
+ + Gives the difference between startDt and endDt as a TimeInterval. The following guarantees about the result is given:
  • All fields will have the same sign.
  • +
  • If startDt.timezone == endDt.timezone, it is guaranteed that startDt + between(startDt, endDt) == endDt.
  • +
  • If startDt.timezone != endDt.timezone, then the result will be equivalent to between(startDt.utc, endDt.utc).
  • +
+ +

Example:

+
var a = dateTime(2015, mMar, 25, 12, 0, 0, 00, utc())
+var b = dateTime(2017, mApr, 1, 15, 0, 15, 00, utc())
+var ti = initTimeInterval(years = 2, weeks = 1, hours = 3, seconds = 15)
+doAssert between(a, b) == ti
+doAssert between(a, b) == -between(b, a)
+ Source   +Edit   + +
+
+ +
+
+
+
proc convert[T: SomeInteger](unitFrom, unitTo: FixedTimeUnit; quantity: T): T {.
+    inline.}
+
+ + Convert a quantity of some duration unit to another duration unit. This proc only deals with integers, so the result might be truncated. +

Example:

+
doAssert convert(Days, Hours, 2) == 48
+doAssert convert(Days, Weeks, 13) == 1 # Truncated
+doAssert convert(Seconds, Milliseconds, -1) == -1000
+ Source   +Edit   + +
+
+ +
+
+
+
proc cpuTime(): float {....tags: [TimeEffect], raises: [], forbids: [].}
+
+ + Gets time spent that the CPU spent to run the current process in seconds. This may be more useful for benchmarking than epochTime. However, it may measure the real time instead (depending on the OS). The value of the result has no meaning. To generate useful timing values, take the difference between the results of two cpuTime calls: +

Example:

+
var t0 = cpuTime()
+# some useless work here (calculate fibonacci)
+var fib = @[0, 1, 1]
+for i in 1..10:
+  fib.add(fib[^1] + fib[^2])
+echo "CPU time [s] ", cpuTime() - t0
+echo "Fib is [s] ", fib
When the flag --benchmarkVM is passed to the compiler, this proc is also available at compile time + Source   +Edit   + +
+
+ +
+
+
+
proc dateTime(year: int; month: Month; monthday: MonthdayRange;
+              hour: HourRange = 0; minute: MinuteRange = 0;
+              second: SecondRange = 0; nanosecond: NanosecondRange = 0;
+              zone: Timezone = local()): DateTime {....raises: [], tags: [],
+    forbids: [].}
+
+ + Create a new DateTime in the specified timezone. +

Example:

+
assert $dateTime(2017, mMar, 30, zone = utc()) == "2017-03-30T00:00:00Z"
+ Source   +Edit   + +
+
+ +
+
+
+
proc days(d: int): TimeInterval {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

TimeInterval of d days.

+

echo getTime() + 2.days

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `div`(a: Duration; b: int64): Duration {....gcsafe, noSideEffect, ...gcsafe,
+    extern: "ntDivDuration", raises: [], tags: [], forbids: [].}
+
+ + Integer division for durations. +

Example:

+
doAssert initDuration(seconds = 3) div 2 ==
+  initDuration(milliseconds = 1500)
+doAssert initDuration(minutes = 45) div 30 ==
+  initDuration(minutes = 1, seconds = 30)
+doAssert initDuration(nanoseconds = 3) div 2 ==
+  initDuration(nanoseconds = 1)
+ Source   +Edit   + +
+
+ +
+
+
+
proc epochTime(): float {....tags: [TimeEffect], raises: [], forbids: [].}
+
+ +

Gets time after the UNIX epoch (1970) in seconds. It is a float because sub-second resolution is likely to be supported (depending on the hardware/OS).

+

getTime should generally be preferred over this proc.

+
Warning: +Unsuitable for benchmarking (but still better than now), use monotimes.getMonoTime or cpuTime instead, depending on the use case.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc format(dt: DateTime; f: static[string]): string {....raises: [].}
+
+ + Overload that validates format at compile time. + Source   +Edit   + +
+
+
+
proc format(dt: DateTime; f: string; loc: DateTimeLocale = DefaultLocale): string {.
+    ...raises: [TimeFormatParseError], tags: [], forbids: [].}
+
+ +

Shorthand for constructing a TimeFormat and using it to format dt.

+

See Parsing and formatting dates for documentation of the format argument.

+ +

Example:

+
let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
+doAssert "2000-01-01" == format(dt, "yyyy-MM-dd")
+ Source   +Edit   + +
+
+
+
proc format(dt: DateTime; f: TimeFormat; loc: DateTimeLocale = DefaultLocale): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Format dt using the format specified by f. +

Example:

+
let f = initTimeFormat("yyyy-MM-dd")
+let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
+doAssert "2000-01-01" == dt.format(f)
+ Source   +Edit   + +
+
+
+
proc format(time: Time; f: static[string]; zone: Timezone = local()): string {.
+    ...raises: [].}
+
+ + Overload that validates f at compile time. + Source   +Edit   + +
+
+
+
proc format(time: Time; f: string; zone: Timezone = local()): string {.
+    ...raises: [TimeFormatParseError], tags: [], forbids: [].}
+
+ +

Shorthand for constructing a TimeFormat and using it to format time. Will use the timezone specified by zone.

+

See Parsing and formatting dates for documentation of the f argument.

+ +

Example:

+
var dt = dateTime(1970, mJan, 01, 00, 00, 00, 00, utc())
+var tm = dt.toTime()
+doAssert format(tm, "yyyy-MM-dd'T'HH:mm:ss", utc()) == "1970-01-01T00:00:00"
+ Source   +Edit   + +
+
+ +
+
+
+
proc formatValue(result: var string; value: DateTime | Time; specifier: string)
+
+ + adapter for strformat. Not intended to be called directly. + Source   +Edit   + +
+
+ +
+
+
+
proc fromUnix(unix: int64): Time {....gcsafe, tags: [], raises: [], noSideEffect,
+                                   ...forbids: [].}
+
+ + Convert a unix timestamp (seconds since 1970-01-01T00:00:00Z) to a Time. +

Example:

+
doAssert $fromUnix(0).utc == "1970-01-01T00:00:00Z"
+ Source   +Edit   + +
+
+ +
+
+
+
proc fromUnixFloat(seconds: float): Time {....gcsafe, tags: [], raises: [],
+    noSideEffect, ...forbids: [].}
+
+ + Convert a unix timestamp in seconds to a Time; same as fromUnix but with subsecond resolution. +

Example:

+
doAssert fromUnixFloat(123456.0) == fromUnixFloat(123456)
+doAssert fromUnixFloat(-123456.0) == fromUnixFloat(-123456)
+ Source   +Edit   + +
+
+ +
+
+
+
proc fromWinTime(win: int64): Time {....raises: [], tags: [], forbids: [].}
+
+ + Convert a Windows file time (100-nanosecond intervals since 1601-01-01T00:00:00Z) to a Time. + Source   +Edit   + +
+
+ +
+
+
+
proc getClockStr(dt = now()): string {....gcsafe, extern: "nt$1",
+                                       tags: [TimeEffect], raises: [],
+                                       forbids: [].}
+
+ + Gets the current local clock time as a string of the format HH:mm:ss. +

Example:

+
echo getClockStr(now() - 1.hours)
+ Source   +Edit   + +
+
+ +
+
+
+
proc getDateStr(dt = now()): string {....gcsafe, extern: "nt$1",
+                                      tags: [TimeEffect], raises: [],
+                                      forbids: [].}
+
+ + Gets the current local date as a string of the format YYYY-MM-dd. +

Example:

+
echo getDateStr(now() - 1.months)
+ Source   +Edit   + +
+
+ +
+
+
+
proc getDayOfWeek(monthday: MonthdayRange; month: Month; year: int): WeekDay {.
+    ...tags: [], raises: [], gcsafe, forbids: [].}
+
+ + Returns the day of the week enum from day, month and year. Equivalent with dateTime(year, month, monthday, 0, 0, 0, 0).weekday. +

Example:

+
doAssert getDayOfWeek(13, mJun, 1990) == dWed
+doAssert $getDayOfWeek(13, mJun, 1990) == "Wednesday"
+ Source   +Edit   + +
+
+ +
+
+
+
proc getDayOfYear(monthday: MonthdayRange; month: Month; year: int): YeardayRange {.
+    ...tags: [], raises: [], gcsafe, forbids: [].}
+
+ + Returns the day of the year. Equivalent with dateTime(year, month, monthday, 0, 0, 0, 0).yearday. +

Example:

+
doAssert getDayOfYear(1, mJan, 2000) == 0
+doAssert getDayOfYear(10, mJan, 2000) == 9
+doAssert getDayOfYear(10, mFeb, 2000) == 40
+ Source   +Edit   + +
+
+ +
+
+
+
proc getDaysInMonth(month: Month; year: int): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + Get the number of days in month of year. +

Example:

+
doAssert getDaysInMonth(mFeb, 2000) == 29
+doAssert getDaysInMonth(mFeb, 2001) == 28
+ Source   +Edit   + +
+
+ +
+
+
+
proc getDaysInYear(year: int): int {....raises: [], tags: [], forbids: [].}
+
+ + Get the number of days in a year +

Example:

+
doAssert getDaysInYear(2000) == 366
+doAssert getDaysInYear(2001) == 365
+ Source   +Edit   + +
+
+ +
+
+
+
proc getIsoWeekAndYear(dt: DateTime): tuple[isoweek: IsoWeekRange,
+    isoyear: IsoYear] {....raises: [], tags: [], forbids: [].}
+
+ + Returns the ISO 8601 week and year.
Warning: +The ISO week-based year can correspond to the following or previous year from 29 December to January 3.
+ +

Example:

+
assert getIsoWeekAndYear(initDateTime(21, mApr, 2018, 00, 00, 00)) == (isoweek: 16.IsoWeekRange, isoyear: 2018.IsoYear)
+block:
+  let (w, y) = getIsoWeekAndYear(initDateTime(30, mDec, 2019, 00, 00, 00))
+  assert w == 01.IsoWeekRange
+  assert y == 2020.IsoYear
+assert getIsoWeekAndYear(initDateTime(13, mSep, 2020, 00, 00, 00)) == (isoweek: 37.IsoWeekRange, isoyear: 2020.IsoYear)
+block:
+  let (w, y) = getIsoWeekAndYear(initDateTime(2, mJan, 2021, 00, 00, 00))
+  assert w.int > 52
+  assert w.int < 54
+  assert y.int mod 100 == 20
+ Source   +Edit   + +
+
+ +
+
+
+
proc getTime(): Time {....tags: [TimeEffect], gcsafe, raises: [], forbids: [].}
+
+ + Gets the current time as a Time with up to nanosecond resolution. + Source   +Edit   + +
+
+ +
+
+
+
proc getWeeksInIsoYear(y: IsoYear): IsoWeekRange {....raises: [], tags: [],
+    forbids: [].}
+
+ + Returns the number of weeks in the specified ISO 8601 week-based year, which can be either 53 or 52. +

Example:

+
assert getWeeksInIsoYear(IsoYear(2019)) == 52
+assert getWeeksInIsoYear(IsoYear(2020)) == 53
+ Source   +Edit   + +
+
+ +
+
+
+
proc high(typ: typedesc[Duration]): Duration
+
+ + Get the longest representable duration. + Source   +Edit   + +
+
+
+
proc high(typ: typedesc[Time]): Time
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hour(dt: DateTime): HourRange {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + The number of hours past midnight, in the range 0 to 23. + Source   +Edit   + +
+
+ +
+
+
+
proc hour=(dt: var DateTime; value: HourRange) {.
+    ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v1.3.1 +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc hours(h: int): TimeInterval {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

TimeInterval of h hours.

+

echo getTime() + 2.hours

+ + Source   +Edit   + +
+
+ +
+
+
+
proc inDays(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}
+
+ + Converts the duration to the number of whole days. +

Example:

+
let dur = initDuration(hours = -50)
+doAssert dur.inDays == -2
+ Source   +Edit   + +
+
+ +
+
+
+
proc inHours(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}
+
+ + Converts the duration to the number of whole hours. +

Example:

+
let dur = initDuration(minutes = 60, days = 2)
+doAssert dur.inHours == 49
+ Source   +Edit   + +
+
+ +
+
+
+
proc initDateTime(monthday: MonthdayRange; month: Month; year: int;
+                  hour: HourRange; minute: MinuteRange; second: SecondRange;
+                  nanosecond: NanosecondRange; zone: Timezone = local()): DateTime {.
+    ...deprecated: "use `dateTime`", raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: use `dateTime` +
+ + Create a new DateTime in the specified timezone. +

Example: cmd: --warning:deprecated:off

+
assert $initDateTime(30, mMar, 2017, 00, 00, 00, 00, utc()) == "2017-03-30T00:00:00Z"
+ Source   +Edit   + +
+
+
+
proc initDateTime(monthday: MonthdayRange; month: Month; year: int;
+                  hour: HourRange; minute: MinuteRange; second: SecondRange;
+                  zone: Timezone = local()): DateTime {.
+    ...deprecated: "use `dateTime`", raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: use `dateTime` +
+ + Create a new DateTime in the specified timezone. +

Example: cmd: --warning:deprecated:off

+
assert $initDateTime(30, mMar, 2017, 00, 00, 00, utc()) == "2017-03-30T00:00:00Z"
+ Source   +Edit   + +
+
+
+
proc initDateTime(weekday: WeekDay; isoweek: IsoWeekRange; isoyear: IsoYear;
+                  hour: HourRange; minute: MinuteRange; second: SecondRange;
+                  nanosecond: NanosecondRange; zone: Timezone = local()): DateTime {.
+    ...gcsafe, raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc initDateTime(weekday: WeekDay; isoweek: IsoWeekRange; isoyear: IsoYear;
+                  hour: HourRange; minute: MinuteRange; second: SecondRange;
+                  zone: Timezone = local()): DateTime {....gcsafe, raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc initDuration(nanoseconds, microseconds, milliseconds, seconds, minutes,
+                  hours, days, weeks: int64 = 0): Duration {....raises: [],
+    tags: [], forbids: [].}
+
+ + Create a new Duration. +

Example:

+
let dur = initDuration(seconds = 1, milliseconds = 1)
+doAssert dur.inMilliseconds == 1001
+doAssert dur.inSeconds == 1
+ Source   +Edit   + +
+
+ +
+
+
+
proc initTime(unix: int64; nanosecond: NanosecondRange): Time {....raises: [],
+    tags: [], forbids: [].}
+
+ + Create a Time from a unix timestamp and a nanosecond part. + Source   +Edit   + +
+
+ +
+
+
+
proc initTimeFormat(format: string): TimeFormat {.
+    ...raises: [TimeFormatParseError], tags: [], forbids: [].}
+
+ +

Construct a new time format for parsing & formatting time types.

+

See Parsing and formatting dates for documentation of the format argument.

+ +

Example:

+
let f = initTimeFormat("yyyy-MM-dd")
+doAssert "2000-01-01" == "2000-01-01".parse(f).format(f)
+ Source   +Edit   + +
+
+ +
+
+
+
proc initTimeInterval(nanoseconds, microseconds, milliseconds, seconds, minutes,
+                      hours, days, weeks, months, years: int = 0): TimeInterval {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Creates a new TimeInterval.

+

This proc doesn't perform any normalization! For example, initTimeInterval(hours = 24) and initTimeInterval(days = 1) are not equal.

+

You can also use the convenience procedures called milliseconds, seconds, minutes, hours, days, months, and years.

+ +

Example:

+
let day = initTimeInterval(hours = 24)
+let dt = dateTime(2000, mJan, 01, 12, 00, 00, 00, utc())
+doAssert $(dt + day) == "2000-01-02T12:00:00Z"
+doAssert initTimeInterval(hours = 24) != initTimeInterval(days = 1)
+ Source   +Edit   + +
+
+ +
+
+
+
proc inMicroseconds(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}
+
+ + Converts the duration to the number of whole microseconds. +

Example:

+
let dur = initDuration(seconds = -2)
+doAssert dur.inMicroseconds == -2000000
+ Source   +Edit   + +
+
+ +
+
+
+
proc inMilliseconds(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}
+
+ + Converts the duration to the number of whole milliseconds. +

Example:

+
let dur = initDuration(seconds = -2)
+doAssert dur.inMilliseconds == -2000
+ Source   +Edit   + +
+
+ +
+
+
+
proc inMinutes(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}
+
+ + Converts the duration to the number of whole minutes. +

Example:

+
let dur = initDuration(hours = 2, seconds = 10)
+doAssert dur.inMinutes == 120
+ Source   +Edit   + +
+
+ +
+
+
+
proc inNanoseconds(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}
+
+ + Converts the duration to the number of whole nanoseconds. +

Example:

+
let dur = initDuration(seconds = -2)
+doAssert dur.inNanoseconds == -2000000000
+ Source   +Edit   + +
+
+ +
+
+
+
proc inSeconds(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}
+
+ + Converts the duration to the number of whole seconds. +

Example:

+
let dur = initDuration(hours = 2, milliseconds = 10)
+doAssert dur.inSeconds == 2 * 60 * 60
+ Source   +Edit   + +
+
+ +
+
+
+
proc inWeeks(dur: Duration): int64 {....raises: [], tags: [], forbids: [].}
+
+ + Converts the duration to the number of whole weeks. +

Example:

+
let dur = initDuration(days = 8)
+doAssert dur.inWeeks == 1
+ Source   +Edit   + +
+
+ +
+
+
+
proc inZone(dt: DateTime; zone: Timezone): DateTime {....tags: [], raises: [],
+    gcsafe, forbids: [].}
+
+ + Returns a DateTime representing the same point in time as dt but using zone as the timezone. + Source   +Edit   + +
+
+
+
proc inZone(time: Time; zone: Timezone): DateTime {....tags: [], raises: [],
+    gcsafe, forbids: [].}
+
+ + Convert time into a DateTime using zone as the timezone. + Source   +Edit   + +
+
+ +
+
+
+
proc isDst(dt: DateTime): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Determines whether DST is in effect. Always false for the JavaScript backend. + Source   +Edit   + +
+
+ +
+
+
+
proc isDst=(dt: var DateTime; value: bool) {.
+    ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v1.3.1 +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isInitialized(dt: DateTime): bool {....raises: [], tags: [], forbids: [].}
+
+ + +

Example:

+
doAssert now().isInitialized
+doAssert not default(DateTime).isInitialized
+ Source   +Edit   + +
+
+ +
+
+
+
proc isLeapDay(dt: DateTime): bool {....raises: [], tags: [], forbids: [].}
+
+ + Returns whether t is a leap day, i.e. Feb 29 in a leap year. This matters as it affects time offset calculations. +

Example:

+
let dt = dateTime(2020, mFeb, 29, 00, 00, 00, 00, utc())
+doAssert dt.isLeapDay
+doAssert dt+1.years-1.years != dt
+let dt2 = dateTime(2020, mFeb, 28, 00, 00, 00, 00, utc())
+doAssert not dt2.isLeapDay
+doAssert dt2+1.years-1.years == dt2
+doAssertRaises(Exception): discard dateTime(2021, mFeb, 29, 00, 00, 00, 00, utc())
+ Source   +Edit   + +
+
+ +
+
+
+
proc isLeapYear(year: int): bool {....raises: [], tags: [], forbids: [].}
+
+ + Returns true if year is a leap year. +

Example:

+
doAssert isLeapYear(2000)
+doAssert not isLeapYear(1900)
+ Source   +Edit   + +
+
+ +
+
+
+
proc local(): Timezone {....raises: [], tags: [], forbids: [].}
+
+ + Get the Timezone implementation for the local timezone. +

Example:

+
doAssert now().timezone == local()
+doAssert local().name == "LOCAL"
+ Source   +Edit   + +
+
+
+
proc local(dt: DateTime): DateTime {....raises: [], tags: [], forbids: [].}
+
+ + Shorthand for dt.inZone(local()). + Source   +Edit   + +
+
+
+
proc local(t: Time): DateTime {....raises: [], tags: [], forbids: [].}
+
+ + Shorthand for t.inZone(local()). + Source   +Edit   + +
+
+ +
+
+
+
proc low(typ: typedesc[Duration]): Duration
+
+ + Get the longest representable duration of negative direction. + Source   +Edit   + +
+
+
+
proc low(typ: typedesc[Time]): Time
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc microseconds(micros: int): TimeInterval {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + TimeInterval of micros microseconds. + Source   +Edit   + +
+
+ +
+
+
+
proc milliseconds(ms: int): TimeInterval {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + TimeInterval of ms milliseconds. + Source   +Edit   + +
+
+ +
+
+
+
proc minute(dt: DateTime): MinuteRange {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + The number of minutes after the hour, in the range 0 to 59. + Source   +Edit   + +
+
+ +
+
+
+
proc minute=(dt: var DateTime; value: MinuteRange) {.
+    ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v1.3.1 +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc minutes(m: int): TimeInterval {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

TimeInterval of m minutes.

+

echo getTime() + 5.minutes

+ + Source   +Edit   + +
+
+ +
+
+
+
proc month(dt: DateTime): Month {....raises: [], tags: [], forbids: [].}
+
+ + The month as an enum, the ordinal value is in the range 1 to 12. + Source   +Edit   + +
+
+ +
+
+
+
proc monthday(dt: DateTime): MonthdayRange {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + The day of the month, in the range 1 to 31. + Source   +Edit   + +
+
+ +
+
+
+
proc monthdayZero=(dt: var DateTime; value: int) {.
+    ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v1.3.1 +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc months(m: int): TimeInterval {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

TimeInterval of m months.

+

echo getTime() + 2.months

+ + Source   +Edit   + +
+
+ +
+
+
+
proc monthZero=(dt: var DateTime; value: int) {.
+    ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v1.3.1 +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc name(zone: Timezone): string {....raises: [], tags: [], forbids: [].}
+
+ +

The name of the timezone.

+

If possible, the name will be the name used in the tz database. If the timezone doesn't exist in the tz database, or if the timezone name is unknown, then any string that describes the timezone unambiguously might be used. For example, the string "LOCAL" is used for the system's local timezone.

+

See also: https://en.wikipedia.org/wiki/Tz_database

+ + Source   +Edit   + +
+
+ +
+
+
+
proc nanosecond(dt: DateTime): NanosecondRange {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + The number of nanoseconds after the second, in the range 0 to 999_999_999. + Source   +Edit   + +
+
+
+
proc nanosecond(time: Time): NanosecondRange {....raises: [], tags: [], forbids: [].}
+
+ + Get the fractional part of a Time as the number of nanoseconds of the second. + Source   +Edit   + +
+
+ +
+
+
+
proc nanosecond=(dt: var DateTime; value: NanosecondRange) {.
+    ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v1.3.1 +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc nanoseconds(nanos: int): TimeInterval {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + TimeInterval of nanos nanoseconds. + Source   +Edit   + +
+
+ +
+
+
+
proc newTimezone(name: string; zonedTimeFromTimeImpl: proc (time: Time): ZonedTime {.
+    ...tags: [], raises: [], gcsafe.}; zonedTimeFromAdjTimeImpl: proc (
+    adjTime: Time): ZonedTime {....tags: [], raises: [], gcsafe.}): owned Timezone {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Create a new Timezone.

+

zonedTimeFromTimeImpl and zonedTimeFromAdjTimeImpl is used as the underlying implementations for zonedTimeFromTime and zonedTimeFromAdjTime.

+

If possible, the name parameter should match the name used in the tz database. If the timezone doesn't exist in the tz database, or if the timezone name is unknown, then any string that describes the timezone unambiguously can be used. Note that the timezones name is used for checking equality!

+ +

Example:

+
proc utcTzInfo(time: Time): ZonedTime =
+  ZonedTime(utcOffset: 0, isDst: false, time: time)
+let utc = newTimezone("Etc/UTC", utcTzInfo, utcTzInfo)
+ Source   +Edit   + +
+
+ +
+
+
+
proc now(): DateTime {....tags: [TimeEffect], gcsafe, raises: [], forbids: [].}
+
+ + Get the current time as a DateTime in the local timezone. Shorthand for getTime().local.
Warning: +Unsuitable for benchmarking, use monotimes.getMonoTime or cpuTime instead, depending on the use case.
+ + Source   +Edit   + +
+
+ +
+
+
+
proc parse(input, f: string; tz: Timezone = local();
+           loc: DateTimeLocale = DefaultLocale): DateTime {.
+    ...raises: [TimeParseError, TimeFormatParseError], tags: [TimeEffect],
+    forbids: [].}
+
+ +

Shorthand for constructing a TimeFormat and using it to parse input as a DateTime.

+

See Parsing and formatting dates for documentation of the f argument.

+ +

Example:

+
let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
+doAssert dt == parse("2000-01-01", "yyyy-MM-dd", utc())
+ Source   +Edit   + +
+
+
+
proc parse(input: string; f: static[string]; zone: Timezone = local();
+           loc: DateTimeLocale = DefaultLocale): DateTime {.
+    ...raises: [TimeParseError].}
+
+ + Overload that validates f at compile time. + Source   +Edit   + +
+
+
+
proc parse(input: string; f: TimeFormat; zone: Timezone = local();
+           loc: DateTimeLocale = DefaultLocale): DateTime {.
+    ...raises: [TimeParseError], tags: [TimeEffect], forbids: [].}
+
+ +

Parses input as a DateTime using the format specified by f. If no UTC offset was parsed, then input is assumed to be specified in the zone timezone. If a UTC offset was parsed, the result will be converted to the zone timezone.

+

Month and day names from the passed in loc are used.

+ +

Example:

+
let f = initTimeFormat("yyyy-MM-dd")
+let dt = dateTime(2000, mJan, 01, 00, 00, 00, 00, utc())
+doAssert dt == "2000-01-01".parse(f, utc())
+ Source   +Edit   + +
+
+ +
+
+
+
proc parseTime(input, f: string; zone: Timezone): Time {.
+    ...raises: [TimeParseError, TimeFormatParseError], tags: [TimeEffect],
+    forbids: [].}
+
+ +

Shorthand for constructing a TimeFormat and using it to parse input as a DateTime, then converting it a Time.

+

See Parsing and formatting dates for documentation of the format argument.

+ +

Example:

+
let tStr = "1970-01-01T00:00:00+00:00"
+doAssert parseTime(tStr, "yyyy-MM-dd'T'HH:mm:sszzz", utc()) == fromUnix(0)
+ Source   +Edit   + +
+
+
+
proc parseTime(input: string; f: static[string]; zone: Timezone): Time {.
+    ...raises: [TimeParseError].}
+
+ + Overload that validates format at compile time. + Source   +Edit   + +
+
+ +
+
+
+
proc second(dt: DateTime): SecondRange {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + The number of seconds after the minute, in the range 0 to 59. + Source   +Edit   + +
+
+ +
+
+
+
proc second=(dt: var DateTime; value: SecondRange) {.
+    ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v1.3.1 +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc seconds(s: int): TimeInterval {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

TimeInterval of s seconds.

+

echo getTime() + 5.seconds

+ + Source   +Edit   + +
+
+ +
+
+
+
proc timezone(dt: DateTime): Timezone {.inline, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ + The timezone represented as an implementation of Timezone. + Source   +Edit   + +
+
+ +
+
+
+
proc timezone=(dt: var DateTime; value: Timezone) {.
+    ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v1.3.1 +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toParts(dur: Duration): DurationParts {....raises: [], tags: [], forbids: [].}
+
+ +

Converts a duration into an array consisting of fixed time units.

+

Each value in the array gives information about a specific unit of time, for example result[Days] gives a count of days.

+

This procedure is useful for converting Duration values to strings.

+ +

Example:

+
var dp = toParts(initDuration(weeks = 2, days = 1))
+doAssert dp[Days] == 1
+doAssert dp[Weeks] == 2
+doAssert dp[Minutes] == 0
+dp = toParts(initDuration(days = -1))
+doAssert dp[Days] == -1
+ Source   +Edit   + +
+
+
+
proc toParts(ti: TimeInterval): TimeIntervalParts {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Converts a TimeInterval into an array consisting of its time units, starting with nanoseconds and ending with years.

+

This procedure is useful for converting TimeInterval values to strings. E.g. then you need to implement custom interval printing

+ +

Example:

+
var tp = toParts(initTimeInterval(years = 1, nanoseconds = 123))
+doAssert tp[Years] == 1
+doAssert tp[Nanoseconds] == 123
+ Source   +Edit   + +
+
+ +
+
+
+
proc toTime(dt: DateTime): Time {....tags: [], raises: [], gcsafe, forbids: [].}
+
+ + Converts a DateTime to a Time representing the same point in time. + Source   +Edit   + +
+
+ +
+
+
+
proc toUnix(t: Time): int64 {....gcsafe, tags: [], raises: [], noSideEffect,
+                              ...forbids: [].}
+
+ + Convert t to a unix timestamp (seconds since 1970-01-01T00:00:00Z). See also toUnixFloat for subsecond resolution. +

Example:

+
doAssert fromUnix(0).toUnix() == 0
+ Source   +Edit   + +
+
+ +
+
+
+
proc toUnixFloat(t: Time): float {....gcsafe, tags: [], raises: [], forbids: [].}
+
+ + Same as toUnix but using subsecond resolution. +

Example:

+
let t = getTime()
+# `<` because of rounding errors
+doAssert abs(t.toUnixFloat().fromUnixFloat - t) < initDuration(nanoseconds = 1000)
+ Source   +Edit   + +
+
+ +
+
+
+
proc toWinTime(t: Time): int64 {....raises: [], tags: [], forbids: [].}
+
+ + Convert t to a Windows file time (100-nanosecond intervals since 1601-01-01T00:00:00Z). + Source   +Edit   + +
+
+ +
+
+
+
proc utc(): Timezone {....raises: [], tags: [], forbids: [].}
+
+ + Get the Timezone implementation for the UTC timezone. +

Example:

+
doAssert now().utc.timezone == utc()
+doAssert utc().name == "Etc/UTC"
+ Source   +Edit   + +
+
+
+
proc utc(dt: DateTime): DateTime {....raises: [], tags: [], forbids: [].}
+
+ + Shorthand for dt.inZone(utc()). + Source   +Edit   + +
+
+
+
proc utc(t: Time): DateTime {....raises: [], tags: [], forbids: [].}
+
+ + Shorthand for t.inZone(utc()). + Source   +Edit   + +
+
+ +
+
+
+
proc utcOffset(dt: DateTime): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + The offset in seconds west of UTC, including any offset due to DST. Note that the sign of this number is the opposite of the one in a formatted offset string like +01:00 (which would be equivalent to the UTC offset -3600). + Source   +Edit   + +
+
+ +
+
+
+
proc utcOffset=(dt: var DateTime; value: int) {.
+    ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v1.3.1 +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc weekday(dt: DateTime): WeekDay {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + The day of the week as an enum, the ordinal value is in the range 0 (monday) to 6 (sunday). + Source   +Edit   + +
+
+ +
+
+
+
proc weekday=(dt: var DateTime; value: WeekDay) {.
+    ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v1.3.1 +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc weeks(w: int): TimeInterval {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

TimeInterval of w weeks.

+

echo getTime() + 2.weeks

+ + Source   +Edit   + +
+
+ +
+
+
+
proc year(dt: DateTime): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + The year, using astronomical year numbering (meaning that before year 1 is year 0, then year -1 and so on). + Source   +Edit   + +
+
+ +
+
+
+
proc year=(dt: var DateTime; value: int) {.
+    ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v1.3.1 +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc yearday(dt: DateTime): YeardayRange {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + The number of days since January 1, in the range 0 to 365. + Source   +Edit   + +
+
+ +
+
+
+
proc yearday=(dt: var DateTime; value: YeardayRange) {.
+    ...deprecated: "Deprecated since v1.3.1", raises: [], tags: [], forbids: [].}
+
+
+ Deprecated: Deprecated since v1.3.1 +
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc years(y: int): TimeInterval {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

TimeInterval of y years.

+

echo getTime() + 2.years

+ + Source   +Edit   + +
+
+ +
+
+
+
proc zonedTimeFromAdjTime(zone: Timezone; adjTime: Time): ZonedTime {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the ZonedTime for some local time.

+

Note that the Time argument does not represent a point in time, it represent a local time! E.g if adjTime is fromUnix(0), it should be interpreted as 1970-01-01T00:00:00 in the zone timezone, not in UTC.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc zonedTimeFromTime(zone: Timezone; time: Time): ZonedTime {....raises: [],
+    tags: [], forbids: [].}
+
+ + Returns the ZonedTime for some point in time. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/times.idx b/times.idx new file mode 100644 index 0000000000000..5dd6a047201dc --- /dev/null +++ b/times.idx @@ -0,0 +1,239 @@ +nimTitle times times.html module std/times 0 +nim mJan times.html#mJan Month.mJan 270 +nim mFeb times.html#mFeb Month.mFeb 270 +nim mMar times.html#mMar Month.mMar 270 +nim mApr times.html#mApr Month.mApr 270 +nim mMay times.html#mMay Month.mMay 270 +nim mJun times.html#mJun Month.mJun 270 +nim mJul times.html#mJul Month.mJul 270 +nim mAug times.html#mAug Month.mAug 270 +nim mSep times.html#mSep Month.mSep 270 +nim mOct times.html#mOct Month.mOct 270 +nim mNov times.html#mNov Month.mNov 270 +nim mDec times.html#mDec Month.mDec 270 +nim Month times.html#Month enum Month 270 +nim dMon times.html#dMon WeekDay.dMon 286 +nim dTue times.html#dTue WeekDay.dTue 286 +nim dWed times.html#dWed WeekDay.dWed 286 +nim dThu times.html#dThu WeekDay.dThu 286 +nim dFri times.html#dFri WeekDay.dFri 286 +nim dSat times.html#dSat WeekDay.dSat 286 +nim dSun times.html#dSun WeekDay.dSun 286 +nim WeekDay times.html#WeekDay enum WeekDay 286 +nim MonthdayRange times.html#MonthdayRange type MonthdayRange 296 +nim HourRange times.html#HourRange type HourRange 297 +nim MinuteRange times.html#MinuteRange type MinuteRange 298 +nim SecondRange times.html#SecondRange type SecondRange 299 +nim YeardayRange times.html#YeardayRange type YeardayRange 302 +nim NanosecondRange times.html#NanosecondRange type NanosecondRange 303 +nim IsoWeekRange times.html#IsoWeekRange type IsoWeekRange 305 +nim IsoYear times.html#IsoYear type IsoYear 307 +nim Time times.html#Time object Time 312 +nim DateTime times.html#DateTime object DateTime 316 +nim Duration times.html#Duration object Duration 334 +nim Nanoseconds times.html#Nanoseconds TimeUnit.Nanoseconds 345 +nim Microseconds times.html#Microseconds TimeUnit.Microseconds 345 +nim Milliseconds times.html#Milliseconds TimeUnit.Milliseconds 345 +nim Seconds times.html#Seconds TimeUnit.Seconds 345 +nim Minutes times.html#Minutes TimeUnit.Minutes 345 +nim Hours times.html#Hours TimeUnit.Hours 345 +nim Days times.html#Days TimeUnit.Days 345 +nim Weeks times.html#Weeks TimeUnit.Weeks 345 +nim Months times.html#Months TimeUnit.Months 345 +nim Years times.html#Years TimeUnit.Years 345 +nim TimeUnit times.html#TimeUnit enum TimeUnit 345 +nim FixedTimeUnit times.html#FixedTimeUnit type FixedTimeUnit 349 +nim TimeInterval times.html#TimeInterval object TimeInterval 353 +nim Timezone times.html#Timezone type Timezone 380 +nim ZonedTime times.html#ZonedTime object ZonedTime 390 +nim DurationParts times.html#DurationParts type DurationParts 398 +nim TimeIntervalParts times.html#TimeIntervalParts type TimeIntervalParts 399 +nim convert times.html#convert,FixedTimeUnit,FixedTimeUnit,T proc convert[T: SomeInteger](unitFrom, unitTo: FixedTimeUnit; quantity: T): T 437 +nim isLeapYear times.html#isLeapYear,int proc isLeapYear(year: int): bool 461 +nim getDaysInMonth times.html#getDaysInMonth,Month,int proc getDaysInMonth(month: Month; year: int): int 468 +nim getDayOfYear times.html#getDayOfYear,MonthdayRange,Month,int proc getDayOfYear(monthday: MonthdayRange; month: Month; year: int): YeardayRange 519 +nim getDayOfWeek times.html#getDayOfWeek,MonthdayRange,Month,int proc getDayOfWeek(monthday: MonthdayRange; month: Month; year: int): WeekDay 539 +nim getDaysInYear times.html#getDaysInYear,int proc getDaysInYear(year: int): int 556 +nim `==` times.html#==,IsoYear,IsoYear proc `==`(a, b: IsoYear): bool 563 +nim `$` times.html#$,IsoYear proc `$`(p: IsoYear): string 564 +nim getWeeksInIsoYear times.html#getWeeksInIsoYear,IsoYear proc getWeeksInIsoYear(y: IsoYear): IsoWeekRange 566 +nim getIsoWeekAndYear times.html#getIsoWeekAndYear,DateTime proc getIsoWeekAndYear(dt: DateTime): tuple[isoweek: IsoWeekRange, isoyear: IsoYear] 584 +nim DurationZero times.html#DurationZero const DurationZero 657 +nim initDuration times.html#initDuration,int64,int64,int64,int64,int64,int64,int64,int64 proc initDuration(nanoseconds, microseconds, milliseconds, seconds, minutes, hours,\n days, weeks: int64 = 0): Duration 664 +nim inWeeks times.html#inWeeks,Duration proc inWeeks(dur: Duration): int64 705 +nim inDays times.html#inDays,Duration proc inDays(dur: Duration): int64 712 +nim inHours times.html#inHours,Duration proc inHours(dur: Duration): int64 719 +nim inMinutes times.html#inMinutes,Duration proc inMinutes(dur: Duration): int64 726 +nim inSeconds times.html#inSeconds,Duration proc inSeconds(dur: Duration): int64 733 +nim inMilliseconds times.html#inMilliseconds,Duration proc inMilliseconds(dur: Duration): int64 740 +nim inMicroseconds times.html#inMicroseconds,Duration proc inMicroseconds(dur: Duration): int64 747 +nim inNanoseconds times.html#inNanoseconds,Duration proc inNanoseconds(dur: Duration): int64 754 +nim toParts times.html#toParts,Duration proc toParts(dur: Duration): DurationParts 761 +nim `$` times.html#$,Duration proc `$`(dur: Duration): string 796 +nim `+` times.html#+,Duration,Duration proc `+`(a, b: Duration): Duration 815 +nim `-` times.html#-,Duration,Duration proc `-`(a, b: Duration): Duration 822 +nim `-` times.html#-,Duration proc `-`(a: Duration): Duration 829 +nim `<` times.html#<,Duration,Duration proc `<`(a, b: Duration): bool 835 +nim `<=` times.html#<=,Duration,Duration proc `<=`(a, b: Duration): bool 847 +nim `==` times.html#==,Duration,Duration proc `==`(a, b: Duration): bool 850 +nim `*` times.html#*,int64,Duration proc `*`(a: int64; b: Duration): Duration 858 +nim `*` times.html#*,Duration,int64 proc `*`(a: Duration; b: int64): Duration 866 +nim `+=` times.html#+=,Duration,Duration proc `+=`(d1: var Duration; d2: Duration) 874 +nim `-=` times.html#-=,Duration,Duration proc `-=`(dt: var Duration; ti: Duration) 877 +nim `*=` times.html#*=,Duration,int proc `*=`(a: var Duration; b: int) 880 +nim `div` times.html#div,Duration,int64 proc `div`(a: Duration; b: int64): Duration 883 +nim high times.html#high,typedesc[Duration] proc high(typ: typedesc[Duration]): Duration 896 +nim low times.html#low,typedesc[Duration] proc low(typ: typedesc[Duration]): Duration 900 +nim abs times.html#abs,Duration proc abs(a: Duration): Duration 904 +nim initTime times.html#initTime,int64,NanosecondRange proc initTime(unix: int64; nanosecond: NanosecondRange): Time 914 +nim nanosecond times.html#nanosecond,Time proc nanosecond(time: Time): NanosecondRange 919 +nim fromUnix times.html#fromUnix,int64 proc fromUnix(unix: int64): Time 924 +nim toUnix times.html#toUnix,Time proc toUnix(t: Time): int64 932 +nim fromUnixFloat times.html#fromUnixFloat,float proc fromUnixFloat(seconds: float): Time 939 +nim toUnixFloat times.html#toUnixFloat,Time proc toUnixFloat(t: Time): float 949 +nim fromWinTime times.html#fromWinTime,int64 proc fromWinTime(win: int64): Time 962 +nim toWinTime times.html#toWinTime,Time proc toWinTime(t: Time): int64 970 +nim getTime times.html#getTime proc getTime(): Time 978 +nim `-` times.html#-,Time,Time proc `-`(a, b: Time): Duration 1003 +nim `+` times.html#+,Time,Duration proc `+`(a: Time; b: Duration): Time 1010 +nim `-` times.html#-,Time,Duration proc `-`(a: Time; b: Duration): Time 1016 +nim `<` times.html#<,Time,Time proc `<`(a, b: Time): bool 1022 +nim `<=` times.html#<=,Time,Time proc `<=`(a, b: Time): bool 1028 +nim `==` times.html#==,Time,Time proc `==`(a, b: Time): bool 1032 +nim `+=` times.html#+=,Time,Duration proc `+=`(t: var Time; b: Duration) 1036 +nim `-=` times.html#-=,Time,Duration proc `-=`(t: var Time; b: Duration) 1039 +nim high times.html#high,typedesc[Time] proc high(typ: typedesc[Time]): Time 1042 +nim low times.html#low,typedesc[Time] proc low(typ: typedesc[Time]): Time 1045 +nim nanosecond times.html#nanosecond,DateTime proc nanosecond(dt: DateTime): NanosecondRange 1055 +nim second times.html#second,DateTime proc second(dt: DateTime): SecondRange 1061 +nim minute times.html#minute,DateTime proc minute(dt: DateTime): MinuteRange 1067 +nim hour times.html#hour,DateTime proc hour(dt: DateTime): HourRange 1073 +nim monthday times.html#monthday,DateTime proc monthday(dt: DateTime): MonthdayRange 1079 +nim month times.html#month,DateTime proc month(dt: DateTime): Month 1085 +nim year times.html#year,DateTime proc year(dt: DateTime): int 1092 +nim weekday times.html#weekday,DateTime proc weekday(dt: DateTime): WeekDay 1099 +nim yearday times.html#yearday,DateTime proc yearday(dt: DateTime): YeardayRange 1105 +nim isDst times.html#isDst,DateTime proc isDst(dt: DateTime): bool 1111 +nim timezone times.html#timezone,DateTime proc timezone(dt: DateTime): Timezone 1117 +nim utcOffset times.html#utcOffset,DateTime proc utcOffset(dt: DateTime): int 1123 +nim isInitialized times.html#isInitialized,DateTime proc isInitialized(dt: DateTime): bool 1133 +nim isLeapDay times.html#isLeapDay,DateTime proc isLeapDay(dt: DateTime): bool 1143 +nim toTime times.html#toTime,DateTime proc toTime(dt: DateTime): Time 1157 +nim newTimezone times.html#newTimezone,string,proc(Time),proc(Time) proc newTimezone(name: string; zonedTimeFromTimeImpl: proc (time: Time): ZonedTime {.\n tags: [], raises: [], gcsafe.}; zonedTimeFromAdjTimeImpl: proc (\n adjTime: Time): ZonedTime {.tags: [], raises: [], gcsafe.}): owned Timezone 1197 +nim name times.html#name,Timezone proc name(zone: Timezone): string 1225 +nim zonedTimeFromTime times.html#zonedTimeFromTime,Timezone,Time proc zonedTimeFromTime(zone: Timezone; time: Time): ZonedTime 1237 +nim zonedTimeFromAdjTime times.html#zonedTimeFromAdjTime,Timezone,Time proc zonedTimeFromAdjTime(zone: Timezone; adjTime: Time): ZonedTime 1241 +nim `$` times.html#$,Timezone proc `$`(zone: Timezone): string 1249 +nim `==` times.html#==,Timezone,Timezone proc `==`(zone1, zone2: Timezone): bool 1253 +nim inZone times.html#inZone,Time,Timezone proc inZone(time: Time; zone: Timezone): DateTime 1264 +nim inZone times.html#inZone,DateTime,Timezone proc inZone(dt: DateTime; zone: Timezone): DateTime 1269 +nim utc times.html#utc proc utc(): Timezone 1377 +nim local times.html#local proc local(): Timezone 1386 +nim utc times.html#utc,DateTime proc utc(dt: DateTime): DateTime 1396 +nim local times.html#local,DateTime proc local(dt: DateTime): DateTime 1400 +nim utc times.html#utc,Time proc utc(t: Time): DateTime 1404 +nim local times.html#local,Time proc local(t: Time): DateTime 1408 +nim now times.html#now proc now(): DateTime 1412 +nim dateTime times.html#dateTime,int,Month,MonthdayRange,HourRange,MinuteRange,SecondRange,NanosecondRange,Timezone proc dateTime(year: int; month: Month; monthday: MonthdayRange; hour: HourRange = 0;\n minute: MinuteRange = 0; second: SecondRange = 0;\n nanosecond: NanosecondRange = 0; zone: Timezone = local()): DateTime 1420 +nim initDateTime times.html#initDateTime,MonthdayRange,Month,int,HourRange,MinuteRange,SecondRange,NanosecondRange,Timezone proc initDateTime(monthday: MonthdayRange; month: Month; year: int; hour: HourRange;\n minute: MinuteRange; second: SecondRange;\n nanosecond: NanosecondRange; zone: Timezone = local()): DateTime 1440 +nim initDateTime times.html#initDateTime,MonthdayRange,Month,int,HourRange,MinuteRange,SecondRange,Timezone proc initDateTime(monthday: MonthdayRange; month: Month; year: int; hour: HourRange;\n minute: MinuteRange; second: SecondRange; zone: Timezone = local()): DateTime 1449 +nim `+` times.html#+,DateTime,Duration proc `+`(dt: DateTime; dur: Duration): DateTime 1457 +nim `-` times.html#-,DateTime,Duration proc `-`(dt: DateTime; dur: Duration): DateTime 1465 +nim `-` times.html#-,DateTime,DateTime proc `-`(dt1, dt2: DateTime): Duration 1473 +nim `<` times.html#<,DateTime,DateTime proc `<`(a, b: DateTime): bool 1483 +nim `<=` times.html#<=,DateTime,DateTime proc `<=`(a, b: DateTime): bool 1487 +nim `==` times.html#==,DateTime,DateTime proc `==`(a, b: DateTime): bool 1491 +nim `+=` times.html#+=,DateTime,Duration proc `+=`(a: var DateTime; b: Duration) 1497 +nim `-=` times.html#-=,DateTime,Duration proc `-=`(a: var DateTime; b: Duration) 1500 +nim getDateStr times.html#getDateStr proc getDateStr(dt = now()): string 1503 +nim getClockStr times.html#getClockStr proc getClockStr(dt = now()): string 1515 +nim initDateTime times.html#initDateTime,WeekDay,IsoWeekRange,IsoYear,HourRange,MinuteRange,SecondRange,NanosecondRange,Timezone proc initDateTime(weekday: WeekDay; isoweek: IsoWeekRange; isoyear: IsoYear;\n hour: HourRange; minute: MinuteRange; second: SecondRange;\n nanosecond: NanosecondRange; zone: Timezone = local()): DateTime 1532 +nim initDateTime times.html#initDateTime,WeekDay,IsoWeekRange,IsoYear,HourRange,MinuteRange,SecondRange,Timezone proc initDateTime(weekday: WeekDay; isoweek: IsoWeekRange; isoyear: IsoYear;\n hour: HourRange; minute: MinuteRange; second: SecondRange;\n zone: Timezone = local()): DateTime 1537 +nim DateTimeLocale times.html#DateTimeLocale object DateTimeLocale 1549 +nim TimeFormat times.html#TimeFormat object TimeFormat 1607 +nim TimeParseError times.html#TimeParseError object TimeParseError 1620 +nim TimeFormatParseError times.html#TimeFormatParseError object TimeFormatParseError 1623 +nim DefaultLocale times.html#DefaultLocale const DefaultLocale 1627 +nim `$` times.html#$,TimeFormat proc `$`(f: TimeFormat): string 1639 +nim initTimeFormat times.html#initTimeFormat,string proc initTimeFormat(format: string): TimeFormat 1763 +nim format times.html#format,DateTime,TimeFormat,DateTimeLocale proc format(dt: DateTime; f: TimeFormat; loc: DateTimeLocale = DefaultLocale): string 2182 +nim format times.html#format,DateTime,string,DateTimeLocale proc format(dt: DateTime; f: string; loc: DateTimeLocale = DefaultLocale): string 2205 +nim format times.html#format,DateTime,static[string] proc format(dt: DateTime; f: static[string]): string 2217 +nim formatValue times.html#formatValue,string,,string proc formatValue(result: var string; value: DateTime | Time; specifier: string) 2222 +nim format times.html#format,Time,string,Timezone proc format(time: Time; f: string; zone: Timezone = local()): string 2227 +nim format times.html#format,Time,static[string],Timezone proc format(time: Time; f: static[string]; zone: Timezone = local()): string 2240 +nim parse times.html#parse,string,TimeFormat,Timezone,DateTimeLocale proc parse(input: string; f: TimeFormat; zone: Timezone = local();\n loc: DateTimeLocale = DefaultLocale): DateTime 2246 +nim parse times.html#parse,string,string,Timezone,DateTimeLocale proc parse(input, f: string; tz: Timezone = local();\n loc: DateTimeLocale = DefaultLocale): DateTime 2294 +nim parse times.html#parse,string,static[string],Timezone,DateTimeLocale proc parse(input: string; f: static[string]; zone: Timezone = local();\n loc: DateTimeLocale = DefaultLocale): DateTime 2307 +nim parseTime times.html#parseTime,string,string,Timezone proc parseTime(input, f: string; zone: Timezone): Time 2313 +nim parseTime times.html#parseTime,string,static[string],Timezone proc parseTime(input: string; f: static[string]; zone: Timezone): Time 2324 +nim `$` times.html#$,DateTime proc `$`(dt: DateTime): string 2330 +nim `$` times.html#$,Time proc `$`(time: Time): string 2342 +nim initTimeInterval times.html#initTimeInterval,int,int,int,int,int,int,int,int,int,int proc initTimeInterval(nanoseconds, microseconds, milliseconds, seconds, minutes,\n hours, days, weeks, months, years: int = 0): TimeInterval 2355 +nim `+` times.html#+,TimeInterval,TimeInterval proc `+`(ti1, ti2: TimeInterval): TimeInterval 2382 +nim `-` times.html#-,TimeInterval proc `-`(ti: TimeInterval): TimeInterval 2395 +nim `-` times.html#-,TimeInterval,TimeInterval proc `-`(ti1, ti2: TimeInterval): TimeInterval 2414 +nim `+=` times.html#+=,TimeInterval,TimeInterval proc `+=`(a: var TimeInterval; b: TimeInterval) 2425 +nim `-=` times.html#-=,TimeInterval,TimeInterval proc `-=`(a: var TimeInterval; b: TimeInterval) 2428 +nim between times.html#between,DateTime,DateTime proc between(startDt, endDt: DateTime): TimeInterval 2444 +nim toParts times.html#toParts,TimeInterval proc toParts(ti: TimeInterval): TimeIntervalParts 2549 +nim `$` times.html#$,TimeInterval proc `$`(ti: TimeInterval): string 2565 +nim nanoseconds times.html#nanoseconds,int proc nanoseconds(nanos: int): TimeInterval 2580 +nim microseconds times.html#microseconds,int proc microseconds(micros: int): TimeInterval 2584 +nim milliseconds times.html#milliseconds,int proc milliseconds(ms: int): TimeInterval 2588 +nim seconds times.html#seconds,int proc seconds(s: int): TimeInterval 2592 +nim minutes times.html#minutes,int proc minutes(m: int): TimeInterval 2598 +nim hours times.html#hours,int proc hours(h: int): TimeInterval 2604 +nim days times.html#days,int proc days(d: int): TimeInterval 2610 +nim weeks times.html#weeks,int proc weeks(w: int): TimeInterval 2616 +nim months times.html#months,int proc months(m: int): TimeInterval 2622 +nim years times.html#years,int proc years(y: int): TimeInterval 2628 +nim `+` times.html#+,DateTime,TimeInterval proc `+`(dt: DateTime; interval: TimeInterval): DateTime 2675 +nim `-` times.html#-,DateTime,TimeInterval proc `-`(dt: DateTime; interval: TimeInterval): DateTime 2704 +nim `+` times.html#+,Time,TimeInterval proc `+`(time: Time; interval: TimeInterval): Time 2715 +nim `-` times.html#-,Time,TimeInterval proc `-`(time: Time; interval: TimeInterval): Time 2728 +nim `+=` times.html#+=,DateTime,TimeInterval proc `+=`(a: var DateTime; b: TimeInterval) 2741 +nim `-=` times.html#-=,DateTime,TimeInterval proc `-=`(a: var DateTime; b: TimeInterval) 2744 +nim `+=` times.html#+=,Time,TimeInterval proc `+=`(t: var Time; b: TimeInterval) 2747 +nim `-=` times.html#-=,Time,TimeInterval proc `-=`(t: var Time; b: TimeInterval) 2750 +nim epochTime times.html#epochTime proc epochTime(): float 2784 +nim cpuTime times.html#cpuTime proc cpuTime(): float 2825 +nim nanosecond= times.html#nanosecond=,DateTime,NanosecondRange proc nanosecond=(dt: var DateTime; value: NanosecondRange) 2857 +nim second= times.html#second=,DateTime,SecondRange proc second=(dt: var DateTime; value: SecondRange) 2860 +nim minute= times.html#minute=,DateTime,MinuteRange proc minute=(dt: var DateTime; value: MinuteRange) 2863 +nim hour= times.html#hour=,DateTime,HourRange proc hour=(dt: var DateTime; value: HourRange) 2866 +nim monthdayZero= times.html#monthdayZero=,DateTime,int proc monthdayZero=(dt: var DateTime; value: int) 2869 +nim monthZero= times.html#monthZero=,DateTime,int proc monthZero=(dt: var DateTime; value: int) 2872 +nim year= times.html#year=,DateTime,int proc year=(dt: var DateTime; value: int) 2875 +nim weekday= times.html#weekday=,DateTime,WeekDay proc weekday=(dt: var DateTime; value: WeekDay) 2878 +nim yearday= times.html#yearday=,DateTime,YeardayRange proc yearday=(dt: var DateTime; value: YeardayRange) 2881 +nim isDst= times.html#isDst=,DateTime,bool proc isDst=(dt: var DateTime; value: bool) 2884 +nim timezone= times.html#timezone=,DateTime,Timezone proc timezone=(dt: var DateTime; value: Timezone) 2887 +nim utcOffset= times.html#utcOffset=,DateTime,int proc utcOffset=(dt: var DateTime; value: int) 2890 +heading Examples times.html#examples Examples 0 +heading Parsing and Formatting Dates times.html#parsing-and-formatting-dates Parsing and Formatting Dates 0 +heading Duration vs TimeInterval times.html#duration-vs-timeinterval Duration vs TimeInterval 0 +heading Duration times.html#duration-vs-timeinterval-duration Duration 0 +heading TimeInterval times.html#duration-vs-timeinterval-timeinterval TimeInterval 0 +heading How long is a day? times.html#duration-vs-timeinterval-how-long-is-a-dayqmark How long is a day? 0 +heading See also times.html#see-also See also 0 +nimgrp - times.html#--procs-all proc 822 +nimgrp < times.html#<-procs-all proc 835 +nimgrp parse times.html#parse-procs-all proc 2246 +nimgrp initdatetime times.html#initDateTime-procs-all proc 1440 +nimgrp == times.html#==-procs-all proc 563 +nimgrp format times.html#format-procs-all proc 2182 +nimgrp * times.html#*-procs-all proc 858 +nimgrp += times.html#+=-procs-all proc 874 +nimgrp parsetime times.html#parseTime-procs-all proc 2313 +nimgrp -= times.html#-=-procs-all proc 877 +nimgrp high times.html#high-procs-all proc 896 +nimgrp <= times.html#<=-procs-all proc 847 +nimgrp nanosecond times.html#nanosecond-procs-all proc 919 +nimgrp low times.html#low-procs-all proc 900 +nimgrp + times.html#+-procs-all proc 815 +nimgrp $ times.html#$-procs-all proc 564 +nimgrp inzone times.html#inZone-procs-all proc 1264 +nimgrp local times.html#local-procs-all proc 1386 +nimgrp toparts times.html#toParts-procs-all proc 761 +nimgrp utc times.html#utc-procs-all proc 1377 diff --git a/tinyc.html b/tinyc.html new file mode 100644 index 0000000000000..3e0ff09b3415c --- /dev/null +++ b/tinyc.html @@ -0,0 +1,540 @@ + + + + + + + +std/tinyc + + + + + + + + + + + + + + + + +
+
+

std/tinyc

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
+

Types

+
+
+
ErrorFunc = proc (opaque: pointer; msg: cstring) {.cdecl.}
+
+ + + Source   +Edit   + +
+
+
+
PccState = ptr CcState
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
OutputDll: cint = 3
+
+ + dynamic library + Source   +Edit   + +
+
+
+
OutputExe: cint = 2
+
+ + executable file + Source   +Edit   + +
+
+
+
OutputMemory: cint = 1
+
+ + output will be ran in memory (no output file) (default) + Source   +Edit   + +
+
+
+
OutputObj: cint = 4
+
+ + object file + Source   +Edit   + +
+
+
+
OutputPreprocess: cint = 5
+
+ + preprocessed file (used internally) + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc addFile(s: PccState; filename: cstring): cint {.cdecl,
+    importc: "tcc_add_file", ...raises: [], tags: [], forbids: [].}
+
+ + add a file (either a C file, dll, an object, a library or an ld script). Return -1 if error. + Source   +Edit   + +
+
+ +
+
+
+
proc addIncludePath(s: PccState; pathname: cstring) {.cdecl,
+    importc: "tcc_add_include_path", ...raises: [], tags: [], forbids: [].}
+
+ + add include path + Source   +Edit   + +
+
+ +
+
+
+
proc addLibrary(s: PccState; libraryname: cstring): cint {.cdecl,
+    importc: "tcc_add_library", ...raises: [], tags: [], forbids: [].}
+
+ + the library name is the same as the argument of the '-l' option + Source   +Edit   + +
+
+ +
+
+
+
proc addLibraryPath(s: PccState; pathname: cstring): cint {.cdecl,
+    importc: "tcc_add_library_path", ...raises: [], tags: [], forbids: [].}
+
+ + equivalent to -Lpath option + Source   +Edit   + +
+
+ +
+
+
+
proc addSymbol(s: PccState; name: cstring; val: pointer): cint {.cdecl,
+    importc: "tcc_add_symbol", ...raises: [], tags: [], forbids: [].}
+
+ + add a symbol to the compiled program + Source   +Edit   + +
+
+ +
+
+
+
proc addSysincludePath(s: PccState; pathname: cstring) {.cdecl,
+    importc: "tcc_add_sysinclude_path", ...raises: [], tags: [], forbids: [].}
+
+ + add in system include path + Source   +Edit   + +
+
+ +
+
+
+
proc closeCCState(s: PccState) {.importc: "tcc_delete", cdecl, ...raises: [],
+                                 tags: [], forbids: [].}
+
+ + free a TCC compilation context + Source   +Edit   + +
+
+ +
+
+
+
proc compileString(s: PccState; buf: cstring): cint {.cdecl,
+    importc: "tcc_compile_string", ...raises: [], tags: [], forbids: [].}
+
+ + compile a string containing a C source. Return non zero if error. + Source   +Edit   + +
+
+ +
+
+
+
proc defineSymbol(s: PccState; sym, value: cstring) {.cdecl,
+    importc: "tcc_define_symbol", ...raises: [], tags: [], forbids: [].}
+
+ + define preprocessor symbol 'sym'. Can put optional value + Source   +Edit   + +
+
+ +
+
+
+
proc getSymbol(s: PccState; name: cstring): pointer {.cdecl,
+    importc: "tcc_get_symbol", ...raises: [], tags: [], forbids: [].}
+
+ + return symbol value or NULL if not found + Source   +Edit   + +
+
+ +
+
+
+
proc openCCState(): PccState {.importc: "tcc_new", cdecl, ...raises: [], tags: [],
+                               forbids: [].}
+
+ + create a new TCC compilation context + Source   +Edit   + +
+
+ +
+
+
+
proc outputFile(s: PccState; filename: cstring): cint {.cdecl,
+    importc: "tcc_output_file", ...raises: [], tags: [], forbids: [].}
+
+ + output an executable, library or object file. DO NOT call tcc_relocate() before. + Source   +Edit   + +
+
+ +
+
+
+
proc relocate(s: PccState; p: pointer): cint {.cdecl, importc: "tcc_relocate",
+    ...raises: [], tags: [], forbids: [].}
+
+ + copy code into memory passed in by the caller and do all relocations (needed before using tcc_get_symbol()). returns -1 on error and required size if ptr is NULL + Source   +Edit   + +
+
+ +
+
+
+
proc run(s: PccState; argc: cint; argv: cstringArray): cint {.cdecl,
+    importc: "tcc_run", ...raises: [], tags: [], forbids: [].}
+
+ + link and run main() function and return its value. DO NOT call tcc_relocate() before. + Source   +Edit   + +
+
+ +
+
+
+
proc setErrorFunc(s: PccState; errorOpaque: pointer; errorFun: ErrorFunc) {.
+    cdecl, importc: "tcc_set_error_func", ...raises: [], tags: [], forbids: [].}
+
+ + set error/warning display callback + Source   +Edit   + +
+
+ +
+
+
+
proc setLibPath(s: PccState; path: cstring) {.cdecl,
+    importc: "tcc_set_lib_path", ...raises: [], tags: [], forbids: [].}
+
+ + set CONFIG_TCCDIR at runtime + Source   +Edit   + +
+
+ +
+
+
+
proc setOptions(s: PccState; options: cstring) {.cdecl,
+    importc: "tcc_set_options", ...raises: [], tags: [], forbids: [].}
+
+ + set a options + Source   +Edit   + +
+
+ +
+
+
+
proc setOutputType(s: PccState; outputType: cint): cint {.cdecl,
+    importc: "tcc_set_output_type", ...raises: [], tags: [], forbids: [].}
+
+ + set output type. MUST BE CALLED before any compilation + Source   +Edit   + +
+
+ +
+
+
+
proc undefineSymbol(s: PccState; sym: cstring) {.cdecl,
+    importc: "tcc_undefine_symbol", ...raises: [], tags: [], forbids: [].}
+
+ + undefine preprocess symbol 'sym' + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/tools.html b/tools.html new file mode 100644 index 0000000000000..71821603199a0 --- /dev/null +++ b/tools.html @@ -0,0 +1,52 @@ + + + + + + + +Tools available with Nim + + + + + + + + + + + + + + + + +
+
+

Tools available with Nim

+

The standard distribution ships with the following tools:

+
  • atlas
    atlas is a simple package cloner tool. It manages an isolated workspace that contains projects and dependencies.

  • +
  • Hot code reloading
    The "Hot code reloading" feature is built into the compiler but has its own document explaining how it works.

  • +
  • Documentation generator
    The builtin document generator nim doc generates HTML documentation from .nim source files.

  • +
  • Nimsuggest for IDE support
    Through the nimsuggest tool, any IDE can query a .nim source file and obtain useful information like the definition of symbols or suggestions for completion.

  • +
  • C2nim
    C to Nim source converter. Translates C header files to Nim.

  • +
  • niminst
    niminst is a tool to generate an installer for a Nim program.

  • +
  • nimgrep
    Nim search and replace utility.

  • +
  • nimpretty
    nimpretty is a Nim source code beautifier, to format code according to the official style guide.

  • +
  • testament
    testament is an advanced automatic unittests runner for Nim tests, is used for the development of Nim itself, offers process isolation for your tests, it can generate statistics about test cases, supports multiple targets (C, JS, etc), has logging, can generate HTML reports, skip tests from a file, and more, so can be useful to run your tests, even the most complex ones.

  • +
+ + + + +
+
+ + + + diff --git a/tools.idx b/tools.idx new file mode 100644 index 0000000000000..6d993578dcf96 --- /dev/null +++ b/tools.idx @@ -0,0 +1 @@ +markupTitle Tools available with Nim tools.html Tools available with Nim 0 diff --git a/tut1.html b/tut1.html new file mode 100644 index 0000000000000..23d049fc937f7 --- /dev/null +++ b/tut1.html @@ -0,0 +1,1070 @@ + + + + + + + +Nim Tutorial (Part I) + + + + + + + + + + + + + + + + +
+
+

Nim Tutorial (Part I)

+
+ +
+ Source   +Edit   + +
+ +

+ +
Author:Andreas Rumpf
Version:2.2.1
+

Introduction

"Der Mensch ist doch ein Augentier -- Schöne Dinge wünsch' ich mir."

+

This document is a tutorial for the programming language Nim.

+

This tutorial assumes that you are familiar with basic programming concepts like variables, types, or statements.

+

Here are several other resources for learning Nim:

+ +

All code examples in this tutorial, as well as the ones found in the rest of Nim's documentation, follow the Nim style guide.

+ +

The first program

We start the tour with a modified "hello world" program:

+

# This is a comment
+echo "What's your name? "
+var name: string = readLine(stdin)
+echo "Hi, ", name, "!"

+

Save this code to the file "greetings.nim". Now compile and run it:

+

nim compile --run greetings.nim

+

With the --run switch Nim executes the file automatically after compilation. You can give your program command-line arguments by appending them after the filename:

+

nim compile --run greetings.nim arg1 arg2

+

Commonly used commands and switches have abbreviations, so you can also use:

+

nim c -r greetings.nim

+

This is a debug version. To compile a release version use:

+

nim c -d:release greetings.nim

+

By default, the Nim compiler generates a large number of runtime checks aiming for your debugging pleasure. With -d:release some checks are turned off and optimizations are turned on.

+

For benchmarking or production code, use the -d:release switch. For comparing the performance with unsafe languages like C, use the -d:danger switch in order to get meaningful, comparable results. Otherwise, Nim might be handicapped by checks that are not even available for C.

+

Though it should be pretty obvious what the program does, I will explain the syntax: statements which are not indented are executed when the program starts. Indentation is Nim's way of grouping statements. Indentation is done with spaces only, tabulators are not allowed.

+

String literals are enclosed in double-quotes. The var statement declares a new variable named name of type string with the value that is returned by the readLine procedure. Since the compiler knows that readLine returns a string, you can leave out the type in the declaration (this is called local type inference). So this will work too:

+

var name = readLine(stdin)

+

Note that this is basically the only form of type inference that exists in Nim: it is a good compromise between brevity and readability.

+

The "hello world" program contains several identifiers that are already known to the compiler: echo, readLine, etc. These built-ins are declared in the system module which is implicitly imported by any other module.

+ +

Lexical elements

Let us look at Nim's lexical elements in more detail: like other programming languages Nim consists of (string) literals, identifiers, keywords, comments, operators, and other punctuation marks.

+ +

String and character literals

String literals are enclosed in double-quotes; character literals in single quotes. Special characters are escaped with \: \n means newline, \t means tabulator, etc. There are also raw string literals:

+

r"C:\program files\nim"

+

In raw literals, the backslash is not an escape character.

+

The third and last way to write string literals is long-string literals. They are written with three quotes: """ ... """; they can span over multiple lines and the \ is not an escape character either. They are very useful for embedding HTML code templates for example.

+ +

Comments

Comments start anywhere outside a string or character literal with the hash character #. Documentation comments start with ##:

+

# A comment.
+
+var myVariable: int ## a documentation comment

+

Documentation comments are tokens; they are only allowed at certain places in the input file as they belong to the syntax tree! This feature enables simpler documentation generators.

+

Multiline comments are started with #[ and terminated with ]#. Multiline comments can also be nested.

+

#[
+You can have any Nim code text commented
+out inside this with no indentation restrictions.
+      yes("May I ask a pointless question?")
+  #[
+     Note: these can be nested!!
+  ]#
+]#

+ +

Numbers

Numerical literals are written as in most other languages. As a special twist, underscores are allowed for better readability: 1_000_000 (one million). A number that contains a dot (or 'e' or 'E') is a floating-point literal: 1.0e9 (one billion). Hexadecimal literals are prefixed with 0x, binary literals with 0b and octal literals with 0o. A leading zero alone does not produce an octal.

+ +

The var statement

The var statement declares a new local or global variable:

+

var x, y: int # declares x and y to have the type `int`

+

Indentation can be used after the var keyword to list a whole section of variables:

+

var
+  x, y: int
+  # a comment can occur here too
+  a, b, c: string

+ +

Constants

Constants are symbols which are bound to a value. The constant's value cannot change. The compiler must be able to evaluate the expression in a constant declaration at compile time:

+

const x = "abc" # the constant x contains the string "abc"

+

Indentation can be used after the const keyword to list a whole section of constants:

+

const
+  x = 1
+  # a comment can occur here too
+  y = 2
+  z = y + 5 # computations are possible

+ +

The let statement

The let statement works like the var statement but the declared symbols are single assignment variables: After the initialization their value cannot change:

+

let x = "abc" # introduces a new variable `x` and binds a value to it
+x = "xyz"     # Illegal: assignment to `x`

+

The difference between let and const is: let introduces a variable that can not be re-assigned, const means "enforce compile time evaluation and put it into a data section":

+

const input = readLine(stdin) # Error: constant expression expected

+

let input = readLine(stdin)   # works

+ +

The assignment statement

The assignment statement assigns a new value to a variable or more generally to a storage location:

+

var x = "abc" # introduces a new variable `x` and assigns a value to it
+x = "xyz"     # assigns a new value to `x`

+

= is the assignment operator. The assignment operator can be overloaded. You can declare multiple variables with a single assignment statement and all the variables will have the same value:

+

var x, y = 3  # assigns 3 to the variables `x` and `y`
+echo "x ", x  # outputs "x 3"
+echo "y ", y  # outputs "y 3"
+x = 42        # changes `x` to 42 without changing `y`
+echo "x ", x  # outputs "x 42"
+echo "y ", y  # outputs "y 3"

+ +

Control flow statements

The greetings program consists of 3 statements that are executed sequentially. Only the most primitive programs can get away with that: branching and looping are needed too.

+ +

If statement

The if statement is one way to branch the control flow:

+

let name = readLine(stdin)
+if name == "":
+  echo "Poor soul, you lost your name?"
+elif name == "name":
+  echo "Very funny, your name is name."
+else:
+  echo "Hi, ", name, "!"

+

There can be zero or more elif parts, and the else part is optional. The keyword elif is short for else if, and is useful to avoid excessive indentation. (The "" is the empty string. It contains no characters.)

+ +

Case statement

Another way to branch is provided by the case statement. A case statement allows for multiple branches:

+

let name = readLine(stdin)
+case name
+of "":
+  echo "Poor soul, you lost your name?"
+of "name":
+  echo "Very funny, your name is name."
+of "Dave", "Frank":
+  echo "Cool name!"
+else:
+  echo "Hi, ", name, "!"

+

As it can be seen, for an of branch a comma-separated list of values is also allowed.

+

The case statement can deal with integers, other ordinal types, and strings. (What an ordinal type is will be explained soon.) For integers or other ordinal types value ranges are also possible:

+

# this statement will be explained later:
+from std/strutils import parseInt
+
+echo "A number please: "
+let n = parseInt(readLine(stdin))
+case n
+of 0..2, 4..7: echo "The number is in the set: {0, 1, 2, 4, 5, 6, 7}"
+of 3, 8: echo "The number is 3 or 8"

+

However, the above code does not compile: the reason is that you have to cover every value that n may contain, but the code only handles the values 0..8. Since it is not very practical to list every other possible integer (though it is possible thanks to the range notation), we fix this by telling the compiler that for every other value nothing should be done:

+

...
+case n
+of 0..2, 4..7: echo "The number is in the set: {0, 1, 2, 4, 5, 6, 7}"
+of 3, 8: echo "The number is 3 or 8"
+else: discard

+

The empty discard statement is a do nothing statement. The compiler knows that a case statement with an else part cannot fail and thus the error disappears. Note that it is impossible to cover all possible string values: that is why string cases always need an else branch.

+

In general, the case statement is used for subrange types or enumerations where it is of great help that the compiler checks that you covered any possible value.

+ +

While statement

The while statement is a simple looping construct:

+

echo "What's your name? "
+var name = readLine(stdin)
+while name == "":
+  echo "Please tell me your name: "
+  name = readLine(stdin) # no `var`, because we do not declare a new variable here

+

The example uses a while loop to keep asking the users for their name, as long as the user types in nothing (only presses RETURN).

+ +

For statement

The for statement is a construct to loop over any element an iterator provides. The example uses the built-in countup iterator:

+

echo "Counting to ten: "
+for i in countup(1, 10):
+  echo i
+# --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines

+

The variable i is implicitly declared by the for loop and has the type int, because that is what countup returns. i runs through the values 1, 2, .., 10. Each value is echo-ed. This code does the same:

+

echo "Counting to 10: "
+var i = 1
+while i <= 10:
+  echo i
+  inc i # increment i by 1
+# --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines

+

Since counting up occurs so often in programs, Nim also has a .. iterator that does the same:

+

for i in 1 .. 10:
+  ...

+

Counting down can be achieved as easily (but is less often needed):

+

echo "Counting down from 10 to 1: "
+for i in countdown(10, 1):
+  echo i
+# --> Outputs 10 9 8 7 6 5 4 3 2 1 on different lines

+

Zero-indexed counting has two shortcuts ..< and .. ^1 (backward index operator) to simplify counting to one less than the higher index:

+

for i in 0 ..< 10:
+  ...  # the same as 0 .. 9

+

or

+

var s = "some string"
+for i in 0 ..< s.len:
+  ...

+

or

+

var s = "some string"
+for idx, c in s[0 .. ^1]:
+  ... # ^1 is the last element, ^2 would be one before it, and so on

+

Other useful iterators for collections (like arrays and sequences) are

+
  • items and mitems, which provides immutable and mutable elements respectively, and
  • +
  • pairs and mpairs which provides the element and an index number (immutable and mutable respectively)

    +

    for index, item in ["a","b"].pairs:
    +  echo item, " at index ", index
    +# => a at index 0
    +# => b at index 1

    +
  • +
+ +

Scopes and the block statement

Control flow statements have a feature not covered yet: they open a new scope. This means that in the following example, x is not accessible outside the loop:

+

while false:
+  var x = "hi"
+echo x # does not work

+

A while (for) statement introduces an implicit block. Identifiers are only visible within the block they have been declared. The block statement can be used to open a new block explicitly:

+

block myblock:
+  var x = "hi"
+echo x # does not work either

+

The block's label (myblock in the example) is optional.

+ +

Break statement

A block can be left prematurely with a break statement. The break statement can leave a while, for, or a block statement. It leaves the innermost construct, unless a label of a block is given:

+

block myblock:
+  echo "entering block"
+  while true:
+    echo "looping"
+    break # leaves the loop, but not the block
+  echo "still in block"
+echo "outside the block"
+
+block myblock2:
+  echo "entering block"
+  while true:
+    echo "looping"
+    break myblock2 # leaves the block (and the loop)
+  echo "still in block" # it won't be printed
+echo "outside the block"

+ +

Continue statement

Like in many other programming languages, a continue statement starts the next iteration immediately:

+

for i in 1 .. 5:
+  if i <= 3: continue
+  echo i # will only print 4 and 5

+ +

When statement

Example:

+

when system.hostOS == "windows":
+  echo "running on Windows!"
+elif system.hostOS == "linux":
+  echo "running on Linux!"
+elif system.hostOS == "macosx":
+  echo "running on Mac OS X!"
+else:
+  echo "unknown operating system"

+

The when statement is almost identical to the if statement, but with these differences:

+
  • Each condition must be a constant expression since it is evaluated by the compiler.
  • +
  • The statements within a branch do not open a new scope.
  • +
  • The compiler checks the semantics and produces code only for the statements that belong to the first condition that evaluates to true.
  • +
+

The when statement is useful for writing platform-specific code, similar to the #ifdef construct in the C programming language.

+ +

Statements and indentation

Now that we covered the basic control flow statements, let's return to Nim indentation rules.

+

In Nim, there is a distinction between simple statements and complex statements. Simple statements cannot contain other statements: Assignment, procedure calls, or the return statement are all simple statements. Complex statements like if, when, for, while can contain other statements. To avoid ambiguities, complex statements must always be indented, but single simple statements do not:

+

# no indentation needed for single-assignment statement:
+if x: x = false
+
+# indentation needed for nested if statement:
+if x:
+  if y:
+    y = false
+  else:
+    y = true
+
+# indentation needed, because two statements follow the condition:
+if x:
+  x = false
+  y = false

+

Expressions are parts of a statement that usually result in a value. The condition in an if statement is an example of an expression. Expressions can contain indentation at certain places for better readability:

+

if thisIsaLongCondition() and
+    thisIsAnotherLongCondition(1,
+       2, 3, 4):
+  x = true

+

As a rule of thumb, indentation within expressions is allowed after operators, an open parenthesis and after commas.

+

With parenthesis and semicolons (;) you can use statements where only an expression is allowed:

+

# computes fac(4) at compile time:
+const fac4 = (var x = 1; for i in 1..4: x *= i; x)

+ +

Procedures

To define new commands like echo and readLine in the examples, the concept of a procedure is needed. You might be used to them being called methods or functions in other languages, but Nim differentiates these concepts. In Nim, new procedures are defined with the proc keyword:

+

proc yes(question: string): bool =
+  echo question, " (y/n)"
+  while true:
+    case readLine(stdin)
+    of "y", "Y", "yes", "Yes": return true
+    of "n", "N", "no", "No": return false
+    else: echo "Please be clear: yes or no"
+
+if yes("Should I delete all your important files?"):
+  echo "I'm sorry Dave, I'm afraid I can't do that."
+else:
+  echo "I think you know what the problem is just as well as I do."

+

This example shows a procedure named yes that asks the user a question and returns true if they answered "yes" (or something similar) and returns false if they answered "no" (or something similar). A return statement leaves the procedure (and therefore the while loop) immediately. The (question: string): bool syntax describes that the procedure expects a parameter named question of type string and returns a value of type bool. The bool type is built-in: the only valid values for bool are true and false. The conditions in if or while statements must be of type bool.

+

Some terminology: in the example question is called a (formal) parameter, "Should I..." is called an argument that is passed to this parameter.

+ +

Result variable

A procedure that returns a value has an implicit result variable declared that represents the return value. A return statement with no expression is shorthand for return result. The result value is always returned automatically at the end of a procedure if there is no return statement at the exit.

+

proc sumTillNegative(x: varargs[int]): int =
+  for i in x:
+    if i < 0:
+      return
+    result = result + i
+
+echo sumTillNegative() # echoes 0
+echo sumTillNegative(3, 4, 5) # echoes 12
+echo sumTillNegative(3, 4 , -1 , 6) # echoes 7

+

The result variable is already implicitly declared at the start of the function, so declaring it again with 'var result', for example, would shadow it with a normal variable of the same name. The result variable is also already initialized with the type's default value. Note that referential data types will be nil at the start of the procedure, and thus may require manual initialization.

+

A procedure that does not have any return statement and does not use the special result variable returns the value of its last expression. For example, this procedure

+

proc helloWorld(): string =
+  "Hello, World!"

+

returns the string "Hello, World!".

+ +

Parameters

Parameters are immutable in the procedure body. By default, their value cannot be changed because this allows the compiler to implement parameter passing in the most efficient way. If a mutable variable is needed inside the procedure, it has to be declared with var in the procedure body. Shadowing the parameter name is possible, and actually an idiom:

+

proc printSeq(s: seq, nprinted: int = -1) =
+  var nprinted = if nprinted == -1: s.len else: min(nprinted, s.len)
+  for i in 0 ..< nprinted:
+    echo s[i]

+

If the procedure needs to modify the argument for the caller, a var parameter can be used:

+

proc divmod(a, b: int; res, remainder: var int) =
+  res = a div b        # integer division
+  remainder = a mod b  # integer modulo operation
+
+var
+  x, y: int
+divmod(8, 5, x, y) # modifies x and y
+echo x
+echo y

+

In the example, res and remainder are var parameters. Var parameters can be modified by the procedure and the changes are visible to the caller. Note that the above example would better make use of a tuple as a return value instead of using var parameters.

+ +

Discard statement

To call a procedure that returns a value just for its side effects and ignoring its return value, a discard statement must be used. Nim does not allow silently throwing away a return value:

+

discard yes("May I ask a pointless question?")

+

The return value can be ignored implicitly if the called proc/iterator has been declared with the discardable pragma:

+

proc p(x, y: int): int {.discardable.} =
+  return x + y
+
+p(3, 4) # now valid

+ +

Named arguments

Often a procedure has many parameters and it is not clear in which order the parameters appear. This is especially true for procedures that construct a complex data type. Therefore, the arguments to a procedure can be named, so that it is clear which argument belongs to which parameter:

+

proc createWindow(x, y, width, height: int; title: string;
+                  show: bool): Window =
+   ...
+
+var w = createWindow(show = true, title = "My Application",
+                     x = 0, y = 0, height = 600, width = 800)

+

Now that we use named arguments to call createWindow the argument order does not matter anymore. Mixing named arguments with ordered arguments is also possible, but not very readable:

+

var w = createWindow(0, 0, title = "My Application",
+                     height = 600, width = 800, true)

+

The compiler checks that each parameter receives exactly one argument.

+ +

Default values

To make the createWindow proc easier to use it should provide default values; these are values that are used as arguments if the caller does not specify them:

+

proc createWindow(x = 0, y = 0, width = 500, height = 700,
+                  title = "unknown",
+                  show = true): Window =
+   ...
+
+var w = createWindow(title = "My Application", height = 600, width = 800)

+

Now the call to createWindow only needs to set the values that differ from the defaults.

+

Note that type inference works for parameters with default values; there is no need to write title: string = "unknown", for example.

+ +

Overloaded procedures

Nim provides the ability to overload procedures similar to C++:

+

proc toString(x: int): string =
+  result =
+    if x < 0: "negative"
+    elif x > 0: "positive"
+    else: "zero"
+
+proc toString(x: bool): string =
+  result =
+    if x: "yep"
+    else: "nope"
+
+assert toString(13) == "positive" # calls the toString(x: int) proc
+assert toString(true) == "yep"    # calls the toString(x: bool) proc

+

(Note that toString is usually the $ operator in Nim.) The compiler chooses the most appropriate proc for the toString calls. How this overloading resolution algorithm works exactly is not discussed here -- see the manual for details. Ambiguous calls are reported as errors.

+ +

Operators

The Nim standard library makes heavy use of overloading - one reason for this is that each operator like + is just an overloaded proc. The parser lets you use operators in infix notation (a + b) or prefix notation (+ a). An infix operator always receives two arguments, a prefix operator always one. (Postfix operators are not possible, because this would be ambiguous: does a @ @ b mean (a) @ (@b) or (a@) @ (b)? It always means (a) @ (@b), because there are no postfix operators in Nim.)

+

Apart from a few built-in keyword operators such as and, or, not, operators always consist of these characters: + - * \ / < > = @ $ ~ & % ! ? ^ . |

+

User-defined operators are allowed. Nothing stops you from defining your own @!?+~ operator, but doing so may reduce readability.

+

The operator's precedence is determined by its first character. The details can be found in the manual.

+

To define a new operator enclose the operator in backticks "`":

+

proc `$` (x: myDataType): string = ...
+# now the $ operator also works with myDataType, overloading resolution
+# ensures that $ works for built-in types just like before

+

The "`" notation can also be used to call an operator just like any other procedure:

+

if `==`( `+`(3, 4), 7): echo "true"

+ +

Forward declarations

Every variable, procedure, etc. needs to be declared before it can be used. (The reason for this is that it is non-trivial to avoid this need in a language that supports metaprogramming as extensively as Nim does.) However, this cannot be done for mutually recursive procedures:

+

# forward declaration:
+proc even(n: int): bool

+

proc odd(n: int): bool =
+  assert(n >= 0) # makes sure we don't run into negative recursion
+  if n == 0: false
+  else:
+    n == 1 or even(n-1)
+
+proc even(n: int): bool =
+  assert(n >= 0) # makes sure we don't run into negative recursion
+  if n == 1: false
+  else:
+    n == 0 or odd(n-1)

+

Here odd depends on even and vice versa. Thus even needs to be introduced to the compiler before it is completely defined. The syntax for such a forward declaration is simple: just omit the = and the procedure's body. The assert just adds border conditions, and will be covered later in Modules section.

+

Later versions of the language will weaken the requirements for forward declarations.

+

The example also shows that a proc's body can consist of a single expression whose value is then returned implicitly.

+ +

Funcs and methods

As mentioned in the introduction, Nim differentiates between procedures, functions, and methods, defined by the proc, func, and method keywords respectively. In some ways, Nim is a bit more pedantic in its definitions than other languages.

+

Functions are closer to the concept of a pure mathematical function, which might be familiar to you if you've ever done functional programming. Essentially they are procedures with additional limitations set on them: they can't access global state (except const) and can't produce side-effects. The func keyword is basically an alias for proc tagged with {.noSideEffects.}. Functions can still change their mutable arguments however, which are those marked as var, along with any ref objects.

+

Unlike procedures, methods are dynamically dispatched. This sounds a bit complicated, but it is a concept closely related to inheritance and object-oriented programming. If you overload a procedure (two procedures with the same name but of different types or with different sets of arguments are said to be overloaded), the procedure to use is determined at compile-time. Methods, on the other hand, depend on objects that inherit from the RootObj. This is something that is covered in much greater depth in the second part of the tutorial.

+ +

Iterators

Let's return to the simple counting example:

+

echo "Counting to ten: "
+for i in countup(1, 10):
+  echo i

+

Can a countup proc be written that supports this loop? Let's try:

+

proc countup(a, b: int): int =
+  var res = a
+  while res <= b:
+    return res
+    inc(res)

+

However, this does not work. The problem is that the procedure should not only return, but return and continue after an iteration has finished. This return and continue is called a yield statement. Now the only thing left to do is to replace the proc keyword by iterator and here it is -- our first iterator:

+

iterator countup(a, b: int): int =
+  var res = a
+  while res <= b:
+    yield res
+    inc(res)

+

Iterators look very similar to procedures, but there are several important differences:

+
  • Iterators can only be called from for loops.
  • +
  • Iterators cannot contain a return statement (and procs cannot contain a yield statement).
  • +
  • Iterators have no implicit result variable.
  • +
  • Iterators do not support recursion.
  • +
  • Iterators cannot be forward declared, because the compiler must be able to inline an iterator. (This restriction will be gone in a future version of the compiler.)
  • +
+

However, you can also use a closure iterator to get a different set of restrictions. See first-class iterators for details. Iterators can have the same name and parameters as a proc since essentially they have their own namespaces. Therefore, it is common to wrap iterators in procs of the same name which accumulate the result of the iterator and return it as a sequence, like split from the strutils module.

+ +

Basic types

This section deals with the basic built-in types and the operations that are available for them in detail.

+ +

Booleans

Nim's boolean type is called bool and consists of the two pre-defined values true and false. Conditions in while, if, elif, and when statements must be of type bool.

+

The operators not, and, or, xor, <, <=, >, >=, !=, == are defined for the bool type. The and and or operators perform short-circuit evaluation. For example:

+

while p != nil and p.name != "xyz":
+  # p.name is not evaluated if p == nil
+  p = p.next

+ +

Characters

The character type is called char. Its size is always one byte, so it cannot represent most UTF-8 characters, but it can represent one of the bytes that makes up a multibyte UTF-8 character. The reason for this is efficiency: for the overwhelming majority of use-cases, the resulting programs will still handle UTF-8 properly as UTF-8 was especially designed for this. Character literals are enclosed in single quotes.

+

Chars can be compared with the ==, <, <=, >, >= operators. The $ operator converts a char to a string. Chars cannot be mixed with integers; to get the ordinal value of a char use the ord proc. Converting from an integer to a char is done with the chr proc.

+ +

Strings

String variables are mutable, so appending to a string is possible, and quite efficient. Strings in Nim are both zero-terminated and have a length field. A string's length can be retrieved with the builtin len procedure; the length never counts the terminating zero. Accessing the terminating zero is an error, it only exists so that a Nim string can be converted to a cstring without doing a copy.

+

The assignment operator for strings copies the string. You can use the & operator to concatenate strings and add to append to a string.

+

Strings are compared using their lexicographical order. All the comparison operators are supported. By convention, all strings are UTF-8 encoded, but this is not enforced. For example, when reading strings from binary files, they are merely a sequence of bytes. The index operation s[i] means the i-th char of s, not the i-th unichar.

+

A string variable is initialized with the empty string "".

+ +

Integers

Nim has these integer types built-in: int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64.

+

The default integer type is int. Integer literals can have a type suffix to specify a non-default integer type:

+

let
+  x = 0     # x is of type `int`
+  y = 0'i8  # y is of type `int8`
+  z = 0'i32 # z is of type `int32`
+  u = 0'u   # u is of type `uint`

+

Most often integers are used for counting objects that reside in memory, so int has the same size as a pointer.

+

The common operators + - * div mod < <= == != > >= are defined for integers. The and or xor not operators are also defined for integers and provide bitwise operations. Left bit shifting is done with the shl, right shifting with the shr operator. Bit shifting operators always treat their arguments as unsigned. For arithmetic bit shifts ordinary multiplication or division can be used.

+

Unsigned operations all wrap around; they cannot lead to over- or under-flow errors.

+

Lossless Automatic type conversion is performed in expressions where different kinds of integer types are used. However, if the type conversion would cause loss of information, the RangeDefect is raised (if the error cannot be detected at compile time).

+ +

Floats

Nim has these floating-point types built-in: float float32 float64.

+

The default float type is float. In the current implementation, float is always 64-bits.

+

Float literals can have a type suffix to specify a non-default float type:

+

var
+  x = 0.0      # x is of type `float`
+  y = 0.0'f32  # y is of type `float32`
+  z = 0.0'f64  # z is of type `float64`

+

The common operators + - * / < <= == != > >= are defined for floats and follow the IEEE-754 standard.

+

Automatic type conversion in expressions with different kinds of floating-point types is performed: the smaller type is converted to the larger. Integer types are not converted to floating-point types automatically, nor vice versa. Use the toInt and toFloat procs for these conversions.

+ +

Type Conversion

Conversion between numerical types is performed by using the type as a function:

+

var
+  x: int32 = 1.int32   # same as calling int32(1)
+  y: int8  = int8('a') # 'a' == 97'i8
+  z: float = 2.5       # int(2.5) rounds down to 2
+  sum: int = int(x) + int(y) + int(z) # sum == 100

+ +

Internal type representation

As mentioned earlier, the built-in $ (stringify) operator turns any basic type into a string, which you can then print to the console using the echo proc. However, advanced types, and your own custom types, won't work with the $ operator until you define it for them. Sometimes you just want to debug the current value of a complex type without having to write its $ operator. You can use then the repr proc which works with any type and even complex data graphs with cycles. The following example shows that even for basic types there is a difference between the $ and repr outputs:

+

var
+  myBool = true
+  myCharacter = 'n'
+  myString = "nim"
+  myInteger = 42
+  myFloat = 3.14
+echo myBool, ":", repr(myBool)
+# --> true:true
+echo myCharacter, ":", repr(myCharacter)
+# --> n:'n'
+echo myString, ":", repr(myString)
+# --> nim:0x10fa8c050"nim"
+echo myInteger, ":", repr(myInteger)
+# --> 42:42
+echo myFloat, ":", repr(myFloat)
+# --> 3.14:3.14

+ +

Advanced types

In Nim new types can be defined within a type statement:

+

type
+  biggestInt = int64      # biggest integer type that is available
+  biggestFloat = float64  # biggest float type that is available

+

Enumeration and object types may only be defined within a type statement.

+ +

Enumerations

A variable of an enumeration type can only be assigned one of the enumeration's specified values. These values are a set of ordered symbols. Each symbol is mapped to an integer value internally. The first symbol is represented at runtime by 0, the second by 1, and so on. For example:

+

type
+  Direction = enum
+    north, east, south, west
+
+var x = south     # `x` is of type `Direction`; its value is `south`
+echo x            # prints "south"
+
+if x == Direction.south:
+  echo "It's south!"

+

All the comparison operators can be used with enumeration types.

+

An enumeration's symbol can be qualified to avoid ambiguities: Direction.south.

+

The $ operator can convert any enumeration value to its name, and the ord proc can convert it to its underlying integer value.

+

For better interfacing to other programming languages, the symbols of enum types can be assigned an explicit ordinal value. However, the ordinal values must be in ascending order.

+ +

Ordinal types

Enumerations, integer types, char and bool (and subranges) are called ordinal types. Ordinal types have quite a few special operations:

+ + + + + + + + + + +
OperationComment
ord(x)returns the integer value that is used to represent x's value
inc(x)increments x by one
inc(x, n)increments x by n; n is an integer
dec(x)decrements x by one
dec(x, n)decrements x by n; n is an integer
succ(x)returns the successor of x
succ(x, n)returns the n'th successor of x
pred(x)returns the predecessor of x
pred(x, n)returns the n'th predecessor of x

The inc, dec, succ and pred operations can fail by raising an RangeDefect or OverflowDefect. (If the code has been compiled with the proper runtime checks turned on.)

+ +

Subranges

A subrange type is a range of values from an integer or enumeration type (the base type). Example:

+

type
+  MySubrange = range[0..5]

+

MySubrange is a subrange of int which can only hold the values 0 to 5. Assigning any other value to a variable of type MySubrange is a compile-time or runtime error. Assignments from the base type to one of its subrange types (and vice versa) are allowed.

+

The system module defines the important Natural type as range[0..high(int)] (high returns the maximal value). Other programming languages may suggest the use of unsigned integers for natural numbers. This is often unwise: you don't want unsigned arithmetic (which wraps around) just because the numbers cannot be negative. Nim's Natural type helps to avoid this common programming error.

+ +

Sets

The set type models the mathematical notion of a set. The set's basetype can only be an ordinal type of a certain size, namely:
  • int8-int16
  • +
  • uint8/byte-uint16
  • +
  • char
  • +
  • enum
  • +
  • Ordinal subrange types, i.e. range[-10..10]
  • +
+

or equivalent. When constructing a set with signed integer literals, the set's base type is defined to be in the range 0 .. DefaultSetElements-1 where DefaultSetElements is currently always 2^8. The maximum range length for the base type of a set is MaxSetElements which is currently always 2^16. Types with a bigger range length are coerced into the range 0 .. MaxSetElements-1.

+

The reason is that sets are implemented as high performance bit vectors. Attempting to declare a set with a larger type will result in an error:

+

  var s: set[int64] # Error: set is too large; use `std/sets` for ordinal types
+                    # with more than 2^16 elements

+

Note: Nim also offers hash sets (which you need to import with import std/sets), which have no such restrictions.

+

Sets can be constructed via the set constructor: {} is the empty set. The empty set is type compatible with any concrete set type. The constructor can also be used to include elements (and ranges of elements):

+

type
+  CharSet = set[char]
+var
+  x: CharSet
+x = {'a'..'z', '0'..'9'} # This constructs a set that contains the
+                         # letters from 'a' to 'z' and the digits
+                         # from '0' to '9'

+

The module `std/setutils` provides a way to initialize a set from an iterable:

+

import std/setutils
+
+let uniqueChars = myString.toSet

+

These operations are supported by sets:

+ + + + + + + + + + + + + +
operationmeaning
A + Bunion of two sets
A * Bintersection of two sets
A - Bdifference of two sets (A without B's elements)
A == Bset equality
A <= Bsubset relation (A is subset of B or equal to B)
A < Bstrict subset relation (A is a proper subset of B)
e in Aset membership (A contains element e)
e notin AA does not contain element e
contains(A, e)A contains element e
card(A)the cardinality of A (number of elements in A)
incl(A, elem)same as A = A + {elem}
excl(A, elem)same as A = A - {elem}
+

Bit fields

Sets are often used to define a type for the flags of a procedure. This is a cleaner (and type safe) solution than defining integer constants that have to be or'ed together.

+

Enum, sets and casting can be used together as in:

+

type
+  MyFlag* {.size: sizeof(cint).} = enum
+    A
+    B
+    C
+    D
+  MyFlags = set[MyFlag]
+
+proc toNum(f: MyFlags): int = cast[cint](f)
+proc toFlags(v: int): MyFlags = cast[MyFlags](v)
+
+assert toNum({}) == 0
+assert toNum({A}) == 1
+assert toNum({D}) == 8
+assert toNum({A, C}) == 5
+assert toFlags(0) == {}
+assert toFlags(7) == {A, B, C}

+

Note how the set turns enum values into powers of 2.

+

If using enums and sets with C, use distinct cint.

+

For interoperability with C see also the bitsize pragma.

+ +

Arrays

An array is a simple fixed-length container. Each element in an array has the same type. The array's index type can be any ordinal type.

+

Arrays can be constructed using []:

+

type
+  IntArray = array[0..5, int] # an array that is indexed with 0..5
+var
+  x: IntArray
+x = [1, 2, 3, 4, 5, 6]
+for i in low(x) .. high(x):
+  echo x[i]

+

The notation x[i] is used to access the i-th element of x. Array access is always bounds checked (at compile-time or at runtime). These checks can be disabled via pragmas or invoking the compiler with the --bound_checks:off command line switch.

+

Arrays are value types, like any other Nim type. The assignment operator copies the whole array contents.

+

The built-in len proc returns the array's length. low(a) returns the lowest valid index for the array a and high(a) the highest valid index.

+

type
+  Direction = enum
+    north, east, south, west
+  BlinkLights = enum
+    off, on, slowBlink, mediumBlink, fastBlink
+  LevelSetting = array[north..west, BlinkLights]
+var
+  level: LevelSetting
+level[north] = on
+level[south] = slowBlink
+level[east] = fastBlink
+echo level        # --> [on, fastBlink, slowBlink, off]
+echo low(level)   # --> north
+echo len(level)   # --> 4
+echo high(level)  # --> west

+

The syntax for nested arrays (multidimensional) in other languages is a matter of appending more brackets because usually each dimension is restricted to the same index type as the others. In Nim you can have different dimensions with different index types, so the nesting syntax is slightly different. Building on the previous example where a level is defined as an array of enums indexed by yet another enum, we can add the following lines to add a light tower type subdivided into height levels accessed through their integer index:

+

type
+  LightTower = array[1..10, LevelSetting]
+var
+  tower: LightTower
+tower[1][north] = slowBlink
+tower[1][east] = mediumBlink
+echo len(tower)     # --> 10
+echo len(tower[1])  # --> 4
+echo tower          # --> [[slowBlink, mediumBlink, ...more output..
+# The following lines don't compile due to type mismatch errors
+#tower[north][east] = on
+#tower[0][1] = on

+

Note how the built-in len proc returns only the array's first dimension length. Another way of defining the LightTower to better illustrate its nested nature would be to omit the previous definition of the LevelSetting type and instead write it embedded directly as the type of the first dimension:

+

type
+  LightTower = array[1..10, array[north..west, BlinkLights]]

+

It is quite common to have arrays start at zero, so there's a shortcut syntax to specify a range from zero to the specified index minus one:

+

type
+  IntArray = array[0..5, int] # an array that is indexed with 0..5
+  QuickArray = array[6, int]  # an array that is indexed with 0..5
+var
+  x: IntArray
+  y: QuickArray
+x = [1, 2, 3, 4, 5, 6]
+y = x
+for i in low(x) .. high(x):
+  echo x[i], y[i]

+ +

Sequences

Sequences are similar to arrays but of dynamic length which may change during runtime (like strings). Since sequences are resizable they are always allocated on the heap and garbage collected.

+

Sequences are always indexed with an int starting at position 0. The len, low and high operations are available for sequences too. The notation x[i] can be used to access the i-th element of x.

+

Sequences can be constructed by the array constructor [] in conjunction with the array to sequence operator @. Another way to allocate space for a sequence is to call the built-in newSeq procedure.

+

A sequence may be passed to an openarray parameter.

+

Example:

+

var
+  x: seq[int] # a reference to a sequence of integers
+x = @[1, 2, 3, 4, 5, 6] # the @ turns the array into a sequence allocated on the heap

+

Sequence variables are initialized with @[].

+

The for statement can be used with one or two variables when used with a sequence. When you use the one variable form, the variable will hold the value provided by the sequence. The for statement is looping over the results from the items() iterator from the system module. But if you use the two-variable form, the first variable will hold the index position and the second variable will hold the value. Here the for statement is looping over the results from the pairs() iterator from the system module. Examples:

+

for value in @[3, 4, 5]:
+  echo value
+# --> 3
+# --> 4
+# --> 5
+
+for i, value in @[3, 4, 5]:
+  echo "index: ", $i, ", value:", $value
+# --> index: 0, value:3
+# --> index: 1, value:4
+# --> index: 2, value:5

+ +

Open arrays

Note: Openarrays can only be used for parameters.

+

Often fixed-size arrays turn out to be too inflexible; procedures should be able to deal with arrays of different sizes. The openarray type allows this. Openarrays are always indexed with an int starting at position 0. The len, low and high operations are available for open arrays too. Any array with a compatible base type can be passed to an openarray parameter, the index type does not matter.

+

var
+  fruits:   seq[string]       # reference to a sequence of strings that is initialized with '@[]'
+  capitals: array[3, string]  # array of strings with a fixed size
+
+capitals = ["New York", "London", "Berlin"]   # array 'capitals' allows assignment of only three elements
+fruits.add("Banana")          # sequence 'fruits' is dynamically expandable during runtime
+fruits.add("Mango")
+
+proc openArraySize(oa: openArray[string]): int =
+  oa.len
+
+assert openArraySize(fruits) == 2     # procedure accepts a sequence as parameter
+assert openArraySize(capitals) == 3   # but also an array type

+

The openarray type cannot be nested: multidimensional openarrays are not supported because this is seldom needed and cannot be done efficiently.

+ +

Varargs

A varargs parameter is like an openarray parameter. However, it is also a means to implement passing a variable number of arguments to a procedure. The compiler converts the list of arguments to an array automatically:

+

proc myWriteln(f: File, a: varargs[string]) =
+  for s in items(a):
+    write(f, s)
+  write(f, "\n")
+
+myWriteln(stdout, "abc", "def", "xyz")
+# is transformed by the compiler to:
+myWriteln(stdout, ["abc", "def", "xyz"])

+

This transformation is only done if the varargs parameter is the last parameter in the procedure header. It is also possible to perform type conversions in this context:

+

proc myWriteln(f: File, a: varargs[string, `$`]) =
+  for s in items(a):
+    write(f, s)
+  write(f, "\n")
+
+myWriteln(stdout, 123, "abc", 4.0)
+# is transformed by the compiler to:
+myWriteln(stdout, [$123, $"abc", $4.0])

+

In this example $ is applied to any argument that is passed to the parameter a. Note that $ applied to strings is a nop.

+ +

Slices

Slices look similar to subranges types in syntax but are used in a different context. A slice is just an object of type Slice which contains two bounds, a and b. By itself a slice is not very useful, but other collection types define operators which accept Slice objects to define ranges.

+

var
+  a = "Nim is a programming language"
+  b = "Slices are useless."
+
+echo a[7 .. 12] # --> 'a prog'
+b[11 .. ^2] = "useful"
+echo b # --> 'Slices are useful.'

+

In the previous example slices are used to modify a part of a string. The slice's bounds can hold any value supported by their type, but it is the proc using the slice object which defines what values are accepted.

+

To understand the different ways of specifying the indices of strings, arrays, sequences, etc., it must be remembered that Nim uses zero-based indices.

+

So the string b is of length 19, and two different ways of specifying the indices are

+

"Slices are useless."
+ |          |     |
+ 0         11    17   using indices
+^19        ^8    ^2   using ^ syntax

+

where b[0 .. ^1] is equivalent to b[0 .. b.len-1] and b[0 ..< b.len], and it can be seen that the ^1 provides a shorthand way of specifying the b.len-1. See the backwards index operator.

+

In the above example, because the string ends in a period, to get the portion of the string that is "useless" and replace it with "useful".

+

b[11 .. ^2] is the portion "useless", and b[11 .. ^2] = "useful" replaces the "useless" portion with "useful", giving the result "Slices are useful."

+

Note 1: alternate ways of writing this are b[^8 .. ^2] = "useful" or as b[11 .. b.len-2] = "useful" or as b[11 ..< b.len-1] = "useful".

+

Note 2: As the ^ template returns a distinct int of type BackwardsIndex, we can have a lastIndex constant defined as const lastIndex = ^1, and later used as b[0 .. lastIndex].

+ +

Objects

The default type to pack different values together in a single structure with a name is the object type. An object is a value type, which means that when an object is assigned to a new variable all its components are copied as well.

+

Each object type Foo has a constructor Foo(field: value, ...) where all of its fields can be initialized. Unspecified fields will get their default value.

+

type
+  Person = object
+    name: string
+    age: int
+
+var person1 = Person(name: "Peter", age: 30)
+
+echo person1.name # "Peter"
+echo person1.age  # 30
+
+var person2 = person1 # copy of person 1
+
+person2.age += 14
+
+echo person1.age # 30
+echo person2.age # 44
+
+
+# the order may be changed
+let person3 = Person(age: 12, name: "Quentin")
+
+# not every member needs to be specified
+let person4 = Person(age: 3)
+# unspecified members will be initialized with their default
+# values. In this case it is the empty string.
+doAssert person4.name == ""

+

Object fields that should be visible from outside the defining module have to be marked with *.

+

type
+  Person* = object # the type is visible from other modules
+    name*: string  # the field of this type is visible from other modules
+    age*: int

+ +

Tuples

Tuples are very much like what you have seen so far from objects. They are value types where the assignment operator copies each component. Unlike object types though, tuple types are structurally typed, meaning different tuple-types are equivalent if they specify fields of the same type and of the same name in the same order.

+

The constructor () can be used to construct tuples. The order of the fields in the constructor must match the order in the tuple's definition. But unlike objects, a name for the tuple type may not be used here.

+

Like the object type the notation t.field is used to access a tuple's field. Another notation that is not available for objects is t[i] to access the i'th field. Here i must be a constant integer.

+

type
+  # type representing a person:
+  # A person consists of a name and an age.
+  Person = tuple
+    name: string
+    age: int
+  
+  # Alternative syntax for an equivalent type.
+  PersonX = tuple[name: string, age: int]
+  
+  # anonymous field syntax
+  PersonY = (string, int)
+
+var
+  person: Person
+  personX: PersonX
+  personY: PersonY
+
+person = (name: "Peter", age: 30)
+# Person and PersonX are equivalent
+personX = person
+
+# Create a tuple with anonymous fields:
+personY = ("Peter", 30)
+
+# A tuple with anonymous fields is compatible with a tuple that has
+# field names.
+person = personY
+personY = person
+
+# Usually used for short tuple initialization syntax
+person = ("Peter", 30)
+
+echo person.name # "Peter"
+echo person.age  # 30
+
+echo person[0] # "Peter"
+echo person[1] # 30
+
+# You don't need to declare tuples in a separate type section.
+var building: tuple[street: string, number: int]
+building = ("Rue del Percebe", 13)
+echo building.street
+
+# The following line does not compile, they are different tuples!
+#person = building
+# --> Error: type mismatch: got (tuple[street: string, number: int])
+#     but expected 'Person'

+

Even though you don't need to declare a type for a tuple to use it, tuples created with different field names will be considered different objects despite having the same field types.

+

Tuples can be unpacked during variable assignment. This can be handy to assign directly the fields of the tuples to individually named variables. An example of this is the splitFile proc from the os module which returns the directory, name, and extension of a path at the same time. For tuple unpacking to work you must use parentheses around the values you want to assign the unpacking to, otherwise, you will be assigning the same value to all the individual variables! For example:

+

import std/os
+
+let
+  path = "usr/local/nimc.html"
+  (dir, name, ext) = splitFile(path)
+  baddir, badname, badext = splitFile(path)
+echo dir      # outputs "usr/local"
+echo name     # outputs "nimc"
+echo ext      # outputs ".html"
+# All the following output the same line:
+# "(dir: usr/local, name: nimc, ext: .html)"
+echo baddir
+echo badname
+echo badext

+

Tuple unpacking is also supported in for-loops:

+

let a = [(10, 'a'), (20, 'b'), (30, 'c')]
+
+for (x, c) in a:
+  echo x
+# This will output: 10; 20; 30
+
+# Accessing the index is also possible:
+for i, (x, c) in a:
+  echo i, c
+# This will output: 0a; 1b; 2c

+

Fields of tuples are always public, they don't need to be explicitly marked to be exported, unlike for example fields in an object type.

+ +

Reference and pointer types

References (similar to pointers in other programming languages) are a way to introduce many-to-one relationships. This means different references can point to and modify the same location in memory.

+

Nim distinguishes between traced and untraced references. Untraced references are also called pointers. Traced references point to objects in a garbage-collected heap, untraced references point to manually allocated objects or objects elsewhere in memory. Thus, untraced references are unsafe. However, for certain low-level operations (e.g. accessing the hardware), untraced references are necessary.

+

Traced references are declared with the ref keyword; untraced references are declared with the ptr keyword.

+

The empty [] subscript notation can be used to de-refer a reference, meaning to retrieve the item the reference points to. The . (access a tuple/object field operator) and [] (array/string/sequence index operator) operators perform implicit dereferencing operations for reference types:

+

type
+  Node = ref object
+    le, ri: Node
+    data: int
+
+var n = Node(data: 9)
+echo n.data
+# no need to write n[].data; in fact n[].data is highly discouraged!

+

To allocate a new traced object, the built-in procedure new can be used:

+

var n: Node
+new(n)

+

To deal with untraced memory, the procedures alloc, dealloc and realloc can be used. The system module's documentation contains further details.

+

If a reference points to nothing, it has the value nil.

+ +

Procedural type

A procedural type is a (somewhat abstract) pointer to a procedure. nil is an allowed value for a variable of a procedural type. Nim uses procedural types to achieve functional programming techniques.

+

Example:

+

proc greet(name: string): string =
+  "Hello, " & name & "!"
+
+proc bye(name: string): string =
+  "Goodbye, " & name & "."
+
+proc communicate(greeting: proc (x: string): string, name: string) =
+  echo greeting(name)
+
+communicate(greet, "John")
+communicate(bye, "Mary")

+

A subtle issue with procedural types is that the calling convention of the procedure influences the type compatibility: procedural types are only compatible if they have the same calling convention. The different calling conventions are listed in the manual.

+ +

Distinct type

A Distinct type allows for the creation of a new type that "does not imply a subtype relationship between it and its base type". You must explicitly define all behavior for the distinct type. To help with this, both the distinct type and its base type can cast from one type to the other. Examples are provided in the manual.

+ +

Modules

Nim supports splitting a program into pieces with a module concept. Each module is in its own file. Modules enable information hiding and separate compilation. A module may gain access to the symbols of another module by using the import statement. Only top-level symbols that are marked with an asterisk (*) are exported:

+

# Module A
+var
+  x*, y: int
+
+proc `*` *(a, b: seq[int]): seq[int] =
+  # allocate a new sequence:
+  newSeq(result, len(a))
+  # multiply two int sequences:
+  for i in 0 ..< len(a): result[i] = a[i] * b[i]
+
+when isMainModule:
+  # test the new `*` operator for sequences:
+  assert(@[1, 2, 3] * @[1, 2, 3] == @[1, 4, 9])

+

The above module exports x and *, but not y.

+

A module's top-level statements are executed at the start of the program. This can be used to initialize complex data structures for example.

+

Each module has a special magic constant isMainModule that is true if the module is compiled as the main file. This is very useful to embed tests within the module as shown by the above example.

+

A symbol of a module can be qualified with the module.symbol syntax. And if a symbol is ambiguous, it must be qualified. A symbol is ambiguous if it is defined in two (or more) different modules and both modules are imported by a third one:

+

# Module A
+var x*: string

+

# Module B
+var x*: int

+

# Module C
+import A, B
+write(stdout, x) # error: x is ambiguous
+write(stdout, A.x) # okay: qualifier used
+
+var x = 4
+write(stdout, x) # not ambiguous: uses the module C's x

+

But this rule does not apply to procedures or iterators. Here the overloading rules apply:

+

# Module A
+proc x*(a: int): string = $a

+

# Module B
+proc x*(a: string): string = $a

+

# Module C
+import A, B
+write(stdout, x(3))   # no error: A.x is called
+write(stdout, x(""))  # no error: B.x is called
+
+proc x*(a: int): string = discard
+write(stdout, x(3))   # ambiguous: which `x` is to call?

+ +

Excluding symbols

The normal import statement will bring in all exported symbols. These can be limited by naming symbols that should be excluded using the except qualifier.

+

import mymodule except y

+ +

From statement

We have already seen the simple import statement that just imports all exported symbols. An alternative that only imports listed symbols is the from import statement:

+

from mymodule import x, y, z

+

The from statement can also force namespace qualification on symbols, thereby making symbols available, but needing to be qualified in order to be used.

+

from mymodule import x, y, z
+
+x()           # use x without any qualification

+

from mymodule import nil
+
+mymodule.x()  # must qualify x with the module name as prefix
+
+x()           # using x here without qualification is a compile error

+

Since module names are generally long to be descriptive, you can also define a shorter alias to use when qualifying symbols.

+

from mymodule as m import nil
+
+m.x()         # m is aliasing mymodule

+ +

Include statement

The include statement does something fundamentally different than importing a module: it merely includes the contents of a file. The include statement is useful to split up a large module into several files:

+

include fileA, fileB, fileC

+ +

Part 2

So, now that we are done with the basics, let's see what Nim offers apart from a nice syntax for procedural programming: Part II

+

+ +
+
+ + +
+
+ + + + diff --git a/tut1.idx b/tut1.idx new file mode 100644 index 0000000000000..917c77c57b8a9 --- /dev/null +++ b/tut1.idx @@ -0,0 +1,72 @@ +markupTitle Nim Tutorial (Part I) tut1.html Nim Tutorial (Part I) 0 +heading Introduction tut1.html#introduction Introduction 0 +heading The first program tut1.html#the-first-program The first program 0 +idx local type inference tut1.html#local-type-inference_1 The first program 0 +heading Lexical elements tut1.html#lexical-elements Lexical elements 0 +heading String and character literals tut1.html#lexical-elements-string-and-character-literals String and character literals 0 +heading Comments tut1.html#lexical-elements-comments Comments 0 +heading Numbers tut1.html#lexical-elements-numbers Numbers 0 +heading The var statement tut1.html#the-var-statement The var statement 0 +heading Constants tut1.html#constants Constants 0 +heading The let statement tut1.html#the-let-statement The let statement 0 +heading The assignment statement tut1.html#the-assignment-statement The assignment statement 0 +heading Control flow statements tut1.html#control-flow-statements Control flow statements 0 +heading If statement tut1.html#control-flow-statements-if-statement If statement 0 +heading Case statement tut1.html#control-flow-statements-case-statement Case statement 0 +heading While statement tut1.html#control-flow-statements-while-statement While statement 0 +heading For statement tut1.html#control-flow-statements-for-statement For statement 0 +heading Scopes and the block statement tut1.html#control-flow-statements-scopes-and-the-block-statement Scopes and the block statement 0 +heading Break statement tut1.html#control-flow-statements-break-statement Break statement 0 +heading Continue statement tut1.html#control-flow-statements-continue-statement Continue statement 0 +heading When statement tut1.html#control-flow-statements-when-statement When statement 0 +heading Statements and indentation tut1.html#statements-and-indentation Statements and indentation 0 +heading Procedures tut1.html#procedures Procedures 0 +heading Result variable tut1.html#procedures-result-variable Result variable 0 +heading Parameters tut1.html#procedures-parameters Parameters 0 +heading Discard statement tut1.html#procedures-discard-statement Discard statement 0 +heading Named arguments tut1.html#procedures-named-arguments Named arguments 0 +heading Default values tut1.html#procedures-default-values Default values 0 +heading Overloaded procedures tut1.html#procedures-overloaded-procedures Overloaded procedures 0 +heading Operators tut1.html#procedures-operators Operators 0 +heading Forward declarations tut1.html#procedures-forward-declarations Forward declarations 0 +heading Funcs and methods tut1.html#procedures-funcs-and-methods Funcs and methods 0 +heading Iterators tut1.html#iterators Iterators 0 +heading Basic types tut1.html#basic-types Basic types 0 +heading Booleans tut1.html#basic-types-booleans Booleans 0 +heading Characters tut1.html#basic-types-characters Characters 0 +heading Strings tut1.html#basic-types-strings Strings 0 +heading Integers tut1.html#basic-types-integers Integers 0 +idx arithmetic bit shifts tut1.html#arithmetic-bit-shifts_1 Integers 0 +idx Automatic type conversion tut1.html#automatic-type-conversion_1 Integers 0 +idx RangeDefect tut1.html#rangedefect_1 Integers 0 +heading Floats tut1.html#basic-types-floats Floats 0 +heading Type Conversion tut1.html#basic-types-type-conversion Type Conversion 0 +heading Internal type representation tut1.html#internal-type-representation Internal type representation 0 +heading Advanced types tut1.html#advanced-types Advanced types 0 +heading Enumerations tut1.html#advanced-types-enumerations Enumerations 0 +heading Ordinal types tut1.html#advanced-types-ordinal-types Ordinal types 0 +heading Subranges tut1.html#advanced-types-subranges Subranges 0 +heading Sets tut1.html#advanced-types-sets Sets 0 +heading Bit fields tut1.html#sets-bit-fields Bit fields 0 +heading Arrays tut1.html#advanced-types-arrays Arrays 0 +heading Sequences tut1.html#advanced-types-sequences Sequences 0 +heading Open arrays tut1.html#advanced-types-open-arrays Open arrays 0 +idx openarray tut1.html#openarray_1 Open arrays 0 +heading Varargs tut1.html#advanced-types-varargs Varargs 0 +heading Slices tut1.html#advanced-types-slices Slices 0 +heading Objects tut1.html#advanced-types-objects Objects 0 +heading Tuples tut1.html#advanced-types-tuples Tuples 0 +heading Reference and pointer types tut1.html#advanced-types-reference-and-pointer-types Reference and pointer types 0 +idx traced tut1.html#traced_1 Reference and pointer types 0 +idx untraced tut1.html#untraced_1 Reference and pointer types 0 +heading Procedural type tut1.html#advanced-types-procedural-type Procedural type 0 +idx functional tut1.html#functional_1 Procedural type 0 +heading Distinct type tut1.html#advanced-types-distinct-type Distinct type 0 +heading Modules tut1.html#modules Modules 0 +idx information hiding tut1.html#information-hiding_1 Modules 0 +idx separate compilation tut1.html#separate-compilation_1 Modules 0 +idx import tut1.html#import_1 Modules 0 +heading Excluding symbols tut1.html#modules-excluding-symbols Excluding symbols 0 +heading From statement tut1.html#modules-from-statement From statement 0 +heading Include statement tut1.html#modules-include-statement Include statement 0 +heading Part 2 tut1.html#part-2 Part 2 0 diff --git a/tut2.html b/tut2.html new file mode 100644 index 0000000000000..a32f26cf9e9e1 --- /dev/null +++ b/tut2.html @@ -0,0 +1,485 @@ + + + + + + + +Nim Tutorial (Part II) + + + + + + + + + + + + + + + + +
+
+

Nim Tutorial (Part II)

+
+ +
+ Source   +Edit   + +
+ +

+ +
Author:Andreas Rumpf
Version:2.2.1
+

Introduction

"Repetition renders the ridiculous reasonable." -- Norman Wildberger

+

This document is a tutorial for the advanced constructs of the Nim programming language. Note that this document is somewhat obsolete as the manual contains many more examples of the advanced language features.

+ +

Pragmas

Pragmas are Nim's method to give the compiler additional information/ commands without introducing a massive number of new keywords. Pragmas are enclosed in the special {. and .} curly dot brackets. This tutorial does not cover pragmas. See the manual or user guide for a description of the available pragmas.

+ +

Object Oriented Programming

While Nim's support for object oriented programming (OOP) is minimalistic, powerful OOP techniques can be used. OOP is seen as one way to design a program, not the only way. Often a procedural approach leads to simpler and more efficient code. In particular, preferring composition over inheritance is often the better design.

+ +

Inheritance

Inheritance in Nim is entirely optional. To enable inheritance with runtime type information the object needs to inherit from RootObj. This can be done directly, or indirectly by inheriting from an object that inherits from RootObj. Usually types with inheritance are also marked as ref types even though this isn't strictly enforced. To check at runtime if an object is of a certain type, the of operator can be used.

+

type
+  Person = ref object of RootObj
+    name*: string  # the * means that `name` is accessible from other modules
+    age: int       # no * means that the field is hidden from other modules
+  
+  Student = ref object of Person # Student inherits from Person
+    id: int                      # with an id field
+
+var
+  student: Student
+  person: Person
+assert(student of Student) # is true
+# object construction:
+student = Student(name: "Anton", age: 5, id: 2)
+echo student[]

+

Inheritance is done with the object of syntax. Multiple inheritance is currently not supported. If an object type has no suitable ancestor, RootObj can be used as its ancestor, but this is only a convention. Objects that have no ancestor are implicitly final. You can use the inheritable pragma to introduce new object roots apart from system.RootObj. (This is used in the GTK wrapper for instance.)

+

Ref objects should be used whenever inheritance is used. It isn't strictly necessary, but with non-ref objects, assignments such as let person: Person = Student(id: 123) will truncate subclass fields.

+

Note: Composition (has-a relation) is often preferable to inheritance (is-a relation) for simple code reuse. Since objects are value types in Nim, composition is as efficient as inheritance.

+ +

Mutually recursive types

Objects, tuples and references can model quite complex data structures which depend on each other; they are mutually recursive. In Nim these types can only be declared within a single type section. (Anything else would require arbitrary symbol lookahead which slows down compilation.)

+

Example:

+

type
+  Node = ref object  # a reference to an object with the following field:
+    le, ri: Node     # left and right subtrees
+    sym: ref Sym     # leaves contain a reference to a Sym
+  
+  Sym = object       # a symbol
+    name: string     # the symbol's name
+    line: int        # the line the symbol was declared in
+    code: Node       # the symbol's abstract syntax tree

+ +

Type conversions

Nim distinguishes between type casts and type conversions. Casts are done with the cast operator and force the compiler to interpret a bit pattern to be of another type.

+

Type conversions are a much more polite way to convert a type into another: They preserve the abstract value, not necessarily the bit-pattern. If a type conversion is not possible, the compiler complains or an exception is raised.

+

The syntax for type conversions is destination_type(expression_to_convert) (like an ordinary call):

+

proc getID(x: Person): int =
+  Student(x).id

+

The InvalidObjectConversionDefect exception is raised if x is not a Student.

+ +

Object variants

Often an object hierarchy is overkill in certain situations where simple variant types are needed.

+

An example:

+

# This is an example how an abstract syntax tree could be modelled in Nim
+type
+  NodeKind = enum  # the different node types
+    nkInt,          # a leaf with an integer value
+    nkFloat,        # a leaf with a float value
+    nkString,       # a leaf with a string value
+    nkAdd,          # an addition
+    nkSub,          # a subtraction
+    nkIf            # an if statement
+  Node = ref object
+    case kind: NodeKind  # the `kind` field is the discriminator
+    of nkInt: intVal: int
+    of nkFloat: floatVal: float
+    of nkString: strVal: string
+    of nkAdd, nkSub:
+      leftOp, rightOp: Node
+    of nkIf:
+      condition, thenPart, elsePart: Node
+
+var n = Node(kind: nkFloat, floatVal: 1.0)
+# the following statement raises an `FieldDefect` exception, because
+# n.kind's value does not fit:
+n.strVal = ""

+

As can be seen from the example, an advantage to an object hierarchy is that no conversion between different object types is needed. Yet, access to invalid object fields raises an exception.

+ +

Method call syntax

There is a syntactic sugar for calling routines: The syntax obj.methodName(args) can be used instead of methodName(obj, args). If there are no remaining arguments, the parentheses can be omitted: obj.len (instead of len(obj)).

+

This method call syntax is not restricted to objects, it can be used for any type:

+

import std/strutils
+
+echo "abc".len # is the same as echo len("abc")
+echo "abc".toUpperAscii()
+echo({'a', 'b', 'c'}.card)
+stdout.writeLine("Hallo") # the same as writeLine(stdout, "Hallo")

+

(Another way to look at the method call syntax is that it provides the missing postfix notation.)

+

So "pure object oriented" code is easy to write:

+

import std/[strutils, sequtils]
+
+stdout.writeLine("Give a list of numbers (separated by spaces): ")
+stdout.write(stdin.readLine.splitWhitespace.map(parseInt).max.`$`)
+stdout.writeLine(" is the maximum!")

+ +

Properties

As the above example shows, Nim has no need for get-properties: Ordinary get-procedures that are called with the method call syntax achieve the same. But setting a value is different; for this a special setter syntax is needed:

+

type
+  Socket* = ref object of RootObj
+    h: int # cannot be accessed from the outside of the module due to missing star
+
+proc `host=`*(s: var Socket, value: int) {.inline.} =
+  ## setter of host address
+  s.h = value
+
+proc host*(s: Socket): int {.inline.} =
+  ## getter of host address
+  s.h
+
+var s: Socket
+new s
+s.host = 34  # same as `host=`(s, 34)

+

(The example also shows inline procedures.)

+

The [] array access operator can be overloaded to provide array properties:

+

type
+  Vector* = object
+    x, y, z: float
+
+proc `[]=`* (v: var Vector, i: int, value: float) =
+  # setter
+  case i
+  of 0: v.x = value
+  of 1: v.y = value
+  of 2: v.z = value
+  else: assert(false)
+
+proc `[]`* (v: Vector, i: int): float =
+  # getter
+  case i
+  of 0: result = v.x
+  of 1: result = v.y
+  of 2: result = v.z
+  else: assert(false)

+

The example is silly, since a vector is better modelled by a tuple which already provides v[] access.

+ +

Dynamic dispatch

Procedures always use static dispatch. For dynamic dispatch replace the proc keyword by method:

+

type
+  Expression = ref object of RootObj ## abstract base class for an expression
+  Literal = ref object of Expression
+    x: int
+  PlusExpr = ref object of Expression
+    a, b: Expression
+
+# watch out: 'eval' relies on dynamic binding
+method eval(e: Expression): int {.base.} =
+  # override this base method
+  quit "to override!"
+
+method eval(e: Literal): int = e.x
+method eval(e: PlusExpr): int = eval(e.a) + eval(e.b)
+
+proc newLit(x: int): Literal = Literal(x: x)
+proc newPlus(a, b: Expression): PlusExpr = PlusExpr(a: a, b: b)
+
+echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4)))

+

Note that in the example the constructors newLit and newPlus are procs because it makes more sense for them to use static binding, but eval is a method because it requires dynamic binding.

+

Note: Starting from Nim 0.20, to use multi-methods one must explicitly pass --multimethods:on when compiling.

+

In a multi-method all parameters that have an object type are used for the dispatching:

+

type
+  Thing = ref object of RootObj
+  Unit = ref object of Thing
+    x: int
+
+method collide(a, b: Thing) {.inline.} =
+  quit "to override!"
+
+method collide(a: Thing, b: Unit) {.inline.} =
+  echo "1"
+
+method collide(a: Unit, b: Thing) {.inline.} =
+  echo "2"
+
+var a, b: Unit
+new a
+new b
+collide(a, b) # output: 2

+

As the example demonstrates, invocation of a multi-method cannot be ambiguous: Collide 2 is preferred over collide 1 because the resolution works from left to right. Thus Unit, Thing is preferred over Thing, Unit.

+

Performance note: Nim does not produce a virtual method table, but generates dispatch trees. This avoids the expensive indirect branch for method calls and enables inlining. However, other optimizations like compile time evaluation or dead code elimination do not work with methods.

+ +

Exceptions

In Nim exceptions are objects. By convention, exception types are suffixed with 'Error'. The system module defines an exception hierarchy that you might want to stick to. Exceptions derive from system.Exception, which provides the common interface.

+

Exceptions have to be allocated on the heap because their lifetime is unknown. The compiler will prevent you from raising an exception created on the stack. All raised exceptions should at least specify the reason for being raised in the msg field.

+

A convention is that exceptions should be raised in exceptional cases, they should not be used as an alternative method of control flow.

+ +

Raise statement

Raising an exception is done with the raise statement:

+

var
+  e: ref OSError
+new(e)
+e.msg = "the request to the OS failed"
+raise e

+

If the raise keyword is not followed by an expression, the last exception is re-raised. For the purpose of avoiding repeating this common code pattern, the template newException in the system module can be used:

+

raise newException(OSError, "the request to the OS failed")

+ +

Try statement

The try statement handles exceptions:

+

from std/strutils import parseInt
+
+# read the first two lines of a text file that should contain numbers
+# and tries to add them
+var
+  f: File
+if open(f, "numbers.txt"):
+  try:
+    let a = readLine(f)
+    let b = readLine(f)
+    echo "sum: ", parseInt(a) + parseInt(b)
+  except OverflowDefect:
+    echo "overflow!"
+  except ValueError:
+    echo "could not convert string to integer"
+  except IOError:
+    echo "IO error!"
+  except CatchableError:
+    echo "Unknown exception!"
+    # reraise the unknown exception:
+    raise
+  finally:
+    close(f)

+

The statements after the try are executed unless an exception is raised. Then the appropriate except part is executed.

+

The empty except part is executed if there is an exception that is not explicitly listed. It is similar to an else part in if statements.

+

If there is a finally part, it is always executed after the exception handlers.

+

The exception is consumed in an except part. If an exception is not handled, it is propagated through the call stack. This means that often the rest of the procedure - that is not within a finally clause - is not executed (if an exception occurs).

+

If you need to access the actual exception object or message inside an except branch you can use the getCurrentException() and getCurrentExceptionMsg() procs from the system module. Example:

+

try:
+  doSomethingHere()
+except CatchableError:
+  let
+    e = getCurrentException()
+    msg = getCurrentExceptionMsg()
+  echo "Got exception ", repr(e), " with message ", msg

+ +

Annotating procs with raised exceptions

Through the use of the optional {.raises.} pragma you can specify that a proc is meant to raise a specific set of exceptions, or none at all. If the {.raises.} pragma is used, the compiler will verify that this is true. For instance, if you specify that a proc raises IOError, and at some point it (or one of the procs it calls) starts raising a new exception the compiler will prevent that proc from compiling. Usage example:

+

proc complexProc() {.raises: [IOError, ArithmeticDefect].} =
+  ...
+
+proc simpleProc() {.raises: [].} =
+  ...

+

Once you have code like this in place, if the list of raised exception changes the compiler will stop with an error specifying the line of the proc which stopped validating the pragma and the raised exception not being caught, along with the file and line where the uncaught exception is being raised, which may help you locate the offending code which has changed.

+

If you want to add the {.raises.} pragma to existing code, the compiler can also help you. You can add the {.effects.} pragma statement to your proc and the compiler will output all inferred effects up to that point (exception tracking is part of Nim's effect system). Another more roundabout way to find out the list of exceptions raised by a proc is to use the Nim doc command which generates documentation for a whole module and decorates all procs with the list of raised exceptions. You can read more about Nim's effect system and related pragmas in the manual.

+ +

Generics

Generics are Nim's means to parametrize procs, iterators or types with type parameters. Generic parameters are written within square brackets, for example Foo[T]. They are most useful for efficient type safe containers:

+

type
+  BinaryTree*[T] = ref object # BinaryTree is a generic type with
+                              # generic param `T`
+    le, ri: BinaryTree[T]     # left and right subtrees; may be nil
+    data: T                   # the data stored in a node
+
+proc newNode*[T](data: T): BinaryTree[T] =
+  # constructor for a node
+  new(result)
+  result.data = data
+
+proc add*[T](root: var BinaryTree[T], n: BinaryTree[T]) =
+  # insert a node into the tree
+  if root == nil:
+    root = n
+  else:
+    var it = root
+    while it != nil:
+      # compare the data items; uses the generic `cmp` proc
+      # that works for any type that has a `==` and `<` operator
+      var c = cmp(it.data, n.data)
+      if c < 0:
+        if it.le == nil:
+          it.le = n
+          return
+        it = it.le
+      else:
+        if it.ri == nil:
+          it.ri = n
+          return
+        it = it.ri
+
+proc add*[T](root: var BinaryTree[T], data: T) =
+  # convenience proc:
+  add(root, newNode(data))
+
+iterator preorder*[T](root: BinaryTree[T]): T =
+  # Preorder traversal of a binary tree.
+  # This uses an explicit stack (which is more efficient than
+  # a recursive iterator factory).
+  var stack: seq[BinaryTree[T]] = @[root]
+  while stack.len > 0:
+    var n = stack.pop()
+    while n != nil:
+      yield n.data
+      add(stack, n.ri)  # push right subtree onto the stack
+      n = n.le          # and follow the left pointer
+
+var
+  root: BinaryTree[string] # instantiate a BinaryTree with `string`
+add(root, newNode("hello")) # instantiates `newNode` and `add`
+add(root, "world")          # instantiates the second `add` proc
+for str in preorder(root):
+  stdout.writeLine(str)

+

The example shows a generic binary tree. Depending on context, the brackets are used either to introduce type parameters or to instantiate a generic proc, iterator or type. As the example shows, generics work with overloading: the best match of add is used. The built-in add procedure for sequences is not hidden and is used in the preorder iterator.

+

There is a special [:T] syntax when using generics with the method call syntax:

+

proc foo[T](i: T) =
+  discard
+
+var i: int
+
+# i.foo[int]() # Error: expression 'foo(i)' has no type (or is ambiguous)
+
+i.foo[:int]() # Success

+ +

Templates

Templates are a simple substitution mechanism that operates on Nim's abstract syntax trees. Templates are processed in the semantic pass of the compiler. They integrate well with the rest of the language and share none of C's preprocessor macros flaws.

+

To invoke a template, call it like a procedure.

+

Example:

+

template `!=` (a, b: untyped): untyped =
+  # this definition exists in the System module
+  not (a == b)
+
+assert(5 != 6) # the compiler rewrites that to: assert(not (5 == 6))

+

The !=, >, >=, in, notin, isnot operators are in fact templates: this has the benefit that if you overload the == operator, the != operator is available automatically and does the right thing. (Except for IEEE floating point numbers - NaN breaks basic boolean logic.)

+

a > b is transformed into b < a. a in b is transformed into contains(b, a). notin and isnot have the obvious meanings.

+

Templates are especially useful for lazy evaluation purposes. Consider a simple proc for logging:

+

const
+  debug = true
+
+proc log(msg: string) {.inline.} =
+  if debug: stdout.writeLine(msg)
+
+var
+  x = 4
+log("x has the value: " & $x)

+

This code has a shortcoming: if debug is set to false someday, the quite expensive $ and & operations are still performed! (The argument evaluation for procedures is eager).

+

Turning the log proc into a template solves this problem:

+

const
+  debug = true
+
+template log(msg: string) =
+  if debug: stdout.writeLine(msg)
+
+var
+  x = 4
+log("x has the value: " & $x)

+

The parameters' types can be ordinary types or the meta types untyped, typed, or type. type suggests that only a type symbol may be given as an argument, and untyped means symbol lookups and type resolution is not performed before the expression is passed to the template.

+

If the template has no explicit return type, void is used for consistency with procs and methods.

+

To pass a block of statements to a template, use untyped for the last parameter:

+

template withFile(f: untyped, filename: string, mode: FileMode,
+                  body: untyped) =
+  let fn = filename
+  var f: File
+  if open(f, fn, mode):
+    try:
+      body
+    finally:
+      close(f)
+  else:
+    quit("cannot open: " & fn)
+
+withFile(txt, "ttempl3.txt", fmWrite):
+  txt.writeLine("line 1")
+  txt.writeLine("line 2")

+

In the example the two writeLine statements are bound to the body parameter. The withFile template contains boilerplate code and helps to avoid a common bug: to forget to close the file. Note how the let fn = filename statement ensures that filename is evaluated only once.

+ +

Example: Lifting Procs

import std/math
+
+template liftScalarProc(fname) =
+  ## Lift a proc taking one scalar parameter and returning a
+  ## scalar value (eg `proc sssss[T](x: T): float`),
+  ## to provide templated procs that can handle a single
+  ## parameter of seq[T] or nested seq[seq[]] or the same type
+  ##
+  ##   ```Nim
+  ##   liftScalarProc(abs)
+  ##   # now abs(@[@[1,-2], @[-2,-3]]) == @[@[1,2], @[2,3]]
+  ##   ```
+  proc fname[T](x: openarray[T]): auto =
+    var temp: T
+    type outType = typeof(fname(temp))
+    result = newSeq[outType](x.len)
+    for i in 0..<x.len:
+      result[i] = fname(x[i])
+
+liftScalarProc(sqrt)   # make sqrt() work for sequences
+echo sqrt(@[4.0, 16.0, 25.0, 36.0])   # => @[2.0, 4.0, 5.0, 6.0]

+ +

Compilation to JavaScript

Nim code can be compiled to JavaScript. However in order to write JavaScript-compatible code you should remember the following:

+
  • addr and ptr have slightly different semantic meaning in JavaScript. It is recommended to avoid those if you're not sure how they are translated to JavaScript.
  • +
  • cast[T](x) in JavaScript is translated to (x), except for casting between signed/unsigned ints, in which case it behaves as static cast in C language.
  • +
  • cstring in JavaScript means JavaScript string. It is a good practice to use cstring only when it is semantically appropriate. E.g. don't use cstring as a binary data buffer.
  • +
+ +

Part 3

The next part is entirely about metaprogramming via macros: Part III.

+

+ +
+
+ + +
+
+ + + + diff --git a/tut2.idx b/tut2.idx new file mode 100644 index 0000000000000..7bc7dd823d397 --- /dev/null +++ b/tut2.idx @@ -0,0 +1,24 @@ +markupTitle Nim Tutorial (Part II) tut2.html Nim Tutorial (Part II) 0 +heading Introduction tut2.html#introduction Introduction 0 +heading Pragmas tut2.html#pragmas Pragmas 0 +heading Object Oriented Programming tut2.html#object-oriented-programming Object Oriented Programming 0 +heading Inheritance tut2.html#object-oriented-programming-inheritance Inheritance 0 +heading Mutually recursive types tut2.html#object-oriented-programming-mutually-recursive-types Mutually recursive types 0 +heading Type conversions tut2.html#object-oriented-programming-type-conversions Type conversions 0 +idx type casts tut2.html#type-casts_1 Type conversions 0 +idx type conversions tut2.html#type-conversions_1 Type conversions 0 +heading Object variants tut2.html#object-oriented-programming-object-variants Object variants 0 +heading Method call syntax tut2.html#object-oriented-programming-method-call-syntax Method call syntax 0 +heading Properties tut2.html#object-oriented-programming-properties Properties 0 +idx array properties tut2.html#array-properties_1 Properties 0 +heading Dynamic dispatch tut2.html#object-oriented-programming-dynamic-dispatch Dynamic dispatch 0 +heading Exceptions tut2.html#exceptions Exceptions 0 +heading Raise statement tut2.html#exceptions-raise-statement Raise statement 0 +heading Try statement tut2.html#exceptions-try-statement Try statement 0 +heading Annotating procs with raised exceptions tut2.html#exceptions-annotating-procs-with-raised-exceptions Annotating procs with raised exceptions 0 +heading Generics tut2.html#generics Generics 0 +idx type parameters tut2.html#type-parameters_1 Generics 0 +heading Templates tut2.html#templates Templates 0 +heading Example: Lifting Procs tut2.html#templates-examplecolon-lifting-procs Example: Lifting Procs 0 +heading Compilation to JavaScript tut2.html#compilation-to-javascript Compilation to JavaScript 0 +heading Part 3 tut2.html#part-3 Part 3 0 diff --git a/tut3.html b/tut3.html new file mode 100644 index 0000000000000..2716155872929 --- /dev/null +++ b/tut3.html @@ -0,0 +1,278 @@ + + + + + + + +Nim Tutorial (Part III) + + + + + + + + + + + + + + + + +
+
+

Nim Tutorial (Part III)

+
+ +
+ Source   +Edit   + +
+ +

+ +
Author:Arne Döring
Version:2.2.1
+

Introduction

"With Great Power Comes Great Responsibility." -- Spider Man's Uncle

+

This document is a tutorial about Nim's macro system. A macro is a function that is executed at compile-time and transforms a Nim syntax tree into a different tree.

+

Examples of things that can be implemented in macros:

+
  • An assert macro that prints both sides of a comparison operator, if the assertion fails. myAssert(a == b) is converted to if a != b: quit($a " != " $b)
  • +
  • A debug macro that prints the value and the name of the symbol. myDebugEcho(a) is converted to echo "a: ", a
  • +
  • Symbolic differentiation of an expression. diff(a*pow(x,3) + b*pow(x,2) + c*x + d, x) is converted to 3*a*pow(x,2) + 2*b*x + c
  • +
+ +

Macro Arguments

The types of macro arguments have two faces. One face is used for the overload resolution and the other face is used within the macro body. For example, if macro foo(arg: int) is called in an expression foo(x), x has to be of a type compatible to int, but within the macro's body arg has the type NimNode, not int! Why it is done this way will become obvious later, when we have seen concrete examples.

+

There are two ways to pass arguments to a macro, an argument can be either typed or untyped.

+ +

Untyped Arguments

Untyped macro arguments are passed to the macro before they are semantically checked. This means the syntax tree that is passed down to the macro does not need to make sense for Nim yet, the only limitation is that it needs to be parsable. Usually, the macro does not check the argument either but uses it in the transformation's result somehow. The result of a macro expansion is always checked by the compiler, so apart from weird error messages, nothing bad can happen.

+

The downside for an untyped argument is that these do not play well with Nim's overloading resolution.

+

The upside for untyped arguments is that the syntax tree is quite predictable and less complex compared to its typed counterpart.

+ +

Typed Arguments

For typed arguments, the semantic checker runs on the argument and does transformations on it, before it is passed to the macro. Here identifier nodes are resolved as symbols, implicit type conversions are visible in the tree as calls, templates are expanded, and probably most importantly, nodes have type information. Typed arguments can have the type typed in the arguments list. But all other types, such as int, float or MyObjectType are typed arguments as well, and they are passed to the macro as a syntax tree.

+ +

Static Arguments

Static arguments are a way to pass values as values and not as syntax tree nodes to a macro. For example for macro foo(arg: static[int]) in the expression foo(x), x needs to be an integer constant, but in the macro body arg is just like a normal parameter of type int.

+

import std/macros
+
+macro myMacro(arg: static[int]): untyped =
+  echo arg # just an int (7), not `NimNode`
+
+myMacro(1 + 2 * 3)

+ +

Code Blocks as Arguments

It is possible to pass the last argument of a call expression in a separate code block with indentation. For example, the following code example is a valid (but not a recommended) way to call echo:

+

echo "Hello ":
+  let a = "Wor"
+  let b = "ld!"
+  a & b

+

For macros this way of calling is very useful; syntax trees of arbitrary complexity can be passed to macros with this notation.

+ +

The Syntax Tree

In order to build a Nim syntax tree one needs to know how Nim source code is represented as a syntax tree, and how such a tree needs to look like so that the Nim compiler will understand it. The nodes of the Nim syntax tree are documented in the macros module. But a more interactive way to explore the Nim syntax tree is with macros.treeRepr, it converts a syntax tree into a multi-line string for printing on the console. It can be used to explore how the argument expressions are represented in tree form and for debug printing of generated syntax tree. dumpTree is a predefined macro that just prints its argument in a tree representation, but does nothing else. Here is an example of such a tree representation:

+

dumpTree:
+  var mt: MyType = MyType(a:123.456, b:"abcdef")
+
+# output:
+#   StmtList
+#     VarSection
+#       IdentDefs
+#         Ident "mt"
+#         Ident "MyType"
+#         ObjConstr
+#           Ident "MyType"
+#           ExprColonExpr
+#             Ident "a"
+#             FloatLit 123.456
+#           ExprColonExpr
+#             Ident "b"
+#             StrLit "abcdef"

+ +

Custom Semantic Checking

The first thing that a macro should do with its arguments is to check if the argument is in the correct form. Not every type of wrong input needs to be caught here, but anything that could cause a crash during macro evaluation should be caught and create a nice error message. macros.expectKind and macros.expectLen are a good start. If the checks need to be more complex, arbitrary error messages can be created with the macros.error proc.

+

macro myAssert(arg: untyped): untyped =
+  arg.expectKind nnkInfix

+ +

Generating Code

There are two ways to generate the code. Either by creating the syntax tree with expressions that contain a lot of calls to newTree and newLit, or with quote do: expressions. The first option offers the best low-level control for the syntax tree generation, but the second option is much less verbose. If you choose to create the syntax tree with calls to newTree and newLit the macro macros.dumpAstGen can help you with the verbosity.

+

quote do: allows you to write the code that you want to generate literally. Backticks are used to insert code from NimNode symbols into the generated expression.

+

import std/macros
+macro a(i) = quote do:
+  let `i` = 0
+
+a b
+doAssert b == 0

+

A custom prefix operator can be defined whenever backticks are needed.

+

import std/macros
+macro a(i) = quote("@") do:
+  assert @i == 0
+
+let b = 0
+a b

+

The injected symbol needs accent quoted when it resolves to a symbol.

+

import std/macros
+macro a(i) = quote("@") do:
+  let `@i` = 0
+
+a b
+doAssert b == 0

+

Make sure to inject only symbols of type NimNode into the generated syntax tree. You can use newLit to convert arbitrary values into expressions trees of type NimNode so that it is safe to inject them into the tree.

+

import std/macros
+
+type
+  MyType = object
+    a: float
+    b: string
+
+macro myMacro(arg: untyped): untyped =
+  var mt: MyType = MyType(a:123.456, b:"abcdef")
+  
+  # ...
+  
+  let mtLit = newLit(mt)
+  
+  result = quote do:
+    echo `arg`
+    echo `mtLit`
+
+myMacro("Hallo")

+

The call to myMacro will generate the following code:

+

echo "Hallo"
+echo MyType(a: 123.456'f64, b: "abcdef")

+ +

Building Your First Macro

To give a starting point to writing macros we will show now how to implement the myAssert macro mentioned earlier. The first thing to do is to build a simple example of the macro usage, and then just print the argument. This way it is possible to get an idea of what a correct argument should look like.

+

import std/macros
+
+macro myAssert(arg: untyped): untyped =
+  echo arg.treeRepr
+
+let a = 1
+let b = 2
+
+myAssert(a != b)

+

Infix
+  Ident "!="
+  Ident "a"
+  Ident "b"

+

From the output, it is possible to see that the argument is an infix operator (node kind is "Infix"), as well as that the two operands are at index 1 and 2. With this information, the actual macro can be written.

+

import std/macros
+
+macro myAssert(arg: untyped): untyped =
+  # all node kind identifiers are prefixed with "nnk"
+  arg.expectKind nnkInfix
+  arg.expectLen 3
+  # operator as string literal
+  let op  = newLit(" " & arg[0].repr & " ")
+  let lhs = arg[1]
+  let rhs = arg[2]
+  
+  result = quote do:
+    if not `arg`:
+      raise newException(AssertionDefect,$`lhs` & `op` & $`rhs`)
+
+let a = 1
+let b = 2
+
+myAssert(a != b)
+myAssert(a == b)

+

This is the code that will be generated. To debug what the macro actually generated, the statement echo result.repr can be used, in the last line of the macro. It is also the statement that has been used to get this output.

+

if not (a != b):
+  raise newException(AssertionDefect, $a & " != " & $b)

+ +

Going further

It is possible to create more complex macros by combining different NimNode symbols with quote do: expressions. For example, you may use newStmtList to build your macro iteratively, and ident in cases in which you wish to create an identifier from a string, as shown below.

+

import std/macros
+
+macro createProcedures() =
+  result = newStmtList()
+  
+  for i in 0..<10:
+    let name = ident("myProc" & $i)
+    let content = newLit("I am procedure number #" & $i)
+    
+    result.add quote do:
+      proc `name`() =
+        echo `content`
+
+createProcedures()
+myProc7()

+

The call to myProc7 will echo I am procedure number #7.

+ +

With Power Comes Responsibility

Macros are very powerful. A piece of good advice is to use them as little as possible, but as much as necessary. Macros can change the semantics of expressions, making the code incomprehensible for anybody who does not know exactly what the macro does with it. So whenever a macro is not necessary and the same logic can be implemented using templates or generics, it is probably better not to use a macro. And when a macro is used for something, the macro should better have a well-written documentation. For all the people who claim to write only perfectly self-explanatory code: when it comes to macros, the implementation is not enough for documentation.

+ +

Limitations

Since macros are evaluated in the compiler in the NimVM, macros share all the limitations of the NimVM. They have to be implemented in pure Nim code. Macros can start external processes on the shell, but they cannot call C functions except those that are built in the compiler.

+ +

More Examples

This tutorial can only cover the basics of the macro system. There are macros out there that could be an inspiration for you of what is possible with it.

+ +

Strformat

In the Nim standard library, the strformat library provides a macro that parses a string literal at compile time. Parsing a string in a macro like here is generally not recommended. The parsed AST cannot have type information, and parsing implemented on the VM is generally not very fast. Working on AST nodes is almost always the recommended way. But still strformat is a good example for a practical use case for a macro that is slightly more complex than the assert macro.

+

Strformat

+ +

Ast Pattern Matching

Ast Pattern Matching is a macro library to aid in writing complex macros. This can be seen as a good example of how to repurpose the Nim syntax tree with new semantics.

+

Ast Pattern Matching

+ +

OpenGL Sandbox

This project has a working Nim to GLSL compiler written entirely in macros. It scans recursively through all used function symbols to compile them so that cross library functions can be executed on the GPU.

+

OpenGL Sandbox

+

+ +
+
+ + +
+
+ + + + diff --git a/tut3.idx b/tut3.idx new file mode 100644 index 0000000000000..adef861cd1258 --- /dev/null +++ b/tut3.idx @@ -0,0 +1,18 @@ +markupTitle Nim Tutorial (Part III) tut3.html Nim Tutorial (Part III) 0 +heading Introduction tut3.html#introduction Introduction 0 +heading Macro Arguments tut3.html#introduction-macro-arguments Macro Arguments 0 +heading Untyped Arguments tut3.html#introduction-untyped-arguments Untyped Arguments 0 +heading Typed Arguments tut3.html#introduction-typed-arguments Typed Arguments 0 +heading Static Arguments tut3.html#introduction-static-arguments Static Arguments 0 +heading Code Blocks as Arguments tut3.html#introduction-code-blocks-as-arguments Code Blocks as Arguments 0 +heading The Syntax Tree tut3.html#introduction-the-syntax-tree The Syntax Tree 0 +heading Custom Semantic Checking tut3.html#introduction-custom-semantic-checking Custom Semantic Checking 0 +heading Generating Code tut3.html#introduction-generating-code Generating Code 0 +heading Building Your First Macro tut3.html#introduction-building-your-first-macro Building Your First Macro 0 +heading Going further tut3.html#introduction-going-further Going further 0 +heading With Power Comes Responsibility tut3.html#introduction-with-power-comes-responsibility With Power Comes Responsibility 0 +heading Limitations tut3.html#introduction-limitations Limitations 0 +heading More Examples tut3.html#more-examples More Examples 0 +heading Strformat tut3.html#more-examples-strformat Strformat 0 +heading Ast Pattern Matching tut3.html#more-examples-ast-pattern-matching Ast Pattern Matching 0 +heading OpenGL Sandbox tut3.html#more-examples-opengl-sandbox OpenGL Sandbox 0 diff --git a/typedthreads.html b/typedthreads.html new file mode 100644 index 0000000000000..2a332394c6c64 --- /dev/null +++ b/typedthreads.html @@ -0,0 +1,271 @@ + + + + + + + +std/typedthreads + + + + + + + + + + + + + + + + +
+
+

std/typedthreads

+
+ +
+ Source   +Edit   + +
+ +

Thread support for Nim. Threads allow multiple functions to execute concurrently.

+

In Nim, threads are a low-level construct and using a library like malebolgia, taskpools or weave is recommended.

+

When creating a thread, you can pass arguments to it. As Nim's garbage collector does not use atomic references, sharing ref and other variables managed by the garbage collector between threads is not supported. Use global variables to do so, or pointers.

+

Memory allocated using `sharedAlloc` can be used and shared between threads.

+

To communicate between threads, consider using channels

+ +

Examples

import std/locks
+
+var
+  thr: array[0..4, Thread[tuple[a,b: int]]]
+  L: Lock
+
+proc threadFunc(interval: tuple[a,b: int]) {.thread.} =
+  for i in interval.a..interval.b:
+    acquire(L) # lock stdout
+    echo i
+    release(L)
+
+initLock(L)
+
+for i in 0..high(thr):
+  createThread(thr[i], threadFunc, (i*10, i*10+5))
+joinThreads(thr)
+
+deinitLock(L)

+

When using a memory management strategy that supports shared heaps like arc or boehm, you can pass pointer to threads and share memory between them, but the memory must outlive the thread. The default memory management strategy, orc, supports this. The example below is not valid for memory management strategies that use local heaps like refc!

+

import locks
+
+var l: Lock
+
+proc threadFunc(obj: ptr seq[int]) {.thread.} =
+  withLock l:
+    for i in 0..<100:
+      obj[].add(obj[].len * obj[].len)
+
+proc threadHandler() =
+  var thr: array[0..4, Thread[ptr seq[int]]]
+  var s = newSeq[int]()
+  
+  for i in 0..high(thr):
+    createThread(thr[i], threadFunc, s.addr)
+  joinThreads(thr)
+  echo s
+
+initLock(l)
+threadHandler()
+deinitLock(l)

+

+ +
+

Procs

+
+
+
+
proc createThread(t: var Thread[void]; tp: proc () {.thread, nimcall.}) {.
+    ...raises: [ResourceExhaustedError], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc createThread[TArg](t: var Thread[TArg];
+                        tp: proc (arg: TArg) {.thread, nimcall.}; param: TArg)
+
+ +

Creates a new thread t and starts its execution.

+

Entry point is the proc tp. param is passed to tp. TArg can be void if you don't need to pass any data to the thread.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc handle[TArg](t: Thread[TArg]): SysThread {.inline.}
+
+ + Returns the thread handle of t. + Source   +Edit   + +
+
+ +
+
+
+
proc joinThread[TArg](t: Thread[TArg]) {.inline.}
+
+ + Waits for the thread t to finish. + Source   +Edit   + +
+
+ +
+
+
+
proc joinThreads[TArg](t: varargs[Thread[TArg]])
+
+ + Waits for every thread in t to finish. + Source   +Edit   + +
+
+ +
+
+
+
proc pinToCpu[Arg](t: var Thread[Arg]; cpu: Natural)
+
+ +

Pins a thread to a CPU.

+

In other words sets a thread's affinity. If you don't know what this means, you shouldn't use this proc.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc running[TArg](t: Thread[TArg]): bool {.inline.}
+
+ + Returns true if t is running. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/typedthreads.idx b/typedthreads.idx new file mode 100644 index 0000000000000..5ad8dc3ae952a --- /dev/null +++ b/typedthreads.idx @@ -0,0 +1,12 @@ +nimTitle typedthreads typedthreads.html module std/typedthreads 0 +nim running typedthreads.html#running,Thread[TArg] proc running[TArg](t: Thread[TArg]): bool 152 +nim handle typedthreads.html#handle,Thread[TArg] proc handle[TArg](t: Thread[TArg]): SysThread 156 +nim joinThread typedthreads.html#joinThread,Thread[TArg] proc joinThread[TArg](t: Thread[TArg]) 187 +nim joinThreads typedthreads.html#joinThreads,varargs[Thread[TArg]] proc joinThreads[TArg](t: varargs[Thread[TArg]]) 191 +nim createThread typedthreads.html#createThread,Thread[TArg],proc(TArg),TArg proc createThread[TArg](t: var Thread[TArg]; tp: proc (arg: TArg) {.thread, nimcall.};\n param: TArg) 261 +nim pinToCpu typedthreads.html#pinToCpu,Thread[Arg],Natural proc pinToCpu[Arg](t: var Thread[Arg]; cpu: Natural) 292 +nim createThread typedthreads.html#createThread,Thread[void],proc) proc createThread(t: var Thread[void]; tp: proc () {.thread, nimcall.}) 303 +heading Examples typedthreads.html#examples Examples 0 +idx CPU typedthreads.html#cpu_1 Examples 0 +idx affinity typedthreads.html#affinity_1 Examples 0 +nimgrp createthread typedthreads.html#createThread-procs-all proc 261 diff --git a/typeinfo.html b/typeinfo.html new file mode 100644 index 0000000000000..a7d2bd7ffd263 --- /dev/null +++ b/typeinfo.html @@ -0,0 +1,1093 @@ + + + + + + + +std/typeinfo + + + + + + + + + + + + + + + + +
+
+

std/typeinfo

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements an interface to Nim's runtime type information (RTTI). See the marshal module for an example of what this allows you to do.

Note: +Even though Any and its operations hide the nasty low level details from its users, it remains inherently unsafe! Also, Nim's runtime type information will evolve and may eventually be deprecated. As an alternative approach to programmatically understanding and manipulating types, consider using the macros module to work with the types' AST representation at compile time. See for example the getTypeImpl proc. As an alternative approach to storing arbitrary types at runtime, consider using generics.
+ +

Example:

+
import std/typeinfo
+var x: Any
+
+var i = 42
+x = i.toAny
+assert x.kind == akInt
+assert x.getInt == 42
+
+var s = @[1, 2, 3]
+x = s.toAny
+assert x.kind == akSequence
+assert x.len == 3

+ +
+

Types

+
+
+
Any = object
+  when defined(js):
+  else:
+
+ + A type that can represent any nim value.
Danger: +The wrapped value can be modified with its wrapper! This means that Any keeps a non-traced pointer to its wrapped value and must not live longer than its wrapped value.
+ + Source   +Edit   + +
+
+
+
AnyKind = enum
+  akNone = 0,               ## invalid
+  akBool = 1,               ## bool
+  akChar = 2,               ## char
+  akEnum = 14,              ## enum
+  akArray = 16,             ## array
+  akObject = 17,            ## object
+  akTuple = 18,             ## tuple
+  akSet = 19,               ## set
+  akRange = 20,             ## range
+  akPtr = 21,               ## ptr
+  akRef = 22,               ## ref
+  akSequence = 24,          ## sequence
+  akProc = 25,              ## proc
+  akPointer = 26,           ## pointer
+  akString = 28,            ## string
+  akCString = 29,           ## cstring
+  akInt = 31,               ## int
+  akInt8 = 32,              ## int8
+  akInt16 = 33,             ## int16
+  akInt32 = 34,             ## int32
+  akInt64 = 35,             ## int64
+  akFloat = 36,             ## float
+  akFloat32 = 37,           ## float32
+  akFloat64 = 38,           ## float64
+  akFloat128 = 39,          ## float128
+  akUInt = 40,              ## uint
+  akUInt8 = 41,             ## uint8
+  akUInt16 = 42,            ## uin16
+  akUInt32 = 43,            ## uint32
+  akUInt64 = 44              ## uint64
+
+ + The kind of Any. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `[]`(x: Any): Any {....raises: [], tags: [], forbids: [].}
+
+ + Dereference operator for Any. x needs to represent a ptr or a ref. + Source   +Edit   + +
+
+
+
proc `[]`(x: Any; fieldName: string): Any {....raises: [ValueError], tags: [],
+    forbids: [].}
+
+ + Gets a field of x. x needs to represent an object or a tuple. + Source   +Edit   + +
+
+
+
proc `[]`(x: Any; i: int): Any {....raises: [], tags: [], forbids: [].}
+
+ + Accessor for an any x that represents an array or a sequence. + Source   +Edit   + +
+
+ +
+
+
+
proc `[]=`(x, y: Any) {....raises: [], tags: [], forbids: [].}
+
+ + Dereference operator for Any. x needs to represent a ptr or a ref. + Source   +Edit   + +
+
+
+
proc `[]=`(x: Any; fieldName: string; value: Any) {....raises: [ValueError],
+    tags: [], forbids: [].}
+
+ + Sets a field of x. x needs to represent an object or a tuple. + Source   +Edit   + +
+
+
+
proc `[]=`(x: Any; i: int; y: Any) {....raises: [], tags: [], forbids: [].}
+
+ + Accessor for an any x that represents an array or a sequence. + Source   +Edit   + +
+
+ +
+
+
+
proc assign(x, y: Any) {....raises: [], tags: [], forbids: [].}
+
+ + Copies the value of y to x. The assignment operator for Any does NOT do this; it performs a shallow copy instead! + Source   +Edit   + +
+
+ +
+
+
+
proc base(x: Any): Any {....raises: [], tags: [], forbids: [].}
+
+ + Returns the base type of x (useful for inherited object types). + Source   +Edit   + +
+
+ +
+
+
+
proc baseTypeKind(x: Any): AnyKind {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Gets the base type's kind. If x has no base type, akNone is returned. + Source   +Edit   + +
+
+ +
+
+
+
proc baseTypeSize(x: Any): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Returns the size of x's base type. If x has no base type, 0 is returned. + Source   +Edit   + +
+
+ +
+
+
+
proc extendSeq(x: Any) {....raises: [], tags: [], forbids: [].}
+
+ + Performs setLen(x, x.len+1). x needs to represent a seq. + Source   +Edit   + +
+
+ +
+
+
+
proc getBiggestFloat(x: Any): BiggestFloat {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the float value out of x. x needs to represent some float. The value is extended to BiggestFloat. + Source   +Edit   + +
+
+ +
+
+
+
proc getBiggestInt(x: Any): BiggestInt {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the integer value out of x. x needs to represent some integer, a bool, a char, an enum or a small enough bit set. The value might be sign-extended to BiggestInt. + Source   +Edit   + +
+
+ +
+
+
+
proc getBiggestUint(x: Any): uint64 {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the unsigned integer value out of x. x needs to represent an unsigned integer. + Source   +Edit   + +
+
+ +
+
+
+
proc getBool(x: Any): bool {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the bool value out of x. x needs to represent a bool. + Source   +Edit   + +
+
+ +
+
+
+
proc getChar(x: Any): char {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the char value out of x. x needs to represent a char. + Source   +Edit   + +
+
+ +
+
+
+
proc getCString(x: Any): cstring {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the cstring value out of x. x needs to represent a cstring. + Source   +Edit   + +
+
+ +
+
+
+
proc getEnumField(x: Any): string {....raises: [], tags: [], forbids: [].}
+
+ + Gets the enum field name as a string. x needs to represent an enum. + Source   +Edit   + +
+
+
+
proc getEnumField(x: Any; ordinalValue: int): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + Gets the enum field name as a string. x needs to represent an enum but is only used to access the type information. The field name of ordinalValue is returned. + Source   +Edit   + +
+
+ +
+
+
+
proc getEnumOrdinal(x: Any; name: string): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + Gets the enum field ordinal from name. x needs to represent an enum but is only used to access the type information. In case of an error low(int) is returned. + Source   +Edit   + +
+
+ +
+
+
+
proc getFloat(x: Any): float {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the float value out of x. x needs to represent a float. + Source   +Edit   + +
+
+ +
+
+
+
proc getFloat32(x: Any): float32 {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the float32 value out of x. x needs to represent a float32. + Source   +Edit   + +
+
+ +
+
+
+
proc getFloat64(x: Any): float64 {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the float64 value out of x. x needs to represent a float64. + Source   +Edit   + +
+
+ +
+
+
+
proc getInt(x: Any): int {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the int value out of x. x needs to represent an int. + Source   +Edit   + +
+
+ +
+
+
+
proc getInt8(x: Any): int8 {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the int8 value out of x. x needs to represent an int8. + Source   +Edit   + +
+
+ +
+
+
+
proc getInt16(x: Any): int16 {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the int16 value out of x. x needs to represent an int16. + Source   +Edit   + +
+
+ +
+
+
+
proc getInt32(x: Any): int32 {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the int32 value out of x. x needs to represent an int32. + Source   +Edit   + +
+
+ +
+
+
+
proc getInt64(x: Any): int64 {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the int64 value out of x. x needs to represent an int64. + Source   +Edit   + +
+
+ +
+
+
+
proc getPointer(x: Any): pointer {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the pointer value out of x. x needs to be of kind akString, akCString, akProc, akRef, akPtr, akPointer or akSequence. + Source   +Edit   + +
+
+ +
+
+
+
proc getString(x: Any): string {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the string value out of x. x needs to represent a string. + Source   +Edit   + +
+
+ +
+
+
+
proc getUInt(x: Any): uint {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the uint value out of x. x needs to represent a uint. + Source   +Edit   + +
+
+ +
+
+
+
proc getUInt8(x: Any): uint8 {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the uint8 value out of x. x needs to represent a uint8. + Source   +Edit   + +
+
+ +
+
+
+
proc getUInt16(x: Any): uint16 {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the uint16 value out of x. x needs to represent a uint16. + Source   +Edit   + +
+
+ +
+
+
+
proc getUInt32(x: Any): uint32 {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the uint32 value out of x. x needs to represent a uint32. + Source   +Edit   + +
+
+ +
+
+
+
proc getUInt64(x: Any): uint64 {....raises: [], tags: [], forbids: [].}
+
+ + Retrieves the uint64 value out of x. x needs to represent a uint64. + Source   +Edit   + +
+
+ +
+
+
+
proc inclSetElement(x: Any; elem: int) {....raises: [], tags: [], forbids: [].}
+
+ + Includes an element elem in x. x needs to represent a Nim bitset. + Source   +Edit   + +
+
+ +
+
+
+
proc invokeNew(x: Any) {....raises: [], tags: [], forbids: [].}
+
+ + Performs new(x). x needs to represent a ref. + Source   +Edit   + +
+
+ +
+
+
+
proc invokeNewSeq(x: Any; len: int) {....raises: [], tags: [], forbids: [].}
+
+ + Performs newSeq(x, len). x needs to represent a seq. + Source   +Edit   + +
+
+ +
+
+
+
proc isNil(x: Any): bool {....raises: [], tags: [], forbids: [].}
+
+ + isNil for an x that represents a cstring, proc or some pointer type. + Source   +Edit   + +
+
+ +
+
+
+
proc kind(x: Any): AnyKind {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Gets the type kind. + Source   +Edit   + +
+
+ +
+
+
+
proc len(x: Any): int {....raises: [], tags: [], forbids: [].}
+
+ + len for an any x that represents an array or a sequence. + Source   +Edit   + +
+
+ +
+
+
+
proc setBiggestFloat(x: Any; y: BiggestFloat) {....raises: [], tags: [],
+    forbids: [].}
+
+ + Sets the float value of x. x needs to represent some float. + Source   +Edit   + +
+
+ +
+
+
+
proc setBiggestInt(x: Any; y: BiggestInt) {....raises: [], tags: [], forbids: [].}
+
+ + Sets the integer value of x. x needs to represent some integer, a bool, a char, an enum or a small enough bit set. + Source   +Edit   + +
+
+ +
+
+
+
proc setBiggestUint(x: Any; y: uint64) {....raises: [], tags: [], forbids: [].}
+
+ + Sets the unsigned integer value of x. x needs to represent an unsigned integer. + Source   +Edit   + +
+
+ +
+
+
+
proc setObjectRuntimeType(x: Any) {....raises: [], tags: [], forbids: [].}
+
+ + This needs to be called to set x's runtime object type field. + Source   +Edit   + +
+
+ +
+
+
+
proc setPointer(x: Any; y: pointer) {....raises: [], tags: [], forbids: [].}
+
+ + Sets the pointer value of x. x needs to be of kind akString, akCString, akProc, akRef, akPtr, akPointer or akSequence. + Source   +Edit   + +
+
+ +
+
+
+
proc setString(x: Any; y: string) {....raises: [], tags: [], forbids: [].}
+
+ + Sets the string value of x. x needs to represent a string. + Source   +Edit   + +
+
+ +
+
+
+
proc size(x: Any): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Returns the size of x's type. + Source   +Edit   + +
+
+ +
+
+
+
proc skipRange(x: Any): Any {....raises: [], tags: [], forbids: [].}
+
+ + Skips the range information of x. + Source   +Edit   + +
+
+ +
+
+
+
proc toAny[T](x: var T): Any {.inline.}
+
+ + Constructs an Any object from x. This captures x's address, so x can be modified with its Any wrapper! The caller needs to ensure that the wrapper does not live longer than x! + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator elements(x: Any): int {....raises: [], tags: [], forbids: [].}
+
+ + Iterates over every element of x. x needs to represent a set. + Source   +Edit   + +
+
+ +
+
+
+
iterator fields(x: Any): tuple[name: string, any: Any] {....raises: [], tags: [],
+    forbids: [].}
+
+ + Iterates over every active field of x. x needs to represent an object or a tuple. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/typeinfo.idx b/typeinfo.idx new file mode 100644 index 0000000000000..3d57dc878da22 --- /dev/null +++ b/typeinfo.idx @@ -0,0 +1,90 @@ +nimTitle typeinfo typeinfo.html module std/typeinfo 0 +nim akNone typeinfo.html#akNone AnyKind.akNone 48 +nim akBool typeinfo.html#akBool AnyKind.akBool 48 +nim akChar typeinfo.html#akChar AnyKind.akChar 48 +nim akEnum typeinfo.html#akEnum AnyKind.akEnum 48 +nim akArray typeinfo.html#akArray AnyKind.akArray 48 +nim akObject typeinfo.html#akObject AnyKind.akObject 48 +nim akTuple typeinfo.html#akTuple AnyKind.akTuple 48 +nim akSet typeinfo.html#akSet AnyKind.akSet 48 +nim akRange typeinfo.html#akRange AnyKind.akRange 48 +nim akPtr typeinfo.html#akPtr AnyKind.akPtr 48 +nim akRef typeinfo.html#akRef AnyKind.akRef 48 +nim akSequence typeinfo.html#akSequence AnyKind.akSequence 48 +nim akProc typeinfo.html#akProc AnyKind.akProc 48 +nim akPointer typeinfo.html#akPointer AnyKind.akPointer 48 +nim akString typeinfo.html#akString AnyKind.akString 48 +nim akCString typeinfo.html#akCString AnyKind.akCString 48 +nim akInt typeinfo.html#akInt AnyKind.akInt 48 +nim akInt8 typeinfo.html#akInt8 AnyKind.akInt8 48 +nim akInt16 typeinfo.html#akInt16 AnyKind.akInt16 48 +nim akInt32 typeinfo.html#akInt32 AnyKind.akInt32 48 +nim akInt64 typeinfo.html#akInt64 AnyKind.akInt64 48 +nim akFloat typeinfo.html#akFloat AnyKind.akFloat 48 +nim akFloat32 typeinfo.html#akFloat32 AnyKind.akFloat32 48 +nim akFloat64 typeinfo.html#akFloat64 AnyKind.akFloat64 48 +nim akFloat128 typeinfo.html#akFloat128 AnyKind.akFloat128 48 +nim akUInt typeinfo.html#akUInt AnyKind.akUInt 48 +nim akUInt8 typeinfo.html#akUInt8 AnyKind.akUInt8 48 +nim akUInt16 typeinfo.html#akUInt16 AnyKind.akUInt16 48 +nim akUInt32 typeinfo.html#akUInt32 AnyKind.akUInt32 48 +nim akUInt64 typeinfo.html#akUInt64 AnyKind.akUInt64 48 +nim AnyKind typeinfo.html#AnyKind enum AnyKind 48 +nim Any typeinfo.html#Any object Any 81 +nim toAny typeinfo.html#toAny,T proc toAny[T](x: var T): Any 164 +nim kind typeinfo.html#kind,Any proc kind(x: Any): AnyKind 170 +nim size typeinfo.html#size,Any proc size(x: Any): int 174 +nim baseTypeKind typeinfo.html#baseTypeKind,Any proc baseTypeKind(x: Any): AnyKind 178 +nim baseTypeSize typeinfo.html#baseTypeSize,Any proc baseTypeSize(x: Any): int 183 +nim invokeNew typeinfo.html#invokeNew,Any proc invokeNew(x: Any) 188 +nim invokeNewSeq typeinfo.html#invokeNewSeq,Any,int proc invokeNewSeq(x: Any; len: int) 197 +nim extendSeq typeinfo.html#extendSeq,Any proc extendSeq(x: Any) 209 +nim setObjectRuntimeType typeinfo.html#setObjectRuntimeType,Any proc setObjectRuntimeType(x: Any) 227 +nim `[]` typeinfo.html#[],Any,int proc `[]`(x: Any; i: int): Any 242 +nim `[]=` typeinfo.html#[]=,Any,int,Any proc `[]=`(x: Any; i: int; y: Any) 268 +nim len typeinfo.html#len,Any proc len(x: Any): int 297 +nim base typeinfo.html#base,Any proc base(x: Any): Any 314 +nim isNil typeinfo.html#isNil,Any proc isNil(x: Any): bool 320 +nim getPointer typeinfo.html#getPointer,Any proc getPointer(x: Any): pointer 330 +nim setPointer typeinfo.html#setPointer,Any,pointer proc setPointer(x: Any; y: pointer) 337 +nim fields typeinfo.html#fields.i,Any iterator fields(x: Any): tuple[name: string, any: Any] 361 +nim `[]=` typeinfo.html#[]=,Any,string,Any proc `[]=`(x: Any; fieldName: string; value: Any) 398 +nim `[]` typeinfo.html#[],Any,string proc `[]`(x: Any; fieldName: string): Any 412 +nim `[]` typeinfo.html#[],Any proc `[]`(x: Any): Any 428 +nim `[]=` typeinfo.html#[]=,Any,Any proc `[]=`(x, y: Any) 434 +nim getInt typeinfo.html#getInt,Any proc getInt(x: Any): int 440 +nim getInt8 typeinfo.html#getInt8,Any proc getInt8(x: Any): int8 445 +nim getInt16 typeinfo.html#getInt16,Any proc getInt16(x: Any): int16 450 +nim getInt32 typeinfo.html#getInt32,Any proc getInt32(x: Any): int32 455 +nim getInt64 typeinfo.html#getInt64,Any proc getInt64(x: Any): int64 460 +nim getBiggestInt typeinfo.html#getBiggestInt,Any proc getBiggestInt(x: Any): BiggestInt 465 +nim setBiggestInt typeinfo.html#setBiggestInt,Any,BiggestInt proc setBiggestInt(x: Any; y: BiggestInt) 491 +nim getUInt typeinfo.html#getUInt,Any proc getUInt(x: Any): uint 516 +nim getUInt8 typeinfo.html#getUInt8,Any proc getUInt8(x: Any): uint8 521 +nim getUInt16 typeinfo.html#getUInt16,Any proc getUInt16(x: Any): uint16 526 +nim getUInt32 typeinfo.html#getUInt32,Any proc getUInt32(x: Any): uint32 531 +nim getUInt64 typeinfo.html#getUInt64,Any proc getUInt64(x: Any): uint64 536 +nim getBiggestUint typeinfo.html#getBiggestUint,Any proc getBiggestUint(x: Any): uint64 541 +nim setBiggestUint typeinfo.html#setBiggestUint,Any,uint64 proc setBiggestUint(x: Any; y: uint64) 553 +nim getChar typeinfo.html#getChar,Any proc getChar(x: Any): char 565 +nim getBool typeinfo.html#getBool,Any proc getBool(x: Any): bool 571 +nim skipRange typeinfo.html#skipRange,Any proc skipRange(x: Any): Any 577 +nim getEnumOrdinal typeinfo.html#getEnumOrdinal,Any,string proc getEnumOrdinal(x: Any; name: string): int 583 +nim getEnumField typeinfo.html#getEnumField,Any,int proc getEnumField(x: Any; ordinalValue: int): string 599 +nim getEnumField typeinfo.html#getEnumField,Any proc getEnumField(x: Any): string 617 +nim getFloat typeinfo.html#getFloat,Any proc getFloat(x: Any): float 621 +nim getFloat32 typeinfo.html#getFloat32,Any proc getFloat32(x: Any): float32 626 +nim getFloat64 typeinfo.html#getFloat64,Any proc getFloat64(x: Any): float64 631 +nim getBiggestFloat typeinfo.html#getBiggestFloat,Any proc getBiggestFloat(x: Any): BiggestFloat 636 +nim setBiggestFloat typeinfo.html#setBiggestFloat,Any,BiggestFloat proc setBiggestFloat(x: Any; y: BiggestFloat) 645 +nim getString typeinfo.html#getString,Any proc getString(x: Any): string 654 +nim setString typeinfo.html#setString,Any,string proc setString(x: Any; y: string) 663 +nim getCString typeinfo.html#getCString,Any proc getCString(x: Any): cstring 668 +nim assign typeinfo.html#assign,Any,Any proc assign(x, y: Any) 673 +nim elements typeinfo.html#elements.i,Any iterator elements(x: Any): int 679 +nim inclSetElement typeinfo.html#inclSetElement,Any,int proc inclSetElement(x: Any; elem: int) 701 +idx runtime type information typeinfo.html#runtime-type-information_1 Module typeinfo 0 +idx RTTI typeinfo.html#rtti_1 Module typeinfo 0 +nimgrp []= typeinfo.html#[]=-procs-all proc 268 +nimgrp [] typeinfo.html#[]-procs-all proc 242 +nimgrp getenumfield typeinfo.html#getEnumField-procs-all proc 599 diff --git a/typetraits.html b/typetraits.html new file mode 100644 index 0000000000000..8400df34874b9 --- /dev/null +++ b/typetraits.html @@ -0,0 +1,728 @@ + + + + + + + +std/typetraits + + + + + + + + + + + + + + + + +
+
+

std/typetraits

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module defines compile-time reflection procs for working with types.

+

Unstable API.

+ +

Example:

+
import std/typetraits
+type A = enum a0 = 2, a1 = 4, a2
+type B = enum b0 = 2, b1, b2
+assert A is enum
+assert A is HoleyEnum
+assert A isnot OrdinalEnum
+assert B isnot HoleyEnum
+assert B is OrdinalEnum
+assert int isnot HoleyEnum
+type C[T] = enum h0 = 2, h1 = 4
+assert C[float] is HoleyEnum

+ +
+

Types

+
+
+
HoleyEnum = (not Ordinal) and enum
+
+ + Enum with holes. + Source   +Edit   + +
+
+
+
OrdinalEnum = Ordinal and enum
+
+ + Enum without holes. + Source   +Edit   + +
+
+
+
StaticParam[value] = object
+
+ + Used to wrap a static value in genericParams. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc arity(t: typedesc): int {.magic: "TypeTrait", ...raises: [], tags: [],
+                               forbids: [].}
+
+ + Returns the arity of t. This is the number of "type" components or the number of generic parameters a given type t has. +

Example:

+
doAssert arity(int) == 0
+doAssert arity(seq[string]) == 1
+doAssert arity(array[3, int]) == 2
+doAssert arity((int, int, float, string)) == 4
+ Source   +Edit   + +
+
+ +
+
+
+
proc distinctBase(T: typedesc; recursive: static bool = true): typedesc {.
+    magic: "TypeTrait", ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the base type for distinct types, or the type itself otherwise. If recursive is false, only the immediate distinct base will be returned.

+

See also:

+ + +

Example:

+
type MyInt = distinct int
+type MyOtherInt = distinct MyInt
+doAssert distinctBase(MyInt) is int
+doAssert distinctBase(MyOtherInt) is int
+doAssert distinctBase(MyOtherInt, false) is MyInt
+doAssert distinctBase(int) is int
+ Source   +Edit   + +
+
+ +
+
+
+
proc genericHead(t: typedesc): typedesc {.magic: "TypeTrait", ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Accepts an instantiated generic type and returns its uninstantiated form. A compile-time error will be produced if the supplied type is not generic.

+

See also:

+ + +

Example:

+
type
+  Foo[T] = object
+  FooInst = Foo[int]
+  Foo2 = genericHead(FooInst)
+
+doAssert Foo2 is Foo and Foo is Foo2
+doAssert genericHead(Foo[seq[string]]) is Foo
+doAssert not compiles(genericHead(int))
+
+type Generic = concept f
+  type _ = genericHead(typeof(f))
+
+proc bar(a: Generic): typeof(a) = a
+
+doAssert bar(Foo[string].default) == Foo[string]()
+doAssert not compiles bar(string.default)
+
+when false: # these don't work yet
+  doAssert genericHead(Foo[int])[float] is Foo[float]
+  doAssert seq[int].genericHead is seq
+ Source   +Edit   + +
+
+ +
+
+
+
proc hasClosure(fn: NimNode): bool {....raises: [], tags: [], forbids: [].}
+
+ + Returns true if the func/proc/etc fn has closure. fn has to be a resolved symbol of kind nnkSym. This implies that the macro that calls this proc should accept typed arguments and not untyped arguments. + Source   +Edit   + +
+
+ +
+
+
+
proc hasDefaultValue(t: typedesc): bool {.magic: "TypeTrait", ...raises: [],
+    tags: [], forbids: [].}
+
+ + Returns true if t has a valid default value. +

Example:

+
{.experimental: "strictNotNil".}
+type
+  NilableObject = ref object
+    a: int
+  Object = NilableObject not nil
+  RequiresInit[T] = object
+    a {.requiresInit.}: T
+
+assert hasDefaultValue(NilableObject)
+assert not hasDefaultValue(Object)
+assert hasDefaultValue(string)
+assert not hasDefaultValue(var string)
+assert not hasDefaultValue(RequiresInit[int])
+ Source   +Edit   + +
+
+ +
+
+
+
proc isNamedTuple(T: typedesc): bool {.magic: "TypeTrait", ...raises: [], tags: [],
+                                       forbids: [].}
+
+ + Returns true for named tuples, false for any other type. +

Example:

+
doAssert not isNamedTuple(int)
+doAssert not isNamedTuple((string, int))
+doAssert isNamedTuple(tuple[name: string, age: int])
+ Source   +Edit   + +
+
+ +
+
+
+
proc name(t: typedesc): string {.magic: "TypeTrait", ...raises: [], tags: [],
+                                 forbids: [].}
+
+ +

Returns the name of t.

+

Alias for system.`$`(t) since Nim v0.20.

+ +

Example:

+
doAssert name(int) == "int"
+doAssert name(seq[string]) == "seq[string]"
+ Source   +Edit   + +
+
+ +
+
+
+
proc rangeBase(T: typedesc[range]): typedesc {.magic: "TypeTrait", ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Returns the base type for range types, or the type itself otherwise.

+

See also:

+ + +

Example:

+
type MyRange = range[0..5]
+type MyEnum = enum a, b, c
+type MyEnumRange = range[b..c]
+doAssert rangeBase(MyRange) is int
+doAssert rangeBase(MyEnumRange) is MyEnum
+doAssert rangeBase(range['a'..'z']) is char
+ Source   +Edit   + +
+
+ +
+
+
+
proc stripGenericParams(t: typedesc): typedesc {.magic: "TypeTrait", ...raises: [],
+    tags: [], forbids: [].}
+
+ + This trait is similar to genericHead, but instead of producing an error for non-generic types, it will just return them unmodified. +

Example:

+
type Foo[T] = object
+
+doAssert stripGenericParams(Foo[string]) is Foo
+doAssert stripGenericParams(int) is int
+ Source   +Edit   + +
+
+ +
+
+
+
proc supportsCopyMem(t: typedesc): bool {.magic: "TypeTrait", ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Returns true if t is safe to use for copyMem.

+

Other languages name a type like these blob.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc tupleLen(T: typedesc[tuple]): int {.magic: "TypeTrait", ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Returns the number of elements of the tuple type T.

+

See also:

+ + +

Example:

+
doAssert tupleLen((int, int, float, string)) == 4
+doAssert tupleLen(tuple[name: string, age: int]) == 2
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro enumLen(T: typedesc[enum]): int
+
+ + Returns the number of items in the enum T. +

Example:

+
type Foo = enum
+  fooItem1
+  fooItem2
+
+doAssert Foo.enumLen == 2
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template distinctBase[T](a: T; recursive: static bool = true): untyped
+
+ + Overload of distinctBase for values. +

Example:

+
type MyInt = distinct int
+type MyOtherInt = distinct MyInt
+doAssert 12.MyInt.distinctBase == 12
+doAssert 12.MyOtherInt.distinctBase == 12
+doAssert 12.MyOtherInt.distinctBase(false) is MyInt
+doAssert 12.distinctBase == 12
+ Source   +Edit   + +
+
+ +
+
+
+
template elementType(a: untyped): typedesc
+
+ + Returns the element type of a, which can be any iterable (over which you can iterate). +

Example:

+
iterator myiter(n: int): auto =
+  for i in 0 ..< n:
+    yield i
+
+doAssert elementType(@[1,2]) is int
+doAssert elementType("asdf") is char
+doAssert elementType(myiter(3)) is int
+ Source   +Edit   + +
+
+ +
+
+
+
template genericParams(T: typedesc): untyped
+
+ +

Returns the tuple of generic parameters for the generic type T.

+

Note: For the builtin array type, the index generic parameter will always become a range type after it's bound to a variable.

+ +

Example:

+
type Foo[T1, T2] = object
+
+doAssert genericParams(Foo[float, string]) is (float, string)
+
+type Bar[N: static float, T] = object
+
+doAssert genericParams(Bar[1.0, string]) is (StaticParam[1.0], string)
+doAssert genericParams(Bar[1.0, string]).get(0).value == 1.0
+doAssert genericParams(seq[Bar[2.0, string]]).get(0) is Bar[2.0, string]
+var s: seq[Bar[3.0, string]]
+doAssert genericParams(typeof(s)) is (Bar[3.0, string],)
+
+doAssert genericParams(array[10, int]) is (StaticParam[10], int)
+var a: array[10, int]
+doAssert genericParams(typeof(a)) is (range[0..9], int)
+ Source   +Edit   + +
+
+ +
+
+
+
template get(T: typedesc[tuple]; i: static int): untyped
+
+ + Returns the i-th element of T. +

Example:

+
doAssert get((int, int, float, string), 2) is float
+ Source   +Edit   + +
+
+ +
+
+
+
template pointerBase[T](_: typedesc[ptr T | ref T]): typedesc
+
+ + Returns T for ref T | ptr T. +

Example:

+
assert (ref int).pointerBase is int
+type A = ptr seq[float]
+assert A.pointerBase is seq[float]
+assert (ref A).pointerBase is A # not seq[float]
+assert (var s = "abc"; s[0].addr).typeof.pointerBase is char
+ Source   +Edit   + +
+
+ +
+
+
+
template rangeBase[T: range](a: T): untyped
+
+ + Overload of rangeBase for values. +

Example:

+
type MyRange = range[0..5]
+type MyEnum = enum a, b, c
+type MyEnumRange = range[b..c]
+let x = MyRange(3)
+doAssert rangeBase(x) is int
+doAssert $typeof(rangeBase(x)) == "int"
+doAssert rangeBase(x) == 3
+let y: set[MyEnumRange] = {c}
+for e in y:
+  doAssert rangeBase(e) is MyEnum
+  doAssert $typeof(rangeBase(e)) == "MyEnum"
+  doAssert rangeBase(e) == c
+let z: seq[range['a'..'z']] = @['c']
+doAssert rangeBase(z[0]) is char
+doAssert $typeof(rangeBase(z[0])) == "char"
+doAssert rangeBase(z[0]) == 'c'
+ Source   +Edit   + +
+
+ +
+
+
+
template toSigned(T: typedesc[SomeInteger and not range]): untyped
+
+ + Returns a signed type with same bit size as T. +

Example:

+
assert int8.toSigned is int8
+assert uint16.toSigned is int16
+# range types are currently unsupported:
+assert not compiles(toSigned(range[0..7]))
+ Source   +Edit   + +
+
+ +
+
+
+
template toUnsigned(T: typedesc[SomeInteger and not range]): untyped
+
+ + Returns an unsigned type with same bit size as T. +

Example:

+
assert int8.toUnsigned is uint8
+assert uint.toUnsigned is uint
+assert int.toUnsigned is uint
+# range types are currently unsupported:
+assert not compiles(toUnsigned(range[0..7]))
+ Source   +Edit   + +
+
+ +
+
+
+
template tupleLen(t: tuple): int
+
+ +

Returns the number of elements of the tuple t.

+

See also:

+ + +

Example:

+
doAssert tupleLen((1, 2)) == 2
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/typetraits.idx b/typetraits.idx new file mode 100644 index 0000000000000..6ed0215acf415 --- /dev/null +++ b/typetraits.idx @@ -0,0 +1,27 @@ +nimTitle typetraits typetraits.html module std/typetraits 0 +nim HoleyEnum typetraits.html#HoleyEnum type HoleyEnum 22 +nim OrdinalEnum typetraits.html#OrdinalEnum type OrdinalEnum 23 +nim name typetraits.html#name,typedesc proc name(t: typedesc): string 37 +nim arity typetraits.html#arity,typedesc proc arity(t: typedesc): int 45 +nim genericHead typetraits.html#genericHead,typedesc proc genericHead(t: typedesc): typedesc 54 +nim stripGenericParams typetraits.html#stripGenericParams,typedesc proc stripGenericParams(t: typedesc): typedesc 84 +nim supportsCopyMem typetraits.html#supportsCopyMem,typedesc proc supportsCopyMem(t: typedesc): bool 94 +nim hasDefaultValue typetraits.html#hasDefaultValue,typedesc proc hasDefaultValue(t: typedesc): bool 99 +nim isNamedTuple typetraits.html#isNamedTuple,typedesc proc isNamedTuple(T: typedesc): bool 116 +nim pointerBase typetraits.html#pointerBase.t,typedesc[] template pointerBase[T](_: typedesc[ptr T | ref T]): typedesc 123 +nim rangeBase typetraits.html#rangeBase,typedesc[range] proc rangeBase(T: typedesc[range]): typedesc 133 +nim rangeBase typetraits.html#rangeBase.t,T template rangeBase[T: range](a: T): untyped 146 +nim distinctBase typetraits.html#distinctBase,typedesc,staticbool proc distinctBase(T: typedesc; recursive: static bool = true): typedesc 167 +nim distinctBase typetraits.html#distinctBase.t,T,staticbool template distinctBase[T](a: T; recursive: static bool = true): untyped 182 +nim tupleLen typetraits.html#tupleLen,typedesc[] proc tupleLen(T: typedesc[tuple]): int 196 +nim tupleLen typetraits.html#tupleLen.t template tupleLen(t: tuple): int 205 +nim get typetraits.html#get.t,typedesc[],staticint template get(T: typedesc[tuple]; i: static int): untyped 215 +nim StaticParam typetraits.html#StaticParam object StaticParam 223 +nim elementType typetraits.html#elementType.t,untyped template elementType(a: untyped): typedesc 227 +nim enumLen typetraits.html#enumLen.m,typedesc[] macro enumLen(T: typedesc[enum]): int 243 +nim genericParams typetraits.html#genericParams.t,typedesc template genericParams(T: typedesc): untyped 313 +nim hasClosure typetraits.html#hasClosure,NimNode proc hasClosure(fn: NimNode): bool 341 +nim toUnsigned typetraits.html#toUnsigned.t,typedesc[] template toUnsigned(T: typedesc[SomeInteger and not range]): untyped 349 +nim toSigned typetraits.html#toSigned.t,typedesc[] template toSigned(T: typedesc[SomeInteger and not range]): untyped 364 +idx copyMem typetraits.html#copymem_1 Module typetraits 0 +idx blob typetraits.html#blob_1 Module typetraits 0 diff --git a/underscored_calls.html b/underscored_calls.html new file mode 100644 index 0000000000000..17d26fe2c4a30 --- /dev/null +++ b/underscored_calls.html @@ -0,0 +1,120 @@ + + + + + + + +std/private/underscored_calls + + + + + + + + + + + + + + + + +
+
+

std/private/underscored_calls

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This is an internal helper module. Do not use.

+
+

Imports

+
+ macros +
+
+
+

Procs

+
+
+
+
proc underscoredCalls(result, calls, arg0: NimNode) {....raises: [Exception],
+    tags: [RootEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/underscored_calls.idx b/underscored_calls.idx new file mode 100644 index 0000000000000..1ece475e4882c --- /dev/null +++ b/underscored_calls.idx @@ -0,0 +1,2 @@ +nimTitle underscored_calls underscored_calls.html module std/private/underscored_calls 0 +nim underscoredCalls underscored_calls.html#underscoredCalls,NimNode,NimNode,NimNode proc underscoredCalls(result, calls, arg0: NimNode) 15 diff --git a/unicode.html b/unicode.html new file mode 100644 index 0000000000000..69ce958b8dfed --- /dev/null +++ b/unicode.html @@ -0,0 +1,1950 @@ + + + + + + + +std/unicode + + + + + + + + + + + + + + + + +
+
+

std/unicode

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module provides support to handle the Unicode UTF-8 encoding.

+

There are no specialized insert, delete, add and contains procedures for seq[Rune] in this module because the generic variants of these procedures in the system module already work with it.

+

The current version is compatible with Unicode v12.0.0.

+

See also:

+ +

+
+

Imports

+
+ strbasics +
+
+
+

Types

+
+
+
Rune = distinct RuneImpl
+
+ +

+Type that can hold a single Unicode code point.

+

A Rune may be composed with other Runes to a character on the screen. RuneImpl is the underlying type used to store Runes, currently int32.

+ + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(rune: Rune): string {....raises: [], tags: [], forbids: [].}
+
+ +

An alias for toUTF8.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc `$`(runes: seq[Rune]): string {....raises: [], tags: [], forbids: [].}
+
+ +

Converts a sequence of Runes to a string.

+

See also:

+ + +

Example:

+
let
+  someString = "öÑ"
+  someRunes = toRunes(someString)
+doAssert $someRunes == someString
+ Source   +Edit   + +
+
+ +
+
+
+
proc `<%`(a, b: Rune): bool {....raises: [], tags: [], forbids: [].}
+
+ + Checks if code point of a is smaller than code point of b. +

Example:

+
let
+  a = "ú".runeAt(0)
+  b = "ü".runeAt(0)
+doAssert a <% b
+ Source   +Edit   + +
+
+ +
+
+
+
proc `<=%`(a, b: Rune): bool {....raises: [], tags: [], forbids: [].}
+
+ + Checks if code point of a is smaller or equal to code point of b. +

Example:

+
let
+  a = "ú".runeAt(0)
+  b = "ü".runeAt(0)
+doAssert a <=% b
+ Source   +Edit   + +
+
+ +
+
+
+
proc `==`(a, b: Rune): bool {....raises: [], tags: [], forbids: [].}
+
+ + Checks if two runes are equal. + Source   +Edit   + +
+
+ +
+
+
+
proc add(s: var string; c: Rune) {....raises: [], tags: [], forbids: [].}
+
+ + Adds a rune c to a string s. +

Example:

+
var s = "abc"
+let c = "ä".runeAt(0)
+s.add(c)
+doAssert s == "abcä"
+ Source   +Edit   + +
+
+ +
+
+
+
proc align(s: openArray[char]; count: Natural; padding = ' '.Rune): string {.
+    noSideEffect, ...gcsafe, extern: "nucAlignString", raises: [], tags: [],
+    forbids: [].}
+
+ +

Aligns a unicode string s with padding, so that it has a rune-length of count.

+

padding characters (by default spaces) are added before s resulting in right alignment. If s.runelen >= count, no spaces are added and s is returned unchanged. If you need to left align a string use the alignLeft proc.

+ +

Example:

+
assert align("abc", 4) == " abc"
+assert align("a", 0) == "a"
+assert align("1232", 6) == "  1232"
+assert align("1232", 6, '#'.Rune) == "##1232"
+assert align("Åge", 5) == "  Åge"
+assert align("×", 4, '_'.Rune) == "___×"
+ Source   +Edit   + +
+
+
+
proc align(s: string; count: Natural; padding = ' '.Rune): string {.
+    noSideEffect, inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Aligns a unicode string s with padding, so that it has a rune-length of count.

+

padding characters (by default spaces) are added before s resulting in right alignment. If s.runelen >= count, no spaces are added and s is returned unchanged. If you need to left align a string use the alignLeft proc.

+ +

Example:

+
assert align("abc", 4) == " abc"
+assert align("a", 0) == "a"
+assert align("1232", 6) == "  1232"
+assert align("1232", 6, '#'.Rune) == "##1232"
+assert align("Åge", 5) == "  Åge"
+assert align("×", 4, '_'.Rune) == "___×"
+ Source   +Edit   + +
+
+ +
+
+
+
proc alignLeft(s: openArray[char]; count: Natural; padding = ' '.Rune): string {.
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ +

Left-aligns a unicode string s with padding, so that it has a rune-length of count.

+

padding characters (by default spaces) are added after s resulting in left alignment. If s.runelen >= count, no spaces are added and s is returned unchanged. If you need to right align a string use the align proc.

+ +

Example:

+
assert alignLeft("abc", 4) == "abc "
+assert alignLeft("a", 0) == "a"
+assert alignLeft("1232", 6) == "1232  "
+assert alignLeft("1232", 6, '#'.Rune) == "1232##"
+assert alignLeft("Åge", 5) == "Åge  "
+assert alignLeft("×", 4, '_'.Rune) == "×___"
+ Source   +Edit   + +
+
+
+
proc alignLeft(s: string; count: Natural; padding = ' '.Rune): string {.
+    noSideEffect, inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Left-aligns a unicode string s with padding, so that it has a rune-length of count.

+

padding characters (by default spaces) are added after s resulting in left alignment. If s.runelen >= count, no spaces are added and s is returned unchanged. If you need to right align a string use the align proc.

+ +

Example:

+
assert alignLeft("abc", 4) == "abc "
+assert alignLeft("a", 0) == "a"
+assert alignLeft("1232", 6) == "1232  "
+assert alignLeft("1232", 6, '#'.Rune) == "1232##"
+assert alignLeft("Åge", 5) == "Åge  "
+assert alignLeft("×", 4, '_'.Rune) == "×___"
+ Source   +Edit   + +
+
+ +
+
+
+
proc capitalize(s: openArray[char]): string {.noSideEffect, ...gcsafe,
+    extern: "nuc$1", raises: [], tags: [], forbids: [].}
+
+ + Converts the first character of s into an upper-case rune. +

Example:

+
doAssert capitalize("βeta") == "Βeta"
+ Source   +Edit   + +
+
+
+
proc capitalize(s: string): string {.noSideEffect, ...raises: [], tags: [],
+                                     forbids: [].}
+
+ + Converts the first character of s into an upper-case rune. +

Example:

+
doAssert capitalize("βeta") == "Βeta"
+ Source   +Edit   + +
+
+ +
+
+
+
proc cmpRunesIgnoreCase(a, b: openArray[char]): int {....gcsafe, extern: "nuc$1",
+    raises: [], tags: [], forbids: [].}
+
+ + Compares two UTF-8 strings and ignores the case. Returns:

0 if a == b
< 0 if a < b
> 0 if a > b

+ Source   +Edit   + +
+
+
+
proc cmpRunesIgnoreCase(a, b: string): int {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Compares two UTF-8 strings and ignores the case. Returns:

0 if a == b
< 0 if a < b
> 0 if a > b

+ Source   +Edit   + +
+
+ +
+
+
+
proc graphemeLen(s: openArray[char]; i: Natural): Natural {....raises: [],
+    tags: [], forbids: [].}
+
+ + The number of bytes belonging to byte index s[i], including following combining code units. +

Example:

+
let a = "añyóng"
+doAssert a.graphemeLen(1) == 2 ## ñ
+doAssert a.graphemeLen(2) == 1
+doAssert a.graphemeLen(4) == 2 ## ó
+ Source   +Edit   + +
+
+
+
proc graphemeLen(s: string; i: Natural): Natural {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + The number of bytes belonging to byte index s[i], including following combining code unit. +

Example:

+
let a = "añyóng"
+doAssert a.graphemeLen(1) == 2 ## ñ
+doAssert a.graphemeLen(2) == 1
+doAssert a.graphemeLen(4) == 2 ## ó
+ Source   +Edit   + +
+
+ +
+
+
+
proc isAlpha(c: Rune): bool {....gcsafe, extern: "nuc$1", raises: [], tags: [],
+                              forbids: [].}
+
+ +

Returns true if c is an alpha rune (i.e., a letter).

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc isAlpha(s: openArray[char]): bool {.noSideEffect, ...gcsafe,
+    extern: "nuc$1Str", raises: [], tags: [], forbids: [].}
+
+ + Returns true if s contains all alphabetic runes. +

Example:

+
let a = "añyóng"
+doAssert a.isAlpha
+ Source   +Edit   + +
+
+
+
proc isAlpha(s: string): bool {.noSideEffect, inline, ...raises: [], tags: [],
+                                forbids: [].}
+
+ + Returns true if s contains all alphabetic runes. +

Example:

+
let a = "añyóng"
+doAssert a.isAlpha
+ Source   +Edit   + +
+
+ +
+
+
+
proc isCombining(c: Rune): bool {....gcsafe, extern: "nuc$1", raises: [], tags: [],
+                                  forbids: [].}
+
+ +

Returns true if c is a Unicode combining code unit.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isLower(c: Rune): bool {....gcsafe, extern: "nuc$1", raises: [], tags: [],
+                              forbids: [].}
+
+ +

Returns true if c is a lower case rune.

+

If possible, prefer isLower over isUpper.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isSpace(s: openArray[char]): bool {.noSideEffect, ...gcsafe,
+    extern: "nuc$1Str", raises: [], tags: [], forbids: [].}
+
+ + Returns true if s contains all whitespace runes. +

Example:

+
let a = "\t\l \v\r\f"
+doAssert a.isSpace
+ Source   +Edit   + +
+
+
+
proc isSpace(s: string): bool {.noSideEffect, inline, ...raises: [], tags: [],
+                                forbids: [].}
+
+ + Returns true if s contains all whitespace runes. +

Example:

+
let a = "\t\l \v\r\f"
+doAssert a.isSpace
+ Source   +Edit   + +
+
+ +
+
+
+
proc isTitle(c: Rune): bool {....gcsafe, extern: "nuc$1", raises: [], tags: [],
+                              forbids: [].}
+
+ +

Returns true if c is a Unicode titlecase code point.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isUpper(c: Rune): bool {....gcsafe, extern: "nuc$1", raises: [], tags: [],
+                              forbids: [].}
+
+ +

Returns true if c is a upper case rune.

+

If possible, prefer isLower over isUpper.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isWhiteSpace(c: Rune): bool {....gcsafe, extern: "nuc$1", raises: [],
+                                   tags: [], forbids: [].}
+
+ +

Returns true if c is a Unicode whitespace code point.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc lastRune(s: openArray[char]; last: int): (Rune, int) {....raises: [],
+    tags: [], forbids: [].}
+
+ + Length of the last rune in s[0..last]. Returns the rune and its length in bytes. + Source   +Edit   + +
+
+
+
proc lastRune(s: string; last: int): (Rune, int) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Length of the last rune in s[0..last]. Returns the rune and its length in bytes. + Source   +Edit   + +
+
+ +
+
+
+
proc repeat(c: Rune; count: Natural): string {.noSideEffect, ...gcsafe,
+    extern: "nucRepeatRune", raises: [], tags: [], forbids: [].}
+
+ +

Returns a string of count Runes c.

+

The returned string will have a rune-length of count.

+ +

Example:

+
let a = "ñ".runeAt(0)
+doAssert a.repeat(5) == "ñññññ"
+ Source   +Edit   + +
+
+ +
+
+
+
proc reversed(s: openArray[char]): string {....raises: [], tags: [], forbids: [].}
+
+ +

Returns the reverse of s, interpreting it as runes.

+

Unicode combining characters are correctly interpreted as well.

+ +

Example:

+
assert reversed("Reverse this!") == "!siht esreveR"
+assert reversed("先秦兩漢") == "漢兩秦先"
+assert reversed("as⃝df̅") == "f̅ds⃝a"
+assert reversed("a⃞b⃞c⃞") == "c⃞b⃞a⃞"
+ Source   +Edit   + +
+
+
+
proc reversed(s: string): string {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the reverse of s, interpreting it as runes.

+

Unicode combining characters are correctly interpreted as well.

+ +

Example:

+
assert reversed("Reverse this!") == "!siht esreveR"
+assert reversed("先秦兩漢") == "漢兩秦先"
+assert reversed("as⃝df̅") == "f̅ds⃝a"
+assert reversed("a⃞b⃞c⃞") == "c⃞b⃞a⃞"
+ Source   +Edit   + +
+
+ +
+
+
+
proc runeAt(s: openArray[char]; i: Natural): Rune {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Returns the rune in s at byte index i.

+

See also:

+ + +

Example:

+
let a = "añyóng"
+doAssert a.runeAt(1) == "ñ".runeAt(0)
+doAssert a.runeAt(2) == "ñ".runeAt(1)
+doAssert a.runeAt(3) == "y".runeAt(0)
+ Source   +Edit   + +
+
+
+
proc runeAt(s: string; i: Natural): Rune {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Returns the rune in s at byte index i.

+

See also:

+ + +

Example:

+
let a = "añyóng"
+doAssert a.runeAt(1) == "ñ".runeAt(0)
+doAssert a.runeAt(2) == "ñ".runeAt(1)
+doAssert a.runeAt(3) == "y".runeAt(0)
+ Source   +Edit   + +
+
+ +
+
+
+
proc runeAtPos(s: openArray[char]; pos: int): Rune {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Returns the rune at position pos.

+

Beware: This can lead to unoptimized code and slow execution! Most problems can be solved more efficiently by using an iterator or conversion to a seq of Rune.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc runeAtPos(s: string; pos: int): Rune {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Returns the rune at position pos.

+

Beware: This can lead to unoptimized code and slow execution! Most problems can be solved more efficiently by using an iterator or conversion to a seq of Rune.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc runeLen(s: openArray[char]): int {....gcsafe, extern: "nuc$1", raises: [],
+                                        tags: [], forbids: [].}
+
+ + Returns the number of runes of the string s. +

Example:

+
let a = "añyóng"
+doAssert a.runeLen == 6
+## note: a.len == 8
+ Source   +Edit   + +
+
+
+
proc runeLen(s: string): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Returns the number of runes of the string s. +

Example:

+
let a = "añyóng"
+doAssert a.runeLen == 6
+## note: a.len == 8
+ Source   +Edit   + +
+
+ +
+
+
+
proc runeLenAt(s: openArray[char]; i: Natural): int {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Returns the number of bytes the rune starting at s[i] takes.

+

See also:

+ + +

Example:

+
let a = "añyóng"
+doAssert a.runeLenAt(0) == 1
+doAssert a.runeLenAt(1) == 2
+ Source   +Edit   + +
+
+
+
proc runeLenAt(s: string; i: Natural): int {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Returns the number of bytes the rune starting at s[i] takes.

+

See also:

+ + +

Example:

+
let a = "añyóng"
+doAssert a.runeLenAt(0) == 1
+doAssert a.runeLenAt(1) == 2
+ Source   +Edit   + +
+
+ +
+
+
+
proc runeOffset(s: openArray[char]; pos: Natural; start: Natural = 0): int {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the byte position of rune at position pos in s with an optional start byte position. Returns the special value -1 if it runs out of the string.

+

Beware: This can lead to unoptimized code and slow execution! Most problems can be solved more efficiently by using an iterator or conversion to a seq of Rune.

+

See also:

+ + +

Example:

+
let a = "añyóng"
+doAssert a.runeOffset(1) == 1
+doAssert a.runeOffset(3) == 4
+doAssert a.runeOffset(4) == 6
+ Source   +Edit   + +
+
+
+
proc runeOffset(s: string; pos: Natural; start: Natural = 0): int {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the byte position of rune at position pos in s with an optional start byte position. Returns the special value -1 if it runs out of the string.

+

Beware: This can lead to unoptimized code and slow execution! Most problems can be solved more efficiently by using an iterator or conversion to a seq of Rune.

+

See also:

+ + +

Example:

+
let a = "añyóng"
+doAssert a.runeOffset(1) == 1
+doAssert a.runeOffset(3) == 4
+doAssert a.runeOffset(4) == 6
+ Source   +Edit   + +
+
+ +
+
+
+
proc runeReverseOffset(s: openArray[char]; rev: Positive): (int, int) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Returns a tuple with the byte offset of the rune at position rev in s, counting from the end (starting with 1) and the total number of runes in the string.

+

Returns a negative value for offset if there are too few runes in the string to satisfy the request.

+

Beware: This can lead to unoptimized code and slow execution! Most problems can be solved more efficiently by using an iterator or conversion to a seq of Rune.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc runeReverseOffset(s: string; rev: Positive): (int, int) {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Returns a tuple with the byte offset of the rune at position rev in s, counting from the end (starting with 1) and the total number of runes in the string.

+

Returns a negative value for offset if there are too few runes in the string to satisfy the request.

+

Beware: This can lead to unoptimized code and slow execution! Most problems can be solved more efficiently by using an iterator or conversion to a seq of Rune.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc runeStrAtPos(s: openArray[char]; pos: Natural): string {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Returns the rune at position pos as UTF8 String.

+

Beware: This can lead to unoptimized code and slow execution! Most problems can be solved more efficiently by using an iterator or conversion to a seq of Rune.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc runeStrAtPos(s: string; pos: Natural): string {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Returns the rune at position pos as UTF8 String.

+

Beware: This can lead to unoptimized code and slow execution! Most problems can be solved more efficiently by using an iterator or conversion to a seq of Rune.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc runeSubStr(s: openArray[char]; pos: int; len: int = int.high): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the UTF-8 substring starting at code point pos with len code points.

+

If pos or len is negative they count from the end of the string. If len is not given it means the longest possible string.

+ +

Example:

+
let s = "Hänsel  ««: 10,00€"
+doAssert(runeSubStr(s, 0, 2) == "Hä")
+doAssert(runeSubStr(s, 10, 1) == ":")
+doAssert(runeSubStr(s, -6) == "10,00€")
+doAssert(runeSubStr(s, 10) == ": 10,00€")
+doAssert(runeSubStr(s, 12, 5) == "10,00")
+doAssert(runeSubStr(s, -6, 3) == "10,")
+ Source   +Edit   + +
+
+
+
proc runeSubStr(s: string; pos: int; len: int = int.high): string {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the UTF-8 substring starting at code point pos with len code points.

+

If pos or len is negative they count from the end of the string. If len is not given it means the longest possible string.

+ +

Example:

+
let s = "Hänsel  ««: 10,00€"
+doAssert(runeSubStr(s, 0, 2) == "Hä")
+doAssert(runeSubStr(s, 10, 1) == ":")
+doAssert(runeSubStr(s, -6) == "10,00€")
+doAssert(runeSubStr(s, 10) == ": 10,00€")
+doAssert(runeSubStr(s, 12, 5) == "10,00")
+doAssert(runeSubStr(s, -6, 3) == "10,")
+ Source   +Edit   + +
+
+ +
+
+
+
proc size(r: Rune): int {.noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + Returns the number of bytes the rune r takes. +

Example:

+
let a = toRunes "aá"
+doAssert size(a[0]) == 1
+doAssert size(a[1]) == 2
+ Source   +Edit   + +
+
+ +
+
+
+
proc split(s: openArray[char]; sep: Rune; maxsplit: int = -1): seq[string] {.
+    noSideEffect, ...gcsafe, extern: "nucSplitRune", raises: [], tags: [],
+    forbids: [].}
+
+ + The same as the split iterator, but is a proc that returns a sequence of substrings. + Source   +Edit   + +
+
+
+
proc split(s: openArray[char]; seps: openArray[Rune] = unicodeSpaces;
+           maxsplit: int = -1): seq[string] {.noSideEffect, ...gcsafe,
+    extern: "nucSplitRunes", raises: [], tags: [], forbids: [].}
+
+ + The same as the split iterator, but is a proc that returns a sequence of substrings. + Source   +Edit   + +
+
+
+
proc split(s: string; sep: Rune; maxsplit: int = -1): seq[string] {.
+    noSideEffect, inline, ...raises: [], tags: [], forbids: [].}
+
+ + The same as the split iterator, but is a proc that returns a sequence of substrings. + Source   +Edit   + +
+
+
+
proc split(s: string; seps: openArray[Rune] = unicodeSpaces; maxsplit: int = -1): seq[
+    string] {.noSideEffect, inline, ...raises: [], tags: [], forbids: [].}
+
+ + The same as the split iterator, but is a proc that returns a sequence of substrings. + Source   +Edit   + +
+
+ +
+
+
+
proc splitWhitespace(s: openArray[char]): seq[string] {.noSideEffect, ...gcsafe,
+    extern: "ncuSplitWhitespace", raises: [], tags: [], forbids: [].}
+
+ + The same as the splitWhitespace iterator, but is a proc that returns a sequence of substrings. + Source   +Edit   + +
+
+
+
proc splitWhitespace(s: string): seq[string] {.noSideEffect, inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + The same as the splitWhitespace iterator, but is a proc that returns a sequence of substrings. + Source   +Edit   + +
+
+ +
+
+
+
proc strip(s: openArray[char]; leading = true; trailing = true;
+           runes: openArray[Rune] = unicodeSpaces): string {.noSideEffect,
+    ...gcsafe, extern: "nucStrip", raises: [], tags: [], forbids: [].}
+
+ +

Strips leading or trailing runes from s and returns the resulting string.

+

If leading is true (default), leading runes are stripped. If trailing is true (default), trailing runes are stripped. If both are false, the string is returned unchanged.

+ +

Example:

+
let a = "\táñyóng   "
+doAssert a.strip == "áñyóng"
+doAssert a.strip(leading = false) == "\táñyóng"
+doAssert a.strip(trailing = false) == "áñyóng   "
+ Source   +Edit   + +
+
+
+
proc strip(s: string; leading = true; trailing = true;
+           runes: openArray[Rune] = unicodeSpaces): string {.noSideEffect,
+    inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Strips leading or trailing runes from s and returns the resulting string.

+

If leading is true (default), leading runes are stripped. If trailing is true (default), trailing runes are stripped. If both are false, the string is returned unchanged.

+ +

Example:

+
let a = "\táñyóng   "
+doAssert a.strip == "áñyóng"
+doAssert a.strip(leading = false) == "\táñyóng"
+doAssert a.strip(trailing = false) == "áñyóng   "
+ Source   +Edit   + +
+
+ +
+
+
+
proc swapCase(s: openArray[char]): string {.noSideEffect, ...gcsafe,
+    extern: "nuc$1", raises: [], tags: [], forbids: [].}
+
+ +

Swaps the case of runes in s.

+

Returns a new string such that the cases of all runes are swapped if possible.

+ +

Example:

+
doAssert swapCase("Αlpha Βeta Γamma") == "αLPHA βETA γAMMA"
+ Source   +Edit   + +
+
+
+
proc swapCase(s: string): string {.noSideEffect, inline, ...raises: [], tags: [],
+                                   forbids: [].}
+
+ +

Swaps the case of runes in s.

+

Returns a new string such that the cases of all runes are swapped if possible.

+ +

Example:

+
doAssert swapCase("Αlpha Βeta Γamma") == "αLPHA βETA γAMMA"
+ Source   +Edit   + +
+
+ +
+
+
+
proc title(s: openArray[char]): string {.noSideEffect, ...gcsafe, extern: "nuc$1",
+    raises: [], tags: [], forbids: [].}
+
+ +

Converts s to a unicode title.

+

Returns a new string such that the first character in each word inside s is capitalized.

+ +

Example:

+
doAssert title("αlpha βeta γamma") == "Αlpha Βeta Γamma"
+ Source   +Edit   + +
+
+
+
proc title(s: string): string {.noSideEffect, inline, ...raises: [], tags: [],
+                                forbids: [].}
+
+ +

Converts s to a unicode title.

+

Returns a new string such that the first character in each word inside s is capitalized.

+ +

Example:

+
doAssert title("αlpha βeta γamma") == "Αlpha Βeta Γamma"
+ Source   +Edit   + +
+
+ +
+
+
+
proc toLower(c: Rune): Rune {....gcsafe, extern: "nuc$1", raises: [], tags: [],
+                              forbids: [].}
+
+ +

Converts c into lower case. This works for any rune.

+

If possible, prefer toLower over toUpper.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc toLower(s: openArray[char]): string {.noSideEffect, ...gcsafe,
+    extern: "nuc$1Str", raises: [], tags: [], forbids: [].}
+
+ + Converts s into lower-case runes. +

Example:

+
doAssert toLower("ABΓ") == "abγ"
+ Source   +Edit   + +
+
+
+
proc toLower(s: string): string {.noSideEffect, inline, ...raises: [], tags: [],
+                                  forbids: [].}
+
+ + Converts s into lower-case runes. +

Example:

+
doAssert toLower("ABΓ") == "abγ"
+ Source   +Edit   + +
+
+ +
+
+
+
proc toRunes(s: openArray[char]): seq[Rune] {....raises: [], tags: [], forbids: [].}
+
+ +

Obtains a sequence containing the Runes in s.

+

See also:

+
  • $ proc for a reverse operation
  • +
+ +

Example:

+
let a = toRunes("aáä")
+doAssert a == @["a".runeAt(0), "á".runeAt(0), "ä".runeAt(0)]
+ Source   +Edit   + +
+
+
+
proc toRunes(s: string): seq[Rune] {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Obtains a sequence containing the Runes in s.

+

See also:

+
  • $ proc for a reverse operation
  • +
+ +

Example:

+
let a = toRunes("aáä")
+doAssert a == @["a".runeAt(0), "á".runeAt(0), "ä".runeAt(0)]
+ Source   +Edit   + +
+
+ +
+
+
+
proc toTitle(c: Rune): Rune {....gcsafe, extern: "nuc$1", raises: [], tags: [],
+                              forbids: [].}
+
+ +

Converts c to title case.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toUpper(c: Rune): Rune {....gcsafe, extern: "nuc$1", raises: [], tags: [],
+                              forbids: [].}
+
+ +

Converts c into upper case. This works for any rune.

+

If possible, prefer toLower over toUpper.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc toUpper(s: openArray[char]): string {.noSideEffect, ...gcsafe,
+    extern: "nuc$1Str", raises: [], tags: [], forbids: [].}
+
+ + Converts s into upper-case runes. +

Example:

+
doAssert toUpper("abγ") == "ABΓ"
+ Source   +Edit   + +
+
+
+
proc toUpper(s: string): string {.noSideEffect, inline, ...raises: [], tags: [],
+                                  forbids: [].}
+
+ + Converts s into upper-case runes. +

Example:

+
doAssert toUpper("abγ") == "ABΓ"
+ Source   +Edit   + +
+
+ +
+
+
+
proc toUTF8(c: Rune): string {....gcsafe, extern: "nuc$1", raises: [], tags: [],
+                               forbids: [].}
+
+ +

Converts a rune into its UTF-8 representation.

+

See also:

+ + +

Example:

+
let a = "añyóng"
+doAssert a.runeAt(1).toUTF8 == "ñ"
+ Source   +Edit   + +
+
+ +
+
+
+
proc translate(s: openArray[char]; replacements: proc (key: string): string): string {.
+    ...gcsafe, extern: "nuc$1", effectsOf: replacements, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Translates words in a string using the replacements proc to substitute words inside s with their replacements.

+

replacements is any proc that takes a word and returns a new word to fill it's place.

+ +

Example:

+
proc wordToNumber(s: string): string =
+  case s
+  of "one": "1"
+  of "two": "2"
+  else: s
+let a = "one two three four"
+doAssert a.translate(wordToNumber) == "1 2 three four"
+ Source   +Edit   + +
+
+
+
proc translate(s: string; replacements: proc (key: string): string): string {.
+    effectsOf: replacements, inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Translates words in a string using the replacements proc to substitute words inside s with their replacements.

+

replacements is any proc that takes a word and returns a new word to fill it's place.

+ +

Example:

+
proc wordToNumber(s: string): string =
+  case s
+  of "one": "1"
+  of "two": "2"
+  else: s
+let a = "one two three four"
+doAssert a.translate(wordToNumber) == "1 2 three four"
+ Source   +Edit   + +
+
+ +
+
+
+
proc validateUtf8(s: openArray[char]): int {....raises: [], tags: [], forbids: [].}
+
+ +

Returns the position of the invalid byte in s if the string s does not hold valid UTF-8 data. Otherwise -1 is returned.

+

See also:

+ + + Source   +Edit   + +
+
+
+
proc validateUtf8(s: string): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the position of the invalid byte in s if the string s does not hold valid UTF-8 data. Otherwise -1 is returned.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator runes(s: openArray[char]): Rune {....raises: [], tags: [], forbids: [].}
+
+ + Iterates over any rune of the string s returning runes. + Source   +Edit   + +
+
+
+
iterator runes(s: string): Rune {....raises: [], tags: [], forbids: [].}
+
+ + Iterates over any rune of the string s returning runes. + Source   +Edit   + +
+
+ +
+
+
+
iterator split(s: openArray[char]; sep: Rune; maxsplit: int = -1): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Splits the unicode string s into substrings using a single separator. Substrings are separated by the rune sep. +

Example:

+
import std/sequtils
+
+assert toSeq(split(";;hÃllo;this;is;an;;example;;;是", ";".runeAt(0))) ==
+  @["", "", "hÃllo", "this", "is", "an", "", "example", "", "", "是"]
+ Source   +Edit   + +
+
+
+
iterator split(s: openArray[char]; seps: openArray[Rune] = unicodeSpaces;
+               maxsplit: int = -1): string {....raises: [], tags: [], forbids: [].}
+
+ +

Splits the unicode string s into substrings using a group of separators.

+

Substrings are separated by a substring containing only seps.

+ +

Example:

+
import std/sequtils
+
+assert toSeq("hÃllo\lthis\lis an\texample\l是".split) ==
+  @["hÃllo", "this", "is", "an", "example", "是"]
+
+# And the following code splits the same string using a sequence of Runes.
+assert toSeq(split("añyóng:hÃllo;是$example", ";:$".toRunes)) ==
+  @["añyóng", "hÃllo", "是", "example"]
+
+# example with a `Rune` separator and unused one `;`:
+assert toSeq(split("ab是de:f:", ";:是".toRunes)) == @["ab", "de", "f", ""]
+
+# Another example that splits a string containing a date.
+let date = "2012-11-20T22:08:08.398990"
+
+assert toSeq(split(date, " -:T".toRunes)) ==
+  @["2012", "11", "20", "22", "08", "08.398990"]
+ Source   +Edit   + +
+
+
+
iterator split(s: string; sep: Rune; maxsplit: int = -1): string {....raises: [],
+    tags: [], forbids: [].}
+
+ + Splits the unicode string s into substrings using a single separator. Substrings are separated by the rune sep. +

Example:

+
import std/sequtils
+
+assert toSeq(split(";;hÃllo;this;is;an;;example;;;是", ";".runeAt(0))) ==
+  @["", "", "hÃllo", "this", "is", "an", "", "example", "", "", "是"]
+ Source   +Edit   + +
+
+
+
iterator split(s: string; seps: openArray[Rune] = unicodeSpaces;
+               maxsplit: int = -1): string {....raises: [], tags: [], forbids: [].}
+
+ +

Splits the unicode string s into substrings using a group of separators.

+

Substrings are separated by a substring containing only seps.

+ +

Example:

+
import std/sequtils
+
+assert toSeq("hÃllo\lthis\lis an\texample\l是".split) ==
+  @["hÃllo", "this", "is", "an", "example", "是"]
+
+# And the following code splits the same string using a sequence of Runes.
+assert toSeq(split("añyóng:hÃllo;是$example", ";:$".toRunes)) ==
+  @["añyóng", "hÃllo", "是", "example"]
+
+# example with a `Rune` separator and unused one `;`:
+assert toSeq(split("ab是de:f:", ";:是".toRunes)) == @["ab", "de", "f", ""]
+
+# Another example that splits a string containing a date.
+let date = "2012-11-20T22:08:08.398990"
+
+assert toSeq(split(date, " -:T".toRunes)) ==
+  @["2012", "11", "20", "22", "08", "08.398990"]
+ Source   +Edit   + +
+
+ +
+
+
+
iterator splitWhitespace(s: openArray[char]): string {....raises: [], tags: [],
+    forbids: [].}
+
+ + Splits a unicode string at whitespace runes. + Source   +Edit   + +
+
+
+
iterator splitWhitespace(s: string): string {....raises: [], tags: [], forbids: [].}
+
+ + Splits a unicode string at whitespace runes. + Source   +Edit   + +
+
+ +
+
+
+
iterator utf8(s: openArray[char]): string {....raises: [], tags: [], forbids: [].}
+
+ +

Iterates over any rune of the string s returning utf8 values.

+

See also:

+ + + Source   +Edit   + +
+
+
+
iterator utf8(s: string): string {....raises: [], tags: [], forbids: [].}
+
+ +

Iterates over any rune of the string s returning utf8 values.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template fastRuneAt(s: openArray[char] or string; i: int; result: untyped;
+                    doInc = true)
+
+ +

Returns the rune s[i] in result.

+

If doInc == true (default), i is incremented by the number of bytes that have been processed.

+ + Source   +Edit   + +
+
+ +
+
+
+
template fastToUTF8Copy(c: Rune; s: var string; pos: int; doInc = true)
+
+ +

Copies UTF-8 representation of c into the preallocated string s starting at position pos.

+

If doInc == true (default), pos is incremented by the number of bytes that have been processed.

+

To be the most efficient, make sure s is preallocated with an additional amount equal to the byte length of c.

+

See also:

+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/unicode.idx b/unicode.idx new file mode 100644 index 0000000000000..fd8b214cafb24 --- /dev/null +++ b/unicode.idx @@ -0,0 +1,120 @@ +nimTitle unicode unicode.html module std/unicode 0 +nim Rune unicode.html#Rune type Rune 37 +nim runeLen unicode.html#runeLen,openArray[char] proc runeLen(s: openArray[char]): int 45 +nim runeLenAt unicode.html#runeLenAt,openArray[char],Natural proc runeLenAt(s: openArray[char]; i: Natural): int 64 +nim fastRuneAt unicode.html#fastRuneAt.t,,int,untyped template fastRuneAt(s: openArray[char] or string; i: int; result: untyped; doInc = true) 84 +nim runeAt unicode.html#runeAt,openArray[char],Natural proc runeAt(s: openArray[char]; i: Natural): Rune 162 +nim validateUtf8 unicode.html#validateUtf8,openArray[char] proc validateUtf8(s: openArray[char]): int 176 +nim fastToUTF8Copy unicode.html#fastToUTF8Copy.t,Rune,string,int template fastToUTF8Copy(c: Rune; s: var string; pos: int; doInc = true) 207 +nim toUTF8 unicode.html#toUTF8,Rune proc toUTF8(c: Rune): string 264 +nim add unicode.html#add,string,Rune proc add(s: var string; c: Rune) 279 +nim `$` unicode.html#$,Rune proc `$`(rune: Rune): string 290 +nim `$` unicode.html#$,seq[Rune] proc `$`(runes: seq[Rune]): string 298 +nim runeOffset unicode.html#runeOffset,openArray[char],Natural,Natural proc runeOffset(s: openArray[char]; pos: Natural; start: Natural = 0): int 313 +nim runeReverseOffset unicode.html#runeReverseOffset,openArray[char],Positive proc runeReverseOffset(s: openArray[char]; rev: Positive): (int, int) 340 +nim runeAtPos unicode.html#runeAtPos,openArray[char],int proc runeAtPos(s: openArray[char]; pos: int): Rune 368 +nim runeStrAtPos unicode.html#runeStrAtPos,openArray[char],Natural proc runeStrAtPos(s: openArray[char]; pos: Natural): string 381 +nim runeSubStr unicode.html#runeSubStr,openArray[char],int,int proc runeSubStr(s: openArray[char]; pos: int; len: int = int.high): string 395 +nim `<=%` unicode.html#<=%,Rune,Rune proc `<=%`(a, b: Rune): bool 442 +nim `<%` unicode.html#<%,Rune,Rune proc `<%`(a, b: Rune): bool 451 +nim `==` unicode.html#==,Rune,Rune proc `==`(a, b: Rune): bool 460 +nim toLower unicode.html#toLower,Rune proc toLower(c: Rune): Rune 482 +nim toUpper unicode.html#toUpper,Rune proc toUpper(c: Rune): Rune 500 +nim toTitle unicode.html#toTitle,Rune proc toTitle(c: Rune): Rune 518 +nim isLower unicode.html#isLower,Rune proc isLower(c: Rune): bool 531 +nim isUpper unicode.html#isUpper,Rune proc isUpper(c: Rune): bool 549 +nim isAlpha unicode.html#isAlpha,Rune proc isAlpha(c: Rune): bool 569 +nim isTitle unicode.html#isTitle,Rune proc isTitle(c: Rune): bool 588 +nim isWhiteSpace unicode.html#isWhiteSpace,Rune proc isWhiteSpace(c: Rune): bool 599 +nim isCombining unicode.html#isCombining,Rune proc isCombining(c: Rune): bool 612 +nim isAlpha unicode.html#isAlpha,openArray[char] proc isAlpha(s: openArray[char]): bool 639 +nim isSpace unicode.html#isSpace,openArray[char] proc isSpace(s: openArray[char]): bool 647 +nim toUpper unicode.html#toUpper,openArray[char] proc toUpper(s: openArray[char]): string 668 +nim toLower unicode.html#toLower,openArray[char] proc toLower(s: openArray[char]): string 675 +nim swapCase unicode.html#swapCase,openArray[char] proc swapCase(s: openArray[char]): string 682 +nim capitalize unicode.html#capitalize,openArray[char] proc capitalize(s: openArray[char]): string 704 +nim translate unicode.html#translate,openArray[char],proc(string) proc translate(s: openArray[char]; replacements: proc (key: string): string): string 721 +nim title unicode.html#title,openArray[char] proc title(s: openArray[char]): string 774 +nim runes unicode.html#runes.i,openArray[char] iterator runes(s: openArray[char]): Rune 800 +nim utf8 unicode.html#utf8.i,openArray[char] iterator utf8(s: openArray[char]): string 809 +nim toRunes unicode.html#toRunes,openArray[char] proc toRunes(s: openArray[char]): seq[Rune] 823 +nim cmpRunesIgnoreCase unicode.html#cmpRunesIgnoreCase,openArray[char],openArray[char] proc cmpRunesIgnoreCase(a, b: openArray[char]): int 836 +nim reversed unicode.html#reversed,openArray[char] proc reversed(s: openArray[char]): string 858 +nim graphemeLen unicode.html#graphemeLen,openArray[char],Natural proc graphemeLen(s: openArray[char]; i: Natural): Natural 893 +nim lastRune unicode.html#lastRune,openArray[char],int proc lastRune(s: openArray[char]; last: int): (Rune, int) 912 +nim size unicode.html#size,Rune proc size(r: Rune): int 924 +nim split unicode.html#split.i,openArray[char],openArray[Rune],int iterator split(s: openArray[char]; seps: openArray[Rune] = unicodeSpaces;\n maxsplit: int = -1): string 969 +nim splitWhitespace unicode.html#splitWhitespace.i,openArray[char] iterator splitWhitespace(s: openArray[char]): string 995 +nim splitWhitespace unicode.html#splitWhitespace,openArray[char] proc splitWhitespace(s: openArray[char]): seq[string] 1003 +nim split unicode.html#split.i,openArray[char],Rune,int iterator split(s: openArray[char]; sep: Rune; maxsplit: int = -1): string 1009 +nim split unicode.html#split,openArray[char],openArray[Rune],int proc split(s: openArray[char]; seps: openArray[Rune] = unicodeSpaces;\n maxsplit: int = -1): seq[string] 1020 +nim split unicode.html#split,openArray[char],Rune,int proc split(s: openArray[char]; sep: Rune; maxsplit: int = -1): seq[string] 1026 +nim strip unicode.html#strip,openArray[char],openArray[Rune] proc strip(s: openArray[char]; leading = true; trailing = true;\n runes: openArray[Rune] = unicodeSpaces): string 1032 +nim repeat unicode.html#repeat,Rune,Natural proc repeat(c: Rune; count: Natural): string 1089 +nim align unicode.html#align,openArray[char],Natural proc align(s: openArray[char]; count: Natural; padding = ' '.Rune): string 1103 +nim alignLeft unicode.html#alignLeft,openArray[char],Natural proc alignLeft(s: openArray[char]; count: Natural; padding = ' '.Rune): string 1130 +nim runeLen unicode.html#runeLen,string proc runeLen(s: string): int 1157 +nim runeLenAt unicode.html#runeLenAt,string,Natural proc runeLenAt(s: string; i: Natural): int 1165 +nim runeAt unicode.html#runeAt,string,Natural proc runeAt(s: string; i: Natural): Rune 1176 +nim validateUtf8 unicode.html#validateUtf8,string proc validateUtf8(s: string): int 1190 +nim runeOffset unicode.html#runeOffset,string,Natural,Natural proc runeOffset(s: string; pos: Natural; start: Natural = 0): int 1200 +nim runeReverseOffset unicode.html#runeReverseOffset,string,Positive proc runeReverseOffset(s: string; rev: Positive): (int, int) 1218 +nim runeAtPos unicode.html#runeAtPos,string,int proc runeAtPos(s: string; pos: int): Rune 1235 +nim runeStrAtPos unicode.html#runeStrAtPos,string,Natural proc runeStrAtPos(s: string; pos: Natural): string 1248 +nim runeSubStr unicode.html#runeSubStr,string,int,int proc runeSubStr(s: string; pos: int; len: int = int.high): string 1262 +nim isAlpha unicode.html#isAlpha,string proc isAlpha(s: string): bool 1280 +nim isSpace unicode.html#isSpace,string proc isSpace(s: string): bool 1287 +nim toUpper unicode.html#toUpper,string proc toUpper(s: string): string 1295 +nim toLower unicode.html#toLower,string proc toLower(s: string): string 1301 +nim swapCase unicode.html#swapCase,string proc swapCase(s: string): string 1307 +nim capitalize unicode.html#capitalize,string proc capitalize(s: string): string 1316 +nim translate unicode.html#translate,string,proc(string) proc translate(s: string; replacements: proc (key: string): string): string 1323 +nim title unicode.html#title,string proc title(s: string): string 1339 +nim runes unicode.html#runes.i,string iterator runes(s: string): Rune 1349 +nim utf8 unicode.html#utf8.i,string iterator utf8(s: string): string 1354 +nim toRunes unicode.html#toRunes,string proc toRunes(s: string): seq[Rune] 1365 +nim cmpRunesIgnoreCase unicode.html#cmpRunesIgnoreCase,string,string proc cmpRunesIgnoreCase(a, b: string): int 1375 +nim reversed unicode.html#reversed,string proc reversed(s: string): string 1383 +nim graphemeLen unicode.html#graphemeLen,string,Natural proc graphemeLen(s: string; i: Natural): Natural 1394 +nim lastRune unicode.html#lastRune,string,int proc lastRune(s: string; last: int): (Rune, int) 1404 +nim split unicode.html#split.i,string,openArray[Rune],int iterator split(s: string; seps: openArray[Rune] = unicodeSpaces; maxsplit: int = -1): string 1409 +nim splitWhitespace unicode.html#splitWhitespace.i,string iterator splitWhitespace(s: string): string 1435 +nim splitWhitespace unicode.html#splitWhitespace,string proc splitWhitespace(s: string): seq[string] 1440 +nim split unicode.html#split.i,string,Rune,int iterator split(s: string; sep: Rune; maxsplit: int = -1): string 1445 +nim split unicode.html#split,string,openArray[Rune],int proc split(s: string; seps: openArray[Rune] = unicodeSpaces; maxsplit: int = -1): seq[\n string] 1456 +nim split unicode.html#split,string,Rune,int proc split(s: string; sep: Rune; maxsplit: int = -1): seq[string] 1462 +nim strip unicode.html#strip,string,openArray[Rune] proc strip(s: string; leading = true; trailing = true;\n runes: openArray[Rune] = unicodeSpaces): string 1467 +nim align unicode.html#align,string,Natural proc align(s: string; count: Natural; padding = ' '.Rune): string 1483 +nim alignLeft unicode.html#alignLeft,string,Natural proc alignLeft(s: string; count: Natural; padding = ' '.Rune): string 1500 +nimgrp isspace unicode.html#isSpace-procs-all proc 647 +nimgrp splitwhitespace unicode.html#splitWhitespace-procs-all proc 1003 +nimgrp validateutf8 unicode.html#validateUtf8-procs-all proc 176 +nimgrp $ unicode.html#$-procs-all proc 290 +nimgrp runeatpos unicode.html#runeAtPos-procs-all proc 368 +nimgrp capitalize unicode.html#capitalize-procs-all proc 704 +nimgrp runereverseoffset unicode.html#runeReverseOffset-procs-all proc 340 +nimgrp runesubstr unicode.html#runeSubStr-procs-all proc 395 +nimgrp lastrune unicode.html#lastRune-procs-all proc 912 +nimgrp swapcase unicode.html#swapCase-procs-all proc 682 +nimgrp title unicode.html#title-procs-all proc 774 +nimgrp cmprunesignorecase unicode.html#cmpRunesIgnoreCase-procs-all proc 836 +nimgrp reversed unicode.html#reversed-procs-all proc 858 +nimgrp isalpha unicode.html#isAlpha-procs-all proc 569 +nimgrp strip unicode.html#strip-procs-all proc 1032 +nimgrp runestratpos unicode.html#runeStrAtPos-procs-all proc 381 +nimgrp runelenat unicode.html#runeLenAt-procs-all proc 64 +nimgrp runeoffset unicode.html#runeOffset-procs-all proc 313 +nimgrp align unicode.html#align-procs-all proc 1103 +nimgrp split unicode.html#split-procs-all proc 1020 +nimgrp torunes unicode.html#toRunes-procs-all proc 823 +nimgrp runelen unicode.html#runeLen-procs-all proc 45 +nimgrp translate unicode.html#translate-procs-all proc 721 +nimgrp alignleft unicode.html#alignLeft-procs-all proc 1130 +nimgrp tolower unicode.html#toLower-procs-all proc 482 +nimgrp graphemelen unicode.html#graphemeLen-procs-all proc 893 +nimgrp toupper unicode.html#toUpper-procs-all proc 500 +nimgrp runeat unicode.html#runeAt-procs-all proc 162 +nimgrp splitwhitespace unicode.html#splitWhitespace-iterators-all iterator 995 +nimgrp split unicode.html#split-iterators-all iterator 969 +nimgrp runes unicode.html#runes-iterators-all iterator 800 +nimgrp utf8 unicode.html#utf8-iterators-all iterator 809 diff --git a/unidecode.html b/unidecode.html new file mode 100644 index 0000000000000..40ed6d021899f --- /dev/null +++ b/unidecode.html @@ -0,0 +1,144 @@ + + + + + + + +std/unidecode + + + + + + + + + + + + + + + + +
+
+

std/unidecode

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module is based on Python's Unidecode module by Tomaz Solc, which in turn is based on the Text::Unidecode Perl module by Sean M. Burke.

+

It provides a unidecode proc that does Unicode to ASCII transliterations: It finds the sequence of ASCII characters that is the closest approximation to the Unicode string.

+

For example, the closest to string "Äußerst" in ASCII is "Ausserst". Some information is lost in this transformation, of course, since several Unicode strings can be transformed to the same ASCII representation. So this is a strictly one-way transformation. However, a human reader will probably still be able to guess from the context, what the original string was.

+

This module needs the data file unidecode.dat to work: This file is embedded as a resource into your application by default. You can also define the symbol --define:noUnidecodeTable during compile time and use the loadUnidecodeTable proc to initialize this module.

+

+ +
+

Procs

+
+
+
+
proc loadUnidecodeTable(datafile = "unidecode.dat") {....raises: [], tags: [],
+    forbids: [].}
+
+ + Loads the datafile that unidecode needs to work. This is only required if the module was compiled with the --define:noUnidecodeTable switch. This needs to be called by the main thread before any thread can make a call to unidecode. + Source   +Edit   + +
+
+ +
+
+
+
proc unidecode(s: string): string {....raises: [], tags: [], forbids: [].}
+
+ + Finds the sequence of ASCII characters that is the closest approximation to the UTF-8 string s. +

Example:

+
doAssert unidecode("北京") == "Bei Jing "
+doAssert unidecode("Äußerst") == "Ausserst"
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/unidecode.idx b/unidecode.idx new file mode 100644 index 0000000000000..3587ff9228592 --- /dev/null +++ b/unidecode.idx @@ -0,0 +1,3 @@ +nimTitle unidecode unidecode.html module std/unidecode 0 +nim loadUnidecodeTable unidecode.html#loadUnidecodeTable,string proc loadUnidecodeTable(datafile = "unidecode.dat") 41 +nim unidecode unidecode.html#unidecode,string proc unidecode(s: string): string 53 diff --git a/unittest.html b/unittest.html new file mode 100644 index 0000000000000..11e1277b050fb --- /dev/null +++ b/unittest.html @@ -0,0 +1,910 @@ + + + + + + + +std/unittest + + + + + + + + + + + + + + + + +
+
+

std/unittest

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
Author:Zahary Karadjov

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 as well as nim c -r <testfile.nim> exit with 0 for success (no failed tests) or 1 for failure.

+ +

Testament

Instead of unittest, please consider using the Testament tool which offers process isolation for your tests.

+

Alternatively using when isMainModule: doAssert conditionHere is usually a much simpler solution for testing purposes.

+ +

Running a single test

Specify the test name as a command line argument.

+

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 "::".

+

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.

+

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

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"

+ +

Limitations/Bugs

Since check will rewrite some expressions for supporting checkpoints (namely assigns expressions to variables), some type conversions are not supported. For example check 4.0 == 2 + 2 won't work. But doAssert 4.0 == 2 + 2 works. Make sure both sides of the operator (such as ==, >= and so on) have the same type.

+

+ +
+

Types

+
+
+
ConsoleOutputFormatter = ref object of OutputFormatter
+  ## Have test results printed in color.
+  ## Default is `auto` depending on `isatty(stdout)`, or override it with
+  ## `-d:nimUnittestColor:auto|on|off`.
+  ## 
+  ## Deprecated: Setting the environment variable `NIMTEST_COLOR` to `always`
+  ## or `never` changes the default for the non-js target to true or false respectively.
+  ## Deprecated: the environment variable `NIMTEST_NO_COLOR`, when set, changes the
+  ## default to true, if `NIMTEST_COLOR` is undefined.
+  ## Set the verbosity of test results.
+  ## Default is `PRINT_ALL`, or override with:
+  ## `-d:nimUnittestOutputLevel:PRINT_ALL|PRINT_FAILURES|PRINT_NONE`.
+  ## 
+  ## Deprecated: the `NIMTEST_OUTPUT_LVL` environment variable is set for the non-js target.
+
+ + + Source   +Edit   + +
+
+
+
JUnitOutputFormatter = ref object of OutputFormatter
+
+ + + Source   +Edit   + +
+
+
+
OutputFormatter = ref object of RootObj
+
+ + + Source   +Edit   + +
+
+
+
OutputLevel = enum
+  PRINT_ALL,                ## Print as much as possible.
+  PRINT_FAILURES,           ## Print only the failed tests.
+  PRINT_NONE                 ## Print nothing.
+
+ + The output verbosity of the tests. + Source   +Edit   + +
+
+
+
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
+
+ + + Source   +Edit   + +
+
+
+
TestStatus = enum
+  OK, FAILED, SKIPPED
+
+ + The status of a test when it is done. + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
abortOnError {.threadvar.}: bool
+
+ +

Set to true in order to quit immediately on fail. Default is false, or override with -d:nimUnittestAbortOnError:on|off.

+

Deprecated: can also override depending on whether NIMTEST_ABORT_ON_ERROR environment variable is set.

+ + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc addOutputFormatter(formatter: OutputFormatter) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc checkpoint(msg: string) {....raises: [], tags: [], forbids: [].}
+
+ +

Set a checkpoint identified by msg. Upon test failure all checkpoints encountered so far are printed out. Example:

+

checkpoint("Checkpoint A")
+check((42, "the Answer to life and everything") == (1, "a"))
+checkpoint("Checkpoint B")

+

outputs "Checkpoint A" once it fails.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc close(formatter: JUnitOutputFormatter) {....raises: [IOError, OSError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + Completes the report and closes the underlying stream. + Source   +Edit   + +
+
+ +
+
+
+
proc defaultConsoleFormatter(): ConsoleOutputFormatter {....raises: [ValueError],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc delOutputFormatter(formatter: OutputFormatter) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc disableParamFiltering() {....raises: [], tags: [], forbids: [].}
+
+ + disables filtering tests with the command line params + Source   +Edit   + +
+
+ +
+
+
+
proc newConsoleOutputFormatter(outputLevel: OutputLevel = outputLevelDefault;
+                               colorOutput = true): ConsoleOutputFormatter {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newJUnitOutputFormatter(stream: Stream): JUnitOutputFormatter {.
+    ...raises: [IOError, OSError], tags: [WriteIOEffect], forbids: [].}
+
+ + 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. + Source   +Edit   + +
+
+ +
+
+
+
proc resetOutputFormatters() {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Methods

+
+
+
+
method failureOccurred(formatter: ConsoleOutputFormatter;
+                       checkpoints: seq[string]; stackTrace: string) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
method failureOccurred(formatter: JUnitOutputFormatter;
+                       checkpoints: seq[string]; stackTrace: string) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + stackTrace is provided only if the failure occurred due to an exception. checkpoints is never nil. + Source   +Edit   + +
+
+
+
method failureOccurred(formatter: OutputFormatter; checkpoints: seq[string];
+                       stackTrace: string) {.base, ...gcsafe, raises: [], tags: [],
+    forbids: [].}
+
+ + stackTrace is provided only if the failure occurred due to an exception. checkpoints is never nil. + Source   +Edit   + +
+
+ +
+
+
+
method suiteEnded(formatter: ConsoleOutputFormatter) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
method suiteEnded(formatter: JUnitOutputFormatter) {....raises: [IOError, OSError],
+    tags: [WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
method suiteEnded(formatter: OutputFormatter) {.base, ...gcsafe, raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
method suiteStarted(formatter: ConsoleOutputFormatter; suiteName: string) {.
+    ...raises: [IOError], tags: [WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
method suiteStarted(formatter: JUnitOutputFormatter; suiteName: string) {.
+    ...raises: [IOError, OSError, ValueError], tags: [WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
method suiteStarted(formatter: OutputFormatter; suiteName: string) {.base,
+    ...gcsafe, raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
method testEnded(formatter: ConsoleOutputFormatter; testResult: TestResult) {.
+    ...raises: [IOError], tags: [WriteIOEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
method testEnded(formatter: JUnitOutputFormatter; testResult: TestResult) {.
+    ...raises: [IOError, OSError, ValueError], tags: [TimeEffect, WriteIOEffect],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
method testEnded(formatter: OutputFormatter; testResult: TestResult) {.base,
+    ...gcsafe, raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
method testStarted(formatter: ConsoleOutputFormatter; testName: string) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
method testStarted(formatter: JUnitOutputFormatter; testName: string) {.
+    ...raises: [], tags: [TimeEffect], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
method testStarted(formatter: OutputFormatter; testName: string) {.base, ...gcsafe,
+    raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
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:

+
import std/strutils
+
+check("AKB48".toLowerAscii() == "akb48")
+
+let teams = {'A', 'K', 'B', '4', '8'}
+
+check:
+  "AKB48".toLowerAscii() == "akb48"
+  'C' notin teams
+ Source   +Edit   + +
+
+ +
+
+
+
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:

+
import std/[math, random, strutils]
+proc defectiveRobot() =
+  randomize()
+  case rand(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()
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
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:

+

checkpoint("Checkpoint A")
+complicatedProcInThread()
+fail()

+

outputs "Checkpoint A" before quitting.

+ + Source   +Edit   + +
+
+ +
+
+
+
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. + Source   +Edit   + +
+
+ +
+
+
+
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.

+

if not isGLContextCreated():
+  skip()

+ + Source   +Edit   + +
+
+ +
+
+
+
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.

+

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:

+
[Suite] test suite for addition
+  [OK] 2 + 2 = 4
+  [OK] (2 + -2) != 4
+ + Source   +Edit   + +
+
+ +
+
+
+
template test(name, body) {.dirty.}
+
+ +

Define a single test case identified by name.

+

test "roses are red":
+  let roses = "red"
+  check(roses == "red")

+

The above code outputs:

+
[OK] roses are red
+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/unittest.idx b/unittest.idx new file mode 100644 index 0000000000000..36edac2c93e5c --- /dev/null +++ b/unittest.idx @@ -0,0 +1,56 @@ +nimTitle unittest unittest.html module std/unittest 0 +nim OK unittest.html#OK TestStatus.OK 125 +nim FAILED unittest.html#FAILED TestStatus.FAILED 125 +nim SKIPPED unittest.html#SKIPPED TestStatus.SKIPPED 125 +nim TestStatus unittest.html#TestStatus enum TestStatus 125 +nim PRINT_ALL unittest.html#PRINT_ALL OutputLevel.PRINT_ALL 130 +nim PRINT_FAILURES unittest.html#PRINT_FAILURES OutputLevel.PRINT_FAILURES 130 +nim PRINT_NONE unittest.html#PRINT_NONE OutputLevel.PRINT_NONE 130 +nim OutputLevel unittest.html#OutputLevel enum OutputLevel 130 +nim TestResult unittest.html#TestResult object TestResult 135 +nim OutputFormatter unittest.html#OutputFormatter type OutputFormatter 143 +nim ConsoleOutputFormatter unittest.html#ConsoleOutputFormatter type ConsoleOutputFormatter 145 +nim JUnitOutputFormatter unittest.html#JUnitOutputFormatter type JUnitOutputFormatter 164 +nim abortOnError unittest.html#abortOnError var abortOnError 171 +nim suiteStarted unittest.html#suiteStarted.e,OutputFormatter,string method suiteStarted(formatter: OutputFormatter; suiteName: string) 199 +nim testStarted unittest.html#testStarted.e,OutputFormatter,string method testStarted(formatter: OutputFormatter; testName: string) 201 +nim failureOccurred unittest.html#failureOccurred.e,OutputFormatter,seq[string],string method failureOccurred(formatter: OutputFormatter; checkpoints: seq[string];\n stackTrace: string) 203 +nim testEnded unittest.html#testEnded.e,OutputFormatter,TestResult method testEnded(formatter: OutputFormatter; testResult: TestResult) 208 +nim suiteEnded unittest.html#suiteEnded.e,OutputFormatter method suiteEnded(formatter: OutputFormatter) 210 +nim addOutputFormatter unittest.html#addOutputFormatter,OutputFormatter proc addOutputFormatter(formatter: OutputFormatter) 213 +nim delOutputFormatter unittest.html#delOutputFormatter,OutputFormatter proc delOutputFormatter(formatter: OutputFormatter) 216 +nim resetOutputFormatters unittest.html#resetOutputFormatters proc resetOutputFormatters() 220 +nim newConsoleOutputFormatter unittest.html#newConsoleOutputFormatter,OutputLevel proc newConsoleOutputFormatter(outputLevel: OutputLevel = outputLevelDefault;\n colorOutput = true): ConsoleOutputFormatter 223 +nim defaultConsoleFormatter unittest.html#defaultConsoleFormatter proc defaultConsoleFormatter(): ConsoleOutputFormatter 252 +nim suiteStarted unittest.html#suiteStarted.e,ConsoleOutputFormatter,string method suiteStarted(formatter: ConsoleOutputFormatter; suiteName: string) 262 +nim testStarted unittest.html#testStarted.e,ConsoleOutputFormatter,string method testStarted(formatter: ConsoleOutputFormatter; testName: string) 271 +nim failureOccurred unittest.html#failureOccurred.e,ConsoleOutputFormatter,seq[string],string method failureOccurred(formatter: ConsoleOutputFormatter; checkpoints: seq[string];\n stackTrace: string) 274 +nim testEnded unittest.html#testEnded.e,ConsoleOutputFormatter,TestResult method testEnded(formatter: ConsoleOutputFormatter; testResult: TestResult) 282 +nim suiteEnded unittest.html#suiteEnded.e,ConsoleOutputFormatter method suiteEnded(formatter: ConsoleOutputFormatter) 303 +nim newJUnitOutputFormatter unittest.html#newJUnitOutputFormatter,Stream proc newJUnitOutputFormatter(stream: Stream): JUnitOutputFormatter 321 +nim close unittest.html#close,JUnitOutputFormatter proc close(formatter: JUnitOutputFormatter) 336 +nim suiteStarted unittest.html#suiteStarted.e,JUnitOutputFormatter,string method suiteStarted(formatter: JUnitOutputFormatter; suiteName: string) 341 +nim testStarted unittest.html#testStarted.e,JUnitOutputFormatter,string method testStarted(formatter: JUnitOutputFormatter; testName: string) 344 +nim failureOccurred unittest.html#failureOccurred.e,JUnitOutputFormatter,seq[string],string method failureOccurred(formatter: JUnitOutputFormatter; checkpoints: seq[string];\n stackTrace: string) 349 +nim testEnded unittest.html#testEnded.e,JUnitOutputFormatter,TestResult method testEnded(formatter: JUnitOutputFormatter; testResult: TestResult) 357 +nim suiteEnded unittest.html#suiteEnded.e,JUnitOutputFormatter method suiteEnded(formatter: JUnitOutputFormatter) 398 +nim suite unittest.html#suite.t,, template suite(name, body) 468 +nim test unittest.html#test.t,, template test(name, body) 527 +nim checkpoint unittest.html#checkpoint,string proc checkpoint(msg: string) 581 +nim fail unittest.html#fail.t template fail() 595 +nim skip unittest.html#skip.t template skip() 627 +nim check unittest.html#check.m,untyped macro check(conditions: untyped): untyped 642 +nim require unittest.html#require.t,untyped template require(conditions: untyped) 736 +nim expect unittest.html#expect.m,varargs[typed],untyped macro expect(exceptions: varargs[typed]; body: untyped): untyped 746 +nim disableParamFiltering unittest.html#disableParamFiltering proc disableParamFiltering() 785 +heading Testament unittest.html#testament Testament 0 +heading Running a single test unittest.html#running-a-single-test Running a single test 0 +heading Running a single test suite unittest.html#running-a-single-test-suite Running a single test suite 0 +heading Selecting tests by pattern unittest.html#selecting-tests-by-pattern Selecting tests by pattern 0 +heading Examples unittest.html#examples Examples 0 +heading Limitations/Bugs unittest.html#limitationsslashbugs Limitations/Bugs 0 +nimgrp suitestarted unittest.html#suiteStarted-methods-all method 199 +nimgrp testended unittest.html#testEnded-methods-all method 208 +nimgrp failureoccurred unittest.html#failureOccurred-methods-all method 203 +nimgrp suiteended unittest.html#suiteEnded-methods-all method 210 +nimgrp teststarted unittest.html#testStarted-methods-all method 201 diff --git a/uri.html b/uri.html new file mode 100644 index 0000000000000..8c957c7e1d612 --- /dev/null +++ b/uri.html @@ -0,0 +1,569 @@ + + + + + + + +std/uri + + + + + + + + + + + + + + + + +
+
+

std/uri

+
+ +
+ Source   +Edit   + +
+ +

This module implements URI parsing as specified by RFC 3986.

+

A Uniform Resource Identifier (URI) provides a simple and extensible means for identifying a resource. A URI can be further classified as a locator, a name, or both. The term "Uniform Resource Locator" (URL) refers to the subset of URIs.

+
Warning: +URI parsers in this module do not perform security validation.
+ +

Basic usage

+

Combine URIs

+

Example:

+
import std/uri
+let host = parseUri("https://nim-lang.org")
+assert $host == "https://nim-lang.org"
+assert $(host / "/blog.html") == "https://nim-lang.org/blog.html"
+assert $(host / "blog2.html") == "https://nim-lang.org/blog2.html"
+

Access URI item

+

Example:

+
import std/uri
+let res = parseUri("sftp://127.0.0.1:4343")
+assert isAbsolute(res)
+assert res.port == "4343"
+

Data URI Base64

+

Example:

+
import std/uri
+assert getDataUri("Hello World", "text/plain") == "data:text/plain;charset=utf-8;base64,SGVsbG8gV29ybGQ="
+assert getDataUri("Nim", "text/plain") == "data:text/plain;charset=utf-8;base64,Tmlt"

+ +
+

Types

+
+
+
Uri = object
+  scheme*, username*, password*: string
+  hostname*, port*, path*, query*, anchor*: string
+  opaque*: bool
+  isIpv6*: bool
+
+ + + Source   +Edit   + +
+
+
+
UriParseError = object of ValueError
+
+ + + Source   +Edit   + +
+
+
+
Url = distinct string
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
func `$`(u: Uri): string {....raises: [], tags: [], forbids: [].}
+
+ + Returns the string representation of the specified URI object. +

Example:

+
assert $parseUri("https://nim-lang.org") == "https://nim-lang.org"
+ Source   +Edit   + +
+
+ +
+
+
+
func `/`(x: Uri; path: string): Uri {....raises: [], tags: [], forbids: [].}
+
+ +

Concatenates the path specified to the specified URIs path.

+

Contrary to the combine func you do not have to worry about the slashes at the beginning and end of the path and URIs path respectively.

+

See also:

+ + +

Example:

+
let foo = parseUri("https://nim-lang.org/foo/bar") / "/baz"
+assert foo.path == "/foo/bar/baz"
+let bar = parseUri("https://nim-lang.org/foo/bar") / "baz"
+assert bar.path == "/foo/bar/baz"
+let qux = parseUri("https://nim-lang.org/foo/bar/") / "baz"
+assert qux.path == "/foo/bar/baz"
+ Source   +Edit   + +
+
+ +
+
+
+
func `?`(u: Uri; query: openArray[(string, string)]): Uri {....raises: [],
+    tags: [], forbids: [].}
+
+ + Concatenates the query parameters to the specified URI object. +

Example:

+
let foo = parseUri("https://example.com") / "foo" ? {"bar": "qux"}
+assert $foo == "https://example.com/foo?bar=qux"
+ Source   +Edit   + +
+
+ +
+
+
+
func combine(base: Uri; reference: Uri): Uri {....raises: [], tags: [], forbids: [].}
+
+ +

Combines a base URI with a reference URI.

+

This uses the algorithm specified in section 5.2.2 of RFC 3986.

+

This means that the slashes inside the base URIs path as well as reference URIs path affect the resulting URI.

+

See also:

+ + +

Example:

+
let foo = combine(parseUri("https://nim-lang.org/foo/bar"), parseUri("/baz"))
+assert foo.path == "/baz"
+let bar = combine(parseUri("https://nim-lang.org/foo/bar"), parseUri("baz"))
+assert bar.path == "/foo/baz"
+let qux = combine(parseUri("https://nim-lang.org/foo/bar/"), parseUri("baz"))
+assert qux.path == "/foo/bar/baz"
+ Source   +Edit   + +
+
+
+
func combine(uris: varargs[Uri]): Uri {....raises: [], tags: [], forbids: [].}
+
+ +

Combines multiple URIs together.

+

See also:

+ + +

Example:

+
let foo = combine(parseUri("https://nim-lang.org/"), parseUri("docs/"),
+    parseUri("manual.html"))
+assert foo.hostname == "nim-lang.org"
+assert foo.path == "/docs/manual.html"
+ Source   +Edit   + +
+
+ +
+
+
+
func decodeUrl(s: string; decodePlus = true): string {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Decodes a URL according to RFC3986.

+

This means that any %xx (where xx denotes a hexadecimal value) are converted to the character with ordinal number xx, and every other character is carried over. If xx is not a valid hexadecimal value, it is left intact.

+

As a special rule, when the value of decodePlus is true, + characters are converted to a space.

+

See also:

+ + +

Example:

+
assert decodeUrl("https%3A%2F%2Fnim-lang.org") == "https://nim-lang.org"
+assert decodeUrl("https%3A%2F%2Fnim-lang.org%2Fthis+is+a+test") == "https://nim-lang.org/this is a test"
+assert decodeUrl("https%3A%2F%2Fnim-lang.org%2Fthis%20is%20a%20test",
+    false) == "https://nim-lang.org/this is a test"
+assert decodeUrl("abc%xyz") == "abc%xyz"
+ Source   +Edit   + +
+
+ +
+
+
+
func encodeQuery(query: openArray[(string, string)]; usePlus = true;
+                 omitEq = true; sep = '&'): string {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Encodes a set of (key, value) parameters into a URL query string.

+

Every (key, value) pair is URL-encoded and written as key=value. If the value is an empty string then the = is omitted, unless omitEq is false. The pairs are joined together by the sep character.

+

The usePlus parameter is passed down to the encodeUrl function that is used for the URL encoding of the string values.

+

See also:

+ + +

Example:

+
assert encodeQuery({: }) == ""
+assert encodeQuery({"a": "1", "b": "2"}) == "a=1&b=2"
+assert encodeQuery({"a": "1", "b": ""}) == "a=1&b"
+assert encodeQuery({"a": "1", "b": ""}, omitEq = false, sep = ';') == "a=1;b="
+ Source   +Edit   + +
+
+ +
+
+
+
func encodeUrl(s: string; usePlus = true): string {....raises: [], tags: [],
+    forbids: [].}
+
+ +

Encodes a URL according to RFC3986.

+

This means that characters in the set {'a'..'z', 'A'..'Z', '0'..'9', '-', '.', '_', '~'} are carried over to the result. All other characters are encoded as %xx where xx denotes its hexadecimal value.

+

As a special rule, when the value of usePlus is true, spaces are encoded as + instead of %20.

+

See also:

+ + +

Example:

+
assert encodeUrl("https://nim-lang.org") == "https%3A%2F%2Fnim-lang.org"
+assert encodeUrl("https://nim-lang.org/this is a test") == "https%3A%2F%2Fnim-lang.org%2Fthis+is+a+test"
+assert encodeUrl("https://nim-lang.org/this is a test", false) == "https%3A%2F%2Fnim-lang.org%2Fthis%20is%20a%20test"
+ Source   +Edit   + +
+
+ +
+
+
+
proc getDataUri(data, mime: string; encoding = "utf-8"): string {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Convenience proc for base64.encode returns a standard Base64 Data URI (RFC-2397)

+

See also:

+ + +

Example:

+
static: assert getDataUri("Nim", "text/plain") == "data:text/plain;charset=utf-8;base64,Tmlt"
+ Source   +Edit   + +
+
+ +
+
+
+
func initUri(isIpv6 = false): Uri {....raises: [], tags: [], forbids: [].}
+
+ +

Initializes a URI with scheme, username, password, hostname, port, path, query, anchor and isIpv6.

+

See also:

+
  • Uri type for available fields in the URI type
  • +
+ +

Example:

+
var uri2 = initUri(isIpv6 = true)
+uri2.scheme = "tcp"
+uri2.hostname = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
+uri2.port = "8080"
+assert $uri2 == "tcp://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:8080"
+ Source   +Edit   + +
+
+ +
+
+
+
func isAbsolute(uri: Uri): bool {....raises: [], tags: [], forbids: [].}
+
+ + Returns true if URI is absolute, false otherwise. +

Example:

+
assert parseUri("https://nim-lang.org").isAbsolute
+assert not parseUri("nim-lang").isAbsolute
+ Source   +Edit   + +
+
+ +
+
+
+
func parseUri(uri: string): Uri {....raises: [], tags: [], forbids: [].}
+
+ +

Parses a URI and returns it.

+

See also:

+
  • Uri type for available fields in the URI type
  • +
+ +

Example:

+
let res = parseUri("ftp://Username:Password@Hostname")
+assert res.username == "Username"
+assert res.password == "Password"
+assert res.scheme == "ftp"
+ Source   +Edit   + +
+
+
+
func parseUri(uri: string; result: var Uri) {....raises: [], tags: [], forbids: [].}
+
+ +

Parses a URI. The result variable will be cleared before.

+

See also:

+ + +

Example:

+
var res = initUri()
+parseUri("https://nim-lang.org/docs/manual.html", res)
+assert res.scheme == "https"
+assert res.hostname == "nim-lang.org"
+assert res.path == "/docs/manual.html"
+ Source   +Edit   + +
+
+ +
+
+
+
proc uriParseError(msg: string) {.noreturn, ...raises: [UriParseError], tags: [],
+                                  forbids: [].}
+
+ + Raises a UriParseError exception with message msg. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator decodeQuery(data: string; sep = '&'): tuple[key, value: string] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Reads and decodes the query string data and yields the (key, value) pairs the data consists of. If compiled with -d:nimLegacyParseQueryStrict, a UriParseError is raised when there is an unencoded = character in a decoded value, which was the behavior in Nim < 1.5.1. +

Example:

+
import std/sequtils
+assert toSeq(decodeQuery("foo=1&bar=2=3")) == @[("foo", "1"), ("bar", "2=3")]
+assert toSeq(decodeQuery("foo=1;bar=2=3", ';')) == @[("foo", "1"), ("bar", "2=3")]
+assert toSeq(decodeQuery("&a&=b&=&&")) == @[("", ""), ("a", ""), ("", "b"), ("", ""), ("", "")]
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/uri.idx b/uri.idx new file mode 100644 index 0000000000000..27ae87ba7b223 --- /dev/null +++ b/uri.idx @@ -0,0 +1,25 @@ +nimTitle uri uri.html module std/uri 0 +nim Url uri.html#Url type Url 49 +nim Uri uri.html#Uri object Uri 51 +nim UriParseError uri.html#UriParseError object UriParseError 57 +nim uriParseError uri.html#uriParseError,string proc uriParseError(msg: string) 60 +nim encodeUrl uri.html#encodeUrl,string proc encodeUrl(s: string; usePlus = true): string 64 +nim decodeUrl uri.html#decodeUrl,string proc decodeUrl(s: string; decodePlus = true): string 93 +nim encodeQuery uri.html#encodeQuery,openArray[],char proc encodeQuery(query: openArray[(string, string)]; usePlus = true; omitEq = true;\n sep = '&'): string 130 +nim decodeQuery uri.html#decodeQuery.i,string,char iterator decodeQuery(data: string; sep = '&'): tuple[key, value: string] 159 +nim initUri uri.html#initUri proc initUri(isIpv6 = false): Uri 249 +nim parseUri uri.html#parseUri,string,Uri proc parseUri(uri: string; result: var Uri) 271 +nim parseUri uri.html#parseUri,string proc parseUri(uri: string): Uri 319 +nim combine uri.html#combine,Uri,Uri proc combine(base: Uri; reference: Uri): Uri 381 +nim combine uri.html#combine,varargs[Uri] proc combine(uris: varargs[Uri]): Uri 432 +nim isAbsolute uri.html#isAbsolute,Uri proc isAbsolute(uri: Uri): bool 446 +nim `/` uri.html#/,Uri,string proc `/`(x: Uri; path: string): Uri 453 +nim `?` uri.html#?,Uri,openArray[] proc `?`(u: Uri; query: openArray[(string, string)]): Uri 487 +nim `$` uri.html#$,Uri proc `$`(u: Uri): string 495 +nim getDataUri uri.html#getDataUri,string,string,string proc getDataUri(data, mime: string; encoding = "utf-8"): string 555 +heading Basic usage uri.html#basic-usage Basic usage 0 +heading Combine URIs uri.html#basic-usage-combine-uris Combine URIs 0 +heading Access URI item uri.html#basic-usage-access-uri-item Access URI item 0 +heading Data URI Base64 uri.html#basic-usage-data-uri-base64 Data URI Base64 0 +nimgrp parseuri uri.html#parseUri-procs-all proc 271 +nimgrp combine uri.html#combine-procs-all proc 381 diff --git a/util.html b/util.html new file mode 100644 index 0000000000000..2f4deb0b5dfbb --- /dev/null +++ b/util.html @@ -0,0 +1,119 @@ + + + + + + + +nre/private/util + + + + + + + + + + + + + + + + +
+
+

nre/private/util

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

INTERNAL FILE FOR USE ONLY BY nre.nim.

+
+

Imports

+
+ tables +
+
+
+

Templates

+
+
+
+
template formatStr(howExpr, namegetter, idgetter): untyped
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/util.idx b/util.idx new file mode 100644 index 0000000000000..d92fed264191b --- /dev/null +++ b/util.idx @@ -0,0 +1,2 @@ +nimTitle util util.html module nre/private/util 0 +nim formatStr util.html#formatStr.t,,, template formatStr(howExpr, namegetter, idgetter): untyped 7 diff --git a/var_t_return.html b/var_t_return.html new file mode 100644 index 0000000000000..4a8753cda0a6d --- /dev/null +++ b/var_t_return.html @@ -0,0 +1,53 @@ + + + + + + + +doc/manual/var_t_return + + + + + + + + + + + + + + + + +
+
+

doc/manual/var_t_return

+

Memory safety for returning by var T is ensured by a simple borrowing rule: If result does not refer to a location pointing to the heap (that is in result = X the X involves a ptr or ref access) then it has to be derived from the routine's first parameter:

+

proc forward[T](x: var T): var T =
+  result = x # ok, derived from the first parameter.
+
+proc p(param: var int): var int =
+  var x: int
+  # we know 'forward' provides a view into the location derived from
+  # its first argument 'x'.
+  result = forward(x) # Error: location is derived from `x`
+                      # which is not p's first parameter and lives
+                      # on the stack.

+

In other words, the lifetime of what result points to is attached to the lifetime of the first parameter and that is enough knowledge to verify memory safety at the call site.

+ + + + +
+
+ + + + diff --git a/var_t_return.idx b/var_t_return.idx new file mode 100644 index 0000000000000..7375dce22694b --- /dev/null +++ b/var_t_return.idx @@ -0,0 +1 @@ +markupTitle var_t_return.md var_t_return.html var_t_return.md 0 diff --git a/varints.html b/varints.html new file mode 100644 index 0000000000000..7d9821cf45d63 --- /dev/null +++ b/varints.html @@ -0,0 +1,190 @@ + + + + + + + +std/varints + + + + + + + + + + + + + + + + +
+
+

std/varints

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

A variable length integer encoding implementation inspired by SQLite.

+

Unstable API.

+

+
+

Consts

+
+
+
maxVarIntLen = 9
+
+ + the maximal number of bytes a varint can take + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc decodeZigzag(x: uint64): int64 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc encodeZigzag(x: int64): uint64 {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc readVu64(z: openArray[byte]; pResult: var uint64): int {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc writeVu64(z: var openArray[byte]; x: uint64): int {....raises: [], tags: [],
+    forbids: [].}
+
+ + Write a varint into z. The buffer z must be at least 9 characters long to accommodate the largest possible varint. Returns the number of bytes used. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/varints.idx b/varints.idx new file mode 100644 index 0000000000000..03078ef95a5a5 --- /dev/null +++ b/varints.idx @@ -0,0 +1,6 @@ +nimTitle varints varints.html module std/varints 0 +nim maxVarIntLen varints.html#maxVarIntLen const maxVarIntLen 16 +nim readVu64 varints.html#readVu64,openArray[byte],uint64 proc readVu64(z: openArray[byte]; pResult: var uint64): int 18 +nim writeVu64 varints.html#writeVu64,openArray[byte],uint64 proc writeVu64(z: var openArray[byte]; x: uint64): int 57 +nim encodeZigzag varints.html#encodeZigzag,int64 proc encodeZigzag(x: int64): uint64 116 +nim decodeZigzag varints.html#decodeZigzag,uint64 proc decodeZigzag(x: uint64): int64 119 diff --git a/vmutils.html b/vmutils.html new file mode 100644 index 0000000000000..b4c4ea9bc7f48 --- /dev/null +++ b/vmutils.html @@ -0,0 +1,116 @@ + + + + + + + +std/vmutils + + + + + + + + + + + + + + + + +
+
+

std/vmutils

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

Experimental API, subject to change.

+
+

Procs

+
+
+
+
proc vmTrace(on: bool) {.compileTime, ...raises: [], tags: [], forbids: [].}
+
+ + +

Example:

+
static: vmTrace(true)
+proc fn =
+  var a = 1
+  vmTrace(false)
+static: fn()
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/vmutils.idx b/vmutils.idx new file mode 100644 index 0000000000000..74c60aea8ae34 --- /dev/null +++ b/vmutils.idx @@ -0,0 +1,2 @@ +nimTitle vmutils vmutils.html module std/vmutils 0 +nim vmTrace vmutils.html#vmTrace,bool proc vmTrace(on: bool) 5 diff --git a/volatile.html b/volatile.html new file mode 100644 index 0000000000000..4a490c034d34d --- /dev/null +++ b/volatile.html @@ -0,0 +1,127 @@ + + + + + + + +std/volatile + + + + + + + + + + + + + + + + +
+
+

std/volatile

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module contains code for generating volatile loads and stores, which are useful in embedded and systems programming.

+
+

Procs

+
+
+
+
proc volatileLoad[T](src: ptr T): T {.inline, noinit.}
+
+ + Generates a volatile load of the value stored in the container src. Note that this only effects code generation on C like backends. + Source   +Edit   + +
+
+ +
+
+
+
proc volatileStore[T](dest: ptr T; val: T) {.inline.}
+
+ + Generates a volatile store into the container dest of the value val. Note that this only effects code generation on C like backends. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/volatile.idx b/volatile.idx new file mode 100644 index 0000000000000..9cbd79e6a26ef --- /dev/null +++ b/volatile.idx @@ -0,0 +1,3 @@ +nimTitle volatile volatile.html module std/volatile 0 +nim volatileLoad volatile.html#volatileLoad,ptr.T proc volatileLoad[T](src: ptr T): T 13 +nim volatileStore volatile.html#volatileStore,ptr.T,T proc volatileStore[T](dest: ptr T; val: T) 24 diff --git a/widestrs.html b/widestrs.html new file mode 100644 index 0000000000000..516c2517f6c81 --- /dev/null +++ b/widestrs.html @@ -0,0 +1,354 @@ + + + + + + + +std/widestrs + + + + + + + + + + + + + + + + +
+
+

std/widestrs

+
+ +
+ Source   +Edit   + +
+ +

Nim support for C/C++'s wide strings.

+
+

Types

+
+
+
Utf16Char = distinct int16
+
+ + + Source   +Edit   + +
+
+
+
WideCString = ptr UncheckedArray[Utf16Char]
+
+ + + Source   +Edit   + +
+
+
+
WideCStringObj = object
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(s: WideCString): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `$`(s: WideCStringObj): string {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `$`(s: WideCStringObj; estimate: int; replacement: int = 0x0000FFFD): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc `$`(w: WideCString; estimate: int; replacement: int = 0x0000FFFD): string {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc len(w: WideCString): int {....raises: [], tags: [], forbids: [].}
+
+ + returns the length of a widestring. This traverses the whole string to find the binary zero end marker! + Source   +Edit   + +
+
+
+
proc len(w: WideCStringObj): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc newWideCString(s: cstring): WideCStringObj {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newWideCString(s: string): WideCStringObj {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newWideCString(size: int): WideCStringObj {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+
+
proc newWideCString(source: cstring; L: int): WideCStringObj {....raises: [],
+    tags: [], forbids: [].}
+
+ + Warning:: source needs to be preallocated with the length L + Source   +Edit   + +
+
+ +
+ +
+
+
+

Converters

+
+
+
+
converter toWideCString(x: WideCStringObj): WideCString {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template `[]`(a: WideCStringObj; idx: int): Utf16Char
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template `[]=`(a: WideCStringObj; idx: int; val: Utf16Char)
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/widestrs.idx b/widestrs.idx new file mode 100644 index 0000000000000..16cc1afe0d38f --- /dev/null +++ b/widestrs.idx @@ -0,0 +1,21 @@ +nimTitle widestrs widestrs.html module std/widestrs 0 +nim Utf16Char widestrs.html#Utf16Char type Utf16Char 16 +nim WideCString widestrs.html#WideCString type WideCString 22 +nim WideCStringObj widestrs.html#WideCStringObj object WideCStringObj 24 +nim `[]` widestrs.html#[].t,WideCStringObj,int template `[]`(a: WideCStringObj; idx: int): Utf16Char 57 +nim `[]=` widestrs.html#[]=.t,WideCStringObj,int,Utf16Char template `[]=`(a: WideCStringObj; idx: int; val: Utf16Char) 58 +nim toWideCString widestrs.html#toWideCString.c,WideCStringObj converter toWideCString(x: WideCStringObj): WideCString 62 +nim len widestrs.html#len,WideCString proc len(w: WideCString): int 77 +nim newWideCString widestrs.html#newWideCString,int proc newWideCString(size: int): WideCStringObj 154 +nim newWideCString widestrs.html#newWideCString,cstring,int proc newWideCString(source: cstring; L: int): WideCStringObj 157 +nim newWideCString widestrs.html#newWideCString,cstring proc newWideCString(s: cstring): WideCStringObj 178 +nim newWideCString widestrs.html#newWideCString,string proc newWideCString(s: string): WideCStringObj 183 +nim `$` widestrs.html#$,WideCString,int,int proc `$`(w: WideCString; estimate: int; replacement: int = 0x0000FFFD): string 186 +nim `$` widestrs.html#$,WideCString proc `$`(s: WideCString): string 228 +nim `$` widestrs.html#$,WideCStringObj,int,int proc `$`(s: WideCStringObj; estimate: int; replacement: int = 0x0000FFFD): string 232 +nim `$` widestrs.html#$,WideCStringObj proc `$`(s: WideCStringObj): string 235 +nim len widestrs.html#len,WideCStringObj proc len(w: WideCStringObj): int 238 +idx wide strings widestrs.html#wide-strings_1 Module widestrs 0 +nimgrp $ widestrs.html#$-procs-all proc 186 +nimgrp len widestrs.html#len-procs-all proc 77 +nimgrp newwidecstring widestrs.html#newWideCString-procs-all proc 154 diff --git a/win_getsysteminfo.html b/win_getsysteminfo.html new file mode 100644 index 0000000000000..170b0ccec34f1 --- /dev/null +++ b/win_getsysteminfo.html @@ -0,0 +1,140 @@ + + + + + + + +std/private/win_getsysteminfo + + + + + + + + + + + + + + + + +
+
+

std/private/win_getsysteminfo

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

+
+

Types

+
+
+
SystemInfo = object
+  dwNumberOfProcessors*: uint32
+  dwAllocationGranularity*: uint32
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc getSystemInfo(lpSystemInfo: ptr SystemInfo) {.stdcall, dynlib: "kernel32",
+    importc: "GetSystemInfo", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/win_getsysteminfo.idx b/win_getsysteminfo.idx new file mode 100644 index 0000000000000..35e5db80dc279 --- /dev/null +++ b/win_getsysteminfo.idx @@ -0,0 +1,3 @@ +nimTitle win_getsysteminfo win_getsysteminfo.html module std/private/win_getsysteminfo 0 +nim SystemInfo win_getsysteminfo.html#SystemInfo object SystemInfo 2 +nim getSystemInfo win_getsysteminfo.html#getSystemInfo,ptr.SystemInfo proc getSystemInfo(lpSystemInfo: ptr SystemInfo) 14 diff --git a/win_setenv.html b/win_setenv.html new file mode 100644 index 0000000000000..079a77e65a423 --- /dev/null +++ b/win_setenv.html @@ -0,0 +1,76 @@ + + + + + + + +std/private/win_setenv + + + + + + + + + + + + + + + + +
+
+

std/private/win_setenv

+
+
+
+ + +
+ +
+ Search: +
+ + +
+
+ Source   +Edit   + +
+ +

+ +
+
+ + +
+
+ + + + diff --git a/win_setenv.idx b/win_setenv.idx new file mode 100644 index 0000000000000..ea0ea9b15157a --- /dev/null +++ b/win_setenv.idx @@ -0,0 +1 @@ +nimTitle win_setenv win_setenv.html module std/private/win_setenv 0 diff --git a/winlean.html b/winlean.html new file mode 100644 index 0000000000000..6edd22bf9c542 --- /dev/null +++ b/winlean.html @@ -0,0 +1,5809 @@ + + + + + + + +std/winlean + + + + + + + + + + + + + + + + +
+
+

std/winlean

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements a small wrapper for some needed Win API procedures, so that the Nim compiler does not depend on the huge Windows module.

+ +
+

Types

+
+
+
AddrInfo = object
+  ai_flags*: cint            ## Input flags.
+  ai_family*: cint           ## Address family of socket.
+  ai_socktype*: cint         ## Socket type.
+  ai_protocol*: cint         ## Protocol of socket.
+  ai_addrlen*: csize_t       ## Length of socket address.
+  ai_canonname*: cstring     ## Canonical name of service location.
+  ai_addr*: ptr SockAddr     ## Socket address of socket.
+  ai_next*: ptr AddrInfo     ## Pointer to next in list.
+
+ + + Source   +Edit   + +
+
+
+
BY_HANDLE_FILE_INFORMATION = object
+  dwFileAttributes*: DWORD
+  ftCreationTime*: FILETIME
+  ftLastAccessTime*: FILETIME
+  ftLastWriteTime*: FILETIME
+  dwVolumeSerialNumber*: DWORD
+  nFileSizeHigh*: DWORD
+  nFileSizeLow*: DWORD
+  nNumberOfLinks*: DWORD
+  nFileIndexHigh*: DWORD
+  nFileIndexLow*: DWORD
+
+ + + Source   +Edit   + +
+
+
+
BYTE = uint8
+
+ + + Source   +Edit   + +
+
+
+
DWORD = int32
+
+ + + Source   +Edit   + +
+
+
+
FILETIME = object
+  dwLowDateTime*: DWORD
+  dwHighDateTime*: DWORD
+
+ + CANNOT BE int64 BECAUSE OF ALIGNMENT + Source   +Edit   + +
+
+
+
GUID = object
+  D1*: int32
+  D2*: int16
+  D3*: int16
+  D4*: array[0 .. 7, int8]
+
+ + + Source   +Edit   + +
+
+
+
Handle = int
+
+ + + Source   +Edit   + +
+
+
+
HDC = Handle
+
+ + + Source   +Edit   + +
+
+
+
HGLRC = Handle
+
+ + + Source   +Edit   + +
+
+
+
Hostent = object
+  h_name*: cstring
+  h_aliases*: cstringArray
+  h_addrtype*: int16
+  h_length*: int16
+  h_addr_list*: cstringArray
+
+ + + Source   +Edit   + +
+
+
+
In6_addr {.importc: "IN6_ADDR", header: "winsock2.h".} = object
+  bytes* {.importc: "u.Byte".}: array[0 .. 15, char]
+
+ + + Source   +Edit   + +
+
+
+
InAddr {.importc: "IN_ADDR", header: "winsock2.h", union.} = object
+  s_addr*: uint32
+
+ + + Source   +Edit   + +
+
+
+
KEY_EVENT_RECORD = object
+  eventType*: int16
+  bKeyDown*: WINBOOL
+  wRepeatCount*: int16
+  wVirtualKeyCode*: int16
+  wVirtualScanCode*: int16
+  uChar*: int16
+  dwControlKeyState*: DWORD
+
+ + + Source   +Edit   + +
+
+
+
LONG = int32
+
+ + + Source   +Edit   + +
+
+
+
LPFIBER_START_ROUTINE = proc (param: pointer) {.stdcall.}
+
+ + + Source   +Edit   + +
+
+
+
LPFILETIME = ptr FILETIME
+
+ + + Source   +Edit   + +
+
+
+
LPINT = ptr int32
+
+ + + Source   +Edit   + +
+
+
+
OSVERSIONINFO = object
+  dwOSVersionInfoSize*: DWORD
+  dwMajorVersion*: DWORD
+  dwMinorVersion*: DWORD
+  dwBuildNumber*: DWORD
+  dwPlatformId*: DWORD
+  szCSDVersion*: array[0 .. 127, WinChar]
+
+ + + Source   +Edit   + +
+
+
+
OVERLAPPED {.pure, inheritable.} = object
+  internal*: PULONG
+  internalHigh*: PULONG
+  offset*: DWORD
+  offsetHigh*: DWORD
+  hEvent*: Handle
+
+ + + Source   +Edit   + +
+
+
+
PBOOL = ptr WINBOOL
+
+ + + Source   +Edit   + +
+
+
+
PDWORD = ptr DWORD
+
+ + + Source   +Edit   + +
+
+
+
POVERLAPPED = ptr OVERLAPPED
+
+ + + Source   +Edit   + +
+
+
+
POVERLAPPED_COMPLETION_ROUTINE = proc (para1: DWORD; para2: DWORD;
+                                       para3: POVERLAPPED) {.stdcall.}
+
+ + + Source   +Edit   + +
+
+
+
PROCESS_INFORMATION = object
+  hProcess*: Handle
+  hThread*: Handle
+  dwProcessId*: int32
+  dwThreadId*: int32
+
+ + + Source   +Edit   + +
+
+
+
Protoent = object
+  p_name*: cstring
+  p_aliases*: cstringArray
+  p_proto*: cshort
+
+ + + Source   +Edit   + +
+
+
+
PSID = ptr SID
+
+ + + Source   +Edit   + +
+
+
+
PULONG = ptr int
+
+ + + Source   +Edit   + +
+
+
+
PULONG_PTR = ptr uint
+
+ + + Source   +Edit   + +
+
+
+
PWOHandleArray = ptr WOHandleArray
+
+ + + Source   +Edit   + +
+
+
+
SECURITY_ATTRIBUTES = object
+  nLength*: int32
+  lpSecurityDescriptor*: pointer
+  bInheritHandle*: WINBOOL
+
+ + + Source   +Edit   + +
+
+
+
Servent = object
+  s_name*: cstring
+  s_aliases*: cstringArray
+  when defined(cpu64):
+    s_proto*: cstring
+    s_port*: int16
+  else:
+    s_port*: int16
+    s_proto*: cstring
+
+ + + Source   +Edit   + +
+
+
+
SID {.importc, header: "<windows.h>".} = object
+
+ + + Source   +Edit   + +
+
+
+
SID_IDENTIFIER_AUTHORITY {.importc, header: "<windows.h>".} = object
+  value* {.importc: "Value".}: array[6, BYTE]
+
+ + + Source   +Edit   + +
+
+
+
SockAddr {.importc: "SOCKADDR", header: "winsock2.h".} = object
+  sa_family*: uint16
+  sa_data*: array[0 .. 13, char]
+
+ + + Source   +Edit   + +
+
+
+
Sockaddr_in {.importc: "SOCKADDR_IN", header: "winsock2.h".} = object
+  sin_family*: uint16
+  sin_port*: uint16
+  sin_addr*: InAddr
+  sin_zero*: array[0 .. 7, char]
+
+ + + Source   +Edit   + +
+
+
+
Sockaddr_in6 {.importc: "SOCKADDR_IN6", header: "ws2tcpip.h".} = object
+  sin6_family*: uint16
+  sin6_port*: uint16
+  sin6_flowinfo*: int32
+  sin6_addr*: In6_addr
+  sin6_scope_id*: int32
+
+ + + Source   +Edit   + +
+
+
+
Sockaddr_storage {.importc: "SOCKADDR_STORAGE", header: "winsock2.h".} = object
+  ss_family*: uint16
+
+ + + Source   +Edit   + +
+
+
+
SocketHandle = distinct int
+
+ + + Source   +Edit   + +
+
+
+
SockLen = cuint
+
+ + + Source   +Edit   + +
+
+
+
STARTUPINFO = object
+  cb*: int32
+  lpReserved*: cstring
+  lpDesktop*: cstring
+  lpTitle*: cstring
+  dwX*: int32
+  dwY*: int32
+  dwXSize*: int32
+  dwYSize*: int32
+  dwXCountChars*: int32
+  dwYCountChars*: int32
+  dwFillAttribute*: int32
+  dwFlags*: int32
+  wShowWindow*: int16
+  cbReserved2*: int16
+  lpReserved2*: pointer
+  hStdInput*: Handle
+  hStdOutput*: Handle
+  hStdError*: Handle
+
+ + + Source   +Edit   + +
+
+
+
TFdSet = object
+  fd_count*: cint
+  fd_array*: array[0 .. 64 - 1, SocketHandle]
+
+ + + Source   +Edit   + +
+
+
+
Timeval {.importc: "struct timeval", header: "<time.h>".} = object
+  tv_sec*, tv_usec*: int32
+
+ + + Source   +Edit   + +
+
+
+
TWSABuf {.importc: "WSABUF", header: "winsock2.h".} = object
+  len*: ULONG
+  buf*: cstring
+
+ + + Source   +Edit   + +
+
+
+
ULONG = int32
+
+ + + Source   +Edit   + +
+
+
+
ULONG_PTR = uint
+
+ + + Source   +Edit   + +
+
+
+
WAITORTIMERCALLBACK = proc (para1: pointer; para2: int32) {.stdcall.}
+
+ + + Source   +Edit   + +
+
+
+
WIN32_FIND_DATA {.pure.} = object
+  dwFileAttributes*: int32
+  ftCreationTime*: FILETIME
+  ftLastAccessTime*: FILETIME
+  ftLastWriteTime*: FILETIME
+  nFileSizeHigh*: int32
+  nFileSizeLow*: int32
+  cFileName*: array[0 .. 260 - 1, WinChar]
+  cAlternateFileName*: array[0 .. 13, WinChar]
+
+ + + Source   +Edit   + +
+
+
+
WINBOOL = int32
+
+ + WINBOOL uses opposite convention as posix, !=0 meaning success. + Source   +Edit   + +
+
+
+
WinChar = Utf16Char
+
+ + + Source   +Edit   + +
+
+
+
WinSizeT = uint64
+
+ + + Source   +Edit   + +
+
+
+
WOHandleArray = array[0 .. 0x00000040 - 1, Handle]
+
+ + + Source   +Edit   + +
+
+
+
WSAData {.importc: "WSADATA", header: "winsock2.h".} = object
+
+ + + Source   +Edit   + +
+
+
+
WSAPROC_ACCEPTEX = proc (sListenSocket: SocketHandle;
+                         sAcceptSocket: SocketHandle; lpOutputBuffer: pointer;
+                         dwReceiveDataLength: DWORD;
+                         dwLocalAddressLength: DWORD;
+                         dwRemoteAddressLength: DWORD;
+                         lpdwBytesReceived: ptr DWORD; lpOverlapped: POVERLAPPED): bool {.
+    stdcall, ...gcsafe, raises: [].}
+
+ + + Source   +Edit   + +
+
+
+
WSAPROC_CONNECTEX = proc (s: SocketHandle; name: ptr SockAddr; namelen: cint;
+                          lpSendBuffer: pointer; dwSendDataLength: DWORD;
+                          lpdwBytesSent: ptr DWORD; lpOverlapped: POVERLAPPED): bool {.
+    stdcall, ...gcsafe, raises: [].}
+
+ + + Source   +Edit   + +
+
+
+
WSAPROC_GETACCEPTEXSOCKADDRS = proc (lpOutputBuffer: pointer;
+                                     dwReceiveDataLength: DWORD;
+                                     dwLocalAddressLength: DWORD;
+                                     dwRemoteAddressLength: DWORD;
+                                     LocalSockaddr: ptr PSockAddr;
+                                     LocalSockaddrLength: ptr cint;
+                                     RemoteSockaddr: ptr PSockAddr;
+                                     RemoteSockaddrLength: ptr cint) {.stdcall,
+    ...gcsafe, raises: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Vars

+
+
+
INVALID_SOCKET {.importc, header: "winsock2.h".}: SocketHandle
+
+ + + Source   +Edit   + +
+
+
+
SO_ACCEPTCONN {.importc, header: "winsock2.h".}: cint
+
+ + + Source   +Edit   + +
+
+
+
SO_BROADCAST {.importc, header: "winsock2.h".}: cint
+
+ + + Source   +Edit   + +
+
+
+
SO_DEBUG {.importc, header: "winsock2.h".}: cint
+
+ + turn on debugging info recording + Source   +Edit   + +
+
+
+
SO_DONTLINGER {.importc, header: "winsock2.h".}: cint
+
+ + + Source   +Edit   + +
+
+
+
SO_DONTROUTE {.importc, header: "winsock2.h".}: cint
+
+ + + Source   +Edit   + +
+
+
+
SO_ERROR {.importc, header: "winsock2.h".}: cint
+
+ + + Source   +Edit   + +
+
+
+
SO_EXCLUSIVEADDRUSE {.importc, header: "winsock2.h".}: cint
+
+ + + Source   +Edit   + +
+
+
+
SO_KEEPALIVE {.importc, header: "winsock2.h".}: cint
+
+ + + Source   +Edit   + +
+
+
+
SO_LINGER {.importc, header: "winsock2.h".}: cint
+
+ + + Source   +Edit   + +
+
+
+
SO_OOBINLINE {.importc, header: "winsock2.h".}: cint
+
+ + + Source   +Edit   + +
+
+
+
SO_REUSEADDR {.importc, header: "winsock2.h".}: cint
+
+ + + Source   +Edit   + +
+
+
+
SO_REUSEPORT {.importc: "SO_REUSEADDR", header: "winsock2.h".}: cint
+
+ + + Source   +Edit   + +
+
+
+
SO_USELOOPBACK {.importc, header: "winsock2.h".}: cint
+
+ + + Source   +Edit   + +
+
+
+
SOL_SOCKET {.importc, header: "winsock2.h".}: cint
+
+ + + Source   +Edit   + +
+
+
+
SOMAXCONN {.importc, header: "winsock2.h".}: cint
+
+ + + Source   +Edit   + +
+
+
+
TCP_NODELAY {.importc, header: "winsock2.h".}: cint
+
+ + + Source   +Edit   + +
+
+
+
WSAID_ACCEPTEX: GUID = GUID(D1: 0xB5367DF1'i32, D2: 0xCBAC'i16, D3: 0x000011CF, D4: [
+    0x95'i8, 0xCA'i8, 0x00'i8, 0x80'i8, 0x5F'i8, 0x48'i8, 0xA1'i8, 0x92'i8])
+
+ + + Source   +Edit   + +
+
+
+
WSAID_CONNECTEX: GUID = GUID(D1: 0x25A207B9, D2: 0xDDF3'i16, D3: 0x00004660, D4: [
+    0x8E'i8, 0xE9'i8, 0x76'i8, 0xE5'i8, 0x8C'i8, 0x74'i8, 0x06'i8, 0x3E'i8])
+
+ + + Source   +Edit   + +
+
+
+
WSAID_GETACCEPTEXSOCKADDRS: GUID = GUID(D1: 0xB5367DF2'i32, D2: 0xCBAC'i16,
+                                        D3: 0x000011CF, D4: [0x95'i8, 0xCA'i8,
+    0x00'i8, 0x80'i8, 0x5F'i8, 0x48'i8, 0xA1'i8, 0x92'i8])
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
AF_INET = 2
+
+ + + Source   +Edit   + +
+
+
+
AF_INET6 = 23
+
+ + + Source   +Edit   + +
+
+
+
AF_UNSPEC = 0
+
+ + + Source   +Edit   + +
+
+
+
AI_V4MAPPED = 0x00000008
+
+ + + Source   +Edit   + +
+
+
+
CREATE_ALWAYS = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
CREATE_NEW = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
CREATE_NO_WINDOW = 0x08000000'i32
+
+ + + Source   +Edit   + +
+
+
+
CREATE_UNICODE_ENVIRONMENT = 1024'i32
+
+ + + Source   +Edit   + +
+
+
+
DETACHED_PROCESS = 8'i32
+
+ + + Source   +Edit   + +
+
+
+
DOMAIN_ALIAS_RID_ADMINS = 544
+
+ + + Source   +Edit   + +
+
+
+
DUPLICATE_SAME_ACCESS = 2
+
+ + + Source   +Edit   + +
+
+
+
ERROR_ACCESS_DENIED = 5
+
+ + + Source   +Edit   + +
+
+
+
ERROR_BAD_ARGUMENTS = 165
+
+ + + Source   +Edit   + +
+
+
+
ERROR_FILE_EXISTS = 80
+
+ + + Source   +Edit   + +
+
+ +
+
ERROR_HANDLE_EOF = 38
+
+ + + Source   +Edit   + +
+
+
+
ERROR_IO_PENDING = 997
+
+ + + Source   +Edit   + +
+
+
+
ERROR_LOCK_VIOLATION = 33
+
+ + + Source   +Edit   + +
+
+
+
ERROR_NETNAME_DELETED = 64
+
+ + + Source   +Edit   + +
+
+
+
ERROR_NO_MORE_FILES = 18
+
+ + + Source   +Edit   + +
+
+
+
ERROR_PATH_NOT_FOUND = 3
+
+ + + Source   +Edit   + +
+
+
+
FD_ACCEPT = 0x00000008'i32
+
+ + + Source   +Edit   + +
+
+
+
FD_ADDRESS_LIST_CHANGE = 0x00000200'i32
+
+ + + Source   +Edit   + +
+
+
+
FD_ALL_EVENTS = 0x000003FF'i32
+
+ + + Source   +Edit   + +
+
+
+
FD_CLOSE = 0x00000020'i32
+
+ + + Source   +Edit   + +
+
+
+
FD_CONNECT = 0x00000010'i32
+
+ + + Source   +Edit   + +
+
+
+
FD_GROUP_QQS = 0x00000080'i32
+
+ + + Source   +Edit   + +
+
+
+
FD_OOB = 0x00000004'i32
+
+ + + Source   +Edit   + +
+
+
+
FD_QQS = 0x00000040'i32
+
+ + + Source   +Edit   + +
+
+
+
FD_READ = 0x00000001'i32
+
+ + + Source   +Edit   + +
+
+
+
FD_ROUTING_INTERFACE_CHANGE = 0x00000100'i32
+
+ + + Source   +Edit   + +
+
+
+
FD_SETSIZE = 64
+
+ + + Source   +Edit   + +
+
+
+
FD_WRITE = 0x00000002'i32
+
+ + + Source   +Edit   + +
+
+
+
FIBER_FLAG_FLOAT_SWITCH = 0x00000001
+
+ + + Source   +Edit   + +
+
+
+
FILE_ATTRIBUTE_ARCHIVE = 0x00000020'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_ATTRIBUTE_COMPRESSED = 0x00000800'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_ATTRIBUTE_DEVICE = 0x00000040'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_ATTRIBUTE_DIRECTORY = 0x00000010'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_ATTRIBUTE_HIDDEN = 0x00000002'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_ATTRIBUTE_NORMAL = 0x00000080'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x00002000'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_ATTRIBUTE_OFFLINE = 0x00001000'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_ATTRIBUTE_READONLY = 0x00000001'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_ATTRIBUTE_SPARSE_FILE = 0x00000200'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_ATTRIBUTE_SYSTEM = 0x00000004'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_ATTRIBUTE_TEMPORARY = 0x00000100'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_BEGIN = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_FLAG_BACKUP_SEMANTICS = 0x02000000'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_FLAG_DELETE_ON_CLOSE = 0x04000000'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_FLAG_NO_BUFFERING = 0x20000000'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_FLAG_OPEN_NO_RECALL = 0x00100000'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_FLAG_OVERLAPPED = 0x40000000'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_FLAG_POSIX_SEMANTICS = 0x01000000'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_FLAG_RANDOM_ACCESS = 0x10000000'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_FLAG_WRITE_THROUGH = 0x80000000'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_MAP_READ = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_MAP_WRITE = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_READ_DATA = 0x00000001
+
+ + + Source   +Edit   + +
+
+
+
FILE_SHARE_DELETE = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_SHARE_READ = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_SHARE_WRITE = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
FILE_WRITE_DATA = 0x00000002
+
+ + + Source   +Edit   + +
+
+
+
GENERIC_ALL = 0x10000000'i32
+
+ + + Source   +Edit   + +
+
+
+
GENERIC_READ = 0x80000000'i32
+
+ + + Source   +Edit   + +
+
+
+
GENERIC_WRITE = 0x40000000'i32
+
+ + + Source   +Edit   + +
+
+
+
HANDLE_FLAG_INHERIT = 0x00000001'i32
+
+ + + Source   +Edit   + +
+
+
+
HIGH_PRIORITY_CLASS = 128'i32
+
+ + + Source   +Edit   + +
+
+
+
IDLE_PRIORITY_CLASS = 64'i32
+
+ + + Source   +Edit   + +
+
+
+
INADDR_ANY = 0'u32
+
+ + + Source   +Edit   + +
+
+
+
INADDR_BROADCAST = -1
+
+ + + Source   +Edit   + +
+
+
+
INADDR_LOOPBACK = 0x7F000001
+
+ + + Source   +Edit   + +
+
+
+
INADDR_NONE = -1
+
+ + + Source   +Edit   + +
+
+
+
INFINITE = -1'i32
+
+ + + Source   +Edit   + +
+
+
+
INVALID_FILE_SIZE = -1'i32
+
+ + + Source   +Edit   + +
+
+
+
INVALID_HANDLE_VALUE = -1
+
+ + + Source   +Edit   + +
+
+
+
INVALID_SET_FILE_POINTER = -1'i32
+
+ + + Source   +Edit   + +
+
+
+
IOC_IN = 0x80000000'i32
+
+ + + Source   +Edit   + +
+
+
+
IOC_INOUT = -1073741824'i32
+
+ + + Source   +Edit   + +
+
+
+
IOC_OUT = 0x40000000'i32
+
+ + + Source   +Edit   + +
+
+
+
IOC_WS2 = 0x08000000'i32
+
+ + + Source   +Edit   + +
+
+
+
MAX_PATH = 260
+
+ + + Source   +Edit   + +
+
+
+
MAXIMUM_WAIT_OBJECTS = 0x00000040
+
+ + + Source   +Edit   + +
+
+
+
MOVEFILE_COPY_ALLOWED = 0x00000002'i32
+
+ + + Source   +Edit   + +
+
+ +
+
MOVEFILE_DELAY_UNTIL_REBOOT = 0x00000004'i32
+
+ + + Source   +Edit   + +
+
+
+
MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x00000020'i32
+
+ + + Source   +Edit   + +
+
+
+
MOVEFILE_REPLACE_EXISTING = 0x00000001'i32
+
+ + + Source   +Edit   + +
+
+
+
MOVEFILE_WRITE_THROUGH = 0x00000008'i32
+
+ + + Source   +Edit   + +
+
+
+
MSG_PEEK = 2
+
+ + + Source   +Edit   + +
+
+
+
NO_ERROR = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
NORMAL_PRIORITY_CLASS = 32'i32
+
+ + + Source   +Edit   + +
+
+
+
OPEN_ALWAYS = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
OPEN_EXISTING = 3'i32
+
+ + + Source   +Edit   + +
+
+
+
PAGE_EXECUTE = 0x00000010'i32
+
+ + + Source   +Edit   + +
+
+
+
PAGE_EXECUTE_READ = 0x00000020'i32
+
+ + + Source   +Edit   + +
+
+
+
PAGE_EXECUTE_READWRITE = 0x00000040'i32
+
+ + + Source   +Edit   + +
+
+
+
PAGE_NOACCESS = 0x00000001'i32
+
+ + + Source   +Edit   + +
+
+
+
PAGE_READONLY = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
PAGE_READWRITE = 4'i32
+
+ + + Source   +Edit   + +
+
+
+
PIPE_ACCESS_DUPLEX = 0x00000003'i32
+
+ + + Source   +Edit   + +
+
+
+
PIPE_ACCESS_INBOUND = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
PIPE_ACCESS_OUTBOUND = 2'i32
+
+ + + Source   +Edit   + +
+
+
+
PIPE_NOWAIT = 0x00000001'i32
+
+ + + Source   +Edit   + +
+
+
+
PROCESS_CREATE_PROCESS = 0x00000080'i32
+
+ + + Source   +Edit   + +
+
+
+
PROCESS_CREATE_THREAD = 0x00000002'i32
+
+ + + Source   +Edit   + +
+
+
+
PROCESS_DUP_HANDLE = 0x00000040'i32
+
+ + + Source   +Edit   + +
+
+
+
PROCESS_QUERY_INFORMATION = 0x00000400'i32
+
+ + + Source   +Edit   + +
+
+
+
PROCESS_QUERY_LIMITED_INFORMATION = 0x00001000'i32
+
+ + + Source   +Edit   + +
+
+
+
PROCESS_SET_INFORMATION = 0x00000200'i32
+
+ + + Source   +Edit   + +
+
+
+
PROCESS_SET_LIMITED_INFORMATION = 0x00002000'i32
+
+ + + Source   +Edit   + +
+
+
+
PROCESS_SET_QUOTA = 0x00000100'i32
+
+ + + Source   +Edit   + +
+
+
+
PROCESS_SET_SESSIONID = 0x00000004'i32
+
+ + + Source   +Edit   + +
+
+
+
PROCESS_SUSPEND_RESUME = 0x00000800'i32
+
+ + + Source   +Edit   + +
+
+
+
PROCESS_TERMINATE = 0x00000001'i32
+
+ + + Source   +Edit   + +
+
+
+
PROCESS_VM_OPERATION = 0x00000008'i32
+
+ + + Source   +Edit   + +
+
+
+
PROCESS_VM_READ = 0x00000010'i32
+
+ + + Source   +Edit   + +
+
+
+
PROCESS_VM_WRITE = 0x00000020'i32
+
+ + + Source   +Edit   + +
+
+
+
REALTIME_PRIORITY_CLASS = 256'i32
+
+ + + Source   +Edit   + +
+
+
+
SECURITY_BUILTIN_DOMAIN_RID = 32
+
+ + + Source   +Edit   + +
+
+
+
SECURITY_NT_AUTHORITY = [0'u, 0'u, 0'u, 0'u, 0'u, 5'u]
+
+ + + Source   +Edit   + +
+
+
+
SIO_GET_EXTENSION_FUNCTION_POINTER = -939524090'i32
+
+ + + Source   +Edit   + +
+
+
+
SO_UPDATE_ACCEPT_CONTEXT = 0x0000700B
+
+ + + Source   +Edit   + +
+
+
+
STARTF_USESHOWWINDOW = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
STARTF_USESTDHANDLES = 256'i32
+
+ + + Source   +Edit   + +
+
+
+
STATUS_PENDING = 0x00000103
+
+ + + Source   +Edit   + +
+
+
+
STD_ERROR_HANDLE = -12'i32
+
+ + + Source   +Edit   + +
+
+
+
STD_INPUT_HANDLE = -10'i32
+
+ + + Source   +Edit   + +
+
+
+
STD_OUTPUT_HANDLE = -11'i32
+
+ + + Source   +Edit   + +
+
+
+
STILL_ACTIVE = 0x00000103'i32
+
+ + + Source   +Edit   + +
+
+
+
SW_SHOWNORMAL = 1'i32
+
+ + + Source   +Edit   + +
+
+
+
SYNCHRONIZE = 0x00100000'i32
+
+ + + Source   +Edit   + +
+
+
+
WAIT_FAILED = 0xFFFFFFFF'i32
+
+ + + Source   +Edit   + +
+
+
+
WAIT_OBJECT_0 = 0'i32
+
+ + + Source   +Edit   + +
+
+
+
WAIT_TIMEOUT = 0x00000102'i32
+
+ + + Source   +Edit   + +
+
+
+
WSADESCRIPTION_LEN = 256
+
+ + + Source   +Edit   + +
+
+
+
WSAEADDRINUSE = 10048
+
+ + + Source   +Edit   + +
+
+
+
WSAECONNABORTED = 10053
+
+ + + Source   +Edit   + +
+
+
+
WSAECONNRESET = 10054
+
+ + + Source   +Edit   + +
+
+
+
WSAEDISCON = 10101
+
+ + + Source   +Edit   + +
+
+
+
WSAEINPROGRESS = 10036
+
+ + + Source   +Edit   + +
+
+
+
WSAEINTR = 10004
+
+ + + Source   +Edit   + +
+
+
+
WSAENETRESET = 10052
+
+ + + Source   +Edit   + +
+
+
+
WSAENOTSOCK = 10038
+
+ + + Source   +Edit   + +
+
+
+
WSAESHUTDOWN = 10058
+
+ + + Source   +Edit   + +
+
+
+
WSAETIMEDOUT = 10060
+
+ + + Source   +Edit   + +
+
+
+
WSAEWOULDBLOCK = 10035
+
+ + + Source   +Edit   + +
+
+
+
WSANOTINITIALISED = 10093
+
+ + + Source   +Edit   + +
+
+
+
WSASYS_STATUS_LEN = 128
+
+ + + Source   +Edit   + +
+
+
+
WT_EXECUTEDEFAULT = 0x00000000'i32
+
+ + + Source   +Edit   + +
+
+
+
WT_EXECUTEINIOTHREAD = 0x00000001'i32
+
+ + + Source   +Edit   + +
+
+
+
WT_EXECUTEINPERSISTENTIOTHREAD = 0x00000040'i32
+
+ + + Source   +Edit   + +
+
+
+
WT_EXECUTEINPERSISTENTTHREAD = 0x00000080'i32
+
+ + + Source   +Edit   + +
+
+
+
WT_EXECUTEINTIMERTHREAD = 0x00000020'i32
+
+ + + Source   +Edit   + +
+
+
+
WT_EXECUTEINUITHREAD = 0x00000002'i32
+
+ + + Source   +Edit   + +
+
+
+
WT_EXECUTEINWAITTHREAD = 0x00000004'i32
+
+ + + Source   +Edit   + +
+
+
+
WT_EXECUTELONGFUNCTION = 0x00000010'i32
+
+ + + Source   +Edit   + +
+
+
+
WT_EXECUTEONLYONCE = 0x00000008'i32
+
+ + + Source   +Edit   + +
+
+
+
WT_TRANSFER_IMPERSONATION = 0x00000100'i32
+
+ + + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `==`(x, y: SocketHandle): bool {.borrow, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc accept(s: SocketHandle; a: ptr SockAddr; addrlen: ptr SockLen): SocketHandle {.
+    stdcall, importc: "accept", dynlib: ws2dll, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc allocateAndInitializeSid(pIdentifierAuthority: ptr SID_IDENTIFIER_AUTHORITY;
+                              nSubAuthorityCount: BYTE; nSubAuthority0: DWORD;
+                              nSubAuthority1: DWORD; nSubAuthority2: DWORD;
+                              nSubAuthority3: DWORD; nSubAuthority4: DWORD;
+                              nSubAuthority5: DWORD; nSubAuthority6: DWORD;
+                              nSubAuthority7: DWORD; pSid: ptr PSID): WINBOOL {.
+    stdcall, dynlib: "Advapi32", importc: "AllocateAndInitializeSid",
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc bindSocket(s: SocketHandle; name: ptr SockAddr; namelen: SockLen): cint {.
+    stdcall, importc: "bind", dynlib: ws2dll, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc checkTokenMembership(tokenHandle: Handle; sidToCheck: PSID; isMember: PBOOL): WINBOOL {.
+    stdcall, dynlib: "Advapi32", importc: "CheckTokenMembership", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc closeHandle(hObject: Handle): WINBOOL {.stdcall, dynlib: "kernel32",
+    importc: "CloseHandle", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc closesocket(s: SocketHandle): cint {.stdcall, importc: "closesocket",
+    dynlib: ws2dll, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc connect(s: SocketHandle; name: ptr SockAddr; namelen: SockLen): cint {.
+    stdcall, importc: "connect", dynlib: ws2dll, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ConvertThreadToFiber(param: pointer): pointer {.stdcall, discardable,
+    dynlib: "kernel32", importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc ConvertThreadToFiberEx(param: pointer; flags: int32): pointer {.stdcall,
+    discardable, dynlib: "kernel32", importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc copyFileW(lpExistingFileName, lpNewFileName: WideCString;
+               bFailIfExists: WINBOOL): WINBOOL {.importc: "CopyFileW", stdcall,
+    dynlib: "kernel32", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createDirectoryW(pathName: WideCString; security: pointer = nil): int32 {.
+    importc: "CreateDirectoryW", dynlib: "kernel32", stdcall, sideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createEvent(lpEventAttributes: ptr SECURITY_ATTRIBUTES;
+                 bManualReset: DWORD; bInitialState: DWORD;
+                 lpName: ptr Utf16Char): Handle {.stdcall, dynlib: "kernel32",
+    importc: "CreateEventW", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc CreateFiber(stackSize: int; fn: LPFIBER_START_ROUTINE; param: pointer): pointer {.
+    stdcall, discardable, dynlib: "kernel32", importc, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc CreateFiberEx(stkCommit: int; stkReserve: int; flags: int32;
+                   fn: LPFIBER_START_ROUTINE; param: pointer): pointer {.
+    stdcall, discardable, dynlib: "kernel32", importc, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createFileA(lpFileName: cstring; dwDesiredAccess, dwShareMode: DWORD;
+                 lpSecurityAttributes: pointer;
+                 dwCreationDisposition, dwFlagsAndAttributes: DWORD;
+                 hTemplateFile: Handle): Handle {.stdcall, dynlib: "kernel32",
+    importc: "CreateFileA", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createFileMappingW(hFile: Handle; lpFileMappingAttributes: pointer;
+                        flProtect, dwMaximumSizeHigh: DWORD;
+                        dwMaximumSizeLow: DWORD; lpName: pointer): Handle {.
+    stdcall, dynlib: "kernel32", importc: "CreateFileMappingW", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createFileW(lpFileName: WideCString; dwDesiredAccess, dwShareMode: DWORD;
+                 lpSecurityAttributes: pointer;
+                 dwCreationDisposition, dwFlagsAndAttributes: DWORD;
+                 hTemplateFile: Handle): Handle {.stdcall, dynlib: "kernel32",
+    importc: "CreateFileW", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createHardLinkW(lpFileName, lpExistingFileName: WideCString;
+                     security: pointer = nil): int32 {.
+    importc: "CreateHardLinkW", dynlib: "kernel32", stdcall, sideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createIoCompletionPort(FileHandle: Handle; ExistingCompletionPort: Handle;
+                            CompletionKey: ULONG_PTR;
+                            NumberOfConcurrentThreads: DWORD): Handle {.stdcall,
+    dynlib: "kernel32", importc: "CreateIoCompletionPort", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createNamedPipe(lpName: WideCString; dwOpenMode, dwPipeMode, nMaxInstances,
+    nOutBufferSize, nInBufferSize, nDefaultTimeOut: int32;
+                     lpSecurityAttributes: ptr SECURITY_ATTRIBUTES): Handle {.
+    stdcall, dynlib: "kernel32", importc: "CreateNamedPipeW", sideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createPipe(hReadPipe, hWritePipe: var Handle;
+                lpPipeAttributes: var SECURITY_ATTRIBUTES; nSize: int32): WINBOOL {.
+    stdcall, dynlib: "kernel32", importc: "CreatePipe", sideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createProcessW(lpApplicationName, lpCommandLine: WideCString;
+                    lpProcessAttributes: ptr SECURITY_ATTRIBUTES;
+                    lpThreadAttributes: ptr SECURITY_ATTRIBUTES;
+                    bInheritHandles: WINBOOL; dwCreationFlags: int32;
+                    lpEnvironment, lpCurrentDirectory: WideCString;
+                    lpStartupInfo: var STARTUPINFO;
+                    lpProcessInformation: var PROCESS_INFORMATION): WINBOOL {.
+    stdcall, dynlib: "kernel32", importc: "CreateProcessW", sideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc createSymbolicLinkW(lpSymlinkFileName, lpTargetFileName: WideCString;
+                         flags: DWORD): int32 {.importc: "CreateSymbolicLinkW",
+    dynlib: "kernel32", stdcall, sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc DeleteFiber(fiber: pointer) {.stdcall, discardable, dynlib: "kernel32",
+                                   importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc deleteFileA(pathName: cstring): int32 {.importc: "DeleteFileA",
+    dynlib: "kernel32", stdcall, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc deleteFileW(pathName: WideCString): int32 {.importc: "DeleteFileW",
+    dynlib: "kernel32", stdcall, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc duplicateHandle(hSourceProcessHandle: Handle; hSourceHandle: Handle;
+                     hTargetProcessHandle: Handle; lpTargetHandle: ptr Handle;
+                     dwDesiredAccess: DWORD; bInheritHandle: WINBOOL;
+                     dwOptions: DWORD): WINBOOL {.stdcall, dynlib: "kernel32",
+    importc: "DuplicateHandle", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc FD_ISSET(socket: SocketHandle; set: var TFdSet): cint {....raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc FD_SET(socket: SocketHandle; s: var TFdSet) {....raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc FD_ZERO(s: var TFdSet) {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc findClose(hFindFile: Handle) {.stdcall, dynlib: "kernel32",
+                                    importc: "FindClose", ...raises: [], tags: [],
+                                    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc findFirstFileW(lpFileName: WideCString; lpFindFileData: var WIN32_FIND_DATA): Handle {.
+    stdcall, dynlib: "kernel32", importc: "FindFirstFileW", sideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc findNextFileW(hFindFile: Handle; lpFindFileData: var WIN32_FIND_DATA): int32 {.
+    stdcall, dynlib: "kernel32", importc: "FindNextFileW", sideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc flushFileBuffers(hFile: Handle): WINBOOL {.stdcall, dynlib: "kernel32",
+    importc: "FlushFileBuffers", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc flushViewOfFile(lpBaseAddress: pointer; dwNumberOfBytesToFlush: DWORD): WINBOOL {.
+    stdcall, dynlib: "kernel32", importc: "FlushViewOfFile", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc formatMessageW(dwFlags: int32; lpSource: pointer;
+                    dwMessageId, dwLanguageId: int32; lpBuffer: pointer;
+                    nSize: int32; arguments: pointer): int32 {.
+    importc: "FormatMessageW", stdcall, dynlib: "kernel32", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc freeAddrInfo(ai: ptr AddrInfo) {.stdcall, importc: "freeaddrinfo",
+                                      dynlib: ws2dll, ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc freeEnvironmentStringsW(para1: WideCString): int32 {.stdcall,
+    dynlib: "kernel32", importc: "FreeEnvironmentStringsW", sideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc freeSid(pSid: PSID): PSID {.stdcall, dynlib: "Advapi32",
+                                 importc: "FreeSid", ...raises: [], tags: [],
+                                 forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc get_osfhandle(fd: FileHandle): Handle {.importc: "_get_osfhandle",
+    header: "<io.h>", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getaddrinfo(nodename, servname: cstring; hints: ptr AddrInfo;
+                 res: var ptr AddrInfo): cint {.stdcall, importc: "getaddrinfo",
+    dynlib: ws2dll, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getCommandLineW(): WideCString {.importc: "GetCommandLineW", stdcall,
+                                      dynlib: "kernel32", sideEffect,
+                                      ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getCurrentDirectoryW(nBufferLength: int32; lpBuffer: WideCString): int32 {.
+    importc: "GetCurrentDirectoryW", dynlib: "kernel32", stdcall, sideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc GetCurrentFiber(): pointer {.stdcall, importc, header: "windows.h",
+                                  ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getCurrentProcess(): Handle {.stdcall, dynlib: "kernel32",
+                                   importc: "GetCurrentProcess", ...raises: [],
+                                   tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getEnvironmentStringsW(): WideCString {.stdcall, dynlib: "kernel32",
+    importc: "GetEnvironmentStringsW", sideEffect, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getExitCodeProcess(hProcess: Handle; lpExitCode: var int32): WINBOOL {.
+    stdcall, dynlib: "kernel32", importc: "GetExitCodeProcess", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getFileAttributesW(lpFileName: WideCString): int32 {.stdcall,
+    dynlib: "kernel32", importc: "GetFileAttributesW", sideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getFileInformationByHandle(hFile: Handle; lpFileInformation: ptr BY_HANDLE_FILE_INFORMATION): WINBOOL {.
+    stdcall, dynlib: "kernel32", importc: "GetFileInformationByHandle",
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getFileSize(hFile: Handle; lpFileSizeHigh: ptr DWORD): DWORD {.stdcall,
+    dynlib: "kernel32", importc: "GetFileSize", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getFullPathNameW(lpFileName: WideCString; nBufferLength: int32;
+                      lpBuffer: WideCString; lpFilePart: var WideCString): int32 {.
+    stdcall, dynlib: "kernel32", importc: "GetFullPathNameW", sideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getHandleInformation(hObject: Handle; lpdwFlags: ptr DWORD): WINBOOL {.
+    stdcall, dynlib: "kernel32", importc: "GetHandleInformation", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc gethostbyaddr(ip: ptr InAddr; len: cuint; theType: cint): ptr Hostent {.
+    stdcall, importc: "gethostbyaddr", dynlib: ws2dll, sideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc gethostbyname(name: cstring): ptr Hostent {.stdcall,
+    importc: "gethostbyname", dynlib: ws2dll, sideEffect, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc gethostname(hostname: cstring; len: cint): cint {.stdcall,
+    importc: "gethostname", dynlib: ws2dll, sideEffect, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getLastError(): int32 {.importc: "GetLastError", stdcall,
+                             dynlib: "kernel32", sideEffect, ...raises: [],
+                             tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getModuleFileNameW(handle: Handle; buf: WideCString; size: int32): int32 {.
+    importc: "GetModuleFileNameW", dynlib: "kernel32", stdcall, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getnameinfo(a1: ptr SockAddr; a2: SockLen; a3: cstring; a4: SockLen;
+                 a5: cstring; a6: SockLen; a7: cint): cint {.stdcall,
+    importc: "getnameinfo", dynlib: ws2dll, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getOverlappedResult(hFile: Handle; lpOverlapped: POVERLAPPED;
+                         lpNumberOfBytesTransferred: var DWORD; bWait: WINBOOL): WINBOOL {.
+    stdcall, dynlib: "kernel32", importc: "GetOverlappedResult", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getpeername(s: SocketHandle; name: ptr SockAddr; namelen: ptr SockLen): cint {.
+    stdcall, importc, dynlib: ws2dll, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getProcessTimes(hProcess: Handle; lpCreationTime, lpExitTime, lpKernelTime,
+                                       lpUserTime: var FILETIME): WINBOOL {.
+    stdcall, dynlib: "kernel32", importc: "GetProcessTimes", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getprotobyname(name: cstring): ptr Protoent {.stdcall,
+    importc: "getprotobyname", dynlib: ws2dll, sideEffect, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getprotobynumber(proto: cint): ptr Protoent {.stdcall,
+    importc: "getprotobynumber", dynlib: ws2dll, sideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getQueuedCompletionStatus(CompletionPort: Handle;
+                               lpNumberOfBytesTransferred: PDWORD;
+                               lpCompletionKey: PULONG_PTR;
+                               lpOverlapped: ptr POVERLAPPED;
+                               dwMilliseconds: DWORD): WINBOOL {.stdcall,
+    dynlib: "kernel32", importc: "GetQueuedCompletionStatus", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getservbyname(name, proto: cstring): ptr Servent {.stdcall,
+    importc: "getservbyname", dynlib: ws2dll, sideEffect, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getservbyport(port: cint; proto: cstring): ptr Servent {.stdcall,
+    importc: "getservbyport", dynlib: ws2dll, sideEffect, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getsockname(s: SocketHandle; name: ptr SockAddr; namelen: ptr SockLen): cint {.
+    stdcall, importc: "getsockname", dynlib: ws2dll, ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getsockopt(s: SocketHandle; level, optname: cint; optval: pointer;
+                optlen: ptr SockLen): cint {.stdcall, importc: "getsockopt",
+    dynlib: ws2dll, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getStdHandle(nStdHandle: int32): Handle {.stdcall, dynlib: "kernel32",
+    importc: "GetStdHandle", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getSystemTimeAsFileTime(lpSystemTimeAsFileTime: var FILETIME) {.
+    importc: "GetSystemTimeAsFileTime", dynlib: "kernel32", stdcall, sideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getSystemTimePreciseAsFileTime(lpSystemTimeAsFileTime: var FILETIME) {.
+    importc: "GetSystemTimePreciseAsFileTime", dynlib: "kernel32", stdcall,
+    sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getSystemTimes(lpIdleTime, lpKernelTime, lpUserTime: var FILETIME): WINBOOL {.
+    stdcall, dynlib: "kernel32", importc: "GetSystemTimes", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getVersion(): DWORD {.stdcall, dynlib: "kernel32", importc: "GetVersion",
+                           sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getVersionExA(lpVersionInfo: ptr OSVERSIONINFO): WINBOOL {.stdcall,
+    dynlib: "kernel32", importc: "GetVersionExA", sideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc getVersionExW(lpVersionInfo: ptr OSVERSIONINFO): WINBOOL {.stdcall,
+    dynlib: "kernel32", importc: "GetVersionExW", sideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inet_addr(cp: cstring): uint32 {.stdcall, importc: "inet_addr",
+                                      dynlib: ws2dll, ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inet_ntoa(i: InAddr): cstring {.stdcall, importc, dynlib: ws2dll,
+                                     ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc inet_ntop(family: cint; paddr: pointer; pStringBuffer: cstring;
+               stringBufSize: int32): cstring {.stdcall, ...raises: [Exception],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc isSuccess(a: WINBOOL): bool {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Returns true if a != 0. Windows uses a different convention than POSIX, where a == 0 is commonly used on success. + Source   +Edit   + +
+
+ +
+
+
+
proc listen(s: SocketHandle; backlog: cint): cint {.stdcall, importc: "listen",
+    dynlib: ws2dll, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc localFree(p: pointer) {.importc: "LocalFree", stdcall, dynlib: "kernel32",
+                             ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc mapViewOfFileEx(hFileMappingObject: Handle; dwDesiredAccess: DWORD;
+                     dwFileOffsetHigh, dwFileOffsetLow: DWORD;
+                     dwNumberOfBytesToMap: WinSizeT; lpBaseAddress: pointer): pointer {.
+    stdcall, dynlib: "kernel32", importc: "MapViewOfFileEx", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc moveFileExW(lpExistingFileName, lpNewFileName: WideCString; flags: DWORD): WINBOOL {.
+    importc: "MoveFileExW", stdcall, dynlib: "kernel32", sideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc moveFileW(lpExistingFileName, lpNewFileName: WideCString): WINBOOL {.
+    importc: "MoveFileW", stdcall, dynlib: "kernel32", sideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc openProcess(dwDesiredAccess: DWORD; bInheritHandle: WINBOOL;
+                 dwProcessId: DWORD): Handle {.stdcall, dynlib: "kernel32",
+    importc: "OpenProcess", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc peekNamedPipe(hNamedPipe: Handle; lpBuffer: pointer = nil;
+                   nBufferSize: int32 = 0; lpBytesRead: ptr int32 = nil;
+                   lpTotalBytesAvail: ptr int32 = nil;
+                   lpBytesLeftThisMessage: ptr int32 = nil): bool {.stdcall,
+    dynlib: "kernel32", importc: "PeekNamedPipe", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc postQueuedCompletionStatus(CompletionPort: Handle;
+                                dwNumberOfBytesTransferred: DWORD;
+                                dwCompletionKey: ULONG_PTR;
+                                lpOverlapped: pointer): bool {.stdcall,
+    dynlib: "kernel32", importc: "PostQueuedCompletionStatus", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rdFileSize(f: WIN32_FIND_DATA): int64 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc rdFileTime(f: FILETIME): int64 {....raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc readConsoleInput(hConsoleInput: Handle; lpBuffer: pointer; nLength: cint;
+                      lpNumberOfEventsRead: ptr cint): cint {.stdcall,
+    dynlib: "kernel32", importc: "ReadConsoleInputW", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc readFile(hFile: Handle; buffer: pointer; nNumberOfBytesToRead: int32;
+              lpNumberOfBytesRead: ptr int32; lpOverlapped: pointer): WINBOOL {.
+    stdcall, dynlib: "kernel32", importc: "ReadFile", sideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc recv(s: SocketHandle; buf: pointer; len, flags: cint): cint {.stdcall,
+    importc: "recv", dynlib: ws2dll, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc recvfrom(s: SocketHandle; buf: cstring; len, flags: cint;
+              fromm: ptr SockAddr; fromlen: ptr SockLen): cint {.stdcall,
+    importc: "recvfrom", dynlib: ws2dll, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc registerWaitForSingleObject(phNewWaitObject: ptr Handle; hObject: Handle;
+                                 Callback: WAITORTIMERCALLBACK;
+                                 Context: pointer; dwMilliseconds: ULONG;
+                                 dwFlags: ULONG): bool {.stdcall,
+    dynlib: "kernel32", importc: "RegisterWaitForSingleObject", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc removeDirectoryW(lpPathName: WideCString): int32 {.
+    importc: "RemoveDirectoryW", dynlib: "kernel32", stdcall, sideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc resumeThread(hThread: Handle): int32 {.stdcall, dynlib: "kernel32",
+    importc: "ResumeThread", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc select(nfds: cint; readfds, writefds, exceptfds: ptr TFdSet;
+            timeout: ptr Timeval): cint {.stdcall, importc: "select",
+    dynlib: ws2dll, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc send(s: SocketHandle; buf: pointer; len, flags: cint): cint {.stdcall,
+    importc: "send", dynlib: ws2dll, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sendto(s: SocketHandle; buf: pointer; len, flags: cint; to: ptr SockAddr;
+            tolen: SockLen): cint {.stdcall, importc: "sendto", dynlib: ws2dll,
+                                    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setCurrentDirectoryW(lpPathName: WideCString): int32 {.
+    importc: "SetCurrentDirectoryW", dynlib: "kernel32", stdcall, sideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setEndOfFile(hFile: Handle): WINBOOL {.stdcall, dynlib: "kernel32",
+    importc: "SetEndOfFile", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setEnvironmentVariableW(lpName, lpValue: WideCString): int32 {.stdcall,
+    dynlib: "kernel32", importc: "SetEnvironmentVariableW", sideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setEvent(hEvent: Handle): cint {.stdcall, dynlib: "kernel32",
+                                      importc: "SetEvent", ...raises: [], tags: [],
+                                      forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setFileAttributesW(lpFileName: WideCString; dwFileAttributes: int32): WINBOOL {.
+    stdcall, dynlib: "kernel32", importc: "SetFileAttributesW", sideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setFilePointer(hFile: Handle; lDistanceToMove: LONG;
+                    lpDistanceToMoveHigh: ptr LONG; dwMoveMethod: DWORD): DWORD {.
+    stdcall, dynlib: "kernel32", importc: "SetFilePointer", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setFileTime(hFile: Handle; lpCreationTime: LPFILETIME;
+                 lpLastAccessTime: LPFILETIME; lpLastWriteTime: LPFILETIME): WINBOOL {.
+    stdcall, dynlib: "kernel32", importc: "SetFileTime", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setHandleInformation(hObject: Handle; dwMask: DWORD; dwFlags: DWORD): WINBOOL {.
+    stdcall, dynlib: "kernel32", importc: "SetHandleInformation", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setLastError(error: int32) {.importc: "SetLastError", stdcall,
+                                  dynlib: "kernel32", sideEffect, ...raises: [],
+                                  tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setsockopt(s: SocketHandle; level, optname: cint; optval: pointer;
+                optlen: SockLen): cint {.stdcall, importc: "setsockopt",
+    dynlib: ws2dll, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc setStdHandle(nStdHandle: int32; hHandle: Handle): WINBOOL {.stdcall,
+    dynlib: "kernel32", importc: "SetStdHandle", sideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc shellExecuteW(hwnd: Handle;
+                   lpOperation, lpFile, lpParameters, lpDirectory: WideCString;
+                   nShowCmd: int32): Handle {.stdcall, dynlib: "shell32.dll",
+    importc: "ShellExecuteW", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc shutdown(s: SocketHandle; how: cint): cint {.stdcall, importc: "shutdown",
+    dynlib: ws2dll, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc sleep(dwMilliseconds: int32) {.stdcall, dynlib: "kernel32",
+                                    importc: "Sleep", sideEffect, ...raises: [],
+                                    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc socket(af, typ, protocol: cint): SocketHandle {.stdcall, importc: "socket",
+    dynlib: ws2dll, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc suspendThread(hThread: Handle): int32 {.stdcall, dynlib: "kernel32",
+    importc: "SuspendThread", sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc SwitchToFiber(fiber: pointer) {.stdcall, discardable, dynlib: "kernel32",
+                                     importc, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc terminateProcess(hProcess: Handle; uExitCode: int): WINBOOL {.stdcall,
+    dynlib: "kernel32", importc: "TerminateProcess", sideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc toFILETIME(t: int64): FILETIME {....raises: [], tags: [], forbids: [].}
+
+ + Convert the Windows file time timestamp t to FILETIME. + Source   +Edit   + +
+
+ +
+
+
+
proc unmapViewOfFile(lpBaseAddress: pointer): WINBOOL {.stdcall,
+    dynlib: "kernel32", importc: "UnmapViewOfFile", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc unregisterWait(WaitHandle: Handle): DWORD {.stdcall, dynlib: "kernel32",
+    importc: "UnregisterWait", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc waitForMultipleObjects(nCount: DWORD; lpHandles: PWOHandleArray;
+                            bWaitAll: WINBOOL; dwMilliseconds: DWORD): DWORD {.
+    stdcall, dynlib: "kernel32", importc: "WaitForMultipleObjects", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc waitForSingleObject(hHandle: Handle; dwMilliseconds: int32): int32 {.
+    stdcall, dynlib: "kernel32", importc: "WaitForSingleObject", sideEffect,
+    ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc writeFile(hFile: Handle; buffer: pointer; nNumberOfBytesToWrite: int32;
+               lpNumberOfBytesWritten: ptr int32; lpOverlapped: pointer): WINBOOL {.
+    stdcall, dynlib: "kernel32", importc: "WriteFile", sideEffect, ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc wsaCloseEvent(hEvent: Handle): bool {.stdcall, importc: "WSACloseEvent",
+    dynlib: "ws2_32.dll", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc wsaCreateEvent(): Handle {.stdcall, importc: "WSACreateEvent",
+                                dynlib: "ws2_32.dll", ...raises: [], tags: [],
+                                forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc wsaEventSelect(s: SocketHandle; hEventObject: Handle; lNetworkEvents: clong): cint {.
+    stdcall, importc: "WSAEventSelect", dynlib: "ws2_32.dll", ...raises: [],
+    tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc wsaGetLastError(): cint {.importc: "WSAGetLastError", dynlib: ws2dll,
+                               sideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc WSAIoctl(s: SocketHandle; dwIoControlCode: DWORD; lpvInBuffer: pointer;
+              cbInBuffer: DWORD; lpvOutBuffer: pointer; cbOutBuffer: DWORD;
+              lpcbBytesReturned: PDWORD; lpOverlapped: POVERLAPPED;
+              lpCompletionRoutine: POVERLAPPED_COMPLETION_ROUTINE): cint {.
+    stdcall, importc: "WSAIoctl", dynlib: "Ws2_32.dll", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc WSARecv(s: SocketHandle; buf: ptr TWSABuf; bufCount: DWORD;
+             bytesReceived, flags: PDWORD; lpOverlapped: POVERLAPPED;
+             completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {.stdcall,
+    importc: "WSARecv", dynlib: "Ws2_32.dll", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc WSARecvFrom(s: SocketHandle; buf: ptr TWSABuf; bufCount: DWORD;
+                 bytesReceived: PDWORD; flags: PDWORD; name: ptr SockAddr;
+                 namelen: ptr cint; lpOverlapped: POVERLAPPED;
+                 completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {.
+    stdcall, importc: "WSARecvFrom", dynlib: "Ws2_32.dll", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc wsaResetEvent(hEvent: Handle): bool {.stdcall, importc: "WSAResetEvent",
+    dynlib: "ws2_32.dll", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc WSASend(s: SocketHandle; buf: ptr TWSABuf; bufCount: DWORD;
+             bytesSent: PDWORD; flags: DWORD; lpOverlapped: POVERLAPPED;
+             completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {.stdcall,
+    importc: "WSASend", dynlib: "Ws2_32.dll", ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc WSASendTo(s: SocketHandle; buf: ptr TWSABuf; bufCount: DWORD;
+               bytesSent: PDWORD; flags: DWORD; name: ptr SockAddr;
+               namelen: cint; lpOverlapped: POVERLAPPED;
+               completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {.stdcall,
+    importc: "WSASendTo", dynlib: "Ws2_32.dll", ...raises: [], tags: [],
+    forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
proc wsaStartup(wVersionRequired: int16; WSData: ptr WSAData): cint {.stdcall,
+    importc: "WSAStartup", dynlib: ws2dll, ...raises: [], tags: [], forbids: [].}
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template hasOverlappedIoCompleted(lpOverlapped): bool
+
+ + + Source   +Edit   + +
+
+ +
+
+
+
template WSAIORW(x, y): untyped
+
+ + + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/winlean.idx b/winlean.idx new file mode 100644 index 0000000000000..ca40a14ee435d --- /dev/null +++ b/winlean.idx @@ -0,0 +1,375 @@ +nimTitle winlean winlean.html module std/winlean 0 +nim WinChar winlean.html#WinChar type WinChar 24 +nim Handle winlean.html#Handle type Handle 28 +nim LONG winlean.html#LONG type LONG 29 +nim ULONG winlean.html#ULONG type ULONG 30 +nim PULONG winlean.html#PULONG type PULONG 31 +nim WINBOOL winlean.html#WINBOOL type WINBOOL 32 +nim PBOOL winlean.html#PBOOL type PBOOL 35 +nim DWORD winlean.html#DWORD type DWORD 36 +nim PDWORD winlean.html#PDWORD type PDWORD 37 +nim LPINT winlean.html#LPINT type LPINT 38 +nim ULONG_PTR winlean.html#ULONG_PTR type ULONG_PTR 39 +nim PULONG_PTR winlean.html#PULONG_PTR type PULONG_PTR 40 +nim HDC winlean.html#HDC type HDC 41 +nim HGLRC winlean.html#HGLRC type HGLRC 42 +nim BYTE winlean.html#BYTE type BYTE 43 +nim SECURITY_ATTRIBUTES winlean.html#SECURITY_ATTRIBUTES object SECURITY_ATTRIBUTES 45 +nim STARTUPINFO winlean.html#STARTUPINFO object STARTUPINFO 50 +nim PROCESS_INFORMATION winlean.html#PROCESS_INFORMATION object PROCESS_INFORMATION 70 +nim FILETIME winlean.html#FILETIME object FILETIME 76 +nim BY_HANDLE_FILE_INFORMATION winlean.html#BY_HANDLE_FILE_INFORMATION object BY_HANDLE_FILE_INFORMATION 80 +nim OSVERSIONINFO winlean.html#OSVERSIONINFO object OSVERSIONINFO 92 +nim Protoent winlean.html#Protoent object Protoent 100 +nim STARTF_USESHOWWINDOW winlean.html#STARTF_USESHOWWINDOW const STARTF_USESHOWWINDOW 107 +nim STARTF_USESTDHANDLES winlean.html#STARTF_USESTDHANDLES const STARTF_USESTDHANDLES 108 +nim HIGH_PRIORITY_CLASS winlean.html#HIGH_PRIORITY_CLASS const HIGH_PRIORITY_CLASS 109 +nim IDLE_PRIORITY_CLASS winlean.html#IDLE_PRIORITY_CLASS const IDLE_PRIORITY_CLASS 110 +nim NORMAL_PRIORITY_CLASS winlean.html#NORMAL_PRIORITY_CLASS const NORMAL_PRIORITY_CLASS 111 +nim REALTIME_PRIORITY_CLASS winlean.html#REALTIME_PRIORITY_CLASS const REALTIME_PRIORITY_CLASS 112 +nim WAIT_OBJECT_0 winlean.html#WAIT_OBJECT_0 const WAIT_OBJECT_0 113 +nim WAIT_TIMEOUT winlean.html#WAIT_TIMEOUT const WAIT_TIMEOUT 114 +nim WAIT_FAILED winlean.html#WAIT_FAILED const WAIT_FAILED 115 +nim INFINITE winlean.html#INFINITE const INFINITE 116 +nim STILL_ACTIVE winlean.html#STILL_ACTIVE const STILL_ACTIVE 117 +nim STD_INPUT_HANDLE winlean.html#STD_INPUT_HANDLE const STD_INPUT_HANDLE 119 +nim STD_OUTPUT_HANDLE winlean.html#STD_OUTPUT_HANDLE const STD_OUTPUT_HANDLE 120 +nim STD_ERROR_HANDLE winlean.html#STD_ERROR_HANDLE const STD_ERROR_HANDLE 121 +nim DETACHED_PROCESS winlean.html#DETACHED_PROCESS const DETACHED_PROCESS 123 +nim SW_SHOWNORMAL winlean.html#SW_SHOWNORMAL const SW_SHOWNORMAL 125 +nim INVALID_HANDLE_VALUE winlean.html#INVALID_HANDLE_VALUE const INVALID_HANDLE_VALUE 126 +nim CREATE_UNICODE_ENVIRONMENT winlean.html#CREATE_UNICODE_ENVIRONMENT const CREATE_UNICODE_ENVIRONMENT 128 +nim PIPE_ACCESS_DUPLEX winlean.html#PIPE_ACCESS_DUPLEX const PIPE_ACCESS_DUPLEX 130 +nim PIPE_ACCESS_INBOUND winlean.html#PIPE_ACCESS_INBOUND const PIPE_ACCESS_INBOUND 131 +nim PIPE_ACCESS_OUTBOUND winlean.html#PIPE_ACCESS_OUTBOUND const PIPE_ACCESS_OUTBOUND 132 +nim PIPE_NOWAIT winlean.html#PIPE_NOWAIT const PIPE_NOWAIT 133 +nim SYNCHRONIZE winlean.html#SYNCHRONIZE const SYNCHRONIZE 134 +nim CREATE_NO_WINDOW winlean.html#CREATE_NO_WINDOW const CREATE_NO_WINDOW 136 +nim HANDLE_FLAG_INHERIT winlean.html#HANDLE_FLAG_INHERIT const HANDLE_FLAG_INHERIT 138 +nim isSuccess winlean.html#isSuccess,WINBOOL proc isSuccess(a: WINBOOL): bool 140 +nim getVersionExW winlean.html#getVersionExW,ptr.OSVERSIONINFO proc getVersionExW(lpVersionInfo: ptr OSVERSIONINFO): WINBOOL 144 +nim getVersionExA winlean.html#getVersionExA,ptr.OSVERSIONINFO proc getVersionExA(lpVersionInfo: ptr OSVERSIONINFO): WINBOOL 146 +nim getVersion winlean.html#getVersion proc getVersion(): DWORD 149 +nim closeHandle winlean.html#closeHandle,Handle proc closeHandle(hObject: Handle): WINBOOL 151 +nim readFile winlean.html#readFile,Handle,pointer,int32,ptr.int32,pointer proc readFile(hFile: Handle; buffer: pointer; nNumberOfBytesToRead: int32;\n lpNumberOfBytesRead: ptr int32; lpOverlapped: pointer): WINBOOL 154 +nim writeFile winlean.html#writeFile,Handle,pointer,int32,ptr.int32,pointer proc writeFile(hFile: Handle; buffer: pointer; nNumberOfBytesToWrite: int32;\n lpNumberOfBytesWritten: ptr int32; lpOverlapped: pointer): WINBOOL 158 +nim createPipe winlean.html#createPipe,Handle,Handle,SECURITY_ATTRIBUTES,int32 proc createPipe(hReadPipe, hWritePipe: var Handle;\n lpPipeAttributes: var SECURITY_ATTRIBUTES; nSize: int32): WINBOOL 163 +nim createNamedPipe winlean.html#createNamedPipe,WideCString,int32,int32,int32,int32,int32,int32,ptr.SECURITY_ATTRIBUTES proc createNamedPipe(lpName: WideCString; dwOpenMode, dwPipeMode, nMaxInstances,\n nOutBufferSize, nInBufferSize,\n nDefaultTimeOut: int32;\n lpSecurityAttributes: ptr SECURITY_ATTRIBUTES): Handle 168 +nim peekNamedPipe winlean.html#peekNamedPipe,Handle,pointer,int32,ptr.int32,ptr.int32,ptr.int32 proc peekNamedPipe(hNamedPipe: Handle; lpBuffer: pointer = nil;\n nBufferSize: int32 = 0; lpBytesRead: ptr int32 = nil;\n lpTotalBytesAvail: ptr int32 = nil;\n lpBytesLeftThisMessage: ptr int32 = nil): bool 174 +nim createProcessW winlean.html#createProcessW,WideCString,WideCString,ptr.SECURITY_ATTRIBUTES,ptr.SECURITY_ATTRIBUTES,WINBOOL,int32,WideCString,WideCString,STARTUPINFO,PROCESS_INFORMATION proc createProcessW(lpApplicationName, lpCommandLine: WideCString;\n lpProcessAttributes: ptr SECURITY_ATTRIBUTES;\n lpThreadAttributes: ptr SECURITY_ATTRIBUTES;\n bInheritHandles: WINBOOL; dwCreationFlags: int32;\n lpEnvironment, lpCurrentDirectory: WideCString;\n lpStartupInfo: var STARTUPINFO;\n lpProcessInformation: var PROCESS_INFORMATION): WINBOOL 181 +nim suspendThread winlean.html#suspendThread,Handle proc suspendThread(hThread: Handle): int32 190 +nim resumeThread winlean.html#resumeThread,Handle proc resumeThread(hThread: Handle): int32 192 +nim waitForSingleObject winlean.html#waitForSingleObject,Handle,int32 proc waitForSingleObject(hHandle: Handle; dwMilliseconds: int32): int32 195 +nim terminateProcess winlean.html#terminateProcess,Handle,int proc terminateProcess(hProcess: Handle; uExitCode: int): WINBOOL 198 +nim getExitCodeProcess winlean.html#getExitCodeProcess,Handle,int32 proc getExitCodeProcess(hProcess: Handle; lpExitCode: var int32): WINBOOL 201 +nim getStdHandle winlean.html#getStdHandle,int32 proc getStdHandle(nStdHandle: int32): Handle 204 +nim setStdHandle winlean.html#setStdHandle,int32,Handle proc setStdHandle(nStdHandle: int32; hHandle: Handle): WINBOOL 206 +nim flushFileBuffers winlean.html#flushFileBuffers,Handle proc flushFileBuffers(hFile: Handle): WINBOOL 208 +nim getLastError winlean.html#getLastError proc getLastError(): int32 211 +nim setLastError winlean.html#setLastError,int32 proc setLastError(error: int32) 214 +nim formatMessageW winlean.html#formatMessageW,int32,pointer,int32,int32,pointer,int32,pointer proc formatMessageW(dwFlags: int32; lpSource: pointer;\n dwMessageId, dwLanguageId: int32; lpBuffer: pointer;\n nSize: int32; arguments: pointer): int32 217 +nim localFree winlean.html#localFree,pointer proc localFree(p: pointer) 223 +nim getCurrentDirectoryW winlean.html#getCurrentDirectoryW,int32,WideCString proc getCurrentDirectoryW(nBufferLength: int32; lpBuffer: WideCString): int32 226 +nim setCurrentDirectoryW winlean.html#setCurrentDirectoryW,WideCString proc setCurrentDirectoryW(lpPathName: WideCString): int32 229 +nim createDirectoryW winlean.html#createDirectoryW,WideCString,pointer proc createDirectoryW(pathName: WideCString; security: pointer = nil): int32 231 +nim removeDirectoryW winlean.html#removeDirectoryW,WideCString proc removeDirectoryW(lpPathName: WideCString): int32 233 +nim setEnvironmentVariableW winlean.html#setEnvironmentVariableW,WideCString,WideCString proc setEnvironmentVariableW(lpName, lpValue: WideCString): int32 235 +nim getModuleFileNameW winlean.html#getModuleFileNameW,Handle,WideCString,int32 proc getModuleFileNameW(handle: Handle; buf: WideCString; size: int32): int32 238 +nim createSymbolicLinkW winlean.html#createSymbolicLinkW,WideCString,WideCString,DWORD proc createSymbolicLinkW(lpSymlinkFileName, lpTargetFileName: WideCString;\n flags: DWORD): int32 242 +nim createHardLinkW winlean.html#createHardLinkW,WideCString,WideCString,pointer proc createHardLinkW(lpFileName, lpExistingFileName: WideCString;\n security: pointer = nil): int32 245 +nim FILE_ATTRIBUTE_READONLY winlean.html#FILE_ATTRIBUTE_READONLY const FILE_ATTRIBUTE_READONLY 250 +nim FILE_ATTRIBUTE_HIDDEN winlean.html#FILE_ATTRIBUTE_HIDDEN const FILE_ATTRIBUTE_HIDDEN 251 +nim FILE_ATTRIBUTE_SYSTEM winlean.html#FILE_ATTRIBUTE_SYSTEM const FILE_ATTRIBUTE_SYSTEM 252 +nim FILE_ATTRIBUTE_DIRECTORY winlean.html#FILE_ATTRIBUTE_DIRECTORY const FILE_ATTRIBUTE_DIRECTORY 253 +nim FILE_ATTRIBUTE_ARCHIVE winlean.html#FILE_ATTRIBUTE_ARCHIVE const FILE_ATTRIBUTE_ARCHIVE 254 +nim FILE_ATTRIBUTE_DEVICE winlean.html#FILE_ATTRIBUTE_DEVICE const FILE_ATTRIBUTE_DEVICE 255 +nim FILE_ATTRIBUTE_NORMAL winlean.html#FILE_ATTRIBUTE_NORMAL const FILE_ATTRIBUTE_NORMAL 256 +nim FILE_ATTRIBUTE_TEMPORARY winlean.html#FILE_ATTRIBUTE_TEMPORARY const FILE_ATTRIBUTE_TEMPORARY 257 +nim FILE_ATTRIBUTE_SPARSE_FILE winlean.html#FILE_ATTRIBUTE_SPARSE_FILE const FILE_ATTRIBUTE_SPARSE_FILE 258 +nim FILE_ATTRIBUTE_REPARSE_POINT winlean.html#FILE_ATTRIBUTE_REPARSE_POINT const FILE_ATTRIBUTE_REPARSE_POINT 259 +nim FILE_ATTRIBUTE_COMPRESSED winlean.html#FILE_ATTRIBUTE_COMPRESSED const FILE_ATTRIBUTE_COMPRESSED 260 +nim FILE_ATTRIBUTE_OFFLINE winlean.html#FILE_ATTRIBUTE_OFFLINE const FILE_ATTRIBUTE_OFFLINE 261 +nim FILE_ATTRIBUTE_NOT_CONTENT_INDEXED winlean.html#FILE_ATTRIBUTE_NOT_CONTENT_INDEXED const FILE_ATTRIBUTE_NOT_CONTENT_INDEXED 262 +nim FILE_FLAG_FIRST_PIPE_INSTANCE winlean.html#FILE_FLAG_FIRST_PIPE_INSTANCE const FILE_FLAG_FIRST_PIPE_INSTANCE 264 +nim FILE_FLAG_OPEN_NO_RECALL winlean.html#FILE_FLAG_OPEN_NO_RECALL const FILE_FLAG_OPEN_NO_RECALL 265 +nim FILE_FLAG_OPEN_REPARSE_POINT winlean.html#FILE_FLAG_OPEN_REPARSE_POINT const FILE_FLAG_OPEN_REPARSE_POINT 266 +nim FILE_FLAG_POSIX_SEMANTICS winlean.html#FILE_FLAG_POSIX_SEMANTICS const FILE_FLAG_POSIX_SEMANTICS 267 +nim FILE_FLAG_BACKUP_SEMANTICS winlean.html#FILE_FLAG_BACKUP_SEMANTICS const FILE_FLAG_BACKUP_SEMANTICS 268 +nim FILE_FLAG_DELETE_ON_CLOSE winlean.html#FILE_FLAG_DELETE_ON_CLOSE const FILE_FLAG_DELETE_ON_CLOSE 269 +nim FILE_FLAG_SEQUENTIAL_SCAN winlean.html#FILE_FLAG_SEQUENTIAL_SCAN const FILE_FLAG_SEQUENTIAL_SCAN 270 +nim FILE_FLAG_RANDOM_ACCESS winlean.html#FILE_FLAG_RANDOM_ACCESS const FILE_FLAG_RANDOM_ACCESS 271 +nim FILE_FLAG_NO_BUFFERING winlean.html#FILE_FLAG_NO_BUFFERING const FILE_FLAG_NO_BUFFERING 272 +nim FILE_FLAG_OVERLAPPED winlean.html#FILE_FLAG_OVERLAPPED const FILE_FLAG_OVERLAPPED 273 +nim FILE_FLAG_WRITE_THROUGH winlean.html#FILE_FLAG_WRITE_THROUGH const FILE_FLAG_WRITE_THROUGH 274 +nim MAX_PATH winlean.html#MAX_PATH const MAX_PATH 276 +nim MOVEFILE_COPY_ALLOWED winlean.html#MOVEFILE_COPY_ALLOWED const MOVEFILE_COPY_ALLOWED 278 +nim MOVEFILE_CREATE_HARDLINK winlean.html#MOVEFILE_CREATE_HARDLINK const MOVEFILE_CREATE_HARDLINK 279 +nim MOVEFILE_DELAY_UNTIL_REBOOT winlean.html#MOVEFILE_DELAY_UNTIL_REBOOT const MOVEFILE_DELAY_UNTIL_REBOOT 280 +nim MOVEFILE_FAIL_IF_NOT_TRACKABLE winlean.html#MOVEFILE_FAIL_IF_NOT_TRACKABLE const MOVEFILE_FAIL_IF_NOT_TRACKABLE 281 +nim MOVEFILE_REPLACE_EXISTING winlean.html#MOVEFILE_REPLACE_EXISTING const MOVEFILE_REPLACE_EXISTING 282 +nim MOVEFILE_WRITE_THROUGH winlean.html#MOVEFILE_WRITE_THROUGH const MOVEFILE_WRITE_THROUGH 283 +nim WIN32_FIND_DATA winlean.html#WIN32_FIND_DATA object WIN32_FIND_DATA 286 +nim findFirstFileW winlean.html#findFirstFileW,WideCString,WIN32_FIND_DATA proc findFirstFileW(lpFileName: WideCString; lpFindFileData: var WIN32_FIND_DATA): Handle 298 +nim findNextFileW winlean.html#findNextFileW,Handle,WIN32_FIND_DATA proc findNextFileW(hFindFile: Handle; lpFindFileData: var WIN32_FIND_DATA): int32 301 +nim findClose winlean.html#findClose,Handle proc findClose(hFindFile: Handle) 305 +nim getFullPathNameW winlean.html#getFullPathNameW,WideCString,int32,WideCString,WideCString proc getFullPathNameW(lpFileName: WideCString; nBufferLength: int32;\n lpBuffer: WideCString; lpFilePart: var WideCString): int32 308 +nim getFileAttributesW winlean.html#getFileAttributesW,WideCString proc getFileAttributesW(lpFileName: WideCString): int32 313 +nim setFileAttributesW winlean.html#setFileAttributesW,WideCString,int32 proc setFileAttributesW(lpFileName: WideCString; dwFileAttributes: int32): WINBOOL 316 +nim copyFileW winlean.html#copyFileW,WideCString,WideCString,WINBOOL proc copyFileW(lpExistingFileName, lpNewFileName: WideCString; bFailIfExists: WINBOOL): WINBOOL 320 +nim moveFileW winlean.html#moveFileW,WideCString,WideCString proc moveFileW(lpExistingFileName, lpNewFileName: WideCString): WINBOOL 324 +nim moveFileExW winlean.html#moveFileExW,WideCString,WideCString,DWORD proc moveFileExW(lpExistingFileName, lpNewFileName: WideCString; flags: DWORD): WINBOOL 326 +nim getEnvironmentStringsW winlean.html#getEnvironmentStringsW proc getEnvironmentStringsW(): WideCString 330 +nim freeEnvironmentStringsW winlean.html#freeEnvironmentStringsW,WideCString proc freeEnvironmentStringsW(para1: WideCString): int32 332 +nim getCommandLineW winlean.html#getCommandLineW proc getCommandLineW(): WideCString 335 +nim rdFileTime winlean.html#rdFileTime,FILETIME proc rdFileTime(f: FILETIME): int64 338 +nim rdFileSize winlean.html#rdFileSize,WIN32_FIND_DATA proc rdFileSize(f: WIN32_FIND_DATA): int64 341 +nim getSystemTimeAsFileTime winlean.html#getSystemTimeAsFileTime,FILETIME proc getSystemTimeAsFileTime(lpSystemTimeAsFileTime: var FILETIME) 344 +nim sleep winlean.html#sleep,int32 proc sleep(dwMilliseconds: int32) 347 +nim shellExecuteW winlean.html#shellExecuteW,Handle,WideCString,WideCString,WideCString,WideCString,int32 proc shellExecuteW(hwnd: Handle;\n lpOperation, lpFile, lpParameters, lpDirectory: WideCString;\n nShowCmd: int32): Handle 350 +nim getFileInformationByHandle winlean.html#getFileInformationByHandle,Handle,ptr.BY_HANDLE_FILE_INFORMATION proc getFileInformationByHandle(hFile: Handle;\n lpFileInformation: ptr BY_HANDLE_FILE_INFORMATION): WINBOOL 355 +nim WSADESCRIPTION_LEN winlean.html#WSADESCRIPTION_LEN const WSADESCRIPTION_LEN 360 +nim WSASYS_STATUS_LEN winlean.html#WSASYS_STATUS_LEN const WSASYS_STATUS_LEN 361 +nim FD_SETSIZE winlean.html#FD_SETSIZE const FD_SETSIZE 362 +nim MSG_PEEK winlean.html#MSG_PEEK const MSG_PEEK 363 +nim INADDR_ANY winlean.html#INADDR_ANY const INADDR_ANY 365 +nim INADDR_LOOPBACK winlean.html#INADDR_LOOPBACK const INADDR_LOOPBACK 366 +nim INADDR_BROADCAST winlean.html#INADDR_BROADCAST const INADDR_BROADCAST 367 +nim INADDR_NONE winlean.html#INADDR_NONE const INADDR_NONE 368 +nim wsaGetLastError winlean.html#wsaGetLastError proc wsaGetLastError(): cint 372 +nim SocketHandle winlean.html#SocketHandle type SocketHandle 375 +nim WSAData winlean.html#WSAData object WSAData 378 +nim SockAddr winlean.html#SockAddr object SockAddr 385 +nim InAddr winlean.html#InAddr object InAddr 391 +nim Sockaddr_in winlean.html#Sockaddr_in object Sockaddr_in 395 +nim In6_addr winlean.html#In6_addr object In6_addr 401 +nim Sockaddr_in6 winlean.html#Sockaddr_in6 object Sockaddr_in6 405 +nim Sockaddr_storage winlean.html#Sockaddr_storage object Sockaddr_storage 413 +nim Servent winlean.html#Servent object Servent 419 +nim Hostent winlean.html#Hostent object Hostent 429 +nim TFdSet winlean.html#TFdSet object TFdSet 436 +nim AddrInfo winlean.html#AddrInfo object AddrInfo 440 +nim SockLen winlean.html#SockLen type SockLen 450 +nim Timeval winlean.html#Timeval object Timeval 453 +nim SOMAXCONN winlean.html#SOMAXCONN var SOMAXCONN 457 +nim INVALID_SOCKET winlean.html#INVALID_SOCKET var INVALID_SOCKET 458 +nim SOL_SOCKET winlean.html#SOL_SOCKET var SOL_SOCKET 459 +nim SO_DEBUG winlean.html#SO_DEBUG var SO_DEBUG 460 +nim SO_ACCEPTCONN winlean.html#SO_ACCEPTCONN var SO_ACCEPTCONN 461 +nim SO_REUSEADDR winlean.html#SO_REUSEADDR var SO_REUSEADDR 462 +nim SO_REUSEPORT winlean.html#SO_REUSEPORT var SO_REUSEPORT 463 +nim SO_KEEPALIVE winlean.html#SO_KEEPALIVE var SO_KEEPALIVE 465 +nim SO_DONTROUTE winlean.html#SO_DONTROUTE var SO_DONTROUTE 466 +nim SO_BROADCAST winlean.html#SO_BROADCAST var SO_BROADCAST 467 +nim SO_USELOOPBACK winlean.html#SO_USELOOPBACK var SO_USELOOPBACK 468 +nim SO_LINGER winlean.html#SO_LINGER var SO_LINGER 469 +nim SO_OOBINLINE winlean.html#SO_OOBINLINE var SO_OOBINLINE 470 +nim SO_DONTLINGER winlean.html#SO_DONTLINGER var SO_DONTLINGER 472 +nim SO_EXCLUSIVEADDRUSE winlean.html#SO_EXCLUSIVEADDRUSE var SO_EXCLUSIVEADDRUSE 473 +nim SO_ERROR winlean.html#SO_ERROR var SO_ERROR 474 +nim TCP_NODELAY winlean.html#TCP_NODELAY var TCP_NODELAY 475 +nim `==` winlean.html#==,SocketHandle,SocketHandle proc `==`(x, y: SocketHandle): bool 477 +nim getservbyname winlean.html#getservbyname,cstring,cstring proc getservbyname(name, proto: cstring): ptr Servent 479 +nim getservbyport winlean.html#getservbyport,cint,cstring proc getservbyport(port: cint; proto: cstring): ptr Servent 482 +nim gethostbyaddr winlean.html#gethostbyaddr,ptr.InAddr,cuint,cint proc gethostbyaddr(ip: ptr InAddr; len: cuint; theType: cint): ptr Hostent 485 +nim gethostbyname winlean.html#gethostbyname,cstring proc gethostbyname(name: cstring): ptr Hostent 488 +nim gethostname winlean.html#gethostname,cstring,cint proc gethostname(hostname: cstring; len: cint): cint 491 +nim getprotobyname winlean.html#getprotobyname,cstring proc getprotobyname(name: cstring): ptr Protoent 494 +nim getprotobynumber winlean.html#getprotobynumber,cint proc getprotobynumber(proto: cint): ptr Protoent 498 +nim socket winlean.html#socket,cint,cint,cint proc socket(af, typ, protocol: cint): SocketHandle 502 +nim closesocket winlean.html#closesocket,SocketHandle proc closesocket(s: SocketHandle): cint 505 +nim accept winlean.html#accept,SocketHandle,ptr.SockAddr,ptr.SockLen proc accept(s: SocketHandle; a: ptr SockAddr; addrlen: ptr SockLen): SocketHandle 508 +nim bindSocket winlean.html#bindSocket,SocketHandle,ptr.SockAddr,SockLen proc bindSocket(s: SocketHandle; name: ptr SockAddr; namelen: SockLen): cint 510 +nim connect winlean.html#connect,SocketHandle,ptr.SockAddr,SockLen proc connect(s: SocketHandle; name: ptr SockAddr; namelen: SockLen): cint 512 +nim getsockname winlean.html#getsockname,SocketHandle,ptr.SockAddr,ptr.SockLen proc getsockname(s: SocketHandle; name: ptr SockAddr; namelen: ptr SockLen): cint 514 +nim getpeername winlean.html#getpeername,SocketHandle,ptr.SockAddr,ptr.SockLen proc getpeername(s: SocketHandle; name: ptr SockAddr; namelen: ptr SockLen): cint 517 +nim getsockopt winlean.html#getsockopt,SocketHandle,cint,cint,pointer,ptr.SockLen proc getsockopt(s: SocketHandle; level, optname: cint; optval: pointer;\n optlen: ptr SockLen): cint 520 +nim setsockopt winlean.html#setsockopt,SocketHandle,cint,cint,pointer,SockLen proc setsockopt(s: SocketHandle; level, optname: cint; optval: pointer;\n optlen: SockLen): cint 523 +nim listen winlean.html#listen,SocketHandle,cint proc listen(s: SocketHandle; backlog: cint): cint 527 +nim recv winlean.html#recv,SocketHandle,pointer,cint,cint proc recv(s: SocketHandle; buf: pointer; len, flags: cint): cint 529 +nim recvfrom winlean.html#recvfrom,SocketHandle,cstring,cint,cint,ptr.SockAddr,ptr.SockLen proc recvfrom(s: SocketHandle; buf: cstring; len, flags: cint; fromm: ptr SockAddr;\n fromlen: ptr SockLen): cint 531 +nim select winlean.html#select,cint,ptr.TFdSet,ptr.TFdSet,ptr.TFdSet,ptr.Timeval proc select(nfds: cint; readfds, writefds, exceptfds: ptr TFdSet;\n timeout: ptr Timeval): cint 534 +nim send winlean.html#send,SocketHandle,pointer,cint,cint proc send(s: SocketHandle; buf: pointer; len, flags: cint): cint 537 +nim sendto winlean.html#sendto,SocketHandle,pointer,cint,cint,ptr.SockAddr,SockLen proc sendto(s: SocketHandle; buf: pointer; len, flags: cint; to: ptr SockAddr;\n tolen: SockLen): cint 539 +nim shutdown winlean.html#shutdown,SocketHandle,cint proc shutdown(s: SocketHandle; how: cint): cint 543 +nim getnameinfo winlean.html#getnameinfo,ptr.SockAddr,SockLen,cstring,SockLen,cstring,SockLen,cint proc getnameinfo(a1: ptr SockAddr; a2: SockLen; a3: cstring; a4: SockLen;\n a5: cstring; a6: SockLen; a7: cint): cint 546 +nim inet_addr winlean.html#inet_addr,cstring proc inet_addr(cp: cstring): uint32 551 +nim FD_ISSET winlean.html#FD_ISSET,SocketHandle,TFdSet proc FD_ISSET(socket: SocketHandle; set: var TFdSet): cint 557 +nim FD_SET winlean.html#FD_SET,SocketHandle,TFdSet proc FD_SET(socket: SocketHandle; s: var TFdSet) 560 +nim FD_ZERO winlean.html#FD_ZERO,TFdSet proc FD_ZERO(s: var TFdSet) 565 +nim wsaStartup winlean.html#wsaStartup,int16,ptr.WSAData proc wsaStartup(wVersionRequired: int16; WSData: ptr WSAData): cint 568 +nim getaddrinfo winlean.html#getaddrinfo,cstring,cstring,ptr.AddrInfo,ptr.AddrInfo proc getaddrinfo(nodename, servname: cstring; hints: ptr AddrInfo;\n res: var ptr AddrInfo): cint 571 +nim freeAddrInfo winlean.html#freeAddrInfo,ptr.AddrInfo proc freeAddrInfo(ai: ptr AddrInfo) 575 +nim inet_ntoa winlean.html#inet_ntoa,InAddr proc inet_ntoa(i: InAddr): cstring 578 +nim MAXIMUM_WAIT_OBJECTS winlean.html#MAXIMUM_WAIT_OBJECTS const MAXIMUM_WAIT_OBJECTS 582 +nim WOHandleArray winlean.html#WOHandleArray type WOHandleArray 585 +nim PWOHandleArray winlean.html#PWOHandleArray type PWOHandleArray 586 +nim waitForMultipleObjects winlean.html#waitForMultipleObjects,DWORD,PWOHandleArray,WINBOOL,DWORD proc waitForMultipleObjects(nCount: DWORD; lpHandles: PWOHandleArray;\n bWaitAll: WINBOOL; dwMilliseconds: DWORD): DWORD 588 +nim GENERIC_READ winlean.html#GENERIC_READ const GENERIC_READ 596 +nim GENERIC_WRITE winlean.html#GENERIC_WRITE const GENERIC_WRITE 597 +nim GENERIC_ALL winlean.html#GENERIC_ALL const GENERIC_ALL 598 +nim FILE_SHARE_READ winlean.html#FILE_SHARE_READ const FILE_SHARE_READ 599 +nim FILE_SHARE_DELETE winlean.html#FILE_SHARE_DELETE const FILE_SHARE_DELETE 600 +nim FILE_SHARE_WRITE winlean.html#FILE_SHARE_WRITE const FILE_SHARE_WRITE 601 +nim CREATE_ALWAYS winlean.html#CREATE_ALWAYS const CREATE_ALWAYS 603 +nim CREATE_NEW winlean.html#CREATE_NEW const CREATE_NEW 604 +nim OPEN_EXISTING winlean.html#OPEN_EXISTING const OPEN_EXISTING 605 +nim OPEN_ALWAYS winlean.html#OPEN_ALWAYS const OPEN_ALWAYS 606 +nim FILE_BEGIN winlean.html#FILE_BEGIN const FILE_BEGIN 607 +nim INVALID_SET_FILE_POINTER winlean.html#INVALID_SET_FILE_POINTER const INVALID_SET_FILE_POINTER 608 +nim NO_ERROR winlean.html#NO_ERROR const NO_ERROR 609 +nim PAGE_NOACCESS winlean.html#PAGE_NOACCESS const PAGE_NOACCESS 610 +nim PAGE_EXECUTE winlean.html#PAGE_EXECUTE const PAGE_EXECUTE 611 +nim PAGE_EXECUTE_READ winlean.html#PAGE_EXECUTE_READ const PAGE_EXECUTE_READ 612 +nim PAGE_EXECUTE_READWRITE winlean.html#PAGE_EXECUTE_READWRITE const PAGE_EXECUTE_READWRITE 613 +nim PAGE_READONLY winlean.html#PAGE_READONLY const PAGE_READONLY 614 +nim PAGE_READWRITE winlean.html#PAGE_READWRITE const PAGE_READWRITE 615 +nim FILE_MAP_READ winlean.html#FILE_MAP_READ const FILE_MAP_READ 616 +nim FILE_MAP_WRITE winlean.html#FILE_MAP_WRITE const FILE_MAP_WRITE 617 +nim INVALID_FILE_SIZE winlean.html#INVALID_FILE_SIZE const INVALID_FILE_SIZE 618 +nim DUPLICATE_SAME_ACCESS winlean.html#DUPLICATE_SAME_ACCESS const DUPLICATE_SAME_ACCESS 620 +nim FILE_READ_DATA winlean.html#FILE_READ_DATA const FILE_READ_DATA 621 +nim FILE_WRITE_DATA winlean.html#FILE_WRITE_DATA const FILE_WRITE_DATA 622 +nim ERROR_FILE_NOT_FOUND winlean.html#ERROR_FILE_NOT_FOUND const ERROR_FILE_NOT_FOUND 626 +nim ERROR_PATH_NOT_FOUND winlean.html#ERROR_PATH_NOT_FOUND const ERROR_PATH_NOT_FOUND 627 +nim ERROR_ACCESS_DENIED winlean.html#ERROR_ACCESS_DENIED const ERROR_ACCESS_DENIED 628 +nim ERROR_NO_MORE_FILES winlean.html#ERROR_NO_MORE_FILES const ERROR_NO_MORE_FILES 629 +nim ERROR_LOCK_VIOLATION winlean.html#ERROR_LOCK_VIOLATION const ERROR_LOCK_VIOLATION 630 +nim ERROR_HANDLE_EOF winlean.html#ERROR_HANDLE_EOF const ERROR_HANDLE_EOF 631 +nim ERROR_FILE_EXISTS winlean.html#ERROR_FILE_EXISTS const ERROR_FILE_EXISTS 632 +nim ERROR_BAD_ARGUMENTS winlean.html#ERROR_BAD_ARGUMENTS const ERROR_BAD_ARGUMENTS 633 +nim duplicateHandle winlean.html#duplicateHandle,Handle,Handle,Handle,ptr.Handle,DWORD,WINBOOL,DWORD proc duplicateHandle(hSourceProcessHandle: Handle; hSourceHandle: Handle;\n hTargetProcessHandle: Handle; lpTargetHandle: ptr Handle;\n dwDesiredAccess: DWORD; bInheritHandle: WINBOOL;\n dwOptions: DWORD): WINBOOL 635 +nim getHandleInformation winlean.html#getHandleInformation,Handle,ptr.DWORD proc getHandleInformation(hObject: Handle; lpdwFlags: ptr DWORD): WINBOOL 642 +nim setHandleInformation winlean.html#setHandleInformation,Handle,DWORD,DWORD proc setHandleInformation(hObject: Handle; dwMask: DWORD; dwFlags: DWORD): WINBOOL 645 +nim getCurrentProcess winlean.html#getCurrentProcess proc getCurrentProcess(): Handle 649 +nim createFileW winlean.html#createFileW,WideCString,DWORD,DWORD,pointer,DWORD,DWORD,Handle proc createFileW(lpFileName: WideCString; dwDesiredAccess, dwShareMode: DWORD;\n lpSecurityAttributes: pointer;\n dwCreationDisposition, dwFlagsAndAttributes: DWORD;\n hTemplateFile: Handle): Handle 652 +nim deleteFileW winlean.html#deleteFileW,WideCString proc deleteFileW(pathName: WideCString): int32 657 +nim createFileA winlean.html#createFileA,cstring,DWORD,DWORD,pointer,DWORD,DWORD,Handle proc createFileA(lpFileName: cstring; dwDesiredAccess, dwShareMode: DWORD;\n lpSecurityAttributes: pointer;\n dwCreationDisposition, dwFlagsAndAttributes: DWORD;\n hTemplateFile: Handle): Handle 659 +nim deleteFileA winlean.html#deleteFileA,cstring proc deleteFileA(pathName: cstring): int32 664 +nim setEndOfFile winlean.html#setEndOfFile,Handle proc setEndOfFile(hFile: Handle): WINBOOL 667 +nim setFilePointer winlean.html#setFilePointer,Handle,LONG,ptr.LONG,DWORD proc setFilePointer(hFile: Handle; lDistanceToMove: LONG;\n lpDistanceToMoveHigh: ptr LONG; dwMoveMethod: DWORD): DWORD 670 +nim getFileSize winlean.html#getFileSize,Handle,ptr.DWORD proc getFileSize(hFile: Handle; lpFileSizeHigh: ptr DWORD): DWORD 675 +nim WinSizeT winlean.html#WinSizeT type WinSizeT 683 +nim mapViewOfFileEx winlean.html#mapViewOfFileEx,Handle,DWORD,DWORD,DWORD,WinSizeT,pointer proc mapViewOfFileEx(hFileMappingObject: Handle; dwDesiredAccess: DWORD;\n dwFileOffsetHigh, dwFileOffsetLow: DWORD;\n dwNumberOfBytesToMap: WinSizeT; lpBaseAddress: pointer): pointer 685 +nim createFileMappingW winlean.html#createFileMappingW,Handle,pointer,DWORD,DWORD,DWORD,pointer proc createFileMappingW(hFile: Handle; lpFileMappingAttributes: pointer;\n flProtect, dwMaximumSizeHigh: DWORD; dwMaximumSizeLow: DWORD;\n lpName: pointer): Handle 691 +nim unmapViewOfFile winlean.html#unmapViewOfFile,pointer proc unmapViewOfFile(lpBaseAddress: pointer): WINBOOL 698 +nim flushViewOfFile winlean.html#flushViewOfFile,pointer,DWORD proc flushViewOfFile(lpBaseAddress: pointer; dwNumberOfBytesToFlush: DWORD): WINBOOL 701 +nim OVERLAPPED winlean.html#OVERLAPPED object OVERLAPPED 705 +nim POVERLAPPED winlean.html#POVERLAPPED type POVERLAPPED 712 +nim POVERLAPPED_COMPLETION_ROUTINE winlean.html#POVERLAPPED_COMPLETION_ROUTINE type POVERLAPPED_COMPLETION_ROUTINE 714 +nim GUID winlean.html#GUID object GUID 717 +nim ERROR_IO_PENDING winlean.html#ERROR_IO_PENDING const ERROR_IO_PENDING 724 +nim WSAECONNABORTED winlean.html#WSAECONNABORTED const WSAECONNABORTED 725 +nim WSAEADDRINUSE winlean.html#WSAEADDRINUSE const WSAEADDRINUSE 726 +nim WSAECONNRESET winlean.html#WSAECONNRESET const WSAECONNRESET 727 +nim WSAEDISCON winlean.html#WSAEDISCON const WSAEDISCON 728 +nim WSAENETRESET winlean.html#WSAENETRESET const WSAENETRESET 729 +nim WSAETIMEDOUT winlean.html#WSAETIMEDOUT const WSAETIMEDOUT 730 +nim WSANOTINITIALISED winlean.html#WSANOTINITIALISED const WSANOTINITIALISED 731 +nim WSAENOTSOCK winlean.html#WSAENOTSOCK const WSAENOTSOCK 732 +nim WSAEINPROGRESS winlean.html#WSAEINPROGRESS const WSAEINPROGRESS 733 +nim WSAEINTR winlean.html#WSAEINTR const WSAEINTR 734 +nim WSAEWOULDBLOCK winlean.html#WSAEWOULDBLOCK const WSAEWOULDBLOCK 735 +nim WSAESHUTDOWN winlean.html#WSAESHUTDOWN const WSAESHUTDOWN 736 +nim ERROR_NETNAME_DELETED winlean.html#ERROR_NETNAME_DELETED const ERROR_NETNAME_DELETED 737 +nim STATUS_PENDING winlean.html#STATUS_PENDING const STATUS_PENDING 738 +nim createIoCompletionPort winlean.html#createIoCompletionPort,Handle,Handle,ULONG_PTR,DWORD proc createIoCompletionPort(FileHandle: Handle; ExistingCompletionPort: Handle;\n CompletionKey: ULONG_PTR;\n NumberOfConcurrentThreads: DWORD): Handle 740 +nim getQueuedCompletionStatus winlean.html#getQueuedCompletionStatus,Handle,PDWORD,PULONG_PTR,ptr.POVERLAPPED,DWORD proc getQueuedCompletionStatus(CompletionPort: Handle;\n lpNumberOfBytesTransferred: PDWORD;\n lpCompletionKey: PULONG_PTR;\n lpOverlapped: ptr POVERLAPPED; dwMilliseconds: DWORD): WINBOOL 745 +nim getOverlappedResult winlean.html#getOverlappedResult,Handle,POVERLAPPED,DWORD,WINBOOL proc getOverlappedResult(hFile: Handle; lpOverlapped: POVERLAPPED;\n lpNumberOfBytesTransferred: var DWORD; bWait: WINBOOL): WINBOOL 751 +nim hasOverlappedIoCompleted winlean.html#hasOverlappedIoCompleted.t template hasOverlappedIoCompleted(lpOverlapped): bool 758 +nim IOC_OUT winlean.html#IOC_OUT const IOC_OUT 762 +nim IOC_IN winlean.html#IOC_IN const IOC_IN 763 +nim IOC_WS2 winlean.html#IOC_WS2 const IOC_WS2 764 +nim IOC_INOUT winlean.html#IOC_INOUT const IOC_INOUT 765 +nim WSAIORW winlean.html#WSAIORW.t,, template WSAIORW(x, y): untyped 767 +nim SIO_GET_EXTENSION_FUNCTION_POINTER winlean.html#SIO_GET_EXTENSION_FUNCTION_POINTER const SIO_GET_EXTENSION_FUNCTION_POINTER 770 +nim SO_UPDATE_ACCEPT_CONTEXT winlean.html#SO_UPDATE_ACCEPT_CONTEXT const SO_UPDATE_ACCEPT_CONTEXT 771 +nim AI_V4MAPPED winlean.html#AI_V4MAPPED const AI_V4MAPPED 772 +nim AF_UNSPEC winlean.html#AF_UNSPEC const AF_UNSPEC 773 +nim AF_INET winlean.html#AF_INET const AF_INET 774 +nim AF_INET6 winlean.html#AF_INET6 const AF_INET6 775 +nim WSAID_CONNECTEX winlean.html#WSAID_CONNECTEX var WSAID_CONNECTEX 778 +nim WSAID_ACCEPTEX winlean.html#WSAID_ACCEPTEX var WSAID_ACCEPTEX 780 +nim WSAID_GETACCEPTEXSOCKADDRS winlean.html#WSAID_GETACCEPTEXSOCKADDRS var WSAID_GETACCEPTEXSOCKADDRS 782 +nim WSAIoctl winlean.html#WSAIoctl,SocketHandle,DWORD,pointer,DWORD,pointer,DWORD,PDWORD,POVERLAPPED,POVERLAPPED_COMPLETION_ROUTINE proc WSAIoctl(s: SocketHandle; dwIoControlCode: DWORD; lpvInBuffer: pointer;\n cbInBuffer: DWORD; lpvOutBuffer: pointer; cbOutBuffer: DWORD;\n lpcbBytesReturned: PDWORD; lpOverlapped: POVERLAPPED;\n lpCompletionRoutine: POVERLAPPED_COMPLETION_ROUTINE): cint 785 +nim TWSABuf winlean.html#TWSABuf object TWSABuf 792 +nim WSARecv winlean.html#WSARecv,SocketHandle,ptr.TWSABuf,DWORD,PDWORD,PDWORD,POVERLAPPED,POVERLAPPED_COMPLETION_ROUTINE proc WSARecv(s: SocketHandle; buf: ptr TWSABuf; bufCount: DWORD;\n bytesReceived, flags: PDWORD; lpOverlapped: POVERLAPPED;\n completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint 796 +nim WSARecvFrom winlean.html#WSARecvFrom,SocketHandle,ptr.TWSABuf,DWORD,PDWORD,PDWORD,ptr.SockAddr,ptr.cint,POVERLAPPED,POVERLAPPED_COMPLETION_ROUTINE proc WSARecvFrom(s: SocketHandle; buf: ptr TWSABuf; bufCount: DWORD;\n bytesReceived: PDWORD; flags: PDWORD; name: ptr SockAddr;\n namelen: ptr cint; lpOverlapped: POVERLAPPED;\n completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint 801 +nim WSASend winlean.html#WSASend,SocketHandle,ptr.TWSABuf,DWORD,PDWORD,DWORD,POVERLAPPED,POVERLAPPED_COMPLETION_ROUTINE proc WSASend(s: SocketHandle; buf: ptr TWSABuf; bufCount: DWORD; bytesSent: PDWORD;\n flags: DWORD; lpOverlapped: POVERLAPPED;\n completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint 807 +nim WSASendTo winlean.html#WSASendTo,SocketHandle,ptr.TWSABuf,DWORD,PDWORD,DWORD,ptr.SockAddr,cint,POVERLAPPED,POVERLAPPED_COMPLETION_ROUTINE proc WSASendTo(s: SocketHandle; buf: ptr TWSABuf; bufCount: DWORD; bytesSent: PDWORD;\n flags: DWORD; name: ptr SockAddr; namelen: cint;\n lpOverlapped: POVERLAPPED;\n completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint 812 +nim get_osfhandle winlean.html#get_osfhandle,FileHandle proc get_osfhandle(fd: FileHandle): Handle 818 +nim getSystemTimes winlean.html#getSystemTimes,FILETIME,FILETIME,FILETIME proc getSystemTimes(lpIdleTime, lpKernelTime, lpUserTime: var FILETIME): WINBOOL 821 +nim getProcessTimes winlean.html#getProcessTimes,Handle,FILETIME,FILETIME,FILETIME,FILETIME proc getProcessTimes(hProcess: Handle; lpCreationTime, lpExitTime, lpKernelTime,\n lpUserTime: var FILETIME): WINBOOL 825 +nim getSystemTimePreciseAsFileTime winlean.html#getSystemTimePreciseAsFileTime,FILETIME proc getSystemTimePreciseAsFileTime(lpSystemTimeAsFileTime: var FILETIME) 829 +nim inet_ntop winlean.html#inet_ntop,cint,pointer,cstring,int32 proc inet_ntop(family: cint; paddr: pointer; pStringBuffer: cstring;\n stringBufSize: int32): cstring 869 +nim WSAPROC_ACCEPTEX winlean.html#WSAPROC_ACCEPTEX type WSAPROC_ACCEPTEX 884 +nim WSAPROC_CONNECTEX winlean.html#WSAPROC_CONNECTEX type WSAPROC_CONNECTEX 893 +nim WSAPROC_GETACCEPTEXSOCKADDRS winlean.html#WSAPROC_GETACCEPTEXSOCKADDRS type WSAPROC_GETACCEPTEXSOCKADDRS 899 +nim WT_EXECUTEDEFAULT winlean.html#WT_EXECUTEDEFAULT const WT_EXECUTEDEFAULT 910 +nim WT_EXECUTEINIOTHREAD winlean.html#WT_EXECUTEINIOTHREAD const WT_EXECUTEINIOTHREAD 911 +nim WT_EXECUTEINUITHREAD winlean.html#WT_EXECUTEINUITHREAD const WT_EXECUTEINUITHREAD 912 +nim WT_EXECUTEINWAITTHREAD winlean.html#WT_EXECUTEINWAITTHREAD const WT_EXECUTEINWAITTHREAD 913 +nim WT_EXECUTEONLYONCE winlean.html#WT_EXECUTEONLYONCE const WT_EXECUTEONLYONCE 914 +nim WT_EXECUTELONGFUNCTION winlean.html#WT_EXECUTELONGFUNCTION const WT_EXECUTELONGFUNCTION 915 +nim WT_EXECUTEINTIMERTHREAD winlean.html#WT_EXECUTEINTIMERTHREAD const WT_EXECUTEINTIMERTHREAD 916 +nim WT_EXECUTEINPERSISTENTIOTHREAD winlean.html#WT_EXECUTEINPERSISTENTIOTHREAD const WT_EXECUTEINPERSISTENTIOTHREAD 917 +nim WT_EXECUTEINPERSISTENTTHREAD winlean.html#WT_EXECUTEINPERSISTENTTHREAD const WT_EXECUTEINPERSISTENTTHREAD 918 +nim WT_TRANSFER_IMPERSONATION winlean.html#WT_TRANSFER_IMPERSONATION const WT_TRANSFER_IMPERSONATION 919 +nim PROCESS_TERMINATE winlean.html#PROCESS_TERMINATE const PROCESS_TERMINATE 920 +nim PROCESS_CREATE_THREAD winlean.html#PROCESS_CREATE_THREAD const PROCESS_CREATE_THREAD 921 +nim PROCESS_SET_SESSIONID winlean.html#PROCESS_SET_SESSIONID const PROCESS_SET_SESSIONID 922 +nim PROCESS_VM_OPERATION winlean.html#PROCESS_VM_OPERATION const PROCESS_VM_OPERATION 923 +nim PROCESS_VM_READ winlean.html#PROCESS_VM_READ const PROCESS_VM_READ 924 +nim PROCESS_VM_WRITE winlean.html#PROCESS_VM_WRITE const PROCESS_VM_WRITE 925 +nim PROCESS_DUP_HANDLE winlean.html#PROCESS_DUP_HANDLE const PROCESS_DUP_HANDLE 926 +nim PROCESS_CREATE_PROCESS winlean.html#PROCESS_CREATE_PROCESS const PROCESS_CREATE_PROCESS 927 +nim PROCESS_SET_QUOTA winlean.html#PROCESS_SET_QUOTA const PROCESS_SET_QUOTA 928 +nim PROCESS_SET_INFORMATION winlean.html#PROCESS_SET_INFORMATION const PROCESS_SET_INFORMATION 929 +nim PROCESS_QUERY_INFORMATION winlean.html#PROCESS_QUERY_INFORMATION const PROCESS_QUERY_INFORMATION 930 +nim PROCESS_SUSPEND_RESUME winlean.html#PROCESS_SUSPEND_RESUME const PROCESS_SUSPEND_RESUME 931 +nim PROCESS_QUERY_LIMITED_INFORMATION winlean.html#PROCESS_QUERY_LIMITED_INFORMATION const PROCESS_QUERY_LIMITED_INFORMATION 932 +nim PROCESS_SET_LIMITED_INFORMATION winlean.html#PROCESS_SET_LIMITED_INFORMATION const PROCESS_SET_LIMITED_INFORMATION 933 +nim WAITORTIMERCALLBACK winlean.html#WAITORTIMERCALLBACK type WAITORTIMERCALLBACK 935 +nim postQueuedCompletionStatus winlean.html#postQueuedCompletionStatus,Handle,DWORD,ULONG_PTR,pointer proc postQueuedCompletionStatus(CompletionPort: Handle;\n dwNumberOfBytesTransferred: DWORD;\n dwCompletionKey: ULONG_PTR; lpOverlapped: pointer): bool 937 +nim registerWaitForSingleObject winlean.html#registerWaitForSingleObject,ptr.Handle,Handle,WAITORTIMERCALLBACK,pointer,ULONG,ULONG proc registerWaitForSingleObject(phNewWaitObject: ptr Handle; hObject: Handle;\n Callback: WAITORTIMERCALLBACK; Context: pointer;\n dwMilliseconds: ULONG; dwFlags: ULONG): bool 943 +nim unregisterWait winlean.html#unregisterWait,Handle proc unregisterWait(WaitHandle: Handle): DWORD 950 +nim openProcess winlean.html#openProcess,DWORD,WINBOOL,DWORD proc openProcess(dwDesiredAccess: DWORD; bInheritHandle: WINBOOL; dwProcessId: DWORD): Handle 953 +nim createEvent winlean.html#createEvent,ptr.SECURITY_ATTRIBUTES,DWORD,DWORD,ptr.Utf16Char proc createEvent(lpEventAttributes: ptr SECURITY_ATTRIBUTES; bManualReset: DWORD;\n bInitialState: DWORD; lpName: ptr Utf16Char): Handle 957 +nim setEvent winlean.html#setEvent,Handle proc setEvent(hEvent: Handle): cint 962 +nim FD_READ winlean.html#FD_READ const FD_READ 966 +nim FD_WRITE winlean.html#FD_WRITE const FD_WRITE 967 +nim FD_OOB winlean.html#FD_OOB const FD_OOB 968 +nim FD_ACCEPT winlean.html#FD_ACCEPT const FD_ACCEPT 969 +nim FD_CONNECT winlean.html#FD_CONNECT const FD_CONNECT 970 +nim FD_CLOSE winlean.html#FD_CLOSE const FD_CLOSE 971 +nim FD_QQS winlean.html#FD_QQS const FD_QQS 972 +nim FD_GROUP_QQS winlean.html#FD_GROUP_QQS const FD_GROUP_QQS 973 +nim FD_ROUTING_INTERFACE_CHANGE winlean.html#FD_ROUTING_INTERFACE_CHANGE const FD_ROUTING_INTERFACE_CHANGE 974 +nim FD_ADDRESS_LIST_CHANGE winlean.html#FD_ADDRESS_LIST_CHANGE const FD_ADDRESS_LIST_CHANGE 975 +nim FD_ALL_EVENTS winlean.html#FD_ALL_EVENTS const FD_ALL_EVENTS 976 +nim wsaEventSelect winlean.html#wsaEventSelect,SocketHandle,Handle,clong proc wsaEventSelect(s: SocketHandle; hEventObject: Handle; lNetworkEvents: clong): cint 978 +nim wsaCreateEvent winlean.html#wsaCreateEvent proc wsaCreateEvent(): Handle 982 +nim wsaCloseEvent winlean.html#wsaCloseEvent,Handle proc wsaCloseEvent(hEvent: Handle): bool 985 +nim wsaResetEvent winlean.html#wsaResetEvent,Handle proc wsaResetEvent(hEvent: Handle): bool 988 +nim KEY_EVENT_RECORD winlean.html#KEY_EVENT_RECORD object KEY_EVENT_RECORD 992 +nim readConsoleInput winlean.html#readConsoleInput,Handle,pointer,cint,ptr.cint proc readConsoleInput(hConsoleInput: Handle; lpBuffer: pointer; nLength: cint;\n lpNumberOfEventsRead: ptr cint): cint 1001 +nim LPFIBER_START_ROUTINE winlean.html#LPFIBER_START_ROUTINE type LPFIBER_START_ROUTINE 1006 +nim FIBER_FLAG_FLOAT_SWITCH winlean.html#FIBER_FLAG_FLOAT_SWITCH const FIBER_FLAG_FLOAT_SWITCH 1009 +nim CreateFiber winlean.html#CreateFiber,int,LPFIBER_START_ROUTINE,pointer proc CreateFiber(stackSize: int; fn: LPFIBER_START_ROUTINE; param: pointer): pointer 1011 +nim CreateFiberEx winlean.html#CreateFiberEx,int,int,int32,LPFIBER_START_ROUTINE,pointer proc CreateFiberEx(stkCommit: int; stkReserve: int; flags: int32;\n fn: LPFIBER_START_ROUTINE; param: pointer): pointer 1012 +nim ConvertThreadToFiber winlean.html#ConvertThreadToFiber,pointer proc ConvertThreadToFiber(param: pointer): pointer 1013 +nim ConvertThreadToFiberEx winlean.html#ConvertThreadToFiberEx,pointer,int32 proc ConvertThreadToFiberEx(param: pointer; flags: int32): pointer 1014 +nim DeleteFiber winlean.html#DeleteFiber,pointer proc DeleteFiber(fiber: pointer) 1015 +nim SwitchToFiber winlean.html#SwitchToFiber,pointer proc SwitchToFiber(fiber: pointer) 1016 +nim GetCurrentFiber winlean.html#GetCurrentFiber proc GetCurrentFiber(): pointer 1017 +nim toFILETIME winlean.html#toFILETIME,int64 proc toFILETIME(t: int64): FILETIME 1019 +nim LPFILETIME winlean.html#LPFILETIME type LPFILETIME 1024 +nim setFileTime winlean.html#setFileTime,Handle,LPFILETIME,LPFILETIME,LPFILETIME proc setFileTime(hFile: Handle; lpCreationTime: LPFILETIME;\n lpLastAccessTime: LPFILETIME; lpLastWriteTime: LPFILETIME): WINBOOL 1026 +nim SID_IDENTIFIER_AUTHORITY winlean.html#SID_IDENTIFIER_AUTHORITY object SID_IDENTIFIER_AUTHORITY 1032 +nim SID winlean.html#SID object SID 1035 +nim PSID winlean.html#PSID type PSID 1040 +nim SECURITY_NT_AUTHORITY winlean.html#SECURITY_NT_AUTHORITY const SECURITY_NT_AUTHORITY 1045 +nim SECURITY_BUILTIN_DOMAIN_RID winlean.html#SECURITY_BUILTIN_DOMAIN_RID const SECURITY_BUILTIN_DOMAIN_RID 1046 +nim DOMAIN_ALIAS_RID_ADMINS winlean.html#DOMAIN_ALIAS_RID_ADMINS const DOMAIN_ALIAS_RID_ADMINS 1047 +nim allocateAndInitializeSid winlean.html#allocateAndInitializeSid,ptr.SID_IDENTIFIER_AUTHORITY,BYTE,DWORD,DWORD,DWORD,DWORD,DWORD,DWORD,DWORD,DWORD,ptr.PSID proc allocateAndInitializeSid(pIdentifierAuthority: ptr SID_IDENTIFIER_AUTHORITY;\n nSubAuthorityCount: BYTE; nSubAuthority0: DWORD;\n nSubAuthority1: DWORD; nSubAuthority2: DWORD;\n nSubAuthority3: DWORD; nSubAuthority4: DWORD;\n nSubAuthority5: DWORD; nSubAuthority6: DWORD;\n nSubAuthority7: DWORD; pSid: ptr PSID): WINBOOL 1049 +nim checkTokenMembership winlean.html#checkTokenMembership,Handle,PSID,PBOOL proc checkTokenMembership(tokenHandle: Handle; sidToCheck: PSID; isMember: PBOOL): WINBOOL 1061 +nim freeSid winlean.html#freeSid,PSID proc freeSid(pSid: PSID): PSID 1064 diff --git a/with.html b/with.html new file mode 100644 index 0000000000000..8ee6bf603c7e5 --- /dev/null +++ b/with.html @@ -0,0 +1,144 @@ + + + + + + + +std/with + + + + + + + + + + + + + + + + +
+
+

std/with

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module implements the with macro for easy function chaining. See https://github.com/nim-lang/RFCs/issues/193 and https://github.com/nim-lang/RFCs/issues/192 for details leading to this particular design.

+

Since: version 1.2.

+

+ +
+

Macros

+
+
+
+
macro with(arg: typed; calls: varargs[untyped]): untyped
+
+ + This macro provides chaining of function calls. It does so by patching every call in calls to use arg as the first argument.
Caution: +This evaluates arg multiple times!
+ +

Example:

+
var x = "yay"
+with x:
+  add "abc"
+  add "efg"
+doAssert x == "yayabcefg"
+
+var a = 44
+with a:
+  += 4
+  -= 5
+doAssert a == 43
+
+# Nesting works for object types too!
+var foo = (bar: 1, qux: (baz: 2))
+with foo:
+  bar = 2
+  with qux:
+    baz = 3
+doAssert foo.bar == 2
+doAssert foo.qux.baz == 3
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/with.idx b/with.idx new file mode 100644 index 0000000000000..9beecbe5897fe --- /dev/null +++ b/with.idx @@ -0,0 +1,3 @@ +nimTitle with with.html module std/with 0 +nim with with.html#with.m,typed,varargs[untyped] macro with(arg: typed; calls: varargs[untyped]): untyped 19 +idx chaining with.html#chaining_1 Module with 0 diff --git a/wordwrap.html b/wordwrap.html new file mode 100644 index 0000000000000..a8b2238511501 --- /dev/null +++ b/wordwrap.html @@ -0,0 +1,128 @@ + + + + + + + +std/wordwrap + + + + + + + + + + + + + + + + +
+
+

std/wordwrap

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module contains an algorithm to wordwrap a Unicode string.

+ +
+

Procs

+
+
+
+
proc wrapWords(s: string; maxLineWidth = 80; splitLongWords = true;
+               seps: set[char] = Whitespace; newLine = "\n"): string {.
+    noSideEffect, ...raises: [], tags: [], forbids: [].}
+
+ + Word wraps s. +

Example:

+
doAssert "12345678901234567890".wrapWords() == "12345678901234567890"
+doAssert "123456789012345678901234567890".wrapWords(20) == "12345678901234567890\n1234567890"
+doAssert "Hello Bob. Hello John.".wrapWords(13, false) == "Hello Bob.\nHello John."
+doAssert "Hello Bob. Hello John.".wrapWords(13, true, {';'}) == "Hello Bob. He\nllo John."
+ Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/wordwrap.idx b/wordwrap.idx new file mode 100644 index 0000000000000..c0e8a2d4b5353 --- /dev/null +++ b/wordwrap.idx @@ -0,0 +1,2 @@ +nimTitle wordwrap wordwrap.html module std/wordwrap 0 +nim wrapWords wordwrap.html#wrapWords,string,int,set[char],string proc wrapWords(s: string; maxLineWidth = 80; splitLongWords = true;\n seps: set[char] = Whitespace; newLine = "\n"): string 22 diff --git a/wrapnils.html b/wrapnils.html new file mode 100644 index 0000000000000..45b3ab9bc7305 --- /dev/null +++ b/wrapnils.html @@ -0,0 +1,269 @@ + + + + + + + +std/wrapnils + + + + + + + + + + + + + + + + +
+
+

std/wrapnils

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

This module allows evaluating expressions safely against the following conditions:

  • nil dereferences
  • +
  • field accesses with incorrect discriminant in case objects
  • +
+

default(T) is returned in those cases when evaluating an expression of type T. This simplifies code by reducing need for if-else branches.

+

Note: experimental module, unstable API.

+ +

Example:

+
import std/wrapnils
+type Foo = ref object
+  x1: string
+  x2: Foo
+  x3: ref int
+
+var f: Foo
+assert ?.f.x2.x1 == "" # returns default value since `f` is nil
+
+var f2 = Foo(x1: "a")
+f2.x2 = f2
+assert ?.f2.x1 == "a" # same as f2.x1 (no nil LHS in this chain)
+assert ?.Foo(x1: "a").x1 == "a" # can use constructor inside
+
+# when you know a sub-expression doesn't involve a `nil` (e.g. `f2.x2.x2`),
+# you can scope it as follows:
+assert ?.(f2.x2.x2).x3[] == 0
+
+assert (?.f2.x2.x2).x3 == nil  # this terminates ?. early
+

Example:

+
import std/wrapnils
+# ?. also allows case object
+type B = object
+  b0: int
+  case cond: bool
+  of false: discard
+  of true:
+    b1: float
+
+var b = B(cond: false, b0: 3)
+doAssertRaises(FieldDefect): discard b.b1 # wrong discriminant
+doAssert ?.b.b1 == 0.0 # safe
+b = B(cond: true, b1: 4.5)
+doAssert ?.b.b1 == 4.5
+
+# lvalue semantics are preserved:
+if (let p = ?.b.b1.addr; p != nil): p[] = 4.7
+doAssert b.b1 == 4.7

+
+

Imports

+
+ macros, options +
+
+
+

Procs

+
+
+
+
func `[]`[T, I](a: Option[T]; i: I): auto {.inline.}
+
+ + See top-level example. + Source   +Edit   + +
+
+
+
func `[]`[U](a: Option[U]): auto {.inline.}
+
+ + See top-level example. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro `?.`(a: typed): auto
+
+ + Transforms a into an expression that can be safely evaluated even in presence of intermediate nil pointers/references, in which case a default value is produced. + Source   +Edit   + +
+
+ +
+
+
+
macro `??.`(a: typed): Option
+
+ + Same as ?. but returns an Option. +

Example:

+
import std/options
+type Foo = ref object
+  x1: ref int
+  x2: int
+# `?.` can't distinguish between a valid vs invalid default value, but `??.` can:
+var f1 = Foo(x1: int.new, x2: 2)
+doAssert (??.f1.x1[]).get == 0 # not enough to tell when the chain was valid.
+doAssert (??.f1.x1[]).isSome # a nil didn't occur in the chain
+doAssert (??.f1.x2).get == 2
+
+var f2: Foo
+doAssert not (??.f2.x1[]).isSome # f2 was nil
+
+doAssertRaises(UnpackDefect): discard (??.f2.x1[]).get
+doAssert ?.f2.x1[] == 0 # in contrast, this returns default(int)
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Templates

+
+
+
+
template fakeDot(a: Option; b): untyped
+
+ + See top-level example. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/wrapnils.idx b/wrapnils.idx new file mode 100644 index 0000000000000..16b3ea4665193 --- /dev/null +++ b/wrapnils.idx @@ -0,0 +1,7 @@ +nimTitle wrapnils wrapnils.html module std/wrapnils 0 +nim `?.` wrapnils.html#?..m,typed macro `?.`(a: typed): auto 111 +nim `??.` wrapnils.html#??..m,typed macro `??.`(a: typed): Option 127 +nim fakeDot wrapnils.html#fakeDot.t,Option, template fakeDot(a: Option; b): untyped 158 +nim `[]` wrapnils.html#[],Option[T],I proc `[]`[T, I](a: Option[T]; i: I): auto 177 +nim `[]` wrapnils.html#[],Option[U] proc `[]`[U](a: Option[U]): auto 183 +nimgrp [] wrapnils.html#[]-procs-all proc 177 diff --git a/xmlparser.html b/xmlparser.html new file mode 100644 index 0000000000000..4134eaa644bb3 --- /dev/null +++ b/xmlparser.html @@ -0,0 +1,212 @@ + + + + + + + +std/xmlparser + + + + + + + + + + + + + + + + +
+
+

std/xmlparser

+
+ +
+ Source   +Edit   + +
+ +

This module parses an XML document and creates its XML tree representation.

+ +
+

Types

+
+
+
XmlError = object of ValueError
+  errors*: seq[string]       ## All detected parsing errors.
+
+ + Exception that is raised for invalid XML. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc loadXml(path: string; errors: var seq[string];
+             options: set[XmlParseOption] = {reportComments}): XmlNode {.
+    ...raises: [IOError, OSError, ValueError, Exception],
+    tags: [ReadIOEffect, RootEffect, WriteIOEffect], forbids: [].}
+
+ + Loads and parses XML from file specified by path, and returns a XmlNode. Every occurred parsing error is added to the errors sequence. + Source   +Edit   + +
+
+
+
proc loadXml(path: string; options: set[XmlParseOption] = {reportComments}): XmlNode {.
+    ...raises: [IOError, OSError, ValueError, Exception, XmlError],
+    tags: [ReadIOEffect, RootEffect, WriteIOEffect], forbids: [].}
+
+ + Loads and parses XML from file specified by path, and returns a XmlNode. All parsing errors are turned into an XmlError exception. + Source   +Edit   + +
+
+ +
+
+
+
proc parseXml(s: Stream; filename: string; errors: var seq[string];
+              options: set[XmlParseOption] = {reportComments}): XmlNode {.
+    ...raises: [IOError, OSError, ValueError, Exception],
+    tags: [ReadIOEffect, RootEffect, WriteIOEffect], forbids: [].}
+
+ + Parses the XML from stream s and returns a XmlNode. Every occurred parsing error is added to the errors sequence. + Source   +Edit   + +
+
+
+
proc parseXml(s: Stream; options: set[XmlParseOption] = {reportComments}): XmlNode {.
+    ...raises: [IOError, OSError, ValueError, Exception, XmlError],
+    tags: [ReadIOEffect, RootEffect, WriteIOEffect], forbids: [].}
+
+ + Parses the XML from stream s and returns a XmlNode. All parsing errors are turned into an XmlError exception. + Source   +Edit   + +
+
+
+
proc parseXml(str: string; options: set[XmlParseOption] = {reportComments}): XmlNode {.
+    ...raises: [IOError, OSError, ValueError, Exception, XmlError],
+    tags: [ReadIOEffect, RootEffect, WriteIOEffect], forbids: [].}
+
+ + Parses the XML from string str and returns a XmlNode. All parsing errors are turned into an XmlError exception. + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/xmlparser.idx b/xmlparser.idx new file mode 100644 index 0000000000000..fe7c8f43098d1 --- /dev/null +++ b/xmlparser.idx @@ -0,0 +1,9 @@ +nimTitle xmlparser xmlparser.html module std/xmlparser 0 +nim XmlError xmlparser.html#XmlError object XmlError 18 +nim parseXml xmlparser.html#parseXml,Stream,string,seq[string],set[XmlParseOption] proc parseXml(s: Stream; filename: string; errors: var seq[string];\n options: set[XmlParseOption] = {reportComments}): XmlNode 104 +nim parseXml xmlparser.html#parseXml,Stream,set[XmlParseOption] proc parseXml(s: Stream; options: set[XmlParseOption] = {reportComments}): XmlNode 124 +nim parseXml xmlparser.html#parseXml,string,set[XmlParseOption] proc parseXml(str: string; options: set[XmlParseOption] = {reportComments}): XmlNode 131 +nim loadXml xmlparser.html#loadXml,string,seq[string],set[XmlParseOption] proc loadXml(path: string; errors: var seq[string];\n options: set[XmlParseOption] = {reportComments}): XmlNode 136 +nim loadXml xmlparser.html#loadXml,string,set[XmlParseOption] proc loadXml(path: string; options: set[XmlParseOption] = {reportComments}): XmlNode 144 +nimgrp loadxml xmlparser.html#loadXml-procs-all proc 136 +nimgrp parsexml xmlparser.html#parseXml-procs-all proc 104 diff --git a/xmltree.html b/xmltree.html new file mode 100644 index 0000000000000..c107af34edb69 --- /dev/null +++ b/xmltree.html @@ -0,0 +1,1417 @@ + + + + + + + +std/xmltree + + + + + + + + + + + + + + + + +
+
+

std/xmltree

+
+
+
+ + +
+ +
+ Search: +
+ + + +
+
+ Source   +Edit   + +
+ +

A simple XML tree generator. +

Example:

+
import std/xmltree
+var g = newElement("myTag")
+g.add newText("some text")
+g.add newComment("this is comment")
+
+var h = newElement("secondTag")
+h.add newEntity("some entity")
+
+let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
+let k = newXmlTree("treeTag", [g, h], att)
+
+doAssert $k == """<treeTag key1="first value" key2="second value">
+  <myTag>some text<!-- this is comment --></myTag>
+  <secondTag>&some entity;</secondTag>
+</treeTag>"""
See also: +

+ +
+

Types

+
+
+
XmlAttributes = StringTableRef
+
+ +

An alias for a string to string mapping.

+

Use toXmlAttributes proc to create XmlAttributes.

+ + Source   +Edit   + +
+
+
+
XmlNode = ref XmlNodeObj
+
+ +

An XML tree consisting of XML nodes.

+

Use newXmlTree proc for creating a new tree.

+ + Source   +Edit   + +
+
+
+
XmlNodeKind = enum
+  xnText,                   ## a text element
+  xnVerbatimText, xnElement, ## an element with 0 or more children
+  xnCData,                  ## a CDATA node
+  xnEntity,                 ## an entity (like ``&thing;``)
+  xnComment                  ## an XML comment
+
+ + Different kinds of XML nodes. + Source   +Edit   + +
+
+ +
+
+
+

Consts

+
+
+
xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
+
+ + Header to use for complete XML output. + Source   +Edit   + +
+
+ +
+
+
+

Procs

+
+
+
+
proc `$`(n: XmlNode): string {....raises: [], tags: [], forbids: [].}
+
+ +

Converts n into its string representation.

+

No <$xml ...$> declaration is produced, so that the produced XML fragments are composable.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc `[]`(n: var XmlNode; i: int): var XmlNode {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Returns the i'th child of n so that it can be modified. + Source   +Edit   + +
+
+
+
proc `[]`(n: XmlNode; i: int): XmlNode {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Returns the i'th child of n. +

Example:

+
var f = newElement("myTag")
+f.add newElement("first")
+f.insert(newElement("second"), 0)
+assert $f[1] == "<first />"
+assert $f[0] == "<second />"
+ Source   +Edit   + +
+
+ +
+
+
+
proc add(father, son: XmlNode) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Adds the child son to father. father must be of xnElement type

+

See also:

+ + +

Example:

+
var f = newElement("myTag")
+f.add newText("my text")
+f.add newElement("sonTag")
+f.add newEntity("my entity")
+assert $f == "<myTag>my text<sonTag />&my entity;</myTag>"
+ Source   +Edit   + +
+
+
+
proc add(father: XmlNode; sons: openArray[XmlNode]) {.inline, ...raises: [],
+    tags: [], forbids: [].}
+
+ +

Adds the children sons to father. father must be of xnElement type

+

See also:

+ + +

Example:

+
var f = newElement("myTag")
+f.add(@[newText("my text"), newElement("sonTag"), newEntity("my entity")])
+assert $f == "<myTag>my text<sonTag />&my entity;</myTag>"
+ Source   +Edit   + +
+
+
+
proc add(result: var string; n: XmlNode; indent = 0; indWidth = 2;
+         addNewLines = true) {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Adds the textual representation of n to string result. +

Example:

+
var
+  a = newElement("firstTag")
+  b = newText("my text")
+  c = newComment("my comment")
+  s = ""
+s.add(c)
+s.add(a)
+s.add(b)
+assert s == "<!-- my comment --><firstTag />my text"
+ Source   +Edit   + +
+
+ +
+
+
+
proc addEscaped(result: var string; s: string) {....raises: [], tags: [],
+    forbids: [].}
+
+ + The same as result.add(escape(s)), but more efficient. + Source   +Edit   + +
+
+ +
+
+
+
proc attr(n: XmlNode; name: string): string {....raises: [], tags: [], forbids: [].}
+
+ +

Finds the first attribute of n with a name of name. Returns "" on failure.

+

See also:

+ + +

Example:

+
var j = newElement("myTag")
+let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
+j.attrs = att
+assert j.attr("key1") == "first value"
+assert j.attr("key2") == "second value"
+ Source   +Edit   + +
+
+ +
+
+
+
proc attrs(n: XmlNode): XmlAttributes {.inline, ...raises: [], tags: [],
+                                        forbids: [].}
+
+ +

Gets the attributes belonging to n.

+

Returns nil if attributes have not been initialised for this node.

+

See also:

+ + +

Example:

+
var j = newElement("myTag")
+assert j.attrs == nil
+let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
+j.attrs = att
+assert j.attrs == att
+ Source   +Edit   + +
+
+ +
+
+
+
proc attrs=(n: XmlNode; attr: XmlAttributes) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Sets the attributes belonging to n.

+

See also:

+ + +

Example:

+
var j = newElement("myTag")
+assert j.attrs == nil
+let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
+j.attrs = att
+assert j.attrs == att
+ Source   +Edit   + +
+
+ +
+
+
+
proc attrsLen(n: XmlNode): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the number of n's attributes.

+

See also:

+ + +

Example:

+
var j = newElement("myTag")
+assert j.attrsLen == 0
+let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
+j.attrs = att
+assert j.attrsLen == 2
+ Source   +Edit   + +
+
+ +
+
+
+
proc child(n: XmlNode; name: string): XmlNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Finds the first child element of n with a name of name. Returns nil on failure. +

Example:

+
var f = newElement("myTag")
+f.add newElement("firstSon")
+f.add newElement("secondSon")
+f.add newElement("thirdSon")
+assert $(f.child("secondSon")) == "<secondSon />"
+ Source   +Edit   + +
+
+ +
+
+
+
proc clear(n: var XmlNode) {....raises: [], tags: [], forbids: [].}
+
+ + Recursively clears all children of an XmlNode. +

Example:

+
var g = newElement("myTag")
+g.add newText("some text")
+g.add newComment("this is comment")
+
+var h = newElement("secondTag")
+h.add newEntity("some entity")
+
+let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
+var k = newXmlTree("treeTag", [g, h], att)
+
+doAssert $k == """<treeTag key1="first value" key2="second value">
+  <myTag>some text<!-- this is comment --></myTag>
+  <secondTag>&some entity;</secondTag>
+</treeTag>"""
+
+clear(k)
+doAssert $k == """<treeTag key1="first value" key2="second value" />"""
+ Source   +Edit   + +
+
+ +
+
+
+
proc clientData(n: XmlNode): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Gets the client data of n.

+

The client data field is used by the HTML parser and generator.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc clientData=(n: XmlNode; data: int) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Sets the client data of n.

+

The client data field is used by the HTML parser and generator.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc delete(n: XmlNode; i: Natural) {....raises: [], tags: [], forbids: [].}
+
+ +

Deletes the i'th child of n.

+

See also:

+ + +

Example:

+
var f = newElement("myTag")
+f.add newElement("first")
+f.insert(newElement("second"), 0)
+f.delete(0)
+assert $f == """<myTag>
+  <first />
+</myTag>"""
+ Source   +Edit   + +
+
+
+
proc delete(n: XmlNode; slice: Slice[int]) {....raises: [], tags: [], forbids: [].}
+
+ +

Deletes the items n[slice] of n.

+

See also:

+ + +

Example:

+
var f = newElement("myTag")
+f.add newElement("first")
+f.insert([newElement("second"), newElement("third")], 0)
+f.delete(0..1)
+assert $f == """<myTag>
+  <first />
+</myTag>"""
+ Source   +Edit   + +
+
+ +
+
+
+
proc escape(s: string): string {....raises: [], tags: [], forbids: [].}
+
+ +

Escapes s for inclusion into an XML document.

+

Escapes these characters:

+ + + + + + +
charis converted to
<&lt;
>&gt;
&&amp;
"&quot;
'&apos;

You can also use addEscaped proc.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc findAll(n: XmlNode; tag: string; caseInsensitive = false): seq[XmlNode] {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + A shortcut version to assign in let blocks. +

Example:

+
var
+  b = newElement("good")
+  c = newElement("bad")
+  d = newElement("BAD")
+  e = newElement("GOOD")
+b.add newText("b text")
+c.add newText("c text")
+d.add newText("d text")
+e.add newText("e text")
+let a = newXmlTree("father", [b, c, d, e])
+assert $(a.findAll("good")) == "@[<good>b text</good>]"
+assert $(a.findAll("BAD")) == "@[<BAD>d text</BAD>]"
+assert $(a.findAll("good", caseInsensitive = true)) == "@[<good>b text</good>, <GOOD>e text</GOOD>]"
+assert $(a.findAll("BAD", caseInsensitive = true)) == "@[<bad>c text</bad>, <BAD>d text</BAD>]"
+ Source   +Edit   + +
+
+
+
proc findAll(n: XmlNode; tag: string; result: var seq[XmlNode];
+             caseInsensitive = false) {....raises: [], tags: [], forbids: [].}
+
+ +

Iterates over all the children of n returning those matching tag.

+

Found nodes satisfying the condition will be appended to the result sequence.

+ +

Example:

+
var
+  b = newElement("good")
+  c = newElement("bad")
+  d = newElement("BAD")
+  e = newElement("GOOD")
+b.add newText("b text")
+c.add newText("c text")
+d.add newText("d text")
+e.add newText("e text")
+let a = newXmlTree("father", [b, c, d, e])
+var s = newSeq[XmlNode]()
+a.findAll("good", s)
+assert $s == "@[<good>b text</good>]"
+s.setLen(0)
+a.findAll("good", s, caseInsensitive = true)
+assert $s == "@[<good>b text</good>, <GOOD>e text</GOOD>]"
+s.setLen(0)
+a.findAll("BAD", s)
+assert $s == "@[<BAD>d text</BAD>]"
+s.setLen(0)
+a.findAll("BAD", s, caseInsensitive = true)
+assert $s == "@[<bad>c text</bad>, <BAD>d text</BAD>]"
+ Source   +Edit   + +
+
+ +
+
+
+
proc innerText(n: XmlNode): string {....raises: [], tags: [], forbids: [].}
+
+ + Gets the inner text of n:
  • If n is xnText or xnEntity, returns its content.
  • +
  • If n is xnElement, runs recursively on each child node and concatenates the results.
  • +
  • Otherwise returns an empty string.
  • +
+

See also:

+ + +

Example:

+
var f = newElement("myTag")
+f.add newText("my text")
+f.add newComment("my comment")
+f.add newEntity("my entity")
+assert $f == "<myTag>my text<!-- my comment -->&my entity;</myTag>"
+assert innerText(f) == "my textmy entity"
+ Source   +Edit   + +
+
+ +
+
+
+
proc insert(father, son: XmlNode; index: int) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Inserts the child son to a given position in father.

+

father must be of xnElement kind.

+

See also:

+ + +

Example:

+
var f = newElement("myTag")
+f.add newElement("first")
+f.insert(newElement("second"), 0)
+assert $f == """<myTag>
+  <second />
+  <first />
+</myTag>"""
+ Source   +Edit   + +
+
+
+
proc insert(father: XmlNode; sons: openArray[XmlNode]; index: int) {.inline,
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Inserts the children openArray`sons` to a given position in father.

+

father must be of xnElement kind.

+

See also:

+ + +

Example:

+
var f = newElement("myTag")
+f.add newElement("first")
+f.insert([newElement("second"), newElement("third")], 0)
+assert $f == """<myTag>
+  <second />
+  <third />
+  <first />
+</myTag>"""
+ Source   +Edit   + +
+
+ +
+
+
+
proc kind(n: XmlNode): XmlNodeKind {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Returns n's kind. +

Example:

+
var a = newElement("firstTag")
+assert a.kind == xnElement
+var b = newText("my text")
+assert b.kind == xnText
+ Source   +Edit   + +
+
+ +
+
+
+
proc len(n: XmlNode): int {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Returns the number of n's children. +

Example:

+
var f = newElement("myTag")
+f.add newElement("first")
+f.insert(newElement("second"), 0)
+assert len(f) == 2
+ Source   +Edit   + +
+
+ +
+
+
+
proc newCData(cdata: sink string): XmlNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new XmlNode of kind xnCData with the text cdata. +

Example:

+
var d = newCData("my cdata")
+assert d.kind == xnCData
+assert $d == "<![CDATA[my cdata]]>"
+ Source   +Edit   + +
+
+ +
+
+
+
proc newComment(comment: sink string): XmlNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Creates a new XmlNode of kind xnComment with the text comment. +

Example:

+
var c = newComment("my comment")
+assert c.kind == xnComment
+assert $c == "<!-- my comment -->"
+ Source   +Edit   + +
+
+ +
+
+
+
proc newElement(tag: sink string): XmlNode {....raises: [], tags: [], forbids: [].}
+
+ +

Creates a new XmlNode of kind xnElement with the given tag.

+

See also:

+ + +

Example:

+
var a = newElement("firstTag")
+a.add newElement("childTag")
+assert a.kind == xnElement
+assert $a == """<firstTag>
+  <childTag />
+</firstTag>"""
+ Source   +Edit   + +
+
+ +
+
+
+
proc newEntity(entity: string): XmlNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new XmlNode of kind xnEntity with the text entity. +

Example:

+
var e = newEntity("my entity")
+assert e.kind == xnEntity
+assert $e == "&my entity;"
+ Source   +Edit   + +
+
+ +
+
+
+
proc newText(text: sink string): XmlNode {....raises: [], tags: [], forbids: [].}
+
+ + Creates a new XmlNode of kind xnText with the text text. +

Example:

+
var b = newText("my text")
+assert b.kind == xnText
+assert $b == "my text"
+ Source   +Edit   + +
+
+ +
+
+
+
proc newVerbatimText(text: sink string): XmlNode {....raises: [], tags: [],
+    forbids: [].}
+
+ + Creates a new XmlNode of kind xnVerbatimText with the text text. Since: Version 1.3. + Source   +Edit   + +
+
+ +
+
+
+
proc newXmlTree(tag: sink string; children: openArray[XmlNode];
+                attributes: XmlAttributes = nil): XmlNode {....raises: [],
+    tags: [], forbids: [].}
+
+ +

Creates a new XML tree with tag, children and attributes.

+

See also:

+ + +

Example:

+
var g = newElement("myTag")
+g.add newText("some text")
+g.add newComment("this is comment")
+var h = newElement("secondTag")
+h.add newEntity("some entity")
+let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
+let k = newXmlTree("treeTag", [g, h], att)
+
+doAssert $k == """<treeTag key1="first value" key2="second value">
+  <myTag>some text<!-- this is comment --></myTag>
+  <secondTag>&some entity;</secondTag>
+</treeTag>"""
+ Source   +Edit   + +
+
+ +
+
+
+
proc rawTag(n: XmlNode): string {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the underlying 'tag' string by reference.

+

This is only used for speed hacks.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc rawText(n: XmlNode): string {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Returns the underlying 'text' string by reference.

+

This is only used for speed hacks.

+ + Source   +Edit   + +
+
+ +
+
+
+
proc replace(n: XmlNode; i: Natural; replacement: openArray[XmlNode]) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Replaces the i'th child of n with replacement openArray.

+

n must be of xnElement kind.

+

See also:

+ + +

Example:

+
var f = newElement("myTag")
+f.add newElement("first")
+f.insert(newElement("second"), 0)
+f.replace(0, @[newElement("third"), newElement("fourth")])
+assert $f == """<myTag>
+  <third />
+  <fourth />
+  <first />
+</myTag>"""
+ Source   +Edit   + +
+
+
+
proc replace(n: XmlNode; slice: Slice[int]; replacement: openArray[XmlNode]) {.
+    ...raises: [], tags: [], forbids: [].}
+
+ +

Deletes the items n[slice] of n.

+

n must be of xnElement kind.

+

See also:

+ + +

Example:

+
var f = newElement("myTag")
+f.add newElement("first")
+f.insert([newElement("second"), newElement("fifth")], 0)
+f.replace(0..1, @[newElement("third"), newElement("fourth")])
+assert $f == """<myTag>
+  <third />
+  <fourth />
+  <first />
+</myTag>"""
+ Source   +Edit   + +
+
+ +
+
+
+
proc tag(n: XmlNode): lent string {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Gets the tag name of n.

+

n has to be an xnElement node.

+

See also:

+ + +

Example:

+
var a = newElement("firstTag")
+a.add newElement("childTag")
+assert $a == """<firstTag>
+  <childTag />
+</firstTag>"""
+assert a.tag == "firstTag"
+ Source   +Edit   + +
+
+ +
+
+
+
proc tag=(n: XmlNode; tag: sink string) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Sets the tag name of n.

+

n has to be an xnElement node.

+

See also:

+ + +

Example:

+
var a = newElement("firstTag")
+a.add newElement("childTag")
+assert $a == """<firstTag>
+  <childTag />
+</firstTag>"""
+a.tag = "newTag"
+assert $a == """<newTag>
+  <childTag />
+</newTag>"""
+ Source   +Edit   + +
+
+ +
+
+
+
proc text(n: XmlNode): lent string {.inline, ...raises: [], tags: [], forbids: [].}
+
+ +

Gets the associated text with the node n.

+

n can be a CDATA, Text, comment, or entity node.

+

See also:

+ + +

Example:

+
var c = newComment("my comment")
+assert $c == "<!-- my comment -->"
+assert c.text == "my comment"
+ Source   +Edit   + +
+
+ +
+
+
+
proc text=(n: XmlNode; text: sink string) {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ +

Sets the associated text with the node n.

+

n can be a CDATA, Text, comment, or entity node.

+

See also:

+ + +

Example:

+
var e = newEntity("my entity")
+assert $e == "&my entity;"
+e.text = "a new entity text"
+assert $e == "&a new entity text;"
+ Source   +Edit   + +
+
+ +
+
+
+
proc toXmlAttributes(keyValuePairs: varargs[tuple[key, val: string]]): XmlAttributes {.
+    ...raises: [], tags: [], forbids: [].}
+
+ + Converts {key: value} pairs into XmlAttributes. +

Example:

+
let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
+var j = newElement("myTag")
+j.attrs = att
+
+doAssert $j == """<myTag key1="first value" key2="second value" />"""
+ Source   +Edit   + +
+
+ +
+ +
+
+
+

Iterators

+
+
+
+
iterator items(n: XmlNode): XmlNode {.inline, ...raises: [], tags: [], forbids: [].}
+
+ + Iterates over all direct children of n. +

Example:

+
var g = newElement("myTag")
+g.add newText("some text")
+g.add newComment("this is comment")
+
+var h = newElement("secondTag")
+h.add newEntity("some entity")
+g.add h
+
+assert $g == "<myTag>some text<!-- this is comment --><secondTag>&some entity;</secondTag></myTag>"
+
+# for x in g: # the same as `for x in items(g):`
+#   echo x
+
+# some text
+# <!-- this is comment -->
+# <secondTag>&some entity;<![CDATA[some cdata]]></secondTag>
+ Source   +Edit   + +
+
+ +
+
+
+
iterator mitems(n: var XmlNode): var XmlNode {.inline, ...raises: [], tags: [],
+    forbids: [].}
+
+ + Iterates over all direct children of n so that they can be modified. + Source   +Edit   + +
+
+ +
+ +
+
+
+

Macros

+
+
+
+
macro `<>`(x: untyped): untyped
+
+ +

Constructor macro for XML. Example usage:

+

<>a(href="https://nim-lang.org", newText("Nim rules."))

+

Produces an XML tree for:

+
<a href="https://nim-lang.org">Nim rules.</a>
+ + Source   +Edit   + +
+
+ +
+ +
+
+ +
+
+ + +
+
+ + + + diff --git a/xmltree.idx b/xmltree.idx new file mode 100644 index 0000000000000..76d027d487d4a --- /dev/null +++ b/xmltree.idx @@ -0,0 +1,61 @@ +nimTitle xmltree xmltree.html module std/xmltree 0 +nim XmlNode xmltree.html#XmlNode type XmlNode 41 +nim xnText xmltree.html#xnText XmlNodeKind.xnText 46 +nim xnVerbatimText xmltree.html#xnVerbatimText XmlNodeKind.xnVerbatimText 46 +nim xnElement xmltree.html#xnElement XmlNodeKind.xnElement 46 +nim xnCData xmltree.html#xnCData XmlNodeKind.xnCData 46 +nim xnEntity xmltree.html#xnEntity XmlNodeKind.xnEntity 46 +nim xnComment xmltree.html#xnComment XmlNodeKind.xnComment 46 +nim XmlNodeKind xmltree.html#XmlNodeKind enum XmlNodeKind 46 +nim XmlAttributes xmltree.html#XmlAttributes type XmlAttributes 54 +nim xmlHeader xmltree.html#xmlHeader const xmlHeader 70 +nim newElement xmltree.html#newElement,sinkstring proc newElement(tag: sink string): XmlNode 85 +nim newText xmltree.html#newText,sinkstring proc newText(text: sink string): XmlNode 104 +nim newVerbatimText xmltree.html#newVerbatimText,sinkstring proc newVerbatimText(text: sink string): XmlNode 114 +nim newComment xmltree.html#newComment,sinkstring proc newComment(comment: sink string): XmlNode 120 +nim newCData xmltree.html#newCData,sinkstring proc newCData(cdata: sink string): XmlNode 130 +nim newEntity xmltree.html#newEntity,string proc newEntity(entity: string): XmlNode 140 +nim newXmlTree xmltree.html#newXmlTree,sinkstring,openArray[XmlNode],XmlAttributes proc newXmlTree(tag: sink string; children: openArray[XmlNode];\n attributes: XmlAttributes = nil): XmlNode 150 +nim text xmltree.html#text,XmlNode proc text(n: XmlNode): lent string 178 +nim text= xmltree.html#text=,XmlNode,sinkstring proc text=(n: XmlNode; text: sink string) 196 +nim tag xmltree.html#tag,XmlNode proc tag(n: XmlNode): lent string 214 +nim tag= xmltree.html#tag=,XmlNode,sinkstring proc tag=(n: XmlNode; tag: sink string) 235 +nim rawText xmltree.html#rawText,XmlNode proc rawText(n: XmlNode): string 258 +nim rawTag xmltree.html#rawTag,XmlNode proc rawTag(n: XmlNode): string 267 +nim innerText xmltree.html#innerText,XmlNode proc innerText(n: XmlNode): string 276 +nim add xmltree.html#add,XmlNode,XmlNode proc add(father, son: XmlNode) 307 +nim add xmltree.html#add,XmlNode,openArray[XmlNode] proc add(father: XmlNode; sons: openArray[XmlNode]) 329 +nim insert xmltree.html#insert,XmlNode,XmlNode,int proc insert(father, son: XmlNode; index: int) 350 +nim insert xmltree.html#insert,XmlNode,openArray[XmlNode],int proc insert(father: XmlNode; sons: openArray[XmlNode]; index: int) 378 +nim delete xmltree.html#delete,XmlNode,Natural proc delete(n: XmlNode; i: Natural) 407 +nim delete xmltree.html#delete,XmlNode,Slice[int] proc delete(n: XmlNode; slice: Slice[int]) 430 +nim replace xmltree.html#replace,XmlNode,Natural,openArray[XmlNode] proc replace(n: XmlNode; i: Natural; replacement: openArray[XmlNode]) 453 +nim replace xmltree.html#replace,XmlNode,Slice[int],openArray[XmlNode] proc replace(n: XmlNode; slice: Slice[int]; replacement: openArray[XmlNode]) 481 +nim len xmltree.html#len,XmlNode proc len(n: XmlNode): int 509 +nim kind xmltree.html#kind,XmlNode proc kind(n: XmlNode): XmlNodeKind 518 +nim `[]` xmltree.html#[],XmlNode,int proc `[]`(n: XmlNode; i: int): XmlNode 527 +nim `[]` xmltree.html#[],XmlNode,int_2 proc `[]`(n: var XmlNode; i: int): var XmlNode 539 +nim clear xmltree.html#clear,XmlNode proc clear(n: var XmlNode) 544 +nim items xmltree.html#items.i,XmlNode iterator items(n: XmlNode): XmlNode 572 +nim mitems xmltree.html#mitems.i,XmlNode iterator mitems(n: var XmlNode): var XmlNode 596 +nim toXmlAttributes xmltree.html#toXmlAttributes,varargs[tuple[string,string]] proc toXmlAttributes(keyValuePairs: varargs[tuple[key, val: string]]): XmlAttributes 601 +nim attrs xmltree.html#attrs,XmlNode proc attrs(n: XmlNode): XmlAttributes 614 +nim attrs= xmltree.html#attrs=,XmlNode,XmlAttributes proc attrs=(n: XmlNode; attr: XmlAttributes) 633 +nim attrsLen xmltree.html#attrsLen,XmlNode proc attrsLen(n: XmlNode): int 650 +nim attr xmltree.html#attr,XmlNode,string proc attr(n: XmlNode; name: string): string 667 +nim clientData xmltree.html#clientData,XmlNode proc clientData(n: XmlNode): int 686 +nim clientData= xmltree.html#clientData=,XmlNode,int proc clientData=(n: XmlNode; data: int) 692 +nim addEscaped xmltree.html#addEscaped,string,string proc addEscaped(result: var string; s: string) 698 +nim escape xmltree.html#escape,string proc escape(s: string): string 709 +nim add xmltree.html#add,string,XmlNode,int,int proc add(result: var string; n: XmlNode; indent = 0; indWidth = 2; addNewLines = true) 812 +nim `$` xmltree.html#$,XmlNode proc `$`(n: XmlNode): string 827 +nim child xmltree.html#child,XmlNode,string proc child(n: XmlNode; name: string): XmlNode 835 +nim findAll xmltree.html#findAll,XmlNode,string,seq[XmlNode] proc findAll(n: XmlNode; tag: string; result: var seq[XmlNode];\n caseInsensitive = false) 851 +nim findAll xmltree.html#findAll,XmlNode,string proc findAll(n: XmlNode; tag: string; caseInsensitive = false): seq[XmlNode] 890 +nim `<>` xmltree.html#<>.m,untyped macro `<>`(x: untyped): untyped 935 +nimgrp replace xmltree.html#replace-procs-all proc 453 +nimgrp delete xmltree.html#delete-procs-all proc 407 +nimgrp findall xmltree.html#findAll-procs-all proc 851 +nimgrp [] xmltree.html#[]-procs-all proc 527 +nimgrp add xmltree.html#add-procs-all proc 307 +nimgrp insert xmltree.html#insert-procs-all proc 350